feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

@@ -0,0 +1,410 @@
// The iOS host of MyGo: the app's delegates, which start Go, and the
// bridge between Go and UIKit. Go runs on a thread of its own and makes
// its calls (HostCalls) through mygo_drain on the main thread; events go
// to Go through mygo_event.
import UIKit
import os
/// The way to Go.
enum Go {
/// The descriptor of the process's standard error before Go took it,
/// where the app's output still goes, as Xcode and simctl show it.
static var stderr: Int32 = -1
static let log = OSLog(subsystem: Bundle.main.bundleIdentifier ?? "mygo", category: "app")
/// Sends an event Go does not answer.
static func send(_ msg: [UInt8]) { _ = ask(msg) }
/// Sends an event and returns Go's answer, nil when Go answers none
/// (the event is not one it answers, or Go is not running yet).
@discardableResult
static func ask(_ msg: [UInt8]) -> [UInt8]? {
var msg = msg
var reply: UnsafeMutablePointer<UInt8>? = nil
var n = 0
msg.withUnsafeMutableBufferPointer { p in
mygo_event(p.baseAddress, p.count, Thread.isMainThread ? 1 : 0, &reply, &n)
}
guard let reply else { return nil }
defer { mygo_free(reply) }
return Array(UnsafeBufferPointer(start: reply, count: n))
}
/// Decodes Go's answer to an event, or nil when there is none.
static func answer<T>(_ msg: [UInt8], _ decode: (inout WireReader) -> T) -> T? {
guard let reply = ask(msg) else { return nil }
return reply.withUnsafeBytes { buf in
var r = WireReader(buf)
return decode(&r)
}
}
static func start() {
stderr = dup(2)
var host = mygo_host(
call: { msg, len, reply, replyLen in
let out = dispatchCall(Host.shared, UnsafeRawBufferPointer(start: msg, count: len))
guard let out, let reply, let replyLen else {
reply?.pointee = nil
replyLen?.pointee = 0
return
}
let p = malloc(max(out.count, 1))!.assumingMemoryBound(to: UInt8.self)
out.withUnsafeBufferPointer { b in
if let base = b.baseAddress { p.update(from: base, count: out.count) }
}
reply.pointee = p
replyLen.pointee = out.count
},
post: {
DispatchQueue.main.async { mygo_drain() }
},
log: { isError, line, len in
guard let line else { return }
let s = String(decoding: UnsafeBufferPointer(start: line, count: len), as: UTF8.self)
os_log("%{public}@", log: Go.log, type: isError != 0 ? .error : .default, s)
if Go.stderr >= 0 {
var b = Array(s.utf8)
b.append(10)
_ = b.withUnsafeBytes { write(Go.stderr, $0.baseAddress, $0.count) }
}
})
mygo_start(&host)
}
}
@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
UNUserNotificationCenter.current().delegate = Host.shared
registerPlugins()
Go.start()
return true
}
func application(_ application: UIApplication, configurationForConnecting session: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
let c = UISceneConfiguration(name: nil, sessionRole: session.role)
c.delegateClass = SceneDelegate.self
return c
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken token: Data) {
PluginHost.applicationEvent(.pushToken(token))
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
PluginHost.applicationEvent(.pushError(error))
}
func application(_ application: UIApplication, didDiscardSceneSessions sessions: Set<UISceneSession>) {
Scenes.discarded(sessions)
}
func applicationDidReceiveMemoryWarning(_ application: UIApplication) { Go.send(Event.memoryWarning()) }
func applicationWillTerminate(_ application: UIApplication) { Go.ask(Event.terminating()) }
}
/// The windows of their own scenes, on iPad (WindowOptions.OwnScene): a scene
/// asked for with the window's number, in which it's the whole content. iOS may
/// disconnect a scene in the background and connect it again, keeping its session,
/// which keeps the window; the window closes as the session goes.
enum Scenes {
static let activity = "dev.mygo.window"
static var sessions: [Int: UISceneSession] = [:]
/// Those asked for that haven't connected, and those of them no longer wanted.
static var pending = Set<Int>()
static var unwanted = Set<Int>()
static var available: Bool {
UIDevice.current.userInterfaceIdiom == .pad && UIApplication.shared.supportsMultipleScenes
}
static func open(_ w: HostWindow) {
unwanted.remove(w.id)
if pending.contains(w.id) { return }
let request: UISceneSessionActivationRequest
if let s = sessions[w.id] {
request = UISceneSessionActivationRequest(session: s)
} else {
let a = NSUserActivity(activityType: activity)
a.userInfo = ["window": w.id]
request = UISceneSessionActivationRequest(role: .windowApplication, userActivity: a)
pending.insert(w.id)
}
UIApplication.shared.activateSceneSession(for: request) { error in
pending.remove(w.id)
FileHandle.standardError.write(Data("mygo: opening a window: \(error)\n".utf8))
}
}
static func close(_ id: Int) {
if pending.contains(id) { unwanted.insert(id) }
guard let s = sessions.removeValue(forKey: id) else { return }
// Back to the app's first, rather than out of the app, where iPadOS would
// go from the only window on screen.
if let main = Host.shared.window?.windowScene?.session {
UIApplication.shared.activateSceneSession(for: UISceneSessionActivationRequest(session: main)) { _ in }
}
UIApplication.shared.requestSceneSessionDestruction(s, options: nil)
}
/// The user closed these: their windows close.
static func discarded(_ all: Set<UISceneSession>) {
for s in all {
guard let id = s.userInfo?["window"] as? Int, sessions[id] === s else { continue }
sessions[id] = nil
if Host.shared.windows[id] != nil { Go.send(Event.closedByPage(id: id)) }
}
}
}
final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
/// The MyGo window this scene is, for one of its own; 0 for the app's first.
private var ownWindow = 0
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {
guard let scene = scene as? UIWindowScene else { return }
let own = options.userActivities.first(where: { $0.activityType == Scenes.activity })?.userInfo?["window"] as? Int
?? session.userInfo?["window"] as? Int
if let id = own {
Scenes.pending.remove(id)
// A window of its own, unless it's of an earlier run, which the
// system brings back, or wanted no more.
guard let hw = Host.shared.windows[id], Scenes.unwanted.remove(id) == nil else {
UIApplication.shared.requestSceneSessionDestruction(session, options: nil)
return
}
let w = UIWindow(windowScene: scene)
let holder = UIViewController()
let c = Navigation.shared.controller(hw)
holder.addChild(c)
c.view.frame = holder.view.bounds
c.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
holder.view.addSubview(c.view)
c.didMove(toParent: holder)
w.rootViewController = holder
w.makeKeyAndVisible()
window = w
ownWindow = id
session.userInfo = ["window": id]
Scenes.sessions[id] = session
scene.title = c.title
hw.reportSize()
return
}
if Host.shared.window != nil {
// A second of the app's first, which the user asked the system for:
// the app has one such window.
UIApplication.shared.requestSceneSessionDestruction(session, options: nil)
return
}
let w = UIWindow(windowScene: scene)
w.rootViewController = Host.shared.root
w.makeKeyAndVisible()
window = w
Host.shared.window = w
let urls = options.urlContexts.map { $0.url.absoluteString } + options.userActivities.compactMap { $0.webpageURL?.absoluteString }
if !urls.isEmpty { Go.send(Event.openURLs(urls: urls)) }
}
func scene(_ scene: UIScene, openURLContexts contexts: Set<UIOpenURLContext>) {
Go.send(Event.openURLs(urls: contexts.map { $0.url.absoluteString }))
}
func scene(_ scene: UIScene, continue activity: NSUserActivity) {
if let url = activity.webpageURL { Go.send(Event.openURLs(urls: [url.absoluteString])) }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Not closed: its session stays, and the system may connect it again, for
// which the view lets go of the scene's window.
if ownWindow != 0, let c = window?.rootViewController?.children.first {
c.willMove(toParent: nil)
c.view.removeFromSuperview()
c.removeFromParent()
}
window?.rootViewController = nil
window = nil
if ownWindow == 0, Host.shared.window?.windowScene === scene {
Host.shared.window = nil
}
}
func sceneDidBecomeActive(_ scene: UIScene) {
Go.send(Event.active(active: true))
if UIApplication.shared.supportsMultipleScenes { Go.send(Event.windowFront(id: ownWindow)) }
}
func sceneWillResignActive(_ scene: UIScene) {
let others = UIApplication.shared.connectedScenes.filter { $0 !== scene && $0.activationState == .foregroundActive }
if others.isEmpty { Go.send(Event.active(active: false)) }
}
// Waits for Go: it must stop drawing before the app is in the background,
// where iOS ends apps that use the GPU. The app is there once none of its
// scenes is on screen.
func sceneDidEnterBackground(_ scene: UIScene) {
let shown = UIApplication.shared.connectedScenes.contains {
$0 !== scene && ($0.activationState == .foregroundActive || $0.activationState == .foregroundInactive)
}
if !shown { Go.ask(Event.background(background: true)) }
}
func sceneWillEnterForeground(_ scene: UIScene) { Go.ask(Event.background(background: false)) }
}
/// The view controller of the app's window, whose view holds the app's
/// windows, the one in front last.
final class RootViewController: UIViewController, UIScrollViewDelegate {
/// Where the keyboard is, on the screen, nil while it's away.
var keyboardFrame: CGRect?
/// UIKit tells a scroll view of a tap on the status bar, the only way it
/// tells: this one shows nothing, and tells Go.
private let statusBarTap = UIScrollView()
/// What the app asked of the system's bars and the screen's orientation.
var barStyle = "auto"
var barsHidden = false
var orientations: UIInterfaceOrientationMask = .all
override var preferredStatusBarStyle: UIStatusBarStyle {
switch barStyle {
case "light": return .lightContent
case "dark": return .darkContent
default: return .default
}
}
override var prefersStatusBarHidden: Bool { barsHidden }
override var prefersHomeIndicatorAutoHidden: Bool { barsHidden }
override var supportedInterfaceOrientations: UIInterfaceOrientationMask { orientations }
override var childForStatusBarHidden: UIViewController? { nil }
override func loadView() {
view = UIView()
view.backgroundColor = .systemBackground
statusBarTap.scrollsToTop = true
statusBarTap.delegate = self
statusBarTap.contentSize = CGSize(width: 1, height: 3)
statusBarTap.contentOffset = CGPoint(x: 0, y: 1)
statusBarTap.frame = CGRect(x: 0, y: 0, width: 1, height: 1)
view.addSubview(statusBarTap)
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(keyboardChanged(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
nc.addObserver(self, selector: #selector(keyboardChanged(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
nc.addObserver(self, selector: #selector(settingsChanged), name: UIAccessibility.reduceMotionStatusDidChangeNotification, object: nil)
nc.addObserver(self, selector: #selector(settingsChanged), name: UIContentSizeCategory.didChangeNotification, object: nil)
nc.addObserver(self, selector: #selector(localeChanged), name: NSLocale.currentLocaleDidChangeNotification, object: nil)
nc.addObserver(self, selector: #selector(timeZoneChanged), name: .NSSystemTimeZoneDidChange, object: nil)
registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (_: RootViewController, _) in
Go.send(Event.themeChanged())
}
}
func scrollViewShouldScrollToTop(_ s: UIScrollView) -> Bool {
Go.send(Event.statusBarTapped())
return false
}
@objc func settingsChanged() { Go.send(Event.themeChanged()) }
@objc func localeChanged() { Go.send(Event.localeChanged()) }
@objc func timeZoneChanged() {
NSTimeZone.resetSystemTimeZone()
Go.send(Event.timeZoneChanged(id: TimeZone.current.identifier))
}
@objc func keyboardChanged(_ n: Notification) {
var frame: CGRect?
if n.name != UIResponder.keyboardWillHideNotification {
frame = (n.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
}
if frame != keyboardFrame {
keyboardFrame = frame
for w in Host.shared.windows.values { w.reportSize() }
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for w in Host.shared.windows.values { w.reportSize() }
}
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
for w in Host.shared.windows.values { w.reportSize() }
}
override var childForStatusBarStyle: UIViewController? { nil }
}
/// A window of the app: a view filling the screen, which shows a page or
/// native UI.
class HostWindow: UIView {
let id: Int
/// The surface showing this window under it, as a web view in native UI.
weak var holder: SurfaceWindow?
/// It opens in a scene of its own, on iPad.
var ownScene = false
private var lastSize: [Double] = []
init(id: Int) {
self.id = id
super.init(frame: Host.shared.root.view.bounds)
autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
required init?(coder: NSCoder) { fatalError() }
/// How much of this window the keyboard covers: only that of the scene the
/// user is typing in, of those an iPad may show side by side.
private var keyboardCover: CGFloat {
guard let frame = Host.shared.root.keyboardFrame, let w = window,
w.windowScene?.activationState == .foregroundActive else { return 0 }
let local = convert(frame, from: w.screen.coordinateSpace)
return max(0, bounds.maxY - local.minY)
}
/// Tells Go the window's size and what covers it, when they changed.
func reportSize() {
var s = holder == nil ? safeAreaInsets : .zero
// A large title, in the scroll view standing for the page's
// content, covers the page further down than the bars.
if holder == nil, let top = (superview?.next as? ScreenController)?.topInset { s.top = max(s.top, top) }
let scale = window?.screen.scale ?? traitCollection.displayScale
let size = [Double(bounds.width), Double(bounds.height), Double(scale), Double(s.top), Double(s.left),
Double(s.bottom), Double(s.right), Double(keyboardCover)]
if size == lastSize || bounds.width == 0 { return }
lastSize = size
Go.send(Event.resized(id: id, width: size[0], height: size[1], scale: size[2], safeTop: size[3],
safeLeft: size[4], safeBottom: size[5], safeRight: size[6], keyboard: size[7]))
}
override func safeAreaInsetsDidChange() {
super.safeAreaInsetsDidChange()
reportSize()
}
override func layoutSubviews() {
super.layoutSubviews()
reportSize()
}
func close() { removeFromSuperview() }
func focus() {}
func setBackground(_ color: UIColor) { backgroundColor = color }
}
extension UIColor {
/// The color of 0xRRGGBBAA.
convenience init(rgba v: Int) {
self.init(red: CGFloat((v >> 24) & 0xff) / 255, green: CGFloat((v >> 16) & 0xff) / 255,
blue: CGFloat((v >> 8) & 0xff) / 255, alpha: CGFloat(v & 0xff) / 255)
}
var rgba: Int {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
func c(_ v: CGFloat) -> Int { Int((min(max(v, 0), 1) * 255).rounded()) }
return c(r) << 24 | c(g) << 16 | c(b) << 8 | c(a)
}
}
@@ -0,0 +1,622 @@
// The calls Go makes of the host (HostCalls), on the main thread.
import UIKit
import WebKit
import UserNotifications
import UniformTypeIdentifiers
import Security
import Network
final class Host: NSObject, HostCalls, UNUserNotificationCenterDelegate, UIDocumentPickerDelegate {
static let shared = Host()
let root = RootViewController()
var window: UIWindow?
var windows: [Int: HostWindow] = [:]
/// The windows on screen, the one in front last.
var pickers: [UIDocumentPickerViewController: Int] = [:]
/// The view controller to present over: the root, or what it presents.
var presenter: UIViewController {
// Over the window the user is in, which an iPad may have several of.
let active = UIApplication.shared.connectedScenes.lazy
.compactMap { $0 as? UIWindowScene }
.first { $0.activationState == .foregroundActive }
var vc: UIViewController = active?.keyWindow?.rootViewController ?? root
while let p = vc.presentedViewController { vc = p }
return vc
}
/// Presents over what shows, once what shows stops going away: UIKit only
/// logs a presentation it refuses, whose answer would never come.
func present(_ vc: UIViewController, tries: Int = 20, then done: (() -> Void)? = nil) {
let top = presenter
if (top.isBeingDismissed || top.isBeingPresented) && tries > 0 {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { self.present(vc, tries: tries - 1, then: done) }
return
}
top.present(vc, animated: true, completion: done)
}
func timeZone() -> TimeZoneReply {
var r = TimeZoneReply()
r.id = TimeZone.current.identifier
return r
}
func firstFrame(_ c: FirstFrameCall) {} // iOS's launch screen goes by itself
func appInfo() -> AppInfoReply {
var r = AppInfoReply()
r.background = UIApplication.shared.applicationState == .background // the system started it for a task
let b = Bundle.main
r.name = (b.object(forInfoDictionaryKey: "CFBundleDisplayName") ?? b.object(forInfoDictionaryKey: "CFBundleName")) as? String ?? ""
r.version = b.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? ""
r.identifier = b.bundleIdentifier ?? ""
let fm = FileManager.default
r.filesDir = fm.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.path ?? ""
r.cacheDir = fm.urls(for: .cachesDirectory, in: .userDomainMask).first?.path ?? ""
r.tempDir = NSTemporaryDirectory()
r.documentsDir = fm.urls(for: .documentDirectory, in: .userDomainMask).first?.path ?? ""
r.resourcesDir = b.resourcePath ?? ""
r.languages = Locale.preferredLanguages
r.regionLocale = Locale.current.identifier
r.firstWeekday = Calendar.current.firstWeekday - 1
let j = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: .current) ?? ""
r.hourCycle = j.contains("a") ? 12 : 24
r.system = UIDevice.current.systemName
r.systemVersion = UIDevice.current.systemVersion
r.model = UIDevice.current.model
// iOS does not say: what the app kept goes if it was force-quit, which
// the system tells by the scene's session not coming back.
r.restoring = true
return r
}
func theme() -> ThemeReply {
var r = ThemeReply()
let traits = window?.traitCollection ?? root.traitCollection
r.dark = traits.userInterfaceStyle == .dark
r.accent = (window?.tintColor ?? .systemBlue).resolvedColor(with: traits).rgba
r.reduceMotion = UIAccessibility.isReduceMotionEnabled
r.reduceTransparency = UIAccessibility.isReduceTransparencyEnabled
r.increaseContrast = UIAccessibility.isDarkerSystemColorsEnabled
r.textScale = Double(UIFontMetrics.default.scaledValue(for: 17) / 17)
return r
}
func setAppearance(_ c: SetAppearanceCall) {
let style: UIUserInterfaceStyle = c.source == "dark" ? .dark : c.source == "light" ? .light : .unspecified
window?.overrideUserInterfaceStyle = style
}
func screen() -> ScreenReply {
var r = ScreenReply()
let s = window?.windowScene?.screen ?? UIScreen.main
r.width = Double(s.bounds.width)
r.height = Double(s.bounds.height)
r.scale = Double(s.scale)
return r
}
func log(_ c: LogCall) { NSLog("%@", c.line) }
// Windows.
func createWindow(_ c: CreateWindowCall) -> CreateWindowReply {
var r = CreateWindowReply()
let w: HostWindow
if c.surface {
let s = SurfaceWindow(id: c.id)
r.layer = Int(bitPattern: Unmanaged.passUnretained(s.drawHost).toOpaque())
w = s
} else if !c.viewType.isEmpty {
guard let v = PluginHost.makeView(c.viewType, id: c.id, args: c.viewArgs) else {
r.error = "mygo: no view \(c.viewType) in this app"
return r
}
w = PluginViewWindow(id: c.id, view: v)
} else {
w = WebWindow(id: c.id, c)
}
if c.hasBackground { w.setBackground(UIColor(rgba: c.background)) }
w.ownScene = c.ownScene && Scenes.available
windows[c.id] = w
if c.parent != 0 { surface(c.parent)?.hold(w) }
return r
}
func placeViews(_ c: PlaceViewsCall) { surface(c.id)?.placeViews(c.places) }
func showWindow(_ c: ShowWindowCall) {
guard let w = windows[c.id] else { return }
if w.ownScene {
Scenes.open(w)
return
}
Navigation.shared.show(w)
w.reportSize()
}
func hideWindow(_ c: HideWindowCall) {
guard let w = windows[c.id] else { return }
if w.ownScene {
Scenes.close(w.id)
return
}
Navigation.shared.hide(w)
}
func closeWindow(_ c: CloseWindowCall) {
guard let w = windows.removeValue(forKey: c.id) else { return }
if let holder = w.holder {
holder.release(w)
w.close()
return
}
if w.ownScene { Scenes.close(w.id) }
Navigation.shared.hide(w)
Navigation.shared.forget(w)
w.close()
}
func setTitle(_ c: SetTitleCall) { windows[c.id].map { Navigation.shared.controller($0).title = c.title } }
func createTabs(_ c: CreateTabsCall) { Navigation.shared.createTabs(c.id) }
func addTab(_ c: AddTabCall) {
guard let w = windows[c.window] else { return }
Navigation.shared.addTab(c.id, w, title: c.title, symbol: c.symbol, icon: c.icon)
}
func showTabs(_ c: ShowTabsCall) { Navigation.shared.showTabs(c.id) }
func selectTab(_ c: SelectTabCall) { Navigation.shared.tabs[c.id]?.selectedIndex = c.index }
func setTabBadge(_ c: SetTabBadgeCall) {
Navigation.shared.tabs[c.id]?.viewControllers?[safe: c.index]?.tabBarItem.badgeValue = c.badge.isEmpty ? nil : c.badge
}
func closeTabs(_ c: CloseTabsCall) { Navigation.shared.closeTabs(c.id) }
func pushWindow(_ c: PushWindowCall) {
guard let p = windows[c.parent], let w = windows[c.child] else { return }
Navigation.shared.push(w, over: p, title: c.title, animated: c.animated)
}
func setStack(_ c: SetStackCall) -> SetStackReply {
if let w = windows[c.id] { Navigation.shared.setStack(w, titles: c.titles, keys: c.keys) }
return SetStackReply()
}
func stackShown(_ c: StackShownCall) { windows[c.id].map { Navigation.shared.stackShown($0) } }
func popWindow(_ c: PopWindowCall) {
guard let w = windows[c.id] else { return }
Navigation.shared.pop(w, animated: c.animated)
}
func setBackground(_ c: SetBackgroundCall) { windows[c.id]?.setBackground(UIColor(rgba: c.color)) }
func focus(_ c: FocusCall) { windows[c.id]?.focus() }
// Pages.
func web(_ id: Int) -> WebWindow? { windows[id] as? WebWindow }
func loadURL(_ c: LoadURLCall) { web(c.id)?.load(c.url) }
func loadHTML(_ c: LoadHTMLCall) { web(c.id)?.loadHTML(c.html, base: c.baseURL) }
func reload(_ c: ReloadCall) {
if c.ignoreCache { web(c.id)?.webView.reloadFromOrigin() } else { web(c.id)?.webView.reload() }
}
func stopLoading(_ c: StopLoadingCall) { web(c.id)?.webView.stopLoading() }
func goBack(_ c: GoBackCall) { web(c.id)?.webView.goBack() }
func goForward(_ c: GoForwardCall) { web(c.id)?.webView.goForward() }
func eval(_ c: EvalCall) { web(c.id)?.webView.evaluateJavaScript(c.js, completionHandler: nil) }
func callAsync(_ c: CallAsyncCall) {
guard let w = web(c.id) else {
Go.send(Event.asyncResult(req: c.req, result: "", error: "mygo: the window is closed"))
return
}
w.webView.callAsyncJavaScript(c.body, arguments: [:], in: nil, in: .page) { result in
switch result {
case .success(let v):
Go.send(Event.asyncResult(req: c.req, result: (v as? String) ?? "", error: ""))
case .failure(let e):
Go.send(Event.asyncResult(req: c.req, result: "", error: e.localizedDescription))
}
}
}
func setZoom(_ c: SetZoomCall) { web(c.id)?.webView.pageZoom = CGFloat(c.factor) }
func setUserAgent(_ c: SetUserAgentCall) { web(c.id)?.webView.customUserAgent = c.userAgent.isEmpty ? nil : c.userAgent }
func setUserScripts(_ c: SetUserScriptsCall) { web(c.id)?.setScripts(c.scripts, c.scriptFlags) }
func capturePage(_ c: CapturePageCall) {
guard let w = web(c.id) else {
Go.send(Event.captured(req: c.req, png: [], error: "mygo: the window is closed"))
return
}
w.webView.takeSnapshot(with: nil) { image, error in
if let png = image?.pngData() {
Go.send(Event.captured(req: c.req, png: Array(png), error: ""))
} else {
Go.send(Event.captured(req: c.req, png: [], error: error?.localizedDescription ?? "mygo: no snapshot"))
}
}
}
func userAgent(_ c: UserAgentCall) -> UserAgentReply {
var r = UserAgentReply()
r.userAgent = web(c.id)?.userAgent ?? ""
return r
}
func schemeRespond(_ c: SchemeRespondCall) { SchemeHandler.respond(c) }
func schemeData(_ c: SchemeDataCall) { SchemeHandler.data(c) }
func schemeFinish(_ c: SchemeFinishCall) { SchemeHandler.finish(c.req) }
func schemeFail(_ c: SchemeFailCall) { SchemeHandler.fail(c.req, c.message) }
// Dialogs.
func messageBox(_ c: MessageBoxCall) {
let title = c.title.isEmpty ? c.message : c.title
var message = c.title.isEmpty ? c.detail : c.message
if !c.title.isEmpty, !c.detail.isEmpty { message += "\n\n" + c.detail }
let a = UIAlertController(title: title, message: message.isEmpty ? nil : message, preferredStyle: .alert)
for (i, label) in c.buttons.enumerated() {
let style: UIAlertAction.Style = i == c.cancelID && c.buttons.count > 1 ? .cancel : .default
let action = UIAlertAction(title: label, style: style) { _ in
Go.send(Event.messageBoxResult(req: c.req, response: i))
}
a.addAction(action)
if i == c.defaultID { a.preferredAction = action }
}
present(a)
}
func openFiles(_ c: OpenFilesCall) {
var types: [UTType] = c.extensions.compactMap { UTType(filenameExtension: $0) }
if c.directories { types = [.folder] } else if types.isEmpty { types = [.item] }
let p = UIDocumentPickerViewController(forOpeningContentTypes: types, asCopy: !c.directories)
p.allowsMultipleSelection = c.multiple
p.delegate = self
pickers[p] = c.req
present(p)
}
func documentPicker(_ p: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let req = pickers.removeValue(forKey: p) else { return }
for u in urls where !u.isFileURL || u.hasDirectoryPath { _ = u.startAccessingSecurityScopedResource() }
Go.send(Event.filesResult(req: req, paths: urls.map { $0.path }, error: ""))
}
func documentPickerWasCancelled(_ p: UIDocumentPickerViewController) {
guard let req = pickers.removeValue(forKey: p) else { return }
Go.send(Event.filesResult(req: req, paths: [], error: ""))
}
func shareFile(_ c: ShareFileCall) {
let vc = UIActivityViewController(activityItems: [URL(fileURLWithPath: c.path)], applicationActivities: nil)
vc.popoverPresentationController?.sourceView = root.view
vc.popoverPresentationController?.sourceRect = CGRect(x: root.view.bounds.midX, y: root.view.bounds.midY, width: 0, height: 0)
present(vc)
}
// The system.
func clipboardText() -> ClipboardTextReply {
var r = ClipboardTextReply()
let pb = UIPasteboard.general
if pb.hasStrings {
r.text = pb.string ?? ""
r.ok = true
}
return r
}
func setClipboardText(_ c: SetClipboardTextCall) { UIPasteboard.general.string = c.text }
func openURL(_ c: OpenURLCall) -> OpenURLReply {
var r = OpenURLReply()
guard let u = URL(string: c.url) else { return r }
UIApplication.shared.open(u)
r.ok = true
return r
}
func secretQuery(_ service: String, _ account: String) -> [String: Any] {
[kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account]
}
func secretGet(_ c: SecretGetCall) -> SecretGetReply {
var r = SecretGetReply()
var q = secretQuery(c.service, c.account)
q[kSecReturnData as String] = true
q[kSecMatchLimit as String] = kSecMatchLimitOne
var out: CFTypeRef?
let status = SecItemCopyMatching(q as CFDictionary, &out)
switch status {
case errSecSuccess:
r.value = Array((out as? Data) ?? Data())
r.found = true
case errSecItemNotFound:
break
default:
r.error = "mygo: keychain error \(status)"
}
return r
}
func secretSet(_ c: SecretSetCall) -> SecretSetReply {
var r = SecretSetReply()
let q = secretQuery(c.service, c.account)
let attrs: [String: Any] = [kSecValueData as String: Data(c.value),
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock]
var status = SecItemUpdate(q as CFDictionary, attrs as CFDictionary)
if status == errSecItemNotFound {
status = SecItemAdd(q.merging(attrs) { $1 } as CFDictionary, nil)
}
if status != errSecSuccess { r.error = "mygo: keychain error \(status)" }
return r
}
func secretDelete(_ c: SecretDeleteCall) -> SecretDeleteReply {
var r = SecretDeleteReply()
let status = SecItemDelete(secretQuery(c.service, c.account) as CFDictionary)
if status != errSecSuccess, status != errSecItemNotFound { r.error = "mygo: keychain error \(status)" }
return r
}
func notify(_ c: NotifyCall) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
guard granted else {
Go.send(Event.notifyDone(req: c.req, error: error?.localizedDescription ?? "mygo: notifications are not allowed"))
return
}
let content = UNMutableNotificationContent()
content.title = c.title
content.subtitle = c.subtitle
content.body = c.body
if !c.group.isEmpty { content.threadIdentifier = c.group }
if !c.silent { content.sound = .default }
let id = c.notificationID.isEmpty ? UUID().uuidString : c.notificationID
center.add(UNNotificationRequest(identifier: id, content: content, trigger: nil)) { error in
Go.send(Event.notifyDone(req: c.req, error: error?.localizedDescription ?? ""))
}
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent n: UNNotification,
withCompletionHandler done: @escaping (UNNotificationPresentationOptions) -> Void) {
// The app on screen hears of a push here: UIKit's other way needs a
// background mode and a flag in the push.
if n.request.trigger is UNPushNotificationTrigger {
PluginHost.applicationEvent(.pushMessage(n.request.content.userInfo))
}
done([.banner, .list, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
withCompletionHandler done: @escaping () -> Void) {
let n = response.notification
if n.request.trigger is UNPushNotificationTrigger {
PluginHost.applicationEvent(.pushOpened(n.request.content.userInfo))
}
Go.send(Event.notificationClicked(notificationID: n.request.identifier))
done()
}
func removeNotification(_ c: RemoveNotificationCall) {
let center = UNUserNotificationCenter.current()
center.removeDeliveredNotifications(withIdentifiers: [c.notificationID])
center.removePendingNotificationRequests(withIdentifiers: [c.notificationID])
}
func removeAllNotifications() {
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
func keepAwake(_ c: KeepAwakeCall) { UIApplication.shared.isIdleTimerDisabled = c.on }
// Network and power.
private var pathMonitor: NWPathMonitor?
private var path: NWPath?
private let pathQueue = DispatchQueue(label: "mygo.network")
private func monitor() -> NWPathMonitor {
if let m = pathMonitor { return m }
let m = NWPathMonitor()
pathMonitor = m
let ready = DispatchSemaphore(value: 0)
var first = true
m.pathUpdateHandler = { [weak self] p in
DispatchQueue.main.async { self?.path = p }
if first {
first = false
self?.path = p
ready.signal()
} else if self?.watchingNetwork == true {
Go.send(Event.networkChanged(online: p.status == .satisfied, metered: p.isExpensive || p.isConstrained))
}
}
m.start(queue: pathQueue)
// Its first answer comes within milliseconds.
_ = ready.wait(timeout: .now() + 0.5)
return m
}
private var watchingNetwork = false
func networkStatus() -> NetworkStatusReply {
_ = monitor()
var r = NetworkStatusReply()
if let p = path {
r.online = p.status == .satisfied
r.metered = p.isExpensive || p.isConstrained
}
return r
}
func watchNetwork() {
watchingNetwork = true
_ = monitor()
}
func battery() -> BatteryReply {
let d = UIDevice.current
d.isBatteryMonitoringEnabled = true
var r = BatteryReply()
r.level = Double(d.batteryLevel)
r.charging = d.batteryState == .charging || d.batteryState == .full
r.lowPower = ProcessInfo.processInfo.isLowPowerModeEnabled
return r
}
// The system's bars and the screen.
func setSystemBars(_ c: SetSystemBarsCall) {
root.barStyle = c.style
root.barsHidden = c.hidden
root.setNeedsStatusBarAppearanceUpdate()
root.setNeedsUpdateOfHomeIndicatorAutoHidden()
}
func setOrientations(_ c: SetOrientationsCall) {
var m: UIInterfaceOrientationMask = []
if c.mask & 1 != 0 { m.insert(.portrait) }
if c.mask & 2 != 0 { m.insert(.portraitUpsideDown) }
if c.mask & 4 != 0 { m.insert(.landscapeLeft) }
if c.mask & 8 != 0 { m.insert(.landscapeRight) }
root.orientations = m.isEmpty ? .all : m
root.setNeedsUpdateOfSupportedInterfaceOrientations()
window?.windowScene?.requestGeometryUpdate(.iOS(interfaceOrientations: root.orientations))
}
func share(_ c: ShareCall) {
var items: [Any] = []
if !c.text.isEmpty { items.append(c.text) }
if let u = URL(string: c.url), !c.url.isEmpty { items.append(u) }
items += c.paths.map { URL(fileURLWithPath: $0) }
guard !items.isEmpty else {
Go.send(Event.shareResult(req: c.req, error: "mygo: nothing to share"))
return
}
let vc = UIActivityViewController(activityItems: items, applicationActivities: nil)
popover(vc, x: c.x, y: c.y)
present(vc) { Go.send(Event.shareResult(req: c.req, error: "")) }
}
/// Where a sheet points on an iPad, which shows it as a popover.
private func popover(_ vc: UIViewController, x: Double, y: Double) {
guard let p = vc.popoverPresentationController else { return }
p.sourceView = root.view
let at = x == 0 && y == 0 ? CGPoint(x: root.view.bounds.midX, y: root.view.bounds.midY) : CGPoint(x: x, y: y)
p.sourceRect = CGRect(origin: at, size: .zero)
}
func saveFile(_ c: SaveFileCall) {
// Exporting the copy under the name asked for.
let dir = NSTemporaryDirectory() + UUID().uuidString
let named = URL(fileURLWithPath: dir).appendingPathComponent(c.name)
do {
try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
try FileManager.default.copyItem(at: URL(fileURLWithPath: c.path), to: named)
} catch {
Go.send(Event.filesResult(req: c.req, paths: [], error: error.localizedDescription))
return
}
let p = UIDocumentPickerViewController(forExporting: [named], asCopy: true)
p.delegate = self
pickers[p] = c.req
present(p)
}
func clipboardImage() -> ClipboardImageReply {
var r = ClipboardImageReply()
if UIPasteboard.general.hasImages, let png = UIPasteboard.general.image?.pngData() { r.png = Array(png) }
return r
}
func setClipboardImage(_ c: SetClipboardImageCall) {
UIPasteboard.general.image = UIImage(data: Data(c.png))
}
/// A menu shown by the app, as a context menu: an action sheet, from the
/// point on an iPad.
func popupMenu(_ c: PopupMenuCall) {
let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
c.items.withUnsafeBytes { buf in
var r = WireReader(buf)
while r.at < buf.count {
let id = r.int(), label = r.string(), enabled = r.bool(), checked = r.bool()
if id == 0 { continue }
let a = UIAlertAction(title: label, style: .default) { _ in
Go.send(Event.menuPicked(req: c.req, item: id))
}
a.isEnabled = enabled
if checked { a.setValue(true, forKey: "checked") }
sheet.addAction(a)
}
}
sheet.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel) { _ in
Go.send(Event.menuPicked(req: c.req, item: 0))
})
popover(sheet, x: c.x, y: c.y)
present(sheet)
}
func setBarItems(_ c: SetBarItemsCall) {
guard let w = windows[c.id] else { return }
var items: [UIBarButtonItem] = []
for (i, title) in c.titles.enumerated() {
let id = c.id
let action = UIAction(title: title) { _ in Go.send(Event.barItemClicked(id: id, index: i)) }
var image = c.symbols[i].isEmpty ? nil : UIImage(systemName: c.symbols[i])
if image == nil, let d = Data(base64Encoded: c.icons[i]), !d.isEmpty {
image = UIImage(data: d, scale: 3)?.withRenderingMode(.alwaysTemplate)
}
let item = UIBarButtonItem(primaryAction: action)
item.image = image
item.accessibilityLabel = title
items.append(item)
}
Navigation.shared.controller(w).navigationItem.rightBarButtonItems = items.reversed()
}
func pluginCall(_ c: PluginCallCall) { PluginHost.call(c) }
// Sound, called on the audio's thread.
func audioOpen(_ c: AudioOpenCall) -> AudioOpenReply { Sound.shared.open(c) }
func audioWrite(_ c: AudioWriteCall) -> AudioWriteReply { Sound.shared.write(c) }
func audioClose() -> AudioCloseReply {
Sound.shared.close()
return AudioCloseReply()
}
func haptic(_ c: HapticCall) {
switch c.kind {
case "selection": UISelectionFeedbackGenerator().selectionChanged()
case "light": UIImpactFeedbackGenerator(style: .light).impactOccurred()
case "heavy": UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
case "success": UINotificationFeedbackGenerator().notificationOccurred(.success)
case "warning": UINotificationFeedbackGenerator().notificationOccurred(.warning)
case "error": UINotificationFeedbackGenerator().notificationOccurred(.error)
default: UIImpactFeedbackGenerator(style: .medium).impactOccurred()
}
}
// Native UI.
func surface(_ id: Int) -> SurfaceWindow? { windows[id] as? SurfaceWindow }
func requestFrame(_ c: RequestFrameCall) { surface(c.id)?.requestFrame() }
func setTextInput(_ c: SetTextInputCall) { surface(c.id)?.setTextInput(c) }
func setCursor(_ c: SetCursorCall) { surface(c.id)?.setCursor(c.cursor) }
func accessibilityChanged(_ c: AccessibilityChangedCall) { surface(c.id)?.accessibilityChanged(focus: c.focus) }
func announce(_ c: AnnounceCall) { UIAccessibility.post(notification: .announcement, argument: c.text) }
func showMenu(_ c: ShowMenuCall) { surface(c.id)?.showMenu(c) }
// iOS's back is the swipe from the edge the content handles itself.
func setBackAvailable(_ c: SetBackAvailableCall) {}
func showMagnifier(_ c: ShowMagnifierCall) { surface(c.id)?.showMagnifier(c) }
func hideMagnifier(_ c: HideMagnifierCall) { surface(c.id)?.hideMagnifier() }
// Go lays out and draws text with Core Text on iOS.
func textMetrics(_ c: TextMetricsCall) -> TextMetricsReply { TextMetricsReply() }
func measureText(_ c: MeasureTextCall) -> MeasureTextReply { MeasureTextReply() }
func textAdvances(_ c: TextAdvancesCall) -> TextAdvancesReply { TextAdvancesReply() }
func drawText(_ c: DrawTextCall) -> DrawTextReply { DrawTextReply() }
func registerFont(_ c: RegisterFontCall) -> RegisterFontReply { RegisterFontReply() }
}
@@ -0,0 +1,401 @@
// The navigation of phones: each window in a view controller of its own,
// in a navigation controller (a stack, whose bar shows once a window is
// pushed), the navigation controllers of a bar of tabs in a tab bar
// controller, all children of the root view controller, the one shown
// last in front. A window's router may show its pages as screens of the
// stack (SetStack), one view controller each past the window's: the window
// moves into the one shown, and the others hold a snapshot of their page
// as it last showed, as Hotwire Native does with its web view.
import UIKit
/// A screen of a stack, which holds the window while it shows, and else
/// may hold a snapshot of what it showed.
class ScreenController: UIViewController, UIScrollViewDelegate {
let window: HostWindow
/// snapshot shows the page as it last showed, over the window, or in
/// place of it.
var snapshot: UIView?
/// titles is the scroll view UIKit takes for the page's content, over
/// the window, in which iOS 26 shows a large title.
var titles: UIScrollView?
init(_ w: HostWindow) {
window = w
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { fatalError() }
override func loadView() {
let v = UIView(frame: window.frame)
v.backgroundColor = window.backgroundColor
view = v
if window is SurfaceWindow {
// Native UI's scrolls are its own: this one, empty, clear and
// over the window, which nothing scrolls, stands for them as the
// page's content (contentScrollView). iOS 26 shows a large title
// in it, at its top, and moves it with the page under the one a
// finger takes back, beneath it; without one, it shows the title
// at once, over that page.
let t = UIScrollView(frame: v.bounds)
t.autoresizingMask = [.flexibleWidth, .flexibleHeight]
t.isUserInteractionEnabled = false
// The status bar's tap goes to the one scroll view that takes it,
// the root's, which tells Go.
t.scrollsToTop = false
t.backgroundColor = .clear
t.delegate = self
v.addSubview(t)
setContentScrollView(t, for: .top)
titles = t
}
}
/// add puts a view of the page in it, under the large title.
func add(_ sub: UIView) {
if let t = titles { view.insertSubview(sub, belowSubview: t) } else { view.addSubview(sub) }
}
/// topInset is how far down the bars and a large title cover the page.
var topInset: CGFloat? {
guard let t = titles else { return nil }
return t.adjustedContentInset.top
}
func scrollViewDidChangeAdjustedContentInset(_ s: UIScrollView) {
if window.superview === view { window.reportSize() }
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if window.superview === view { window.reportSize() }
}
}
/// The view controller of a window, whose view holds the window.
final class WindowController: ScreenController {
/// barAtRoot shows the navigation bar at the bottom of a stack, as a
/// tab's, with the window's title.
var barAtRoot = false
/// routed is set while the window's router shows its pages as screens
/// of the stack, this the first: the bar shows its title.
var routed = false
override func loadView() {
super.loadView()
window.frame = view.bounds
window.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.insertSubview(window, at: 0)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let nav = navigationController else { return }
let atRoot = nav.viewControllers.first === self
nav.setNavigationBarHidden(atRoot && !barAtRoot && !routed, animated: animated)
}
}
/// A page of a window's router past its first, a screen of its stack.
final class RouteController: ScreenController {
let key: String
init(_ w: HostWindow, key: String, title: String) {
self.key = key
super.init(w)
self.title = title
// As pushed windows: the bar's small title.
navigationItem.largeTitleDisplayMode = .never
}
required init?(coder: NSCoder) { fatalError() }
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
final class Navigation: NSObject, UINavigationControllerDelegate, UITabBarControllerDelegate {
static let shared = Navigation()
private var controllers: [Int: WindowController] = [:]
/// The windows of each stack, as it last showed them, to tell which
/// went (Popped).
private var stacks: [ObjectIdentifier: [Int]] = [:]
var tabs: [Int: UITabBarController] = [:]
private var tabIDs: [ObjectIdentifier: Int] = [:]
/// The screens of each window's router past its first (SetStack).
private var routes: [Int: [RouteController]] = [:]
/// moves counts each window's moves from screen to screen, which a
/// reveal that comes late must not follow.
private var moves: [Int: Int] = [:]
private var root: RootViewController { Host.shared.root }
func controller(_ w: HostWindow) -> WindowController {
if let c = controllers[w.id] { return c }
let c = WindowController(w)
controllers[w.id] = c
return c
}
func forget(_ w: HostWindow) {
controllers[w.id] = nil
routes[w.id] = nil
moves[w.id] = nil
}
private func stack(_ root: UIViewController) -> UINavigationController {
let nav = UINavigationController(rootViewController: root)
nav.delegate = self
nav.navigationBar.prefersLargeTitles = true
stacks[ObjectIdentifier(nav)] = [(root as? WindowController)?.window.id ?? 0]
return nav
}
/// add puts a child view controller of the root in front.
private func add(_ vc: UIViewController) {
if vc.parent !== root {
vc.willMove(toParent: nil)
vc.view.removeFromSuperview()
vc.removeFromParent()
root.addChild(vc)
vc.view.frame = root.view.bounds
vc.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
root.view.addSubview(vc.view)
vc.didMove(toParent: root)
} else {
root.view.bringSubviewToFront(vc.view)
}
}
private func remove(_ vc: UIViewController) {
vc.willMove(toParent: nil)
vc.view.removeFromSuperview()
vc.removeFromParent()
}
/// show brings a window to the front: its tab, its stack, or a stack of
/// its own.
func show(_ w: HostWindow) {
let c = controller(w)
if let nav = c.navigationController {
if let tbc = nav.tabBarController {
tbc.selectedViewController = nav
add(tbc)
} else {
add(nav)
}
return
}
add(stack(c))
}
/// hide takes a window off the screen: its stack, or the windows above
/// it in its stack.
func hide(_ w: HostWindow) {
guard let c = controllers[w.id], let nav = c.navigationController else { return }
if nav.viewControllers.first === c {
if nav.tabBarController == nil {
stacks[ObjectIdentifier(nav)] = nil
remove(nav)
}
} else if let i = nav.viewControllers.firstIndex(of: c) {
nav.setViewControllers(Array(nav.viewControllers[..<i]), animated: false)
}
}
func push(_ w: HostWindow, over parent: HostWindow, title: String, animated: Bool) {
let p = controller(parent)
let nav = p.navigationController ?? {
let n = stack(p)
add(n)
return n
}()
let c = controller(w)
c.title = title
// Pushed windows take the bar's small title, as Settings' pages.
c.navigationItem.largeTitleDisplayMode = .never
// Above the window it is pushed over, as it was pushed from it: above
// the screens of its router.
let over: UIViewController = routes[parent.id]?.last ?? p
if let i = nav.viewControllers.firstIndex(of: over), i < nav.viewControllers.count - 1 {
nav.setViewControllers(Array(nav.viewControllers[...i]), animated: false)
}
nav.pushViewController(c, animated: animated)
}
func pop(_ w: HostWindow, animated: Bool) {
guard let c = controllers[w.id], let nav = c.navigationController,
let i = nav.viewControllers.firstIndex(of: c), i > 0 else { return }
nav.popToViewController(nav.viewControllers[i - 1], animated: animated)
}
func navigationController(_ nav: UINavigationController, didShow vc: UIViewController, animated: Bool) {
// Screens of routers the user took off, with the back button or a
// swipe: the window goes into the screen shown, and its router back.
for (id, rs) in routes {
guard !rs.isEmpty, controllers[id]?.navigationController === nav else { continue }
let left = Array(rs.prefix { nav.viewControllers.contains($0) })
if left.count == rs.count { continue }
routes[id] = left
let w = rs[0].window
let target: ScreenController = left.last ?? controller(w)
move(w, into: target, back: true)
CATransaction.flush()
Go.send(Event.stackPopped(id: id, depth: left.count + 1))
}
let ids = nav.viewControllers.compactMap { ($0 as? WindowController)?.window.id }
let key = ObjectIdentifier(nav)
for id in stacks[key] ?? [] where !ids.contains(id) {
Go.send(Event.popped(id: id))
}
stacks[key] = ids
}
// The screens of routers.
/// setStack shows the pages of w's router as screens of its stack: the
/// window's own first, then a RouteController each. The screens of the
/// keys it shows stay; a page deeper is pushed, one less deep popped
/// back to, and others replace theirs at once. No titles take them away.
func setStack(_ w: HostWindow, titles: [String], keys: [String]) {
let wc = controller(w)
guard let nav = wc.navigationController, let at = nav.viewControllers.firstIndex(of: wc) else { return }
let old = routes[w.id] ?? []
let base = Array(nav.viewControllers[...at])
if titles.isEmpty {
routes[w.id] = nil
wc.routed = false
wc.navigationItem.title = wc.title
uncover(wc)
move(w, into: wc)
w.isHidden = false
if !old.isEmpty { nav.setViewControllers(base, animated: false) }
if nav.topViewController === wc {
nav.setNavigationBarHidden(at == 0 && !wc.barAtRoot, animated: false)
}
return
}
if !wc.routed {
wc.routed = true
if nav.topViewController === wc { nav.setNavigationBarHidden(false, animated: false) }
}
wc.navigationItem.title = titles[0]
let want = Array(zip(titles.dropFirst(), keys.dropFirst()))
var common = 0
while common < old.count, common < want.count, old[common].key == want[common].1 {
old[common].title = want[common].0
common += 1
}
if common == old.count, common == want.count { return } // titles alone
let top: ScreenController = old.last ?? wc
let fresh = want[common...].map { RouteController(w, key: $0.1, title: $0.0) }
let now = Array(old[..<common]) + fresh
routes[w.id] = now
let target: ScreenController = now.last ?? wc
let animated = nav.view.window != nil && (common == old.count || common == want.count)
if animated {
// The page going out of sight stays in its screen, as it last
// showed: the surface shows the page coming next.
cover(top, w)
}
if !fresh.isEmpty { uncover(target) }
move(w, into: target, back: fresh.isEmpty)
nav.setViewControllers(base + now, animated: animated)
// On screen before Go presents the page coming: Metal's frames show
// as they come, not with UIKit's next commit.
CATransaction.flush()
}
/// stackShown shows the window over the snapshot of its screen, once Go
/// presented its page there: a frame later, as the frame presents.
func stackShown(_ w: HostWindow) {
let n = moves[w.id] ?? 0
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0 / 30) { [weak self, weak w] in
guard let self, let w, (self.moves[w.id] ?? 0) == n,
let vc = w.superview?.next as? ScreenController else { return }
self.uncover(vc)
w.isHidden = false
}
}
/// cover leaves in vc a snapshot of what the window shows, over it.
private func cover(_ vc: ScreenController, _ w: HostWindow) {
uncover(vc)
guard w.superview === vc.view, !w.isHidden, let s = w.snapshotView(afterScreenUpdates: false) else { return }
s.frame = w.frame
s.autoresizingMask = [.flexibleWidth, .flexibleHeight]
vc.add(s)
vc.snapshot = s
}
private func uncover(_ vc: ScreenController) {
vc.snapshot?.removeFromSuperview()
vc.snapshot = nil
}
/// move puts the window in vc, under its snapshot. Going back to a screen
/// without one, it hides, as it shows another page: StackShown shows it.
private func move(_ w: HostWindow, into vc: ScreenController, back: Bool = false) {
guard w.superview !== vc.view else { return }
moves[w.id, default: 0] += 1
let from = w.superview
let page = vc.view!
if page.bounds.isEmpty, let from { page.frame = from.bounds }
w.frame = page.bounds
w.autoresizingMask = [.flexibleWidth, .flexibleHeight]
page.insertSubview(w, at: 0)
w.isHidden = back && vc.snapshot == nil
}
// Tabs.
func createTabs(_ id: Int) {
let tbc = UITabBarController()
tbc.delegate = self
tbc.viewControllers = []
tabs[id] = tbc
tabIDs[ObjectIdentifier(tbc)] = id
}
func addTab(_ id: Int, _ w: HostWindow, title: String, symbol: String, icon: [UInt8]) {
guard let tbc = tabs[id] else { return }
let c = controller(w)
if let old = c.navigationController {
// Shown on its own before: the tab takes it.
remove(old)
old.setViewControllers([], animated: false)
}
c.title = title
c.barAtRoot = !title.isEmpty
let nav = stack(c)
var image = symbol.isEmpty ? nil : UIImage(systemName: symbol)
if image == nil, !icon.isEmpty {
image = UIImage(data: Data(icon), scale: 3)?.withRenderingMode(.alwaysTemplate)
}
nav.tabBarItem = UITabBarItem(title: title, image: image, tag: tbc.viewControllers?.count ?? 0)
tbc.viewControllers = (tbc.viewControllers ?? []) + [nav]
}
func showTabs(_ id: Int) {
guard let tbc = tabs[id] else { return }
add(tbc)
}
func closeTabs(_ id: Int) {
guard let tbc = tabs.removeValue(forKey: id) else { return }
tabIDs[ObjectIdentifier(tbc)] = nil
remove(tbc)
}
func tabBarController(_ tbc: UITabBarController, didSelect vc: UIViewController) {
guard let id = tabIDs[ObjectIdentifier(tbc)], let i = tbc.viewControllers?.firstIndex(of: vc) else { return }
Go.send(Event.tabSelected(id: id, index: i))
}
}
extension Array {
subscript(safe i: Int) -> Element? { i >= 0 && i < count ? self[i] : nil }
}
@@ -0,0 +1,2 @@
// What the build replaces with the plugins the app's packages name.
func registerPlugins() {}
@@ -0,0 +1,144 @@
// Plugins' native code. A plugin brings Swift that implements MyGoPlugin
// (mygo-plugin.json names the class), which mygo build compiles into the app
// and registers by the plugin's id; Go calls it with mygo.Native(id).Call. It
// runs on the main thread.
import UIKit
/// The result of a plugin's method: its answer, which JSON can encode, or an
/// error.
public typealias PluginReply = (Result<Any?, PluginFailure>) -> Void
/// An error of a plugin's native code, with a code Go can tell apart.
public struct PluginFailure: Error {
public let code: String
public let message: String
public init(_ code: String, _ message: String = "") {
self.code = code
self.message = message
}
}
/// A plugin's native code.
public protocol MyGoPlugin: AnyObject {
/// Runs a method with its arguments, from JSON, on the main thread. It
/// may answer later: call reply exactly once, from any thread.
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply)
/// Hears what the app's delegate hears that no plugin can get otherwise.
func applicationEvent(_ event: ApplicationEvent)
}
public extension MyGoPlugin {
func applicationEvent(_ event: ApplicationEvent) {}
}
/// What reaches the app's delegate for plugins.
public enum ApplicationEvent {
case pushToken(Data)
case pushError(Error)
case pushMessage([AnyHashable: Any])
/// The user tapped a push's notification.
case pushOpened([AnyHashable: Any])
}
/// What plugins have of the host.
public enum PluginHost {
private static var plugins: [String: MyGoPlugin] = [:]
private static var viewMakers: [String: (Int, [String: Any]) -> UIView] = [:]
public static func register(_ id: String, _ plugin: MyGoPlugin) { plugins[id] = plugin }
/// Registers a type of view that mygo.NewPluginView makes: make gets the
/// number that calls about the view name it, and the arguments.
public static func registerView(_ type: String, _ make: @escaping (_ id: Int, _ args: [String: Any]) -> UIView) {
viewMakers[type] = make
}
static func makeView(_ type: String, id: Int, args: String) -> UIView? {
// A native module's view, which ui.NativeView shows: its handle, an
// object its Swift retained for Go.
if type == "mygo.native" {
guard let h = UInt(args), let p = UnsafeRawPointer(bitPattern: h) else { return nil }
return Unmanaged<AnyObject>.fromOpaque(p).takeUnretainedValue() as? UIView
}
var a: [String: Any] = [:]
if let d = args.data(using: .utf8), let o = try? JSONSerialization.jsonObject(with: d) as? [String: Any] { a = o }
return viewMakers[type]?(id, a)
}
/// The view controller to present over.
public static var presenter: UIViewController { Host.shared.presenter }
/// Presents a view controller, once the one on screen stops going away.
public static func present(_ vc: UIViewController) { Host.shared.present(vc) }
/// The window showing the app.
public static var window: UIWindow? { Host.shared.window }
/// Sends an event to Go (mygo.Native(id).On), from any thread.
public static func emit(_ plugin: String, _ name: String, _ data: Any? = nil) {
Go.send(Event.pluginEvent(plugin: plugin, name: name, data: encode(data)))
}
/// Tells plugins what reached the app's delegate. Public for what a plugin
/// adds to the delegate itself, in an extension of AppDelegate.
public static func applicationEvent(_ e: ApplicationEvent) {
for p in plugins.values { p.applicationEvent(e) }
}
static func encode(_ v: Any?) -> String {
guard let v else { return "null" }
if JSONSerialization.isValidJSONObject(v), let d = try? JSONSerialization.data(withJSONObject: v) {
return String(decoding: d, as: UTF8.self)
}
// Scalars, which JSONSerialization takes only inside something. What
// it can't encode it raises for, which Swift cannot catch.
if JSONSerialization.isValidJSONObject([v]), let d = try? JSONSerialization.data(withJSONObject: [v]), d.count >= 2 {
return String(decoding: d[1..<(d.count - 1)], as: UTF8.self)
}
return "null"
}
static func call(_ c: PluginCallCall) {
guard let p = plugins[c.plugin] else {
Go.send(Event.pluginResult(req: c.req, result: "", error: "no plugin \(c.plugin) in this app", code: "NoPlugin"))
return
}
var args: [String: Any] = [:]
if let d = c.args.data(using: .utf8), let o = try? JSONSerialization.jsonObject(with: d) as? [String: Any] { args = o }
var answered = false
p.call(c.method, args) { r in
DispatchQueue.main.async {
guard !answered else { return }
answered = true
switch r {
case .success(let v):
Go.send(Event.pluginResult(req: c.req, result: encode(v), error: "", code: ""))
case .failure(let f):
Go.send(Event.pluginResult(req: c.req, result: "", error: f.message, code: f.code))
}
}
}
}
}
/// A window showing a plugin's view, which a surface holds.
final class PluginViewWindow: HostWindow {
init(id: Int, view: UIView) {
super.init(id: id)
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
required init?(coder: NSCoder) { fatalError() }
}
/// The windows of the app, for native modules' Swift, which finds this
/// class by its name: a method taking a *mygo.Window gets its view
/// controller.
@objc(MyGoWindows) public final class MyGoWindows: NSObject {
@MainActor @objc public static func controller(_ id: NSNumber) -> UIViewController? {
guard let w = Host.shared.windows[id.intValue] else { return nil }
return Navigation.shared.controller(w)
}
}
@@ -0,0 +1,75 @@
// The sound of package audio, through AVAudioEngine: Go's output writes from a
// thread of its own, which waits here while the engine holds enough.
import AVFoundation
final class Sound {
static let shared = Sound()
private let engine = AVAudioEngine()
private let player = AVAudioPlayerNode()
private var format: AVAudioFormat?
private var room: DispatchSemaphore?
private var attached = false
func open(_ c: AudioOpenCall) -> AudioOpenReply {
var r = AudioOpenReply()
do {
let s = AVAudioSession.sharedInstance()
// Sounds follow the side switch, and mix with what else plays,
// until the app asks for more of the session.
if s.category == .soloAmbient { try s.setCategory(.ambient) }
try s.setActive(true)
guard let f = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: Double(c.rate), channels: 2, interleaved: false) else {
r.error = "audio: no such format"
return r
}
format = f
if !attached {
engine.attach(player)
engine.connect(player, to: engine.mainMixerNode, format: f)
attached = true
}
// Writes of 10 ms: as many as hold what was asked for.
room = DispatchSemaphore(value: max(2, c.ahead / 10))
try engine.start()
player.play()
} catch {
r.error = "audio: \(error.localizedDescription)"
}
return r
}
func write(_ c: AudioWriteCall) -> AudioWriteReply {
var r = AudioWriteReply()
guard let f = format, let room else {
r.error = "audio: closed"
return r
}
let frames = c.samples.count / 8
guard frames > 0, let b = AVAudioPCMBuffer(pcmFormat: f, frameCapacity: AVAudioFrameCount(frames)),
let left = b.floatChannelData?[0], let right = b.floatChannelData?[1] else { return r }
b.frameLength = AVAudioFrameCount(frames)
c.samples.withUnsafeBytes { raw in
let s = raw.bindMemory(to: Float32.self)
for i in 0..<frames {
left[i] = s[2 * i]
right[i] = s[2 * i + 1]
}
}
// An engine that stopped, as for a phone call, plays nothing more and
// frees no room: the output opens it again.
if !engine.isRunning || room.wait(timeout: .now() + 1) == .timedOut {
r.error = "audio: the engine stopped"
return r
}
player.scheduleBuffer(b) { room.signal() }
return r
}
func close() {
player.stop()
engine.stop()
room = nil
}
}
@@ -0,0 +1,735 @@
// Windows showing native UI. Go's Metal renderer draws into a CAMetalLayer
// it adds to the view's layer; the view gives Go the display's refreshes,
// the fingers, the keyboard (UITextInput, with the marked text of input
// methods) and the questions of VoiceOver.
import UIKit
import QuartzCore
final class SurfaceWindow: HostWindow, UITextInput, UIPointerInteractionDelegate {
private var link: CADisplayLink?
private var fingers: [ObjectIdentifier: Int] = [:]
private var nextFinger = 1
// The input being edited, as Go last told it: the text around the
// selection, from base, and offsets in UTF-16 units of the document,
// which is what UITextInput's NSRanges count in.
private var text: [UInt16] = []
private var base = 0, length = 0
private var selStart = 0, selEnd = 0
private var markStart = -1, markEnd = -1
private var caret = CGRect.zero
private var editing = false
private var hasDocument = false
private var shows = 0
private var serial = 0
// The input's traits, which the keyboard reads as it shows.
var keyboardType: UIKeyboardType = .default
var returnKeyType: UIReturnKeyType = .default
var autocapitalizationType: UITextAutocapitalizationType = .sentences
var autocorrectionType: UITextAutocorrectionType = .default
var spellCheckingType: UITextSpellCheckingType = .default
var isSecureTextEntry = false
var textContentType: UITextContentType! = nil
private var elements: [AccessElement]?
/// What Go's renderer adds its layer to, from its thread. The view's own
/// layer is UIKit's, which allows changes on the main thread alone.
let drawHost = CALayer()
override func layoutSubviews() {
super.layoutSubviews()
CATransaction.begin()
CATransaction.setDisableActions(true)
drawHost.frame = bounds
CATransaction.commit()
}
override init(id: Int) {
super.init(id: id)
layer.addSublayer(drawHost)
drawHost.frame = bounds
isMultipleTouchEnabled = true
backgroundColor = .systemBackground
let l = CADisplayLink(target: self, selector: #selector(tick))
l.preferredFrameRateRange = CAFrameRateRange(minimum: 30, maximum: 120, preferred: 120)
l.isPaused = true
l.add(to: .main, forMode: .common)
link = l
// A mouse's or a trackpad's pointer, on an iPad: it hovers, it scrolls
// with the wheel and two fingers, and it takes the content's shape.
let hover = UIHoverGestureRecognizer(target: self, action: #selector(hovered(_:)))
addGestureRecognizer(hover)
let wheel = UIPanGestureRecognizer(target: self, action: #selector(wheeled(_:)))
wheel.allowedScrollTypesMask = .all
wheel.allowedTouchTypes = []
wheel.maximumNumberOfTouches = 0
addGestureRecognizer(wheel)
addInteraction(UIPointerInteraction(delegate: self))
}
@objc private func hovered(_ g: UIHoverGestureRecognizer) {
let p = g.location(in: self)
let phase: String
switch g.state {
case .ended, .cancelled, .failed: phase = "cancel"
default: phase = "move"
}
Go.send(Event.touch(id: id, pointer: 0, phase: phase, kind: "mouse", x: Double(p.x), y: Double(p.y), pressure: 0, buttons: 0, time: CACurrentMediaTime()))
}
private var wheelLast = CGPoint.zero
@objc private func wheeled(_ g: UIPanGestureRecognizer) {
if g.state == .began { wheelLast = .zero }
let t = g.translation(in: self)
let p = g.location(in: self)
// Against the fingers, as what it moves is the view down the content.
Go.send(Event.scroll(id: id, x: Double(p.x), y: Double(p.y), dx: Double(wheelLast.x - t.x), dy: Double(wheelLast.y - t.y), precise: true, phase: ""))
wheelLast = t
}
private var pointerShape = "default"
func setCursor(_ name: String) {
pointerShape = name
for i in interactions { (i as? UIPointerInteraction)?.invalidate() }
}
func pointerInteraction(_ i: UIPointerInteraction, styleFor region: UIPointerRegion) -> UIPointerStyle? {
switch pointerShape {
case "text": return UIPointerStyle(shape: .verticalBeam(length: 20))
case "none": return .hidden()
case "pointer": return UIPointerStyle(shape: .roundedRect(CGRect(x: -12, y: -12, width: 24, height: 24), radius: 12))
default: return .system()
}
}
func pointerInteraction(_ i: UIPointerInteraction, regionFor r: UIPointerRegionRequest, defaultRegion: UIPointerRegion) -> UIPointerRegion? {
// Asked again as it moves: the content changes under it.
UIPointerRegion(rect: CGRect(x: r.location.x - 1, y: r.location.y - 1, width: 2, height: 2))
}
required init?(coder: NSCoder) { fatalError() }
override func didMoveToWindow() {
super.didMoveToWindow()
guard let w = window else { return }
let hz = Double(w.screen.maximumFramesPerSecond)
Go.send(Event.surfaceChanged(id: id, handle: Int(bitPattern: Unmanaged.passUnretained(drawHost).toOpaque()),
width: Double(bounds.width), height: Double(bounds.height),
scale: Double(w.screen.scale), refresh: hz))
}
override func close() {
link?.invalidate()
link = nil
if isFirstResponder { resignFirstResponder() }
super.close()
}
func requestFrame() { link?.isPaused = false }
@objc private func tick() {
// One frame per request: Go asks again while it animates.
link?.isPaused = true
Go.send(Event.frame(id: id))
}
// The views it holds, as web views: under its layer, whose frames are
// transparent where the content shows them, each in a view that clips it.
private final class Held {
let window: HostWindow
let clip = UIView()
var box = CGRect.zero
var covers: [CGRect] = []
init(_ w: HostWindow) { window = w }
func takes(_ p: CGPoint) -> Bool {
!clip.isHidden && box.contains(p) && !covers.contains { $0.contains(p) }
}
}
private var held: [Held] = []
/// What holds them, below the layer Go's renderer adds to this view's.
private lazy var underlay: UIView = {
let v = UIView(frame: bounds)
v.autoresizingMask = [.flexibleWidth, .flexibleHeight]
v.layer.zPosition = -1
insertSubview(v, at: 0)
return v
}()
func hold(_ w: HostWindow) {
w.holder = self
w.autoresizingMask = []
let h = Held(w)
h.clip.clipsToBounds = true
h.clip.isHidden = true
h.clip.addSubview(w)
underlay.addSubview(h.clip)
held.append(h)
}
func release(_ w: HostWindow) {
guard let i = held.firstIndex(where: { $0.window === w }) else { return }
held[i].clip.removeFromSuperview()
held.remove(at: i)
}
func placeViews(_ places: [UInt8]) {
var shown: [Held] = []
places.withUnsafeBytes { buf in
var r = WireReader(buf)
while r.at < buf.count {
let id = r.int()
let frame = CGRect(x: r.float(), y: r.float(), width: r.float(), height: r.float())
let clip = CGRect(x: r.float(), y: r.float(), width: r.float(), height: r.float())
var covers: [CGRect] = []
for _ in 0..<r.int() { covers.append(CGRect(x: r.float(), y: r.float(), width: r.float(), height: r.float())) }
guard let h = held.first(where: { $0.window.id == id }) else { continue }
h.clip.frame = clip
h.window.frame = frame.offsetBy(dx: -clip.minX, dy: -clip.minY)
h.window.reportSize()
h.box = clip
h.covers = covers
h.clip.isHidden = false
underlay.bringSubviewToFront(h.clip)
shown.append(h)
}
}
for h in held where !shown.contains(where: { $0 === h }) { h.clip.isHidden = true }
}
private var pressedAt: TimeInterval = -1
// A finger on a view it holds goes to the view, which the content hears
// of, as it closes what a press outside closes.
override func hitTest(_ p: CGPoint, with e: UIEvent?) -> UIView? {
guard self.point(inside: p, with: e) else { return nil }
for h in held.reversed() where h.takes(p) {
if let t = e?.timestamp, t != pressedAt {
pressedAt = t
Go.send(Event.viewPressed(id: id, x: Double(p.x), y: Double(p.y)))
}
return h.window.hitTest(convert(p, to: h.window), with: e) ?? h.window
}
return self
}
// Fingers.
private func send(_ touches: Set<UITouch>, _ phase: String) {
for t in touches {
let key = ObjectIdentifier(t)
var n = fingers[key]
if n == nil {
n = nextFinger
nextFinger += 1
fingers[key] = n
}
let p = t.location(in: self)
let kind: String
switch t.type {
case .pencil: kind = "pen"
case .indirectPointer: kind = "mouse"
default: kind = "touch"
}
Go.send(Event.touch(id: id, pointer: n!, phase: phase, kind: kind, x: Double(p.x), y: Double(p.y),
pressure: Double(t.force), buttons: 1, time: t.timestamp))
if phase == "up" || phase == "cancel" { fingers[key] = nil }
}
}
override func touchesBegan(_ t: Set<UITouch>, with e: UIEvent?) {
// A finger whose end UIKit never told of, as the view left the window
// under it, would turn every later one into a pinch.
if let all = e?.allTouches {
let live = Set(all.map { ObjectIdentifier($0) })
for (key, n) in fingers where !live.contains(key) {
Go.send(Event.touch(id: id, pointer: n, phase: "cancel", kind: "touch", x: 0, y: 0, pressure: 0, buttons: 0, time: CACurrentMediaTime()))
fingers[key] = nil
}
}
send(t, "down")
}
override func touchesMoved(_ t: Set<UITouch>, with e: UIEvent?) { send(t, "move") }
override func touchesEnded(_ t: Set<UITouch>, with e: UIEvent?) { send(t, "up") }
override func touchesCancelled(_ t: Set<UITouch>, with e: UIEvent?) { send(t, "cancel") }
// A hardware keyboard's keys.
private static let keyNames: [UIKeyboardHIDUsage: String] = [
.keyboardReturnOrEnter: "Enter", .keyboardEscape: "Escape", .keyboardDeleteOrBackspace: "Backspace",
.keyboardTab: "Tab", .keyboardSpacebar: "Space", .keyboardDeleteForward: "Delete", .keyboardHome: "Home",
.keyboardEnd: "End", .keyboardPageUp: "PageUp", .keyboardPageDown: "PageDown", .keyboardLeftArrow: "ArrowLeft",
.keyboardRightArrow: "ArrowRight", .keyboardUpArrow: "ArrowUp", .keyboardDownArrow: "ArrowDown",
]
private func keys(_ presses: Set<UIPress>, down: Bool) -> Set<UIPress> {
var rest = Set<UIPress>()
for p in presses {
guard let k = p.key else { rest.insert(p); continue }
let name = SurfaceWindow.keyNames[k.keyCode] ?? k.charactersIgnoringModifiers
var mods = 0
if k.modifierFlags.contains(.shift) { mods |= 1 }
if k.modifierFlags.contains(.control) { mods |= 2 }
if k.modifierFlags.contains(.alternate) { mods |= 4 }
if k.modifierFlags.contains(.command) { mods |= 8 }
let handled = Go.answer(Event.key(id: id, down: down, key: name, text: k.characters, mods: mods, repeated: false)) {
KeyReply(&$0).handled
} ?? false
// Keys typing text while editing reach insertText too.
if !handled && !(editing && SurfaceWindow.keyNames[k.keyCode] == nil) { rest.insert(p) }
}
return rest
}
override func pressesBegan(_ presses: Set<UIPress>, with e: UIPressesEvent?) {
let rest = keys(presses, down: true)
if !rest.isEmpty { super.pressesBegan(rest, with: e) }
}
override func pressesEnded(_ presses: Set<UIPress>, with e: UIPressesEvent?) {
let rest = keys(presses, down: false)
if !rest.isEmpty { super.pressesEnded(rest, with: e) }
}
// The keyboard.
override var canBecomeFirstResponder: Bool { true }
func setTextInput(_ c: SetTextInputCall) {
let wasEditing = editing
editing = c.active
let another = c.serial != serial
serial = c.serial
hasDocument = c.document
caret = CGRect(x: c.x, y: c.y, width: max(c.width, 2), height: max(c.height, 1))
let traitsChanged = setTraits(c)
let selChanged = c.selStart != selStart || c.selEnd != selEnd
let textChanged = c.base != base || c.length != length || Array(c.text.utf16) != text || c.markStart != markStart
if textChanged { inputDelegate?.textWillChange(self) }
if selChanged { inputDelegate?.selectionWillChange(self) }
apply(text: c.text, base: c.base, length: c.length, selStart: c.selStart, selEnd: c.selEnd, markStart: c.markStart, markEnd: c.markEnd)
if selChanged { inputDelegate?.selectionDidChange(self) }
if textChanged { inputDelegate?.textDidChange(self) }
if editing && (!isFirstResponder || c.show != shows) {
becomeFirstResponder()
} else if !editing && wasEditing && isFirstResponder {
resignFirstResponder()
} else if editing && (traitsChanged || another) {
reloadInputViews()
}
shows = c.show
}
private func setTraits(_ c: SetTextInputCall) -> Bool {
let kb: UIKeyboardType
switch c.keyboard {
case "email": kb = .emailAddress
case "number": kb = .numberPad
case "decimal": kb = .decimalPad
case "phone": kb = .phonePad
case "url": kb = .URL
case "search": kb = .webSearch
default: kb = .default
}
let ret: UIReturnKeyType
switch c.returnKey {
case "done": ret = .done
case "go": ret = .go
case "next": ret = .next
case "search": ret = .search
case "send": ret = .send
default: ret = .default
}
let caps: UITextAutocapitalizationType
switch c.capitalize {
case "none": caps = .none
case "words": caps = .words
case "characters": caps = .allCharacters
case "sentences": caps = .sentences
default: caps = (kb == .default || kb == .webSearch) && !c.secure ? .sentences : .none
}
let correct: UITextAutocorrectionType = c.autocorrect == "off" || c.secure ? .no : c.autocorrect == "on" ? .yes : .default
let content: UITextContentType?
switch c.autofill {
case "username": content = .username
case "password": content = .password
case "newPassword": content = .newPassword
case "oneTimeCode": content = .oneTimeCode
case "email": content = .emailAddress
case "name": content = .name
case "phone": content = .telephoneNumber
case "address": content = .fullStreetAddress
case "postalCode": content = .postalCode
case "creditCard": content = .creditCardNumber
default: content = nil
}
let changed = kb != keyboardType || ret != returnKeyType || caps != autocapitalizationType || correct != autocorrectionType ||
c.secure != isSecureTextEntry || content != textContentType
keyboardType = kb
returnKeyType = ret
autocapitalizationType = caps
autocorrectionType = correct
spellCheckingType = correct == .no ? .no : .default
isSecureTextEntry = c.secure
textContentType = content
return changed
}
private func apply(text t: String, base b: Int, length l: Int, selStart s: Int, selEnd e: Int, markStart ms: Int, markEnd me: Int) {
text = Array(t.utf16)
base = b
length = l
selStart = s
selEnd = e
markStart = ms
markEnd = me
}
/// Sends an edit and takes the state after it, which the keyboard goes
/// on to read at once.
private func edit(_ msg: [UInt8]) {
guard let st = Go.answer(msg, { TextStateReply(&$0) }) else { return }
apply(text: st.text, base: st.base, length: st.length, selStart: st.selStart, selEnd: st.selEnd, markStart: st.markStart, markEnd: st.markEnd)
caret = CGRect(x: st.x, y: st.y, width: max(st.width, 2), height: max(st.height, 1))
}
override func resignFirstResponder() -> Bool {
let r = super.resignFirstResponder()
if editing { Go.send(Event.textInputEnded(id: id)) }
return r
}
var hasText: Bool { length > 0 }
func insertText(_ s: String) { edit(Event.textReplace(id: id, hasRange: false, start: 0, end: 0, text: s)) }
func deleteBackward() {
if markStart >= 0 {
edit(Event.textMark(id: id, hasRange: false, start: 0, end: 0, text: "", selStart: 0, selEnd: 0))
return
}
edit(Event.textCommand(id: id, command: "deleteBackward"))
}
// UITextInput: the document, by UTF-16 offsets.
private func pos(_ i: Int) -> Position { Position(max(0, min(i, length))) }
var selectedTextRange: UITextRange? {
get { Range(pos(selStart), pos(selEnd)) }
set {
guard let r = newValue as? Range, r.lo.i != selStart || r.hi.i != selEnd else { return }
edit(Event.textSelect(id: id, start: r.lo.i, end: r.hi.i))
}
}
var markedTextRange: UITextRange? { markStart < 0 ? nil : Range(pos(markStart), pos(markEnd)) }
var markedTextStyle: [NSAttributedString.Key: Any]?
func setMarkedText(_ s: String?, selectedRange: NSRange) {
let m = s ?? ""
edit(Event.textMark(id: id, hasRange: false, start: 0, end: 0, text: m, selStart: selectedRange.location,
selEnd: selectedRange.location + selectedRange.length))
}
func unmarkText() { edit(Event.textUnmark(id: id)) }
var beginningOfDocument: UITextPosition { pos(0) }
var endOfDocument: UITextPosition { pos(length) }
func text(in range: UITextRange) -> String? {
guard let r = range as? Range else { return nil }
let lo = r.lo.i - base, hi = r.hi.i - base
if lo >= 0 && hi <= text.count {
return String(decoding: text[lo..<hi], as: UTF16.self)
}
return Go.answer(Event.textRange(id: id, start: r.lo.i, end: r.hi.i)) { TextRangeReply(&$0).text }
}
func replace(_ range: UITextRange, withText s: String) {
guard let r = range as? Range else { return }
edit(Event.textReplace(id: id, hasRange: true, start: r.lo.i, end: r.hi.i, text: s))
}
func textRange(from: UITextPosition, to: UITextPosition) -> UITextRange? {
guard let a = from as? Position, let b = to as? Position else { return nil }
return Range(a, b)
}
func position(from p: UITextPosition, offset: Int) -> UITextPosition? {
guard let p = p as? Position else { return nil }
let i = p.i + offset
return i < 0 || i > length ? nil : pos(i)
}
func position(from p: UITextPosition, in direction: UITextLayoutDirection, offset: Int) -> UITextPosition? {
guard let p = p as? Position else { return nil }
switch direction {
case .left: return position(from: p, offset: -offset)
case .right: return position(from: p, offset: offset)
default:
// A line up or down from the caret's place.
let r = rect(p.i, p.i)
let step = max(r.height, 1) * CGFloat(offset) * (direction == .up ? -1 : 1)
return closestPosition(to: CGPoint(x: r.midX, y: r.midY + step))
}
}
func compare(_ a: UITextPosition, to b: UITextPosition) -> ComparisonResult {
let x = (a as? Position)?.i ?? 0, y = (b as? Position)?.i ?? 0
return x < y ? .orderedAscending : x > y ? .orderedDescending : .orderedSame
}
func offset(from: UITextPosition, to: UITextPosition) -> Int {
((to as? Position)?.i ?? 0) - ((from as? Position)?.i ?? 0)
}
weak var inputDelegate: UITextInputDelegate?
lazy var tokenizer: UITextInputTokenizer = UITextInputStringTokenizer(textInput: self)
func position(within range: UITextRange, farthestIn direction: UITextLayoutDirection) -> UITextPosition? {
guard let r = range as? Range else { return nil }
return direction == .left || direction == .up ? r.lo : r.hi
}
func characterRange(byExtending p: UITextPosition, in direction: UITextLayoutDirection) -> UITextRange? {
guard let p = p as? Position else { return nil }
return direction == .left || direction == .up ? Range(pos(0), p) : Range(p, pos(length))
}
func baseWritingDirection(for p: UITextPosition, in d: UITextStorageDirection) -> NSWritingDirection { .natural }
func setBaseWritingDirection(_ d: NSWritingDirection, for r: UITextRange) {}
/// Where the range's first line is, the caret if Go does not tell.
private func rect(_ start: Int, _ end: Int) -> CGRect {
guard hasDocument, let b = Go.answer(Event.textBounds(id: id, start: start, end: end), { TextBoundsReply(&$0) }), b.ok else { return caret }
return CGRect(x: b.x, y: b.y, width: b.width, height: max(b.height, 1))
}
func firstRect(for range: UITextRange) -> CGRect {
guard let r = range as? Range else { return caret }
return rect(r.lo.i, r.hi.i)
}
func caretRect(for p: UITextPosition) -> CGRect {
guard let p = p as? Position else { return caret }
var r = rect(p.i, p.i)
r.size.width = max(r.width, 2)
return r
}
func selectionRects(for range: UITextRange) -> [UITextSelectionRect] {
guard let r = range as? Range else { return [] }
var out: [SelectionRect] = []
var at = r.lo.i
while at < r.hi.i || out.isEmpty {
guard hasDocument, let b = Go.answer(Event.textBounds(id: id, start: at, end: r.hi.i), { TextBoundsReply(&$0) }), b.ok else { break }
out.append(SelectionRect(CGRect(x: b.x, y: b.y, width: b.width, height: b.height)))
if b.end <= at { break }
at = b.end
}
out.first?.starts = true
out.last?.ends = true
return out
}
func closestPosition(to point: CGPoint) -> UITextPosition? {
guard hasDocument, let r = Go.answer(Event.textIndexAt(id: id, x: Double(point.x), y: Double(point.y)), { TextIndexAtReply(&$0) }), r.ok else { return pos(selEnd) }
return pos(r.index)
}
func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? {
guard let r = range as? Range, let p = closestPosition(to: point) as? Position else { return nil }
return pos(max(r.lo.i, min(p.i, r.hi.i)))
}
func characterRange(at point: CGPoint) -> UITextRange? {
guard let p = closestPosition(to: point) as? Position else { return nil }
return Range(p, pos(p.i + 1))
}
// VoiceOver.
func accessibilityChanged(focus: Int) {
elements = nil
let target = focus != 0 ? accessibilityElements?.first(where: { ($0 as? AccessElement)?.node == focus }) : nil
UIAccessibility.post(notification: .layoutChanged, argument: target)
}
override var isAccessibilityElement: Bool {
get { false }
set {}
}
override var accessibilityElements: [Any]? {
get {
if let e = elements { return e }
guard let nodes = Go.answer(Event.accessibilityTree(id: id), { AccessibilityTreeReply(&$0).nodes }) else { return [] }
elements = AccessElement.decode(nodes, in: self)
return elements
}
set {}
}
// VoiceOver's two-finger scrub goes back, as Android's back does.
override func accessibilityPerformEscape() -> Bool {
Go.answer(Event.backPressed(id: id)) { BackPressedReply(&$0).handled } ?? false
}
func accessAction(_ node: Int, _ action: String) -> Bool {
Go.answer(Event.accessibilityAction(id: id, node: node, action: action)) { AccessibilityActionReply(&$0).handled } ?? false
}
// The system's edit menu: UIEditMenuInteraction asks this view, the first
// responder, what it can do, and calls it.
private var menuActions: [String] = []
private lazy var editMenu: UIEditMenuInteraction = {
let i = UIEditMenuInteraction(delegate: nil)
addInteraction(i)
return i
}()
func showMenu(_ c: ShowMenuCall) {
menuActions = c.actions
if !isFirstResponder { becomeFirstResponder() }
let cfg = UIEditMenuConfiguration(identifier: nil, sourcePoint: CGPoint(x: c.x, y: c.y))
cfg.preferredArrowDirection = .down
editMenu.presentEditMenu(with: cfg)
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
switch action {
case #selector(UIResponderStandardEditActions.cut(_:)): return menuActions.contains("cut")
case #selector(UIResponderStandardEditActions.copy(_:)): return menuActions.contains("copy")
case #selector(UIResponderStandardEditActions.paste(_:)): return menuActions.contains("paste")
case #selector(UIResponderStandardEditActions.selectAll(_:)): return menuActions.contains("selectAll")
default: return false
}
}
override func cut(_ sender: Any?) { edit(Event.textCommand(id: id, command: "cut")) }
override func copy(_ sender: Any?) { edit(Event.textCommand(id: id, command: "copy")) }
override func paste(_ sender: Any?) { edit(Event.textCommand(id: id, command: "paste")) }
override func selectAll(_ sender: Any?) { edit(Event.textCommand(id: id, command: "selectAll")) }
// The system's magnifier, while a finger drags a handle.
private var loupe: UITextLoupeSession?
func showMagnifier(_ c: ShowMagnifierCall) {
let at = CGPoint(x: c.x, y: c.y)
if let l = loupe {
l.move(to: at, withCaretRect: caret, trackingCaret: true)
} else {
loupe = UITextLoupeSession.begin(at: at, fromSelectionWidgetView: nil, in: self)
}
}
func hideMagnifier() {
loupe?.invalidate()
loupe = nil
}
}
/// A position in the text being edited, in characters.
private final class Position: UITextPosition {
let i: Int
init(_ i: Int) { self.i = i }
}
private final class Range: UITextRange {
let lo: Position, hi: Position
init(_ a: Position, _ b: Position) {
lo = a.i <= b.i ? a : b
hi = a.i <= b.i ? b : a
}
override var start: UITextPosition { lo }
override var end: UITextPosition { hi }
override var isEmpty: Bool { lo.i == hi.i }
}
/// A line of a selection, for the system's text interactions.
private final class SelectionRect: UITextSelectionRect {
let box: CGRect
var starts = false, ends = false
init(_ box: CGRect) { self.box = box }
override var rect: CGRect { box }
override var writingDirection: NSWritingDirection { .natural }
override var containsStart: Bool { starts }
override var containsEnd: Bool { ends }
override var isVertical: Bool { false }
}
/// An element of native UI, as VoiceOver reads it.
final class AccessElement: UIAccessibilityElement {
var node = 0
var actions = 0
var box = CGRect.zero
weak var surface: SurfaceWindow?
/// What makes VoiceOver say "text field", which UIKit's text fields have
/// and names no constant for.
private static let textEntry = UIAccessibilityTraits(rawValue: 1 << 18)
// platform.AccessRole and its states, as Go numbers them.
private enum Role: Int {
case group = 0, text, button, link, checkBox, radio, toggle, slider, progress, textField, image
case tab = 18, toggleButton = 31, menuItem = 40, heading = 43
}
static func decode(_ b: [UInt8], in surface: SurfaceWindow) -> [AccessElement] {
var out: [AccessElement] = []
b.withUnsafeBytes { buf in
var r = WireReader(buf)
while r.at < buf.count {
let e = AccessElement(accessibilityContainer: surface)
e.surface = surface
e.node = r.int()
_ = r.int() // the parent: VoiceOver reads the elements in order
let role = r.int()
let label = r.string(), value = r.string(), hint = r.string()
e.box = CGRect(x: r.float(), y: r.float(), width: r.float(), height: r.float())
let states = r.int()
e.actions = r.int()
let level = r.int()
e.accessibilityLabel = label
e.accessibilityValue = value.isEmpty ? nil : value
e.accessibilityHint = hint.isEmpty ? nil : hint
e.accessibilityFrameInContainerSpace = e.box
var traits: UIAccessibilityTraits = []
switch Role(rawValue: role) {
case .button, .toggleButton, .menuItem, .tab, .checkBox, .radio, .toggle: traits.insert(.button)
case .link: traits.insert(.link)
case .slider: traits.insert(.adjustable)
case .image: traits.insert(.image)
case .heading: traits.insert(.header)
case .textField: traits.insert(AccessElement.textEntry)
case .text: traits.insert(.staticText)
default: break
}
if role == Role.text.rawValue || role == Role.heading.rawValue { _ = level }
if states & 2 != 0 { traits.insert(.notEnabled) }
if states & (4 | 16) != 0 { traits.insert(.selected) }
e.accessibilityTraits = traits
// Groups without a name of their own hold others, which
// VoiceOver reads instead.
if role == Role.group.rawValue && label.isEmpty && value.isEmpty { continue }
out.append(e)
}
}
return out
}
override func accessibilityActivate() -> Bool { surface?.accessAction(node, "press") ?? false }
override func accessibilityIncrement() { _ = surface?.accessAction(node, "increment") }
override func accessibilityDecrement() { _ = surface?.accessAction(node, "decrement") }
}
@@ -0,0 +1,288 @@
// Windows showing web pages, in a WKWebView.
import UIKit
import WebKit
final class WebWindow: HostWindow, WKNavigationDelegate, WKUIDelegate {
let webView: WKWebView
private let messages = MessageHandler()
private var observers: [NSKeyValueObservation] = []
/// The load the app started, which the app is not asked about
/// (Navigation.Unasked).
private var appLoad = false
private var pinchZoom = false
var userAgent = ""
init(id: Int, _ c: CreateWindowCall) {
let config = WKWebViewConfiguration()
config.allowsInlineMediaPlayback = true
if c.autoplay { config.mediaTypesRequiringUserActionForPlayback = [] }
if !c.userAgentSuffix.isEmpty { config.applicationNameForUserAgent = c.userAgentSuffix }
for s in Set(c.schemes) where !WKWebView.handlesURLScheme(s) {
config.setURLSchemeHandler(SchemeHandler.shared, forURLScheme: s)
}
config.userContentController.add(messages, name: "mygo")
webView = WKWebView(frame: .zero, configuration: config)
super.init(id: id)
messages.window = self
setScripts(c.scripts, c.scriptFlags)
webView.frame = bounds
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
webView.uiDelegate = self
webView.allowsBackForwardNavigationGestures = c.swipeNavigation
webView.isInspectable = c.inspectable
if !c.userAgent.isEmpty { webView.customUserAgent = c.userAgent }
pinchZoom = c.pinchZoom
addSubview(webView)
observers = [
webView.observe(\.title) { [weak self] _, _ in self?.reportState() },
webView.observe(\.url) { [weak self] _, _ in self?.reportState() },
webView.observe(\.isLoading) { [weak self] _, _ in self?.reportState() },
webView.observe(\.canGoBack) { [weak self] _, _ in self?.reportState() },
webView.observe(\.canGoForward) { [weak self] _, _ in self?.reportState() },
]
webView.evaluateJavaScript("navigator.userAgent") { [weak self] v, _ in self?.userAgent = v as? String ?? "" }
}
required init?(coder: NSCoder) { fatalError() }
func setScripts(_ scripts: [String], _ flags: [String]) {
let ucc = webView.configuration.userContentController
ucc.removeAllUserScripts()
for (i, src) in scripts.enumerated() {
let f = i < flags.count ? flags[i] : ""
ucc.addUserScript(WKUserScript(source: src, injectionTime: f.contains("e") ? .atDocumentEnd : .atDocumentStart,
forMainFrameOnly: !f.contains("a")))
}
}
func load(_ url: String) {
guard let u = URL(string: url) else { return }
appLoad = true
if u.isFileURL {
webView.loadFileURL(u, allowingReadAccessTo: u.deletingLastPathComponent())
} else {
webView.load(URLRequest(url: u))
}
}
func loadHTML(_ html: String, base: String) {
appLoad = true
webView.loadHTMLString(html, baseURL: URL(string: base))
}
override func setBackground(_ color: UIColor) {
super.setBackground(color)
webView.isOpaque = color.cgColor.alpha >= 1
webView.backgroundColor = color
webView.scrollView.backgroundColor = color
webView.underPageBackgroundColor = color
}
override func focus() { webView.becomeFirstResponder() }
override func close() {
webView.configuration.userContentController.removeScriptMessageHandler(forName: "mygo")
webView.stopLoading()
observers = []
super.close()
}
private func reportState() {
Go.send(Event.pageState(id: id, url: webView.url?.absoluteString ?? "", title: webView.title ?? "",
loading: webView.isLoading, canGoBack: webView.canGoBack, canGoForward: webView.canGoForward))
}
// WKNavigationDelegate
func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let url = action.request.url
let main = action.targetFrame?.isMainFrame ?? true
// Links of schemes no web view loads (mailto:, tel:, other apps')
// go to the app the system has for them.
if let url, let scheme = url.scheme?.lowercased(), !WKWebView.handlesURLScheme(scheme),
webView.configuration.urlSchemeHandler(forURLScheme: scheme) == nil, scheme != "about", scheme != "blob", scheme != "data" {
decisionHandler(.cancel)
UIApplication.shared.open(url)
return
}
let kind = action.navigationType
var unasked = kind == .backForward || kind == .reload
if main && appLoad && kind == .other {
appLoad = false
unasked = true
}
let user = kind == .linkActivated || kind == .formSubmitted
let allow = Go.answer(Event.willNavigate(id: id, url: url?.absoluteString ?? "", mainFrame: main, userInitiated: user,
unasked: unasked, reload: kind == .reload && main)) { WillNavigateReply(&$0).allow } ?? true
decisionHandler(allow ? .allow : .cancel)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
Go.send(Event.navigationStarted(id: id, url: webView.url?.absoluteString ?? ""))
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
if !pinchZoom { webView.scrollView.pinchGestureRecognizer?.isEnabled = false }
Go.send(Event.navigationCommitted(id: id, url: webView.url?.absoluteString ?? ""))
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
Go.send(Event.loadFinished(id: id))
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { failed(error) }
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { failed(error) }
private func failed(_ error: Error) {
let e = error as NSError
if e.domain == NSURLErrorDomain && e.code == NSURLErrorCancelled { return }
let url = (e.userInfo[NSURLErrorFailingURLStringErrorKey] as? String) ?? webView.url?.absoluteString ?? ""
Go.send(Event.loadFailed(id: id, url: url, code: e.code, description: e.localizedDescription))
}
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
Go.send(Event.processGone(id: id, reason: "crashed"))
}
// WKUIDelegate
func webView(_ webView: WKWebView, createWebViewWith config: WKWebViewConfiguration, for action: WKNavigationAction,
windowFeatures: WKWindowFeatures) -> WKWebView? {
let url = action.request.url?.absoluteString ?? ""
let handled = Go.answer(Event.newWindow(id: id, url: url, userInitiated: action.navigationType == .linkActivated)) {
NewWindowReply(&$0).handled
} ?? false
if !handled, action.navigationType == .linkActivated, let u = action.request.url {
UIApplication.shared.open(u)
}
return nil
}
func webViewDidClose(_ webView: WKWebView) { Go.send(Event.closedByPage(id: id)) }
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping () -> Void) {
let a = UIAlertController(title: nil, message: message, preferredStyle: .alert)
a.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { _ in completionHandler() })
Host.shared.present(a)
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping (Bool) -> Void) {
let a = UIAlertController(title: nil, message: message, preferredStyle: .alert)
a.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel) { _ in completionHandler(false) })
a.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { _ in completionHandler(true) })
Host.shared.present(a)
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?,
initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let a = UIAlertController(title: nil, message: prompt, preferredStyle: .alert)
a.addTextField { $0.text = defaultText }
a.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel) { _ in completionHandler(nil) })
a.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { _ in
completionHandler(a.textFields?.first?.text ?? "")
})
Host.shared.present(a)
}
func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin, initiatedByFrame frame: WKFrameInfo,
type: WKMediaCaptureType, decisionHandler: @escaping (WKPermissionDecision) -> Void) {
var kinds: [String] = []
switch type {
case .camera: kinds = ["camera"]
case .microphone: kinds = ["microphone"]
default: kinds = ["camera", "microphone"]
}
let o = "\(origin.protocol)://\(origin.host)" + (origin.port != 0 ? ":\(origin.port)" : "")
let allow = Go.answer(Event.permissionRequested(id: id, kinds: kinds, origin: o)) { PermissionRequestedReply(&$0).allow } ?? false
decisionHandler(allow ? .grant : .deny)
}
fileprivate func message(_ text: String) { Go.send(Event.message(id: id, text: text)) }
}
/// The handler of the bridge's messages, apart from the window, which
/// WebKit's user content controller keeps.
private final class MessageHandler: NSObject, WKScriptMessageHandler {
weak var window: WebWindow?
func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) {
guard message.frameInfo.isMainFrame, let text = message.body as? String else { return }
window?.message(text)
}
}
/// The handler of the app's schemes: their requests go to Go, which
/// answers them with SchemeRespond, SchemeData and SchemeFinish.
final class SchemeHandler: NSObject, WKURLSchemeHandler {
static let shared = SchemeHandler()
private static var tasks: [Int: WKURLSchemeTask] = [:]
private static var urls: [Int: URL] = [:]
private static var next = 0
func webView(_ webView: WKWebView, start task: WKURLSchemeTask) {
SchemeHandler.next += 1
let req = SchemeHandler.next
SchemeHandler.tasks[req] = task
SchemeHandler.urls[req] = task.request.url
let window = Host.shared.windows.values.first { ($0 as? WebWindow)?.webView === webView }
var header: [String] = []
for (k, v) in task.request.allHTTPHeaderFields ?? [:] { header += [k, v] }
var body: [UInt8] = []
var hasBody = false
if let data = task.request.httpBody {
body = Array(data)
hasBody = true
} else if let stream = task.request.httpBodyStream {
stream.open()
var buf = [UInt8](repeating: 0, count: 65536)
while stream.hasBytesAvailable {
let n = stream.read(&buf, maxLength: buf.count)
if n <= 0 { break }
body += buf[0..<n]
}
stream.close()
hasBody = true
}
Go.send(Event.schemeRequest(id: window?.id ?? 0, req: req, method: task.request.httpMethod ?? "GET",
url: task.request.url?.absoluteString ?? "", header: header, body: body, hasBody: hasBody))
}
func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {
guard let req = SchemeHandler.tasks.first(where: { $0.value === task })?.key else { return }
SchemeHandler.tasks[req] = nil
SchemeHandler.urls[req] = nil
Go.send(Event.schemeCancel(req: req))
}
static func respond(_ c: SchemeRespondCall) {
guard let task = tasks[c.req], let url = urls[c.req] else { return }
var fields: [String: String] = [:]
var i = 0
while i + 1 < c.header.count {
let k = c.header[i], v = c.header[i + 1]
fields[k] = fields[k].map { $0 + ", " + v } ?? v
i += 2
}
if let r = HTTPURLResponse(url: url, statusCode: c.status, httpVersion: "HTTP/1.1", headerFields: fields) {
task.didReceive(r)
}
}
static func data(_ c: SchemeDataCall) { tasks[c.req]?.didReceive(Data(c.data)) }
static func finish(_ req: Int) {
tasks.removeValue(forKey: req)?.didFinish()
urls[req] = nil
}
static func fail(_ req: Int, _ message: String) {
tasks.removeValue(forKey: req)?.didFailWithError(NSError(domain: "mygo", code: 1, userInfo: [NSLocalizedDescriptionKey: message]))
urls[req] = nil
}
}
File diff suppressed because it is too large. Load diff