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,65 @@
// The shell app around a MyGo app. mygo build passes the app's ID, name,
// version, signing key, its Go library for each ABI, its manifest and its
// resources.
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
fun prop(name: String) = providers.gradleProperty(name).orNull
android {
namespace = "dev.mygo.app"
compileSdk = 36
defaultConfig {
applicationId = prop("mygoApplicationId") ?: "dev.mygo.app"
minSdk = (prop("mygoMinSdk") ?: "26").toInt()
targetSdk = 36
versionCode = (prop("mygoVersionCode") ?: "1").toInt()
versionName = prop("mygoVersionName") ?: "1.0"
manifestPlaceholders["mygoAppName"] = prop("mygoAppName") ?: "MyGo"
manifestPlaceholders["mygoIcon"] = prop("mygoIcon") ?: "@android:drawable/sym_def_app_icon"
}
signingConfigs {
create("release") {
prop("mygoKeystore")?.let {
storeFile = file(it)
storePassword = prop("mygoKeystorePassword")
keyAlias = prop("mygoKeyAlias")
keyPassword = prop("mygoKeyPassword") ?: prop("mygoKeystorePassword")
}
}
}
buildTypes {
release {
isMinifyEnabled = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"))
// Go's libraries are stripped; its stack traces need no symbols.
ndk { debugSymbolLevel = "NONE" }
signingConfig = if (prop("mygoKeystore") != null) signingConfigs.getByName("release") else signingConfigs.getByName("debug")
}
}
sourceSets {
getByName("main") {
prop("mygoJniLibs")?.let { jniLibs.srcDir(it) }
prop("mygoAssets")?.let { assets.srcDir(it) }
prop("mygoRes")?.let { res.srcDir(it) }
prop("mygoManifest")?.let { manifest.srcFile(it) }
}
}
packaging { jniLibs { useLegacyPackaging = false } }
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
kotlin { jvmToolchain(17) }
dependencies {
implementation(project(":mygo"))
// The app's native modules' Kotlin (settings.gradle.kts).
providers.gradleProperty("mygoNativeModules").orNull?.split(',')?.filter { it.isNotEmpty() }?.forEach {
implementation(project(":" + it.substringBefore('|')))
}
}
@@ -0,0 +1,23 @@
<!-- The manifest of an app without mygo build's: mygo build writes one
from the app's configuration (permissions, URL schemes). -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="${mygoAppName}"
android:icon="${mygoIcon}"
android:supportsRtl="true"
android:enableOnBackInvokedCallback="true"
android:theme="@style/Theme.MyGo">
<activity
android:name="dev.mygo.MyGoActivity"
android:exported="true"
android:launchMode="singleTask"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|fontScale|density|locale|layoutDirection"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,11 @@
<resources>
<!-- The system's own look, light or dark with the system's setting,
drawn edge to edge: the app's content goes under the bars, and
the insets tell where they are. -->
<style name="Theme.MyGo" parent="@android:style/Theme.DeviceDefault.DayNight">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/transparent</item>
</style>
</resources>
@@ -0,0 +1,49 @@
plugins {
id("com.android.application") version "8.12.0" apply false
id("com.android.library") version "8.12.0" apply false
id("org.jetbrains.kotlin.android") version "2.1.20" apply false
}
// The native modules' libraries: their build sets only their namespace and
// dependencies, and this the rest, as the host's own. They build here, as
// a module in Go's module cache is read-only.
val nativeModules = providers.gradleProperty("mygoNativeModules").orNull?.split(',')?.filter { it.isNotEmpty() }?.associate {
val parts = it.split('|')
parts[0] to parts.getOrElse(2) { "" }.split(' ').filter { d -> d.isNotEmpty() }
} ?: emptyMap()
subprojects {
val uses = nativeModules[name] ?: return@subprojects
layout.buildDirectory.set(rootProject.layout.buildDirectory.dir("native/$name"))
plugins.withId("com.android.library") {
extensions.configure<com.android.build.gradle.LibraryExtension> {
compileSdk = 36
defaultConfig {
minSdk = (providers.gradleProperty("mygoMinSdk").orNull ?: "26").toInt()
// C, which a module builds with externalNativeBuild, builds
// for the ABIs that Go does, with the NDK that builds Go.
providers.gradleProperty("mygoAbis").orNull?.let { ndk { abiFilters += it.split(',').filter { a -> a.isNotEmpty() } } }
}
providers.gradleProperty("mygoNdk").orNull?.let { dir ->
ndkPath = dir
ndkVersion = file("$dir/source.properties").readLines().firstNotNullOfOrNull {
it.substringAfter("Pkg.Revision", "").trimStart(' ', '=').takeIf { v -> v.isNotEmpty() }
} ?: ndkVersion
}
externalNativeBuild {
cmake { buildStagingDirectory = rootProject.layout.buildDirectory.dir("native/$name/cxx").get().asFile }
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
dependencies {
add("implementation", project(":mygo"))
uses.forEach { add("implementation", project(":$it")) }
}
}
plugins.withId("org.jetbrains.kotlin.android") {
extensions.configure<org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension> { jvmToolchain(17) }
}
}
+12
View File
@@ -0,0 +1,12 @@
// Package android holds the Android host, Kotlin and Android's views in a
// Gradle project, which mygo build writes out and builds with the app's
// Go code as a shared library. See internal/mobile for how the two work
// together.
package android
import "embed"
// Files are the host's Gradle project.
//
//go:embed settings.gradle.kts build.gradle.kts gradle.properties gradlew gradle app mygo
var Files embed.FS
@@ -0,0 +1,5 @@
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
org.gradle.caching=true
android.useAndroidX=true
android.nonTransitiveRClass=true
kotlin.code.style=official
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
@@ -0,0 +1,30 @@
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "dev.mygo"
compileSdk = 36
defaultConfig {
minSdk = (providers.gradleProperty("mygoMinSdk").orNull ?: "26").toInt()
consumerProguardFiles("consumer-rules.pro")
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
kotlin { jvmToolchain(17) }
dependencies {
implementation("androidx.core:core-ktx:1.16.0")
implementation("androidx.activity:activity:1.10.1") // back, edge to edge
implementation("androidx.webkit:webkit:1.14.0") // the web view's document-start scripts
implementation("com.google.android.material:material:1.13.0") // bottom navigation, toolbars
// Native modules' Kotlin: suspend funs and Flows.
api("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
// What the app's plugins bring (mygo-plugin.json).
providers.gradleProperty("mygoPluginDependencies").orNull?.split(',')?.filter { it.isNotEmpty() }?.forEach { implementation(it) }
}
@@ -0,0 +1,7 @@
# JNI reaches these by name.
-keep class dev.mygo.Host { *; }
-keep class dev.mygo.MyGoNative { *; }
-keep class dev.mygo.Native { *; }
# Go loads a native module's Kotlin by its generated object's class.
-keep class * extends dev.mygo.NativeModule { public static ** INSTANCE; }
-keepclassmembers class * { @android.webkit.JavascriptInterface <methods>; }
@@ -0,0 +1,14 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- The files the app shares (Shell.OpenPath). -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.mygo.files"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/mygo_file_paths" />
</provider>
</application>
</manifest>
@@ -0,0 +1,62 @@
// The way between Go and the host. Go runs on a thread of its own and
// makes its calls (HostCalls) on the UI thread, through Host.call; events
// go to Go through MyGoNative.event.
package dev.mygo
import android.os.Looper
import android.view.Surface
/**
* A new library of the app's Go code, which mygo dev pushed to a debuggable app
* instead of building and installing it again.
*/
object DevLibrary {
var path: String? = null
fun find(c: android.content.Context) {
if (c.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE == 0) return
val f = java.io.File(c.filesDir, "mygo-dev/libmygoapp.so")
if (f.exists()) path = f.absolutePath
}
}
/** The Go library's native methods (jni_android.c in internal/mobile). */
object MyGoNative {
init {
val dev = DevLibrary.path
if (dev != null) System.load(dev) else System.loadLibrary("mygoapp")
}
/** Starts Go's main function on a thread of its own. UI thread, once. */
@JvmStatic external fun start()
/** Sends an encoded event; for an event Go answers, waits for the answer. */
@JvmStatic external fun event(msg: ByteArray, onUI: Boolean): ByteArray?
/** Runs the calls Go made. UI thread. */
@JvmStatic external fun drain()
/** The ANativeWindow of a surface, which Go draws into; 0 for none. */
@JvmStatic external fun nativeWindow(surface: Surface): Long
@JvmStatic external fun releaseNativeWindow(window: Long)
}
/** What JNI calls of the host: Go's calls, on the UI thread. */
object Host {
@JvmStatic
fun call(msg: ByteArray): ByteArray? = dispatchCall(HostImpl, msg)
}
object Go {
private fun onUI() = Looper.myLooper() == Looper.getMainLooper()
/** Sends an event Go does not answer. */
fun send(msg: ByteArray) {
MyGoNative.event(msg, onUI())
}
/** Sends an event and returns Go's answer, null when Go gives none. */
fun ask(msg: ByteArray): WireReader? = MyGoNative.event(msg, onUI())?.let { WireReader(it) }
}
@@ -0,0 +1,895 @@
// The calls Go makes of the host (HostCalls), on the UI thread.
package dev.mygo
import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.UiModeManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.MutableContextWrapper
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.BatteryManager
import android.os.Build
import android.os.PowerManager
import android.provider.OpenableColumns
import android.provider.Settings
import android.system.Os
import android.text.format.DateFormat
import android.util.Log
import android.view.HapticFeedbackConstants
import android.view.View
import android.view.WindowManager
import android.webkit.MimeTypeMap
import android.widget.FrameLayout
import androidx.core.content.FileProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.WindowInsetsCompat
import java.io.File
import java.util.Calendar
import java.util.Locale
object HostImpl : HostCalls {
/** The Activity showing the app, null while none does. */
var activity: Activity? = null
private set
lateinit var app: Context
private set
/** The context of the views, which follows the Activity. */
private lateinit var context: MutableContextWrapper
lateinit var root: FrameLayout
private set
val windows = HashMap<Long, HostWindow>()
private var started = false
/** Whether Android made the Activity again after ending the process. */
var restoring = false
// What covers the screen's edges, in pixels: the system's bars and
// the cutout, and the keyboard.
var bars = androidx.core.graphics.Insets.NONE
private set
var ime = androidx.core.graphics.Insets.NONE
private set
private const val ASK_NOTIFICATIONS = 0x6d7a
private var pendingNotes = ArrayList<NotifyCall>()
/** Readies what outlives Activities, from the first thing to start the process. */
private fun prepare(c: Context) {
if (::app.isInitialized) return
run {
app = c.applicationContext
context = MutableContextWrapper(c)
root = FrameLayout(context)
ViewCompat.setOnApplyWindowInsetsListener(root) { _, insets ->
bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout())
ime = insets.getInsets(WindowInsetsCompat.Type.ime())
Navigation.insetsChanged()
insets
}
root.addOnLayoutChangeListener { _, l, t, r, b, ol, ot, or, ob ->
if (r - l != or - ol || b - t != ob - ot) for (w in windows.values) w.reportSize()
}
}
}
fun attach(a: Activity) {
activity = a
prepare(a)
context.baseContext = a
(root.parent as? android.view.ViewGroup)?.removeView(root)
root.setBackgroundColor(themeColor(android.R.attr.colorBackground))
a.setContentView(root)
ViewCompat.requestApplyInsets(root)
}
fun detach(a: Activity) {
if (activity === a) activity = null
}
/** Starts Go with no window to show, for what runs in the background. */
fun startHeadless(c: Context) {
if (started) return
DevLibrary.find(c)
prepare(c)
startGo(c, null)
}
/** Starts Go once per process, with the environment a launch passes (mygo dev). */
fun startGo(a: Context, intent: Intent?) {
if (started) return
started = true
val files = a.filesDir.absolutePath
val cache = a.cacheDir.absolutePath
// Android sets none of these, which os.UserHomeDir, UserConfigDir,
// UserCacheDir and TempDir read.
app.registerReceiver(object : android.content.BroadcastReceiver() {
override fun onReceive(c: Context, i: Intent) {
// As the system's zone changes, the default of Java keeps the old one.
java.util.TimeZone.setDefault(null)
Go.send(Event.timeZoneChanged(java.util.TimeZone.getDefault().id))
}
}, android.content.IntentFilter(Intent.ACTION_TIMEZONE_CHANGED))
Os.setenv("HOME", files, true)
Os.setenv("XDG_CONFIG_HOME", files, true)
Os.setenv("XDG_CACHE_HOME", cache, true)
Os.setenv("TMPDIR", cache, true)
// Only mygo dev's, in a debug build: the Activity is exported, and any
// app could otherwise set a proxy for this one's traffic.
val debuggable = a.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0
if (debuggable) {
intent?.getStringExtra("mygo.env")?.split('\n')?.forEach { line ->
val i = line.indexOf('=')
if (i > 0) Os.setenv(line.substring(0, i), line.substring(i + 1), true)
}
}
registerPlugins()
// The first launch of a version copies the app's resources, which may
// be many: off the UI thread, which Android watches. Events sent
// meanwhile wait for the backend.
val ctx = a.applicationContext
Thread {
val dir = Resources.extract(ctx)
// Not by a view's post: with no Activity, the root is in no window
// and would hold it until one comes.
android.os.Handler(android.os.Looper.getMainLooper()).post {
Os.setenv("MYGO_RESOURCES", dir, true)
MyGoNative.start()
}
}.start()
}
fun themeColor(attr: Int): Int {
val a = (activity ?: context).obtainStyledAttributes(intArrayOf(attr))
val c = a.getColor(0, Color.WHITE)
a.recycle()
return c
}
val density get() = app.resources.displayMetrics.density
/** The window in front: the visible window highest on screen. */
fun front(): HostWindow? = windows.values.filter { it.view.isShown }.maxByOrNull { w ->
var depth = 0
var v: View? = w.view
while (v != null && v !== root) {
val parent = v.parent as? android.view.ViewGroup ?: break
depth = depth * 64 + parent.indexOfChild(v)
v = parent
}
depth
}
/** Hears the system's back, while something in the app takes it. */
var backCallback: androidx.activity.OnBackPressedCallback? = null
/** The system's back goes to the app, or leaves it, as predictive back shows beforehand. */
fun updateBack() {
val f = front()
backCallback?.isEnabled = Navigation.canPop() || (f as? SurfaceWindow)?.backAvailable == true || (f as? WebWindow)?.web?.canGoBack() == true
}
/** Android's back: the window in front's page goes back, or the app takes it. */
fun back(): Boolean {
if (Navigation.back()) return true
val w = front() ?: return false
val r = Go.ask(Event.backPressed(w.id)) ?: return false
return BackPressedReply(r).handled
}
override fun timeZone(): TimeZoneReply {
val r = TimeZoneReply()
r.id = java.util.TimeZone.getDefault().id
return r
}
/** Whether the app has something on screen, which the splash waits for. */
@Volatile var drew = false
override fun firstFrame(c: FirstFrameCall) {
drew = true
}
override fun appInfo(): AppInfoReply {
val r = AppInfoReply()
val pm = app.packageManager
val info = pm.getPackageInfo(app.packageName, 0)
r.name = app.applicationInfo.loadLabel(pm).toString()
r.version = info.versionName ?: ""
r.identifier = app.packageName
r.filesDir = app.filesDir.absolutePath
r.cacheDir = app.cacheDir.absolutePath
r.tempDir = app.cacheDir.absolutePath
r.documentsDir = (app.getExternalFilesDir(null) ?: app.filesDir).absolutePath
r.resourcesDir = Resources.dir(app).absolutePath
val locales = app.resources.configuration.locales
r.languages = (0 until locales.size()).map { locales[it].toLanguageTag() }
val format = Locale.getDefault(Locale.Category.FORMAT)
r.regionLocale = format.toLanguageTag()
r.firstWeekday = (Calendar.getInstance(format).firstDayOfWeek - 1).toLong()
r.hourCycle = if (DateFormat.is24HourFormat(app)) 24L else 12L
r.system = "Android"
r.systemVersion = Build.VERSION.RELEASE
r.model = Build.MODEL
r.restoring = restoring
r.background = activity == null // the system started it for a task
return r
}
override fun theme(): ThemeReply {
val r = ThemeReply()
val c = (activity ?: app).resources.configuration
r.dark = c.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
val accent = if (Build.VERSION.SDK_INT >= 31) app.getColor(android.R.color.system_accent1_600) else themeColor(android.R.attr.colorAccent)
r.accent = argbToRGBA(accent)
r.reduceMotion = Settings.Global.getFloat(app.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f
if (Build.VERSION.SDK_INT >= 34) {
r.increaseContrast = (app.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager).contrast > 0.5f
}
r.textScale = c.fontScale.toDouble()
return r
}
override fun setAppearance(c: SetAppearanceCall) {
if (Build.VERSION.SDK_INT < 31) return
val ui = app.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
ui.setApplicationNightMode(
when (c.source) {
"dark" -> UiModeManager.MODE_NIGHT_YES
"light" -> UiModeManager.MODE_NIGHT_NO
else -> UiModeManager.MODE_NIGHT_AUTO
}
)
}
override fun screen(): ScreenReply {
val r = ScreenReply()
val m = app.resources.displayMetrics
r.width = m.widthPixels / m.density.toDouble()
r.height = m.heightPixels / m.density.toDouble()
r.scale = m.density.toDouble()
return r
}
override fun log(c: LogCall) {
Log.println(if (c.error) Log.ERROR else Log.INFO, "mygo", c.line)
}
// Windows.
override fun createWindow(c: CreateWindowCall): CreateWindowReply {
val r = CreateWindowReply()
try {
val w = when {
c.surface -> SurfaceWindow(context, c.id)
c.viewType.isNotEmpty() -> PluginViewWindow(context, c.id, PluginHost.makeView(c.viewType, context, c.id, c.viewArgs)
?: throw IllegalArgumentException("no view ${c.viewType} in this app"))
else -> WebWindow(context, c)
}
if (c.hasBackground) {
w.fill = rgbaToARGB(c.background)
w.setBackground(w.fill)
}
windows[c.id] = w
if (c.parent != 0L) surface(c.parent)?.hold(w)
} catch (e: Throwable) {
r.error = "mygo: ${e.message ?: e.toString()}"
}
return r
}
override fun placeViews(c: PlaceViewsCall) { surface(c.id)?.placeViews(c.places) }
override fun showWindow(c: ShowWindowCall) {
val w = windows[c.id] ?: return
Navigation.show(w)
w.insetsChanged()
updateBack()
}
override fun hideWindow(c: HideWindowCall) {
val w = windows[c.id] ?: return
Navigation.hide(w)
updateBack()
}
override fun closeWindow(c: CloseWindowCall) {
val w = windows.remove(c.id) ?: return
val holder = w.holder
if (holder != null) {
holder.release(w)
w.close()
return
}
Navigation.hide(w)
Navigation.forget(w)
w.close()
}
override fun setTitle(c: SetTitleCall) { windows[c.id]?.let { Navigation.setTitle(it, c.title) } }
override fun createTabs(c: CreateTabsCall) = Navigation.createTabs(c.id, context)
override fun addTab(c: AddTabCall) { windows[c.window]?.let { Navigation.addTab(c.id, it, c.title, c.icon) } }
override fun showTabs(c: ShowTabsCall) = Navigation.showTabs(c.id)
override fun selectTab(c: SelectTabCall) { Navigation.tabs[c.id]?.select(c.index.toInt()) }
override fun setTabBadge(c: SetTabBadgeCall) = Navigation.setBadge(c.id, c.index.toInt(), c.badge)
override fun closeTabs(c: CloseTabsCall) = Navigation.closeTabs(c.id)
override fun pushWindow(c: PushWindowCall) {
val p = windows[c.parent] ?: return
val w = windows[c.child] ?: return
Navigation.push(w, p, c.title, c.animated)
updateBack()
}
override fun setStack(c: SetStackCall): SetStackReply {
windows[c.id]?.let { Navigation.setStack(it, c.titles) }
return SetStackReply()
}
override fun stackShown(c: StackShownCall) {}
override fun popWindow(c: PopWindowCall) {
windows[c.id]?.let { Navigation.pop(it, c.animated) }
updateBack()
}
override fun setBackground(c: SetBackgroundCall) {
val w = windows[c.id] ?: return
val argb = rgbaToARGB(c.color)
w.fill = argb
w.setBackground(argb)
Navigation.backgroundChanged(w)
}
override fun focus(c: FocusCall) {
windows[c.id]?.view?.requestFocus()
}
// Pages.
private fun web(id: Long) = windows[id] as? WebWindow
override fun loadURL(c: LoadURLCall) { web(c.id)?.load(c.url) }
override fun loadHTML(c: LoadHTMLCall) { web(c.id)?.loadHTML(c.html, c.baseURL) }
override fun reload(c: ReloadCall) {
val w = web(c.id) ?: return
if (c.ignoreCache) w.web.clearCache(false)
w.web.reload()
}
override fun stopLoading(c: StopLoadingCall) { web(c.id)?.web?.stopLoading() }
override fun goBack(c: GoBackCall) { web(c.id)?.web?.goBack() }
override fun goForward(c: GoForwardCall) { web(c.id)?.web?.goForward() }
override fun eval(c: EvalCall) { web(c.id)?.web?.evaluateJavascript(c.js, null) }
override fun callAsync(c: CallAsyncCall) {
val w = web(c.id)
if (w == null) {
Go.send(Event.asyncResult(c.req, "", "mygo: the window is closed"))
return
}
w.callAsync(c.req, c.body)
}
override fun setZoom(c: SetZoomCall) { web(c.id)?.web?.settings?.textZoom = (c.factor * 100).toInt() }
override fun setUserAgent(c: SetUserAgentCall) { web(c.id)?.setUserAgent(c.userAgent) }
override fun setUserScripts(c: SetUserScriptsCall) { web(c.id)?.setScripts(c.scripts, c.scriptFlags) }
override fun capturePage(c: CapturePageCall) {
val w = web(c.id)
if (w == null) {
Go.send(Event.captured(c.req, ByteArray(0), "mygo: the window is closed"))
return
}
w.capture(c.req)
}
override fun userAgent(c: UserAgentCall): UserAgentReply {
val r = UserAgentReply()
r.userAgent = web(c.id)?.web?.settings?.userAgentString ?: ""
return r
}
override fun schemeRespond(c: SchemeRespondCall) = Schemes.respond(c)
override fun schemeData(c: SchemeDataCall) = Schemes.data(c.req, c.data)
override fun schemeFinish(c: SchemeFinishCall) = Schemes.finish(c.req, null)
override fun schemeFail(c: SchemeFailCall) = Schemes.finish(c.req, c.message)
// Dialogs.
override fun messageBox(c: MessageBoxCall) {
val a = activity ?: run {
Go.send(Event.messageBoxResult(c.req, c.cancelID))
return
}
val title = if (c.title.isEmpty()) c.message else c.title
var message = if (c.title.isEmpty()) c.detail else c.message
if (c.title.isNotEmpty() && c.detail.isNotEmpty()) message += "\n\n" + c.detail
var answered = false
fun answer(i: Long) {
if (!answered) {
answered = true
Go.send(Event.messageBoxResult(c.req, i))
}
}
val b = AlertDialog.Builder(a).setTitle(title)
if (message.isNotEmpty()) b.setMessage(message)
// Android's dialogs take three buttons: the default one positive,
// the cancel one negative, another neutral; more make a list.
val buttons = c.buttons
if (buttons.size <= 3) {
val order = buttons.indices.sortedBy { if (it.toLong() == c.defaultID) 0 else if (it.toLong() == c.cancelID) 2 else 1 }
order.forEachIndexed { slot, i ->
val l = { _: android.content.DialogInterface, _: Int -> answer(i.toLong()) }
when {
slot == 0 -> b.setPositiveButton(buttons[i], l)
i.toLong() == c.cancelID || slot == 2 -> b.setNegativeButton(buttons[i], l)
else -> b.setNeutralButton(buttons[i], l)
}
}
} else {
b.setItems(buttons.toTypedArray()) { _, i -> answer(i.toLong()) }
}
b.setOnCancelListener { answer(c.cancelID) }
b.show()
}
override fun openFiles(c: OpenFilesCall) {
val a = activity ?: run {
Go.send(Event.filesResult(c.req, emptyList(), ""))
return
}
val code = nextResultCode()
picks[code] = c.req
val intent = if (c.directories) {
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
} else {
Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
val types = c.extensions.mapNotNull { MimeTypeMap.getSingleton().getMimeTypeFromExtension(it.lowercase()) }.distinct()
type = if (types.size == 1) types[0] else "*/*"
if (types.size > 1) putExtra(Intent.EXTRA_MIME_TYPES, types.toTypedArray())
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, c.multiple)
}
}
@Suppress("DEPRECATION")
a.startActivityForResult(intent, code)
}
fun activityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (PluginHost.activityResult(requestCode, resultCode, data)) return
saves.remove(requestCode)?.let { (req, from) ->
val uri = data?.data
if (resultCode != Activity.RESULT_OK || uri == null) {
Go.send(Event.filesResult(req, emptyList(), ""))
return
}
Thread {
try {
app.contentResolver.openOutputStream(uri)!!.use { out -> File(from).inputStream().use { it.copyTo(out) } }
Go.send(Event.filesResult(req, listOf(uri.toString()), ""))
} catch (e: Exception) {
Go.send(Event.filesResult(req, emptyList(), e.toString()))
}
}.start()
return
}
val req = picks.remove(requestCode)
if (req != null) {
if (resultCode != Activity.RESULT_OK || data == null) {
Go.send(Event.filesResult(req, emptyList(), ""))
return
}
val uris = ArrayList<Uri>()
data.clipData?.let { clip -> for (i in 0 until clip.itemCount) uris.add(clip.getItemAt(i).uri) }
if (uris.isEmpty()) data.data?.let { uris.add(it) }
// Copies the app can read by path: phones give apps no paths
// of other apps' documents.
Thread {
try {
val dir = File(app.cacheDir, "picked/${System.nanoTime()}").apply { mkdirs() }
val paths = uris.map { copyToFile(it, dir).absolutePath }
Go.send(Event.filesResult(req, paths, ""))
} catch (e: Exception) {
Go.send(Event.filesResult(req, emptyList(), e.toString()))
}
}.start()
} else {
WebWindow.activityResult(requestCode, resultCode, data)
}
}
fun copyToFile(uri: Uri, dir: File): File {
var name = "file"
app.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
if (it.moveToFirst()) name = it.getString(0) ?: name
}
val f = File(dir, name.replace('/', '_'))
app.contentResolver.openInputStream(uri)!!.use { input -> f.outputStream().use { input.copyTo(it) } }
return f
}
override fun shareFile(c: ShareFileCall) {
val a = activity ?: return
val f = File(c.path)
val uri = FileProvider.getUriForFile(app, app.packageName + ".mygo.files", f)
val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(f.extension.lowercase()) ?: "application/octet-stream"
val send = Intent(Intent.ACTION_SEND).setType(mime).putExtra(Intent.EXTRA_STREAM, uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
a.startActivity(Intent.createChooser(send, null))
}
// The system.
private val clipboard get() = app.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
override fun clipboardText(): ClipboardTextReply {
val r = ClipboardTextReply()
val clip = clipboard.primaryClip
if (clip != null && clip.itemCount > 0) {
r.text = clip.getItemAt(0).coerceToText(app).toString()
r.ok = true
}
return r
}
override fun setClipboardText(c: SetClipboardTextCall) {
clipboard.setPrimaryClip(ClipData.newPlainText(null, c.text))
}
override fun openURL(c: OpenURLCall): OpenURLReply {
val r = OpenURLReply()
try {
val i = Intent(Intent.ACTION_VIEW, Uri.parse(c.url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
(activity ?: app).startActivity(i)
r.ok = true
} catch (e: Exception) {
r.ok = false
}
return r
}
override fun secretGet(c: SecretGetCall): SecretGetReply = Secrets.get(app, c)
override fun secretSet(c: SecretSetCall): SecretSetReply = Secrets.set(app, c)
override fun secretDelete(c: SecretDeleteCall): SecretDeleteReply = Secrets.delete(app, c)
override fun notify(c: NotifyCall) {
val a = activity
if (Build.VERSION.SDK_INT >= 33 && app.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
if (a == null) {
Go.send(Event.notifyDone(c.req, "mygo: notifications are not allowed"))
return
}
pendingNotes.add(c)
if (pendingNotes.size == 1) a.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), ASK_NOTIFICATIONS)
return
}
post(c)
}
fun permissionsResult(requestCode: Int, results: IntArray) {
if (PluginHost.permissionsResult(requestCode, results)) return
if (requestCode == ASK_NOTIFICATIONS) {
val granted = results.isNotEmpty() && results[0] == PackageManager.PERMISSION_GRANTED
val notes = pendingNotes
pendingNotes = ArrayList()
for (c in notes) if (granted) post(c) else Go.send(Event.notifyDone(c.req, "mygo: notifications are not allowed"))
} else {
WebWindow.permissionsResult(requestCode, results)
}
}
private fun post(c: NotifyCall) {
if (Build.VERSION.SDK_INT < 26) { // NotificationChannel needs API 26
Go.send(Event.notifyDone(c.req, "mygo: notifications need Android 8.0"))
return
}
val nm = app.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = if (c.silent) "mygo.silent" else "mygo"
if (nm.getNotificationChannel(channel) == null) {
val ch = NotificationChannel(channel, appInfo().name, if (c.silent) NotificationManager.IMPORTANCE_LOW else NotificationManager.IMPORTANCE_DEFAULT)
nm.createNotificationChannel(ch)
}
val id = c.notificationID.ifEmpty { System.nanoTime().toString() }
val open = Intent(app, MyGoActivity::class.java).putExtra("mygo.notification", id).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
val pi = PendingIntent.getActivity(app, id.hashCode(), open, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val b = android.app.Notification.Builder(app, channel)
.setSmallIcon(app.applicationInfo.icon)
.setContentTitle(c.title)
.setContentText(c.body)
.setContentIntent(pi)
.setAutoCancel(true)
if (c.subtitle.isNotEmpty()) b.setSubText(c.subtitle)
if (c.group.isNotEmpty()) b.setGroup(c.group)
nm.notify(id, 0, b.build())
Go.send(Event.notifyDone(c.req, ""))
}
override fun removeNotification(c: RemoveNotificationCall) {
(app.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(c.notificationID, 0)
}
override fun removeAllNotifications() {
(app.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancelAll()
}
override fun keepAwake(c: KeepAwakeCall) {
val w = activity?.window ?: return
if (c.on) w.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else w.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
// Network and power.
private val connectivity get() = app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private var watchingNetwork = false
private fun networkReply(): NetworkStatusReply {
val r = NetworkStatusReply()
val caps = connectivity.getNetworkCapabilities(connectivity.activeNetwork)
r.online = caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true
r.metered = connectivity.isActiveNetworkMetered
return r
}
override fun networkStatus(): NetworkStatusReply = networkReply()
override fun watchNetwork() {
if (watchingNetwork) return
watchingNetwork = true
val send = {
val r = networkReply()
Go.send(Event.networkChanged(r.online, r.metered))
}
connectivity.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(n: Network) = send()
override fun onLost(n: Network) = send()
override fun onCapabilitiesChanged(n: Network, caps: NetworkCapabilities) = send()
})
}
override fun battery(): BatteryReply {
val r = BatteryReply()
val bm = app.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
r.level = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) / 100.0
r.charging = bm.isCharging
r.lowPower = (app.getSystemService(Context.POWER_SERVICE) as PowerManager).isPowerSaveMode
return r
}
// The system's bars and the screen.
private var barStyle = "auto"
private var barsHidden = false
private var orientationAsked = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
override fun setSystemBars(c: SetSystemBarsCall) {
barStyle = c.style
barsHidden = c.hidden
applyBars()
}
/** Applies what the app asked of the system's bars, to the Activity showing it. */
fun applyBars() {
val a = activity ?: return
val ctl = WindowCompat.getInsetsController(a.window, a.window.decorView)
val darkMode = a.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
val darkIcons = when (barStyle) {
"dark" -> true
"light" -> false
else -> !darkMode
}
ctl.isAppearanceLightStatusBars = darkIcons
ctl.isAppearanceLightNavigationBars = darkIcons
ctl.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
if (barsHidden) ctl.hide(WindowInsetsCompat.Type.systemBars()) else ctl.show(WindowInsetsCompat.Type.systemBars())
a.requestedOrientation = orientationAsked
}
override fun setOrientations(c: SetOrientationsCall) {
val m = c.mask.toInt()
val portrait = m and 3 != 0
val landscape = m and 12 != 0
orientationAsked = when {
m == 0 -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
portrait && landscape -> ActivityInfo.SCREEN_ORIENTATION_FULL_USER
m == 1 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
m == 2 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
m == 3 -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
m == 4 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
m == 8 -> ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
landscape -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
else -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
}
activity?.requestedOrientation = orientationAsked
}
override fun share(c: ShareCall) {
val a = activity ?: run {
Go.send(Event.shareResult(c.req, "mygo: no window to share from"))
return
}
val text = listOf(c.text, c.url).filter { it.isNotEmpty() }.joinToString("\n")
val uris = ArrayList(c.paths.map { FileProvider.getUriForFile(app, app.packageName + ".mygo.files", File(it)) })
val send = when {
uris.size > 1 -> Intent(Intent.ACTION_SEND_MULTIPLE).setType("*/*").putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
uris.size == 1 -> {
val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(File(c.paths[0]).extension.lowercase()) ?: "application/octet-stream"
Intent(Intent.ACTION_SEND).setType(mime).putExtra(Intent.EXTRA_STREAM, uris[0])
}
else -> Intent(Intent.ACTION_SEND).setType("text/plain")
}
if (uris.isNotEmpty()) {
send.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
send.clipData = ClipData.newRawUri(null, uris[0]).also { d -> uris.drop(1).forEach { d.addItem(ClipData.Item(it)) } }
}
if (text.isNotEmpty()) send.putExtra(Intent.EXTRA_TEXT, text)
try {
a.startActivity(Intent.createChooser(send, null))
Go.send(Event.shareResult(c.req, ""))
} catch (e: Exception) {
Go.send(Event.shareResult(c.req, e.toString()))
}
}
// What the pickers on screen answer, by their request codes: one tapped
// twice opens two, each answering its own.
private val picks = HashMap<Int, Long>()
private val saves = HashMap<Int, Pair<Long, String>>()
private var lastResultCode = 0
private fun nextResultCode(): Int {
lastResultCode = (lastResultCode + 1) and 0xff
return 0x6e00 + lastResultCode
}
override fun saveFile(c: SaveFileCall) {
val a = activity ?: run {
Go.send(Event.filesResult(c.req, emptyList(), "mygo: no window to save from"))
return
}
val code = nextResultCode()
saves[code] = Pair(c.req, c.path)
val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(File(c.name).extension.lowercase()) ?: "application/octet-stream"
val i = Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType(mime).putExtra(Intent.EXTRA_TITLE, c.name)
@Suppress("DEPRECATION")
a.startActivityForResult(i, code)
}
override fun clipboardImage(): ClipboardImageReply {
val r = ClipboardImageReply()
val clip = clipboard.primaryClip ?: return r
if (clip.itemCount == 0) return r
val uri = clip.getItemAt(0).uri ?: return r
val mime = app.contentResolver.getType(uri) ?: return r
if (!mime.startsWith("image/")) return r
try {
val bmp = app.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) } ?: return r
val out = java.io.ByteArrayOutputStream()
bmp.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out)
r.png = out.toByteArray()
} catch (_: Exception) {
}
return r
}
override fun setClipboardImage(c: SetClipboardImageCall) {
try {
val dir = File(app.cacheDir, "clipboard").apply { mkdirs() }
val f = File(dir, "image.png")
f.writeBytes(c.png)
val uri = FileProvider.getUriForFile(app, app.packageName + ".mygo.files", f)
clipboard.setPrimaryClip(ClipData.newUri(app.contentResolver, "image", uri))
} catch (_: Exception) {
}
}
/** A menu shown by the app, as a context menu, at a point of the window. */
override fun popupMenu(c: PopupMenuCall) {
val w = surface(c.id)
val a = activity
val host = w?.view ?: front()?.view
if (a == null || host == null) {
Go.send(Event.menuPicked(c.req, 0))
return
}
// Where it shows: a view at the point, gone as the menu goes.
val anchor = View(a)
val d = density
val lp = FrameLayout.LayoutParams(1, 1)
lp.leftMargin = (c.x * d).toInt()
lp.topMargin = (c.y * d).toInt()
root.addView(anchor, lp)
val menu = android.widget.PopupMenu(a, anchor)
val r = WireReader(c.items)
var group = 0
var order = 0
while (!r.done()) {
val id = r.int()
val label = r.string()
val enabled = r.bool()
val checked = r.bool()
if (id == 0L) {
group++
continue
}
val item = menu.menu.add(group, id.toInt(), order++, label)
item.isEnabled = enabled
if (checked) {
item.isCheckable = true
item.isChecked = true
}
}
var picked = 0L
menu.setOnMenuItemClickListener {
picked = it.itemId.toLong()
true
}
menu.setOnDismissListener {
root.removeView(anchor)
Go.send(Event.menuPicked(c.req, picked))
}
root.post { menu.show() }
}
override fun setBarItems(c: SetBarItemsCall) {
windows[c.id]?.let { Navigation.setBarItems(it, c) }
}
override fun pluginCall(c: PluginCallCall) = PluginHost.call(c)
// Sound, called on the audio's thread.
override fun audioOpen(c: AudioOpenCall): AudioOpenReply = Sound.open(c)
override fun audioWrite(c: AudioWriteCall): AudioWriteReply = Sound.write(c)
override fun audioClose(): AudioCloseReply {
Sound.close()
return AudioCloseReply()
}
override fun haptic(c: HapticCall) {
val v: View = front()?.view ?: root
val k = when (c.kind) {
"selection" -> HapticFeedbackConstants.CLOCK_TICK
"light" -> HapticFeedbackConstants.KEYBOARD_TAP
"heavy" -> HapticFeedbackConstants.LONG_PRESS
"medium" -> HapticFeedbackConstants.CONTEXT_CLICK
"success" -> if (Build.VERSION.SDK_INT >= 30) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.VIRTUAL_KEY
"warning", "error" -> if (Build.VERSION.SDK_INT >= 30) HapticFeedbackConstants.REJECT else HapticFeedbackConstants.LONG_PRESS
else -> HapticFeedbackConstants.VIRTUAL_KEY
}
v.performHapticFeedback(k)
}
// Native UI.
private fun surface(id: Long) = windows[id] as? SurfaceWindow
override fun requestFrame(c: RequestFrameCall) { surface(c.id)?.requestFrame() }
override fun setTextInput(c: SetTextInputCall) { surface(c.id)?.setTextInput(c) }
override fun setCursor(c: SetCursorCall) { surface(c.id)?.setCursor(c.cursor) }
override fun accessibilityChanged(c: AccessibilityChangedCall) { surface(c.id)?.accessibilityChanged(c.focus) }
override fun announce(c: AnnounceCall) { (front()?.view ?: root).announceForAccessibility(c.text) }
override fun showMenu(c: ShowMenuCall) { surface(c.id)?.showMenu(c) }
override fun setBackAvailable(c: SetBackAvailableCall) {
surface(c.id)?.backAvailable = c.on
updateBack()
}
override fun showMagnifier(c: ShowMagnifierCall) { surface(c.id)?.showMagnifier(c) }
override fun hideMagnifier(c: HideMagnifierCall) { surface(c.id)?.hideMagnifier() }
override fun textMetrics(c: TextMetricsCall): TextMetricsReply = Text.metrics(c)
override fun measureText(c: MeasureTextCall): MeasureTextReply = Text.measure(c)
override fun textAdvances(c: TextAdvancesCall): TextAdvancesReply = Text.advances(c)
override fun drawText(c: DrawTextCall): DrawTextReply = Text.draw(c)
override fun registerFont(c: RegisterFontCall): RegisterFontReply = Text.register(c)
}
/** 0xRRGGBBAA, as Go writes colors, to Android's 0xAARRGGBB. */
fun rgbaToARGB(v: Long): Int = (((v and 0xff) shl 24) or ((v ushr 8) and 0xffffff)).toInt()
fun argbToRGBA(c: Int): Long = ((c.toLong() and 0xffffff) shl 8) or ((c.toLong() ushr 24) and 0xff)
@@ -0,0 +1,66 @@
package dev.mygo
import android.content.Context
import android.view.View
/**
* A window of the app: a view filling the screen, which shows a page or
* native UI.
*/
abstract class HostWindow(val context: Context, val id: Long) {
abstract val view: View
private var last: DoubleArray? = null
/** The color the window's content fills it with, 0 while unknown. */
var fill = 0
/** The surface showing this window under it, as a web view in native UI. */
var holder: SurfaceWindow? = null
/**
* What covers the window, in pixels: the system's bars and the cutout
* where they cover it, wherever it is on the screen (under a toolbar,
* above a bar of tabs), and the keyboard: top, left, bottom, right,
* keyboard.
*/
fun covered(): IntArray {
val root = HostImpl.root
// Where layout puts it, without the translation of a page sliding
// in, which ends where layout put it.
var x = 0
var y = 0
var v: View? = view
while (v != null && v !== root) {
x += v.left
y += v.top
v = v.parent as? View
}
val w = if (view.width > 0) view.width else root.width
val h = if (view.height > 0) view.height else root.height
val bars = HostImpl.bars
val below = root.height - (y + h)
val right = root.width - (x + w)
return intArrayOf(
maxOf(0, bars.top - y), maxOf(0, bars.left - x), maxOf(0, bars.bottom - below), maxOf(0, bars.right - right),
maxOf(0, HostImpl.ime.bottom - below),
)
}
/** Tells Go the window's size and what covers it, when they changed. */
fun reportSize() {
val root = HostImpl.root
if (root.width == 0) return
val d = HostImpl.density.toDouble()
val w = if (view.width > 0) view.width else root.width
val h = if (view.height > 0) view.height else root.height
val c = if (holder != null) IntArray(5) else covered()
val size = doubleArrayOf(w / d, h / d, d, c[0] / d, c[1] / d, c[2] / d, c[3] / d, c[4] / d)
if (last?.contentEquals(size) == true) return
last = size
Go.send(Event.resized(id, size[0], size[1], size[2], size[3], size[4], size[5], size[6], size[7]))
}
/** The insets changed: lays the window out again and tells Go. */
open fun insetsChanged() = reportSize()
abstract fun setBackground(argb: Int)
open fun close() {}
}
@@ -0,0 +1,150 @@
package dev.mygo
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.BackEventCompat
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.core.view.WindowCompat
/**
* The app's one Activity. Go and the app's windows live in the process,
* not the Activity: an Activity Android makes again takes them over.
*/
class MyGoActivity : ComponentActivity() {
private var lastConfig: Configuration? = null
override fun onCreate(savedInstanceState: Bundle?) {
DevLibrary.find(this)
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
lastConfig = Configuration(resources.configuration)
HostImpl.restoring = HostImpl.restoring || savedInstanceState != null
HostImpl.attach(this)
HostImpl.applyBars()
holdSplash()
val back = object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
// Back the app does not take leaves it running, as the
// system's launcher does with apps it goes back from.
if (!HostImpl.back()) moveTaskToBack(true)
}
// Predictive back: the page follows the gesture.
private fun gesture(phase: String, progress: Double) {
(HostImpl.front() as? SurfaceWindow)?.let { Go.send(Event.backGesture(it.id, phase, progress)) }
}
override fun handleOnBackStarted(e: BackEventCompat) = gesture("started", 0.0)
override fun handleOnBackProgressed(e: BackEventCompat) = gesture("progress", e.progress.toDouble())
override fun handleOnBackCancelled() = gesture("cancelled", 0.0)
}
onBackPressedDispatcher.addCallback(this, back)
HostImpl.backCallback = back
HostImpl.updateBack()
HostImpl.startGo(this, intent)
openIntent(intent)
}
/**
* The system's splash stays until the window first draws: holding that back
* until the app has drawn leaves no moment of an empty surface, black on a
* cold start. What shows no first frame goes on after a while.
*/
private fun holdSplash() {
val content = findViewById<android.view.View>(android.R.id.content)
val until = android.os.SystemClock.uptimeMillis() + 4000
content.viewTreeObserver.addOnPreDrawListener(object : android.view.ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
if (!HostImpl.drew && android.os.SystemClock.uptimeMillis() < until) return false
content.viewTreeObserver.removeOnPreDrawListener(this)
return true
}
})
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
openIntent(intent)
}
private fun openIntent(intent: Intent?) {
intent ?: return
PluginHost.onIntent?.invoke(intent)
// A notification tapped: once, as the Activity is made again with
// the same Intent after Android ends the process.
intent.getStringExtra("mygo.notification")?.let {
intent.removeExtra("mygo.notification")
Go.send(Event.notificationClicked(it))
}
val data = intent.data ?: return
if (intent.action == Intent.ACTION_VIEW) Go.send(Event.openURLs(listOf(data.toString())))
}
override fun onResume() {
super.onResume()
Go.ask(Event.background(false))
Go.send(Event.active(true))
}
override fun onPause() {
Go.send(Event.active(false))
super.onPause()
}
override fun onStop() {
Go.ask(Event.background(true))
super.onStop()
}
override fun onConfigurationChanged(c: Configuration) {
super.onConfigurationChanged(c)
val old = lastConfig
lastConfig = Configuration(c)
if (old == null) return
val diff = old.diff(c)
if (diff and (ActivityInfoChanges.UI_MODE or ActivityInfoChanges.FONT_SCALE) != 0) {
HostImpl.applyBars()
Go.send(Event.themeChanged())
}
if (diff and ActivityInfoChanges.LOCALE != 0) Go.send(Event.localeChanged())
}
override fun onLowMemory() {
super.onLowMemory()
Go.send(Event.memoryWarning())
}
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
// Running low, or next to be ended in the background.
@Suppress("DEPRECATION")
if (level == TRIM_MEMORY_RUNNING_LOW || level == TRIM_MEMORY_RUNNING_CRITICAL || level >= TRIM_MEMORY_MODERATE) {
Go.send(Event.memoryWarning())
}
}
override fun onDestroy() {
HostImpl.detach(this)
super.onDestroy()
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
HostImpl.activityResult(requestCode, resultCode, data)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, results: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, results)
HostImpl.permissionsResult(requestCode, results)
}
}
/** ActivityInfo's configuration change bits, as Configuration.diff gives them. */
private object ActivityInfoChanges {
const val LOCALE = android.content.pm.ActivityInfo.CONFIG_LOCALE
const val UI_MODE = android.content.pm.ActivityInfo.CONFIG_UI_MODE
const val FONT_SCALE = android.content.pm.ActivityInfo.CONFIG_FONT_SCALE
}
@@ -0,0 +1,565 @@
// Native modules on Android: Go interfaces implemented in Kotlin (see
// docs/native-modules.md). Go calls the module's generated object
// (MygoModule, a NativeModule) through JNI (internal/mobile's
// jni_android.c), on the calling goroutine's thread, as it calls a Swift
// library's functions elsewhere; the module tells Go what happens later
// through Native.send, the callback every module shares.
//
// Values cross in package native's binary encoding: every integer as 8
// bytes, little-endian, floats as a Double's bits, bools as a byte,
// strings, byte arrays, lists and maps as their count then their contents,
// optionals as a bool then the value, structs as their fields, enums as
// their values.
package dev.mygo
import android.os.Handler
import android.os.Looper
import java.lang.ref.PhantomReference
import java.lang.ref.ReferenceQueue
import java.nio.ByteBuffer
import java.time.Instant
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicLong
import kotlin.coroutines.resume
import kotlin.time.Duration
import kotlin.time.Duration.Companion.nanoseconds
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
// What the implementation uses.
/** What the system lacks, such as an API of a newer Android: Go gets errors.ErrUnsupported. */
class NativeUnsupportedException(message: String = "unsupported") : Exception(message)
/** A call of an object that was closed: Go gets native.ErrClosed. */
class NativeClosedException(message: String = "native: object closed") : Exception(message)
/** An error a Go function or method returned. */
class NativeGoException(message: String) : Exception(message)
/**
* An error of a domain of the platform's, as an NSError: Go gets a
* *native.Error with its domain, number and message. Any other exception
* reaches Go with its class as the domain.
*/
open class NativeException(val domain: String, val number: Long, message: String) : Exception(message)
/** A value Go sent that the implementation's types do not have. */
class NativeWireException(message: String) : Exception(message)
/** An error a module declares (native.NewError): Go gets that error. Each module's exception implements it. */
interface NativeCodedError {
val nativeCode: String
}
/** An AutoCloseable that runs a function, once: what a method returning io.Closer returns. */
class NativeCloser(fn: () -> Unit) : AutoCloseable {
private var fn: (() -> Unit)? = fn
override fun close() {
val f = synchronized(this) { fn.also { fn = null } }
f?.invoke()
}
}
/** Memory of Go's that the implementation reads and writes, valid while the call runs: a *native.Buffer. */
class NativeBuffer internal constructor(
/** The address of the memory. */
val address: Long,
/** Its size in bytes. */
val size: Int,
) {
/** The memory, as a direct buffer. */
val bytes: ByteBuffer by lazy { Native.buffer(address, size.toLong()).order(java.nio.ByteOrder.nativeOrder()) }
}
// The encoding.
/** Writes values for Go, after 8 bytes for the status of an answer. */
class NativeWriter {
private var b = ByteArray(64)
private var n = HEAD
private fun room(k: Int) {
if (n + k > b.size) b = b.copyOf(maxOf(b.size * 2, n + k))
}
fun u64(v: Long) {
room(8)
for (i in 0 until 8) b[n + i] = (v ushr (8 * i)).toByte()
n += 8
}
fun i64(v: Long) = u64(v)
fun bool(v: Boolean) { room(1); b[n++] = if (v) 1 else 0 }
fun u8(v: Int) { room(1); b[n++] = v.toByte() }
fun double(v: Double) = u64(v.toRawBits())
fun count(c: Int) = i64(c.toLong())
fun string(v: String) = data(v.toByteArray(Charsets.UTF_8))
fun data(v: ByteArray) {
count(v.size)
room(v.size)
System.arraycopy(v, 0, b, n, v.size)
n += v.size
}
/** A time: seconds and nanoseconds since 1970. */
fun time(v: Instant) { i64(v.epochSecond); i64(v.nano.toLong()) }
fun duration(v: Duration) = i64(v.inWholeNanoseconds)
fun rect(v: android.graphics.RectF) {
double(v.left.toDouble()); double(v.top.toDouble()); double(v.width().toDouble()); double(v.height().toDouble())
}
fun reset() { n = HEAD }
/** The values written. */
fun values(): ByteArray? = if (n == HEAD) null else b.copyOfRange(HEAD, n)
/** The values as an answer of status. */
fun answer(status: Long): ByteArray {
for (i in 0 until 8) b[i] = (status ushr (8 * i)).toByte()
return b.copyOf(n)
}
private companion object {
const val HEAD = 8
}
}
/** Reads the values Go wrote; past them, it throws. */
class NativeReader(private val b: ByteArray, private var p: Int = 0) {
private fun take(k: Int): Int {
if (k < 0 || b.size - p < k) throw NativeWireException("native: a short message")
val at = p
p += k
return at
}
fun u64(): Long {
val at = take(8)
var v = 0L
for (i in 7 downTo 0) v = (v shl 8) or (b[at + i].toLong() and 0xff)
return v
}
fun i64(): Long = u64()
fun u8(): Int = b[take(1)].toInt() and 0xff
fun bool(): Boolean = u8() != 0
fun double(): Double = Double.fromBits(u64())
/** The count of a list or a map, whose elements take a byte each at least. */
fun count(): Int {
val c = i64()
if (c < 0 || c > b.size - p) throw NativeWireException("native: a short message")
return c.toInt()
}
fun string(): String {
val c = count()
val at = take(c)
return String(b, at, c, Charsets.UTF_8)
}
fun data(): ByteArray {
val c = count()
val at = take(c)
return b.copyOfRange(at, at + c)
}
fun time(): Instant {
val s = i64()
val ns = i64()
return Instant.ofEpochSecond(s, ns)
}
fun duration(): Duration = i64().nanoseconds
fun rect(): android.graphics.RectF {
val x = double().toFloat()
val y = double().toFloat()
val w = double().toFloat()
val h = double().toFloat()
return android.graphics.RectF(x, y, x + w, y + h)
}
fun buffer(): NativeBuffer {
val p = u64()
return NativeBuffer(p, i64().toInt())
}
}
/**
* A module's Kotlin, as mygo generates it (its MygoModule object), which
* Go loads by its class's name.
*/
abstract class NativeModule {
/** The module's index, from Go, in the high bits of every id, which makes the ids of continuations unique among modules. */
@Volatile internal var idBase = 0L
private val lastID = AtomicLong()
/** Calls a function: an object's method, a factory (new_T), or close. */
abstract fun invoke(sym: String, h: Long, args: ByteArray, call: Long): ByteArray
/** Calls a method of numbers. */
open fun direct(sym: String, h: Long, args: LongArray): Long = 0
/** The exception of an error the module declares, by its code. */
open fun error(code: String): Throwable? = null
protected fun nextID(): Long = idBase or lastID.incrementAndGet()
/** Runs what returns at once, which writes its result to the writer. */
protected inline fun answer(body: (NativeWriter) -> Unit): ByteArray {
val w = NativeWriter()
return try {
body(w)
w.answer(0)
} catch (e: Throwable) {
w.reset()
Native.writeError(w, e)
w.answer(1)
}
}
/** Runs what starts an asynchronous call or a stream: Go waits for its results through the callback. */
protected inline fun start(body: () -> Unit): ByteArray {
val w = NativeWriter()
return try {
body()
w.answer(2)
} catch (e: Throwable) {
Native.writeError(w, e)
w.answer(1)
}
}
/** Starts the task of an asynchronous call, on the main thread when main. */
protected fun task(call: Long, main: Boolean, body: suspend (NativeWriter) -> Unit) {
val job = Native.scope.launch(if (main) Dispatchers.Main else Dispatchers.Default) {
val w = NativeWriter()
var status = 0L
try {
body(w)
} catch (e: Throwable) {
w.reset()
Native.writeError(w, e)
status = 1
}
Native.tasks.finish(call)
Native.send(KIND_RESULT, call, status, w.values())
}
Native.tasks.put(call, job)
}
/** Starts a stream: each value Go asks for (next), then its end or its error. */
protected fun <T> stream(call: Long, main: Boolean, make: () -> Flow<T>, enc: (NativeWriter, T) -> Unit) {
val demand = Channel<Unit>(Channel.UNLIMITED)
Native.demands[call] = demand
val job = Native.scope.launch(if (main) Dispatchers.Main else Dispatchers.Default) {
val w = NativeWriter()
try {
demand.receive()
make().collect { v ->
w.reset()
enc(w, v)
Native.send(KIND_ITEM, call, 0, w.values() ?: ByteArray(0))
demand.receive()
}
Native.send(KIND_ITEM, call, 3, null)
} catch (e: CancellationException) {
// Go stopped the stream, and hears no more of it.
} catch (e: Throwable) {
w.reset()
Native.writeError(w, e)
Native.send(KIND_ITEM, call, 1, w.values())
} finally {
Native.demands.remove(call)
Native.tasks.finish(call)
}
}
Native.tasks.put(call, job)
}
/** The object of a handle Go passed. */
@Suppress("UNCHECKED_CAST")
protected fun <T> obj(h: Long): T = (Native.objects[h] ?: throw NativeClosedException()) as T
/** Keeps an object for Go: its handle. */
protected fun retain(v: Any): Long = Native.retain(v)
/** Closes an object Go closes, as io.Closer's Close. */
protected fun close(h: Long) {
when (val o = Native.objects[h]) {
is AutoCloseable -> o.close()
is android.view.View -> (o.parent as? android.view.ViewGroup)?.removeView(o)
}
}
/** The view of a window Go passed: the window's own. */
protected fun window(h: Long): android.view.View =
HostImpl.windows[h]?.view ?: throw NativeClosedException("native: the window is closed")
/** A rectangle of native UI, in points from the window's top-left, in the pixels of the window's view. */
protected fun pixels(r: android.graphics.RectF, w: android.view.View): android.graphics.RectF {
val d = w.resources.displayMetrics.density
return android.graphics.RectF(r.left * d, r.top * d, r.right * d, r.bottom * d)
}
protected fun unknown(sym: String): ByteArray = answer { throw NativeUnsupportedException("native: no function $sym: generate the module's Kotlin again") }
/** Calls the method of a value of Go's, which answers at once. */
fun <R> invokeGo(id: Long, w: NativeWriter, read: (NativeReader) -> R): R =
Native.answerOf(this, Native.send(KIND_INVOKE, id, 0, w.values()), read)
/** Calls the method of a value of Go's that takes a context, which the coroutine's cancellation cancels. */
suspend fun <R> invokeGoAsync(id: Long, w: NativeWriter, read: (NativeReader) -> R): R {
val cont = nextID()
val b = try {
suspendCancellableCoroutine<ByteArray?> { c ->
Native.conts[cont] = { b -> c.resume(b) }
c.invokeOnCancellation { Native.send(KIND_CANCEL, cont, 0, null) }
Native.send(KIND_INVOKE_ASYNC, id, cont, w.values())
}
} finally {
Native.conts.remove(cont)
}
return Native.answerOf(this, b, read)
}
/** A Go function the implementation calls, released once nothing holds it. */
fun goFunc(id: Long): GoFunc = GoFunc(this, id)
/** Ties the release of the value of Go's id to the life of holder. */
fun releaseWith(holder: Any, id: Long) = Native.releaseWith(holder, id)
companion object {
const val KIND_RESULT = 1L
const val KIND_ITEM = 2L
const val KIND_NOTIFY = 3L
const val KIND_ASK = 4L
const val KIND_RELEASE = 5L
const val KIND_INVOKE = 6L
const val KIND_INVOKE_ASYNC = 7L
const val KIND_CANCEL = 8L
}
}
/** A Go function the implementation calls: a notification, or a question Go answers at once. */
class GoFunc internal constructor(private val module: NativeModule, val id: Long) {
init {
if (id != 0L) Native.releaseWith(this, id)
}
fun notify(w: NativeWriter) {
if (id != 0L) Native.send(NativeModule.KIND_NOTIFY, id, 0, w.values())
}
fun <R> ask(w: NativeWriter, read: (NativeReader) -> R): R {
if (id == 0L) throw NativeClosedException()
return Native.answerOf(module, Native.send(NativeModule.KIND_ASK, id, 0, w.values()), read)
}
}
/** The runtime of native modules' Kotlin, which Go reaches through JNI. */
object Native {
private val modules = ConcurrentHashMap<String, NativeModule>()
/** The objects Go holds, by handle. */
internal val objects = ConcurrentHashMap<Long, Any>()
private val lastHandle = AtomicLong()
internal val tasks = Tasks()
internal val demands = ConcurrentHashMap<Long, Channel<Unit>>()
internal val conts = ConcurrentHashMap<Long, (ByteArray?) -> Unit>()
/** Where the tasks of asynchronous calls and streams run. */
@JvmField val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val main = Handler(Looper.getMainLooper())
/** The application's context, for a module's Android APIs, from any thread. */
val context: android.content.Context get() = HostImpl.app
/** The activity showing the app, if one is, for what needs one (a dialog, a permission request). Main thread. */
val activity: android.app.Activity? get() = HostImpl.activity
/** Runs body on the main thread, now if this is it, else waiting for it: to make an object there. */
fun <T> onMain(body: () -> T): T {
if (Looper.myLooper() == Looper.getMainLooper()) return body()
var result: Result<T>? = null
val latch = CountDownLatch(1)
main.post {
result = runCatching(body)
latch.countDown()
}
latch.await()
return result!!.getOrThrow()
}
// What Go calls, through JNI.
/** Loads a module's Kotlin: its generated object's class. Returns what went wrong, or null. */
@JvmStatic fun init(name: String, cls: String, idBase: Long): String? = try {
val m = Class.forName(cls).getField("INSTANCE").get(null) as NativeModule
m.idBase = idBase
modules[name] = m
null
} catch (e: ReflectiveOperationException) {
"the app has no Kotlin of the native module $name ($cls): build it with mygo build"
} catch (e: Throwable) {
"loading the Kotlin of the native module $name: $e"
}
@JvmStatic fun invoke(name: String, sym: String, h: Long, args: ByteArray, call: Long): ByteArray {
val m = modules[name] ?: return NativeWriter().also { writeError(it, NativeClosedException("native: $name is not loaded")) }.answer(1)
return m.invoke(sym, h, args, call)
}
@JvmStatic fun direct(name: String, sym: String, h: Long, args: LongArray): Long = modules[name]?.direct(sym, h, args) ?: 0
@JvmStatic fun op(name: String, op: String, a: Long, status: Long, data: ByteArray?) {
when (op) {
"release" -> objects.remove(a)
"cancel" -> tasks.cancel(a)
"next" -> demands[a]?.trySend(Unit)
"resume" -> conts.remove(a)?.invoke(answer(status, data))
}
}
/** Tells Go something; its answer is the status and then the data, null when there is none. */
@JvmStatic external fun send(kind: Long, id: Long, status: Long, data: ByteArray?): ByteArray?
/** The n bytes at p, which Go owns, as a direct buffer. Public, as JNI finds it by its name. */
@JvmStatic external fun buffer(p: Long, n: Long): ByteBuffer
/** The view of a handle, for ui.NativeView. */
internal fun view(h: Long): android.view.View? = objects[h] as? android.view.View
internal fun retain(v: Any): Long {
val h = lastHandle.incrementAndGet()
objects[h] = v
return h
}
private fun answer(status: Long, data: ByteArray?): ByteArray {
val b = ByteArray(8 + (data?.size ?: 0))
for (i in 0 until 8) b[i] = (status ushr (8 * i)).toByte()
data?.copyInto(b, 8)
return b
}
/** Reads an answer of Go's. */
internal fun <R> answerOf(m: NativeModule, b: ByteArray?, read: (NativeReader) -> R): R {
if (b == null || b.size < 8) throw NativeClosedException()
val r = NativeReader(b)
val status = r.u64()
if (status == 1L) throw readError(m, r)
return read(r)
}
// The kinds of errors, as they cross both ways: the kind, then the
// code, domain, number and message.
private const val ERR_OTHER = 0
private const val ERR_CODE = 1
private const val ERR_UNSUPPORTED = 2
private const val ERR_CLOSED = 3
private const val ERR_CANCELED = 4
private const val ERR_GO = 5
fun writeError(w: NativeWriter, e: Throwable) {
var kind = ERR_OTHER
var code = ""
var domain = ""
var number = 0L
var message = e.message ?: e.toString()
when (e) {
is NativeException -> { domain = e.domain; number = e.number }
is NativeCodedError -> { kind = ERR_CODE; code = e.nativeCode }
is NativeUnsupportedException -> kind = ERR_UNSUPPORTED
is NativeClosedException -> kind = ERR_CLOSED
is NativeGoException -> kind = ERR_GO
is CancellationException -> kind = ERR_CANCELED
else -> domain = e.javaClass.name
}
w.u8(kind)
w.string(code)
w.string(domain)
w.i64(number)
w.string(message)
}
private fun readError(m: NativeModule, r: NativeReader): Throwable = try {
val kind = r.u8()
val code = r.string()
r.string()
r.i64()
val message = r.string()
when (kind) {
ERR_CODE -> m.error(code) ?: NativeGoException(message)
ERR_UNSUPPORTED -> NativeUnsupportedException(message)
ERR_CLOSED -> NativeClosedException(message)
ERR_CANCELED -> CancellationException(message)
else -> NativeGoException(message)
}
} catch (e: NativeWireException) {
NativeGoException("an error of Go's that does not decode")
}
// Values of Go's that Kotlin holds, released once it no longer does.
private val collected = ReferenceQueue<Any>()
private val held = ConcurrentHashMap.newKeySet<Held>()
private class Held(holder: Any, val id: Long) : PhantomReference<Any>(holder, collected)
internal fun releaseWith(holder: Any, id: Long) {
held.add(Held(holder, id))
releaser
}
private val releaser: Thread by lazy {
Thread({
while (true) {
val r = collected.remove() as Held
held.remove(r)
send(NativeModule.KIND_RELEASE, r.id, 0, null)
}
}, "mygo-native-release").apply {
isDaemon = true
start()
}
}
/** The tasks of asynchronous calls and streams, by their call, which Go cancels. */
internal class Tasks {
private val jobs = HashMap<Long, Job>()
private val done = HashSet<Long>()
private val canceled = HashSet<Long>()
@Synchronized fun put(call: Long, job: Job) {
if (done.remove(call)) return
if (canceled.remove(call)) job.cancel()
jobs[call] = job
}
@Synchronized fun finish(call: Long) {
if (jobs.remove(call) == null) done.add(call)
canceled.remove(call)
}
fun cancel(call: Long) {
val job = synchronized(this) {
jobs.remove(call).also { if (it == null && !done.remove(call)) canceled.add(call) }
}
job?.cancel()
}
}
}
@@ -0,0 +1,411 @@
// The navigation of phones on Android: each window in a page of a stack,
// whose pages above the first have a toolbar with a back arrow and the
// window's title, and bars of tabs (Material's bottom navigation), a
// stack in each tab, all in the root view, the one shown last in front.
// A window's router may show its pages as a stack of its own (SetStack):
// the window's toolbar then shows the title of the page shown, with a back
// arrow past the first, and the router moves the pages, as Android's apps
// move theirs.
package dev.mygo
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.appcompat.view.ContextThemeWrapper
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.color.DynamicColors
object Navigation {
/** A window's page in a stack: its toolbar, when it has one, over it. */
class Page(val window: HostWindow, var toolbar: MaterialToolbar?, val view: LinearLayout)
/** A stack of pages: the first is the window it shows, the others pushed over it. */
class Stack(context: Context) : FrameLayout(context) {
val pages = ArrayList<Page>()
var tabs: Tabs? = null
var barAtRoot = ""
}
/** A bar of tabs, a stack in each. */
class Tabs(context: Context, val id: Long) : LinearLayout(context) {
val content = FrameLayout(context)
val stacks = ArrayList<Stack>()
val bar = BottomNavigationView(material(context))
var selected = 0
init {
orientation = VERTICAL
addView(content, LayoutParams(LayoutParams.MATCH_PARENT, 0, 1f))
addView(bar, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))
bar.labelVisibilityMode = BottomNavigationView.LABEL_VISIBILITY_LABELED
bar.setOnItemSelectedListener { item ->
val i = item.itemId
if (i != selected) {
select(i)
Go.send(Event.tabSelected(id, i.toLong()))
}
true
}
}
fun select(i: Int) {
if (i !in stacks.indices) return
selected = i
stacks[i].pages.lastOrNull()?.window?.let { tint(it) }
for ((k, s) in stacks.withIndex()) s.visibility = if (k == i) View.VISIBLE else View.GONE
if (bar.selectedItemId != i) bar.selectedItemId = i
for (p in stacks[i].pages) p.window.reportSize()
}
}
private val stacks = HashMap<Long, Stack>() // by window
val tabs = HashMap<Long, Tabs>()
private val root get() = HostImpl.root
/** A context with Material 3's theme, and the wallpaper's colors where the system has them. */
fun material(context: Context): Context =
DynamicColors.wrapContextIfAvailable(ContextThemeWrapper(context, com.google.android.material.R.style.Theme_Material3_DayNight_NoActionBar))
private fun toolbar(w: HostWindow, title: String): MaterialToolbar {
val t = MaterialToolbar(material(w.context))
t.title = title
t.setBackgroundColor(if (w.fill != 0) w.fill else HostImpl.themeColor(android.R.attr.colorBackground))
return t
}
/** back gives a toolbar the back arrow, which runs fn, or (null) takes it away. */
private fun back(t: MaterialToolbar, fn: (() -> Unit)?) {
if (fn == null) {
t.navigationIcon = null
t.setNavigationOnClickListener(null)
return
}
t.setNavigationIcon(androidx.appcompat.R.drawable.abc_ic_ab_back_material)
t.setNavigationContentDescription(androidx.appcompat.R.string.abc_action_bar_up_description)
t.setNavigationOnClickListener { fn() }
}
private fun page(w: HostWindow, title: String?, back: Boolean): Page {
(w.view.parent as? ViewGroup)?.removeView(w.view)
val v = LinearLayout(w.context).apply { orientation = LinearLayout.VERTICAL }
var toolbar: MaterialToolbar? = null
if (title != null) {
val t = toolbar(w, title)
if (back) back(t) { pop(w, true) }
v.addView(t, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
toolbar = t
}
v.addView(w.view, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
w.view.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> w.reportSize() }
return Page(w, toolbar, v)
}
private fun front(v: View) {
(v.parent as? ViewGroup)?.let { if (it !== root) it.removeView(v) }
if (v.parent == null) {
root.addView(v, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
} else {
v.bringToFront()
}
insetsChanged()
arrange()
}
/**
* Only what is in front stays on screen: the surfaces of two windows have
* no order of their own, whatever the order of their views. Not now: Go
* may be waiting for this call, and a surface going waits for Go.
*/
private fun arrange() {
root.post {
val top = root.childCount - 1
for (k in 0..top) {
val v = root.getChildAt(k)
if (v is Stack || v is Tabs) v.visibility = if (k == top) View.VISIBLE else View.INVISIBLE
}
}
}
/** show brings a window to the front: its tab, its stack, or a stack of its own. */
fun show(w: HostWindow) {
val s = stacks[w.id]
if (s != null) {
val t = s.tabs
if (t != null) {
t.select(t.stacks.indexOf(s))
front(t)
} else {
front(s)
}
return
}
val stack = Stack(w.context)
val p = page(w, null, false)
stack.pages.add(p)
stack.addView(p.view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
stacks[w.id] = stack
front(stack)
}
/** hide takes a window off the screen: its stack, or the pages above it in its stack. */
fun hide(w: HostWindow) {
val s = stacks[w.id] ?: return
val i = s.pages.indexOfFirst { it.window === w }
if (i == 0) {
if (s.tabs == null) {
root.removeView(s)
for (p in s.pages) stacks.remove(p.window.id)
arrange()
}
} else if (i > 0) {
truncate(s, i, false)
}
}
fun forget(w: HostWindow) {
routed.remove(w.id)
val s = stacks.remove(w.id) ?: return
s.pages.removeAll { it.window === w }
}
fun push(w: HostWindow, parent: HostWindow, title: String, animated: Boolean) {
val s = stacks[parent.id] ?: run {
show(parent)
stacks[parent.id]!!
}
val at = s.pages.indexOfFirst { it.window === parent }
if (at >= 0 && at < s.pages.size - 1) truncate(s, at + 1, false)
val below = s.pages.lastOrNull()
val p = page(w, title, true)
s.pages.add(p)
stacks[w.id] = s
s.addView(p.view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
insetsChanged()
tint(w)
if (animated && s.width > 0) {
p.view.translationX = s.width.toFloat()
p.view.animate().translationX(0f).setDuration(250).withEndAction { below?.view?.visibility = View.INVISIBLE }.start()
below?.view?.animate()?.translationX(-s.width * 0.25f)?.setDuration(250)?.start()
} else {
below?.view?.visibility = View.INVISIBLE
}
}
fun pop(w: HostWindow, animated: Boolean) {
val s = stacks[w.id] ?: return
val i = s.pages.indexOfFirst { it.window === w }
if (i > 0) truncate(s, i, animated)
}
/** truncate takes the pages from i up off the stack, which tells Go they went. */
private fun truncate(s: Stack, i: Int, animated: Boolean) {
val gone = s.pages.subList(i, s.pages.size).toList()
s.pages.subList(i, s.pages.size).clear()
val below = s.pages.lastOrNull()
below?.view?.visibility = View.VISIBLE
below?.view?.translationX = 0f
below?.window?.let { tint(it) }
for ((k, p) in gone.withIndex()) {
stacks.remove(p.window.id)
val last = k == gone.size - 1
if (animated && last && s.width > 0) {
below?.view?.translationX = -s.width * 0.25f
below?.view?.animate()?.translationX(0f)?.setDuration(220)?.start()
p.view.animate().translationX(s.width.toFloat()).setDuration(220).withEndAction { s.removeView(p.view) }.start()
} else {
s.removeView(p.view)
}
Go.send(Event.popped(p.window.id))
}
HostImpl.updateBack()
}
/** Whether the window in front can go off its stack. */
fun canPop(): Boolean {
for (k in root.childCount - 1 downTo 0) {
val s = when (val v = root.getChildAt(k)) {
is Tabs -> v.stacks.getOrNull(v.selected)
is Stack -> v
else -> null
} ?: continue
return s.pages.size > 1
}
return false
}
/** back pops the window in front off its stack, and reports whether there was one to pop. */
fun back(): Boolean {
for (k in root.childCount - 1 downTo 0) {
val v = root.getChildAt(k)
val s = when (v) {
is Tabs -> v.stacks.getOrNull(v.selected)
is Stack -> v
else -> null
} ?: continue
if (s.pages.size > 1) {
pop(s.pages.last().window, true)
return true
}
return false
}
return false
}
// The pages of routers.
/** A window's router showing its pages in its stack: how deep, the window's title, and whether the toolbar is the router's. */
private class Routed(var depth: Int, val title: String, val added: Boolean)
private val routed = HashMap<Long, Routed>()
/**
* setStack shows the pages of w's router as a stack: the toolbar shows the
* title of the page shown, with a back arrow past the first, which takes
* the router back. No titles take it away.
*/
fun setStack(w: HostWindow, titles: List<String>) {
val s = stacks[w.id] ?: return
val i = s.pages.indexOfFirst { it.window === w }
if (i < 0) return
val p = s.pages[i]
val r = routed[w.id]
if (titles.isEmpty()) {
if (r == null) return
routed.remove(w.id)
val t = p.toolbar ?: return
if (r.added) {
p.view.removeView(t)
p.toolbar = null
} else {
t.title = r.title
back(t, if (i > 0) ({ pop(w, true) }) else null)
}
return
}
var t = p.toolbar
if (r == null) {
val added = t == null
if (t == null) {
t = toolbar(w, titles.last())
p.view.addView(t, 0, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
p.toolbar = t
insetsChanged()
}
routed[w.id] = Routed(titles.size, t.title?.toString() ?: "", added)
}
routed[w.id]?.depth = titles.size
t!!.title = titles.last()
when {
titles.size > 1 -> back(t) {
val d = routed[w.id]?.depth ?: 1
if (d > 1) Go.send(Event.stackPopped(w.id, (d - 1).toLong()))
}
i > 0 -> back(t) { pop(w, true) }
else -> back(t, null)
}
}
// Tabs.
fun createTabs(id: Long, context: Context) {
tabs[id] = Tabs(context, id)
}
fun addTab(id: Long, w: HostWindow, title: String, icon: ByteArray) {
val t = tabs[id] ?: return
stacks[w.id]?.let { old ->
if (old.tabs == null) {
root.removeView(old)
arrange()
}
stacks.remove(w.id)
}
val stack = Stack(w.context)
stack.tabs = t
val p = page(w, title.ifEmpty { null }, false)
stack.pages.add(p)
stack.addView(p.view, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
stacks[w.id] = stack
val i = t.stacks.size
t.stacks.add(stack)
t.content.addView(stack, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
val item = t.bar.menu.add(0, i, i, title)
if (icon.isNotEmpty()) {
BitmapFactory.decodeByteArray(icon, 0, icon.size)?.let { item.icon = BitmapDrawable(w.context.resources, it) }
}
}
fun showTabs(id: Long) {
val t = tabs[id] ?: return
t.select(0)
front(t)
}
fun setBadge(id: Long, i: Int, badge: String) {
val t = tabs[id] ?: return
if (badge.isEmpty()) {
t.bar.removeBadge(i)
return
}
val b = t.bar.getOrCreateBadge(i)
badge.toIntOrNull()?.let { b.number = it } ?: run { b.text = badge }
}
fun closeTabs(id: Long) {
val t = tabs.remove(id) ?: return
root.removeView(t)
arrange()
}
/**
* The bars around a window take the color its content fills it with:
* its toolbar, and the bar of tabs while it is in front of its tab.
*/
fun backgroundChanged(w: HostWindow) {
val s = stacks[w.id] ?: return
s.pages.firstOrNull { it.window === w }?.toolbar?.setBackgroundColor(w.fill)
val t = s.tabs ?: return
if (t.stacks.getOrNull(t.selected) === s && s.pages.lastOrNull()?.window === w) tint(w)
}
private fun tint(w: HostWindow) {
if (w.fill == 0) return
val s = stacks[w.id] ?: return
s.tabs?.bar?.setBackgroundColor(w.fill)
}
/** Buttons at the end of the window's toolbar. */
fun setBarItems(w: HostWindow, c: SetBarItemsCall) {
val t = stacks[w.id]?.pages?.firstOrNull { it.window === w }?.toolbar ?: return
t.menu.clear()
c.titles.forEachIndexed { i, title ->
val item = t.menu.add(0, i, i, title)
val icon = android.util.Base64.decode(c.icons[i], android.util.Base64.DEFAULT)
if (icon.isNotEmpty()) {
BitmapFactory.decodeByteArray(icon, 0, icon.size)?.let { item.icon = BitmapDrawable(w.context.resources, it) }
}
item.setShowAsAction(android.view.MenuItem.SHOW_AS_ACTION_IF_ROOM)
}
t.setOnMenuItemClickListener {
Go.send(Event.barItemClicked(c.id, it.itemId.toLong()))
true
}
}
fun setTitle(w: HostWindow, title: String) {
if (w.id in routed) return // the router's page has the toolbar's title
stacks[w.id]?.pages?.firstOrNull { it.window === w }?.toolbar?.title = title
}
/** The toolbars at the top of the screen take the status bar's room. */
fun insetsChanged() {
val top = HostImpl.bars.top
for (s in stacks.values.toSet()) for (p in s.pages) p.toolbar?.setPadding(0, top, 0, 0)
for (w in HostImpl.windows.values) w.insetsChanged()
}
}
@@ -0,0 +1,4 @@
// What the build replaces with the plugins the app's packages name.
package dev.mygo
internal fun registerPlugins() {}
@@ -0,0 +1,156 @@
// Plugins' native code. A plugin brings Kotlin 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 UI thread.
package dev.mygo
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
/** An error of a plugin's native code, with a code Go can tell apart. */
class PluginFailure(val code: String, message: String = "") : Exception(message)
/** The answer of a plugin's method: call success or failure once, from any thread. */
interface PluginReply {
fun success(result: Any?)
fun failure(error: PluginFailure)
}
/** A plugin's native code. */
interface MyGoPlugin {
/** Runs a method with its arguments, from JSON, on the UI thread. It may answer later. */
fun call(method: String, args: JSONObject, reply: PluginReply)
}
/** What plugins have of the host. */
object PluginHost {
private val plugins = HashMap<String, MyGoPlugin>()
private var nextCode = 0x7000
private val onResults = HashMap<Int, (Int, Intent?) -> Unit>()
private val onPermissions = HashMap<Int, (Boolean) -> Unit>()
private val viewMakers = HashMap<String, (Context, Long, JSONObject) -> android.view.View>()
fun 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. */
fun registerView(type: String, make: (context: Context, id: Long, args: JSONObject) -> android.view.View) {
viewMakers[type] = make
}
internal fun makeView(type: String, context: Context, id: Long, args: String): android.view.View? {
// A native module's view, which ui.NativeView shows: its handle.
if (type == "mygo.native") return Native.view(args.toLongOrNull() ?: 0)
val a = (if (args.isEmpty()) null else runCatching { JSONTokener(args).nextValue() as? JSONObject }.getOrNull()) ?: JSONObject()
return viewMakers[type]?.invoke(context, id, a)
}
/** Hears the Intents that open the app, for what a plugin's own open it with. */
var onIntent: ((Intent) -> Unit)? = null
/** The app's context, which outlives Activities. */
val context: Context get() = HostImpl.app
/** The Activity showing the app, null while none does. */
val activity: Activity? get() = HostImpl.activity
/** Sends an event to Go (mygo.Native(id).On), from any thread. */
fun emit(plugin: String, name: String, data: Any? = null) {
Go.send(Event.pluginEvent(plugin, name, encode(data)))
}
/** Starts an Activity for its result. */
fun startForResult(intent: Intent, done: (resultCode: Int, data: Intent?) -> Unit) {
val a = activity
if (a == null) {
done(Activity.RESULT_CANCELED, null)
return
}
val code = nextCode++
onResults[code] = done
@Suppress("DEPRECATION")
a.startActivityForResult(intent, code)
}
/** Has the system ask the user for permissions the app lacks, and tells whether it has them all. */
fun requestPermissions(permissions: Array<String>, done: (granted: Boolean) -> Unit) {
val a = activity
if (a == null) {
done(false)
return
}
val missing = permissions.filter { a.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (missing.isEmpty()) {
done(true)
return
}
val code = nextCode++
onPermissions[code] = done
a.requestPermissions(missing.toTypedArray(), code)
}
internal fun activityResult(code: Int, result: Int, data: Intent?): Boolean {
val f = onResults.remove(code) ?: return false
f(result, data)
return true
}
internal fun permissionsResult(code: Int, results: IntArray): Boolean {
val f = onPermissions.remove(code) ?: return false
f(results.isNotEmpty() && results.all { it == PackageManager.PERMISSION_GRANTED })
return true
}
/** JSON of what org.json can write. */
internal fun encode(v: Any?): String = when (v) {
null -> "null"
is JSONObject, is JSONArray -> v.toString()
is Map<*, *> -> JSONObject(v).toString()
is Collection<*> -> JSONArray(v).toString()
else -> JSONObject.wrap(v)?.let { w -> JSONArray().put(w).toString().let { it.substring(1, it.length - 1) } } ?: "null"
}
internal fun call(c: PluginCallCall) {
val p = plugins[c.plugin]
if (p == null) {
Go.send(Event.pluginResult(c.req, "", "no plugin ${c.plugin} in this app", "NoPlugin"))
return
}
val args = (if (c.args.isEmpty()) null else runCatching { JSONTokener(c.args).nextValue() as? JSONObject }.getOrNull()) ?: JSONObject()
var answered = false
val reply = object : PluginReply {
override fun success(result: Any?) {
if (answered) return
val text = try {
encode(result)
} catch (e: Exception) {
failure(PluginFailure("Encoding", e.toString()))
return
}
answered = true
Go.send(Event.pluginResult(c.req, text, "", ""))
}
override fun failure(error: PluginFailure) {
if (answered) return
answered = true
Go.send(Event.pluginResult(c.req, "", error.message ?: "", error.code))
}
}
try {
p.call(c.method, args, reply)
} catch (e: Exception) {
reply.failure(PluginFailure("Exception", e.toString()))
}
}
}
/** A window showing a plugin's view, which a surface holds. */
internal class PluginViewWindow(context: Context, id: Long, override val view: android.view.View) : HostWindow(context, id) {
override fun setBackground(argb: Int) = view.setBackgroundColor(argb)
}
@@ -0,0 +1,42 @@
package dev.mygo
import android.content.Context
import android.content.pm.PackageManager
import java.io.File
/**
* The app's resources (mygo.PathResources): mygo build puts them in the
* APK's assets, under resources/, which are no files. They are copied
* into the app's files once per version of the app, for Go to read them
* by path.
*/
object Resources {
fun dir(c: Context) = File(c.filesDir, "mygo-resources")
fun extract(c: Context): String {
val dir = dir(c)
val info = c.packageManager.getPackageInfo(c.packageName, 0)
val stamp = File(dir, ".version")
val version = "${info.longVersionCode}-${info.lastUpdateTime}"
if (stamp.exists() && stamp.readText() == version) return dir.absolutePath
dir.deleteRecursively()
dir.mkdirs()
copy(c, "resources", dir)
stamp.writeText(version)
return dir.absolutePath
}
private fun copy(c: Context, path: String, to: File) {
val names = c.assets.list(path) ?: return
for (n in names) {
val p = "$path/$n"
val sub = c.assets.list(p)
if (sub != null && sub.isNotEmpty()) {
File(to, n).mkdirs()
copy(c, p, File(to, n))
} else {
c.assets.open(p).use { input -> File(to, n).outputStream().use { input.copyTo(it) } }
}
}
}
}
@@ -0,0 +1,68 @@
package dev.mygo
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* Secrets, encrypted with an AES key of Android's keystore, which never
* leaves it, and kept in the app's shared preferences.
*/
object Secrets {
private const val KEY = "mygo.secrets"
private fun key(): SecretKey {
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(ks.getEntry(KEY, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
gen.init(
KeyGenParameterSpec.Builder(KEY, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
)
return gen.generateKey()
}
private fun prefs(c: Context) = c.getSharedPreferences(KEY, Context.MODE_PRIVATE)
private fun name(service: String, account: String) = service + "\u0000" + account
fun get(c: Context, call: SecretGetCall): SecretGetReply {
val r = SecretGetReply()
val stored = prefs(c).getString(name(call.service, call.account), null) ?: return r
try {
val data = Base64.decode(stored, Base64.NO_WRAP)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, data, 0, 12))
r.value = cipher.doFinal(data, 12, data.size - 12)
r.found = true
} catch (e: Exception) {
r.error = "mygo: keystore: ${e.message}"
}
return r
}
fun set(c: Context, call: SecretSetCall): SecretSetReply {
val r = SecretSetReply()
try {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key())
val data = cipher.iv + cipher.doFinal(call.value)
prefs(c).edit().putString(name(call.service, call.account), Base64.encodeToString(data, Base64.NO_WRAP)).apply()
} catch (e: Exception) {
r.error = "mygo: keystore: ${e.message}"
}
return r
}
fun delete(c: Context, call: SecretDeleteCall): SecretDeleteReply {
prefs(c).edit().remove(name(call.service, call.account)).apply()
return SecretDeleteReply()
}
}
@@ -0,0 +1,57 @@
package dev.mygo
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioTrack
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* The sound of package audio, through AudioTrack: Go's output writes from a
* thread of its own, which AudioTrack makes wait while it holds enough.
*/
object Sound {
private var track: AudioTrack? = null
fun open(c: AudioOpenCall): AudioOpenReply {
val r = AudioOpenReply()
try {
val format = AudioFormat.Builder().setSampleRate(c.rate.toInt()).setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT).build()
val least = AudioTrack.getMinBufferSize(c.rate.toInt(), AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_FLOAT)
val asked = (c.rate * c.ahead / 1000 * 8).toInt()
val t = AudioTrack.Builder()
.setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build())
.setAudioFormat(format).setBufferSizeInBytes(maxOf(least, asked)).setTransferMode(AudioTrack.MODE_STREAM)
.setPerformanceMode(AudioTrack.PERFORMANCE_MODE_LOW_LATENCY).build()
t.play()
track = t
} catch (e: Exception) {
r.error = "audio: $e"
}
return r
}
fun write(c: AudioWriteCall): AudioWriteReply {
val r = AudioWriteReply()
val t = track
if (t == null) {
r.error = "audio: closed"
return r
}
val b = ByteBuffer.wrap(c.samples).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer()
val a = FloatArray(b.remaining())
b.get(a)
val n = t.write(a, 0, a.size, AudioTrack.WRITE_BLOCKING)
if (n < 0) r.error = "audio: AudioTrack error $n"
return r
}
fun close() {
track?.run {
stop()
release()
}
track = null
}
}
@@ -0,0 +1,808 @@
package dev.mygo
import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.text.InputType
import android.view.Choreographer
import android.view.InputDevice
import android.view.ActionMode
import android.view.KeyEvent
import android.widget.Magnifier
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.PointerIcon
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.view.accessibility.AccessibilityNodeProvider
import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
/**
* A window showing native UI, which Go draws with OpenGL ES into the
* surface's ANativeWindow. The view gives Go the display's refreshes
* (Choreographer), the fingers, a hardware keyboard, the soft keyboard
* (an InputConnection, with the composing text of input methods) and
* TalkBack's questions.
*/
class SurfaceWindow(context: Context, id: Long) : HostWindow(context, id) {
/** The window's number, which views' own id would shadow. */
private val wid: Long = id
private val surface = Surface(context)
/** The surface, and under it the views it holds. */
private val box = android.widget.FrameLayout(context).apply {
addView(surface, android.widget.FrameLayout.LayoutParams(android.widget.FrameLayout.LayoutParams.MATCH_PARENT, android.widget.FrameLayout.LayoutParams.MATCH_PARENT))
}
override val view: View get() = box
private var native = 0L
private var framePending = false
private val frame = Choreographer.FrameCallback {
framePending = false
Go.send(Event.frame(wid))
}
// The input being edited, as Go last told it (SetTextInput): the text
// around the selection, from base, and offsets in UTF-16 units of the
// document, as InputConnection counts.
private var input = SetTextInputCall(markStart = -1, markEnd = -1)
private val editing get() = input.active
private var nodes: List<Node>? = null
/** Whether the content takes the system's back. */
var backAvailable = false
// A SurfaceView's background would draw over its surface, hiding the
// frames: the page around it takes the color.
override fun setBackground(argb: Int) {
box.setBackgroundColor(argb)
}
/** A view the surface holds, in a view that clips it. */
private class Held(val window: HostWindow, val clip: android.widget.FrameLayout) {
var box = Rect()
var covers = emptyList<Rect>()
fun takes(x: Int, y: Int) = clip.visibility == View.VISIBLE && box.contains(x, y) && covers.none { it.contains(x, y) }
}
private val held = ArrayList<Held>()
/**
* Holds a view under the surface, whose frames are transparent where the
* content shows it: the surface goes over the window, which it does only as
* it is made, so it is made again the first time.
*/
fun hold(w: HostWindow) {
w.holder = this
(w.view.parent as? android.view.ViewGroup)?.removeView(w.view)
val clip = android.widget.FrameLayout(context)
clip.clipChildren = true
clip.visibility = View.GONE
clip.addView(w.view, android.widget.FrameLayout.LayoutParams(0, 0))
box.addView(clip, 0, android.widget.FrameLayout.LayoutParams(0, 0))
if (held.isEmpty()) {
// Not now: Go waits for this call, and the surface going waits
// for Go.
box.post {
surface.setZOrderOnTop(true)
surface.holder.setFormat(android.graphics.PixelFormat.TRANSLUCENT)
box.removeView(surface)
box.addView(surface, android.widget.FrameLayout.LayoutParams(android.widget.FrameLayout.LayoutParams.MATCH_PARENT, android.widget.FrameLayout.LayoutParams.MATCH_PARENT))
}
}
held.add(Held(w, clip))
}
fun release(w: HostWindow) {
val i = held.indexOfFirst { it.window === w }
if (i < 0) return
box.removeView(held[i].clip)
held.removeAt(i)
}
fun placeViews(places: ByteArray) {
val r = WireReader(places)
val d = density
fun rect(): Rect {
val x = r.float()
val y = r.float()
val w = r.float()
val h = r.float()
return Rect((x * d).toInt(), (y * d).toInt(), ((x + w) * d).toInt(), ((y + h) * d).toInt())
}
val shown = HashSet<Held>()
var order = 0
while (!r.done()) {
val id = r.int()
val frame = rect()
val clip = rect()
val covers = List(r.int().toInt()) { rect() }
val h = held.firstOrNull { it.window.id == id } ?: continue
val lp = h.clip.layoutParams as android.widget.FrameLayout.LayoutParams
lp.leftMargin = clip.left
lp.topMargin = clip.top
lp.width = clip.width()
lp.height = clip.height()
h.clip.layoutParams = lp
val vp = h.window.view.layoutParams as android.widget.FrameLayout.LayoutParams
vp.leftMargin = frame.left - clip.left
vp.topMargin = frame.top - clip.top
vp.width = frame.width()
vp.height = frame.height()
h.window.view.layoutParams = vp
h.window.view.post { h.window.reportSize() }
h.box = clip
h.covers = covers
h.clip.visibility = View.VISIBLE
if (box.indexOfChild(h.clip) != order) {
box.removeView(h.clip)
box.addView(h.clip, order)
}
order++
shown.add(h)
}
for (h in held) if (h !in shown) h.clip.visibility = View.GONE
}
/** A finger going down on a view it holds, which gets it: the content hears of it. */
private fun heldTakes(e: MotionEvent): Boolean {
val x = e.x.toInt()
val y = e.y.toInt()
if (held.asReversed().none { it.takes(x, y) }) return false
if (e.actionMasked == MotionEvent.ACTION_DOWN) Go.send(Event.viewPressed(wid, e.x / density, e.y / density))
return true
}
fun requestFrame() {
if (framePending) return
framePending = true
Choreographer.getInstance().postFrameCallback(frame)
}
override fun close() {
if (framePending) Choreographer.getInstance().removeFrameCallback(frame)
releaseNative()
}
private fun releaseNative() {
if (native != 0L) {
Go.ask(Event.surfaceDestroyed(wid))
MyGoNative.releaseNativeWindow(native)
native = 0
}
}
private val density get() = HostImpl.density.toDouble()
/** The virtual view that stands for the input in focus, to autofill. */
private val autofillNode = 1
fun setTextInput(c: SetTextInputCall) {
val was = input
input = c
tellAutofill(was, c)
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val traits = was.multiline != c.multiline || was.secure != c.secure || was.keyboard != c.keyboard || was.returnKey != c.returnKey ||
was.capitalize != c.capitalize || was.autocorrect != c.autocorrect || was.autofill != c.autofill
when {
c.active && (!was.active || traits || c.serial != was.serial) -> {
surface.requestFocus()
imm.restartInput(surface)
imm.showSoftInput(surface, 0)
}
!c.active && was.active -> {
imm.hideSoftInputFromWindow(surface.windowToken, 0)
imm.restartInput(surface)
}
c.active -> {
if (c.show != was.show) imm.showSoftInput(surface, 0)
if (c.selStart != was.selStart || c.selEnd != was.selEnd || c.markStart != was.markStart || c.markEnd != was.markEnd) {
imm.updateSelection(surface, c.selStart.toInt(), c.selEnd.toInt(), c.markStart.toInt(), c.markEnd.toInt())
}
}
}
}
/** Sends an edit and takes the state after it, which the keyboard goes on to read at once. */
private fun edit(msg: ByteArray) {
val r = Go.ask(msg) ?: return
val st = TextStateReply(r)
val c = input
val changed = st.selStart != c.selStart || st.selEnd != c.selEnd || st.markStart != c.markStart || st.markEnd != c.markEnd
c.text = st.text
c.base = st.base
c.length = st.length
c.selStart = st.selStart
c.selEnd = st.selEnd
c.markStart = st.markStart
c.markEnd = st.markEnd
if (autofillHint(c) != null) {
context.getSystemService(android.view.autofill.AutofillManager::class.java)
?.notifyValueChanged(surface, autofillNode, android.view.autofill.AutofillValue.forText(wholeText(c)))
}
if (changed) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.updateSelection(surface, c.selStart.toInt(), c.selEnd.toInt(), c.markStart.toInt(), c.markEnd.toInt())
}
}
/** The part of the document from a to b, the host's copy holding it or not. */
private fun document(a: Int, b: Int): CharSequence {
val c = input
val lo = a - c.base.toInt()
val hi = b - c.base.toInt()
if (lo >= 0 && hi <= c.text.length && lo <= hi) return c.text.substring(lo, hi)
val r = Go.ask(Event.textRange(wid, a.toLong(), b.toLong())) ?: return ""
return TextRangeReply(r).text
}
/** A mouse's pointer, on a Chromebook or a tablet with one. */
fun setCursor(cursor: String) {
val kind = when (cursor) {
"text" -> PointerIcon.TYPE_TEXT
"pointer" -> PointerIcon.TYPE_HAND
"move" -> PointerIcon.TYPE_ALL_SCROLL
"resizeX" -> PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW
"resizeY" -> PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW
"grab" -> PointerIcon.TYPE_GRAB
"grabbing" -> PointerIcon.TYPE_GRABBING
"crosshair" -> PointerIcon.TYPE_CROSSHAIR
"notAllowed" -> PointerIcon.TYPE_NO_DROP
"none" -> PointerIcon.TYPE_NULL
else -> PointerIcon.TYPE_DEFAULT
}
surface.pointerIcon = PointerIcon.getSystemIcon(context, kind)
}
private var actionMode: ActionMode? = null
/** The system's floating menu of the editing commands asked for. */
fun showMenu(c: ShowMenuCall) {
actionMode?.finish()
val d = density
val at = Rect((c.x * d).toInt(), (c.y * d).toInt(), (c.x * d).toInt() + 1, (c.y * d).toInt() + 1)
actionMode = surface.startActionMode(object : ActionMode.Callback2() {
override fun onCreateActionMode(m: ActionMode, menu: Menu): Boolean {
val labels = mapOf("cut" to android.R.string.cut, "copy" to android.R.string.copy,
"paste" to android.R.string.paste, "selectAll" to android.R.string.selectAll)
c.actions.forEachIndexed { i, name -> labels[name]?.let { menu.add(0, i, i, it) } }
return true
}
override fun onPrepareActionMode(m: ActionMode, menu: Menu) = false
override fun onActionItemClicked(m: ActionMode, item: MenuItem): Boolean {
c.actions.getOrNull(item.itemId)?.let { edit(Event.textCommand(wid, it)) }
m.finish()
return true
}
override fun onDestroyActionMode(m: ActionMode) { actionMode = null }
override fun onGetContentRect(m: ActionMode, v: View, out: Rect) { out.set(at) }
}, ActionMode.TYPE_FLOATING)
}
private var magnifier: Magnifier? = null // API 28
/** The system's magnifier of what is at a point. */
fun showMagnifier(c: ShowMagnifierCall) {
if (android.os.Build.VERSION.SDK_INT < 28) return
val m = magnifier ?: Magnifier.Builder(surface).build().also { magnifier = it }
m.show((c.x * density).toFloat(), (c.y * density).toFloat())
}
fun hideMagnifier() {
if (android.os.Build.VERSION.SDK_INT >= 28) magnifier?.dismiss()
}
fun accessibilityChanged(focus: Long) {
nodes = null
surface.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED)
}
private fun tree(): List<Node> {
nodes?.let { return it }
val r = Go.ask(Event.accessibilityTree(wid)) ?: return emptyList()
val n = Node.decode(AccessibilityTreeReply(r).nodes)
nodes = n
return n
}
private inner class Surface(context: Context) : SurfaceView(context), SurfaceHolder.Callback {
init {
holder.addCallback(this)
isFocusable = true
isFocusableInTouchMode = true
}
override fun surfaceCreated(h: SurfaceHolder) {
native = MyGoNative.nativeWindow(h.surface)
val hz = display?.supportedModes?.maxOfOrNull { it.refreshRate }?.toDouble() ?: display?.refreshRate?.toDouble() ?: 60.0
Go.send(Event.surfaceChanged(wid, native, width / density, height / density, density, hz))
}
override fun surfaceChanged(h: SurfaceHolder, format: Int, w: Int, ht: Int) {
preferFastest(h)
reportSize()
requestFrame()
}
/** Asks the display for its fastest refresh, which Choreographer then gives. */
private fun preferFastest(h: SurfaceHolder) {
if (android.os.Build.VERSION.SDK_INT < 30) return
val modes = display?.supportedModes ?: return
val hz = modes.maxOfOrNull { it.refreshRate } ?: return
runCatching { h.surface.setFrameRate(hz, android.view.Surface.FRAME_RATE_COMPATIBILITY_DEFAULT) }
}
// A mouse's pointer hovers.
override fun onHoverEvent(e: MotionEvent): Boolean {
val d = density
val phase = if (e.actionMasked == MotionEvent.ACTION_HOVER_EXIT) "cancel" else "move"
Go.send(Event.touch(wid, 0, phase, "mouse", e.x / d, e.y / d, 0.0, 0, e.eventTime / 1000.0))
return true
}
override fun surfaceDestroyed(h: SurfaceHolder) = releaseNative()
// A finger on a view it holds passes through to it, under this view.
override fun dispatchTouchEvent(e: MotionEvent): Boolean {
if (e.actionMasked == MotionEvent.ACTION_DOWN && heldTakes(e)) return false
return super.dispatchTouchEvent(e)
}
override fun onTouchEvent(e: MotionEvent): Boolean {
val d = density
fun send(i: Int, phase: String) {
val kind = when (e.getToolType(i)) {
MotionEvent.TOOL_TYPE_MOUSE -> "mouse"
MotionEvent.TOOL_TYPE_STYLUS -> "pen"
else -> "touch"
}
Go.send(Event.touch(wid, e.getPointerId(i).toLong(), phase, kind, e.getX(i) / d, e.getY(i) / d,
e.getPressure(i).toDouble(), e.buttonState.toLong().coerceAtLeast(1), e.eventTime / 1000.0))
}
when (e.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> send(e.actionIndex, "down")
MotionEvent.ACTION_MOVE -> for (i in 0 until e.pointerCount) send(i, "move")
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> send(e.actionIndex, "up")
MotionEvent.ACTION_CANCEL -> for (i in 0 until e.pointerCount) send(i, "cancel")
}
return true
}
override fun onGenericMotionEvent(e: MotionEvent): Boolean {
if (e.isFromSource(InputDevice.SOURCE_CLASS_POINTER) && e.actionMasked == MotionEvent.ACTION_SCROLL) {
val d = density
val line = 48.0
Go.send(Event.scroll(wid, e.x / d, e.y / d, -e.getAxisValue(MotionEvent.AXIS_HSCROLL) * line,
-e.getAxisValue(MotionEvent.AXIS_VSCROLL) * line, false, ""))
return true
}
return super.onGenericMotionEvent(e)
}
private fun key(code: Int, e: KeyEvent, down: Boolean): Boolean {
val name = keyNames[code] ?: e.unicodeChar.takeIf { it > 0 }?.let { String(Character.toChars(it)) } ?: return false
var mods = 0L
if (e.isShiftPressed) mods = mods or 1
if (e.isCtrlPressed) mods = mods or 2
if (e.isAltPressed) mods = mods or 4
if (e.isMetaPressed) mods = mods or 8
val text = if (e.unicodeChar > 0) String(Character.toChars(e.unicodeChar)) else ""
val r = Go.ask(Event.key(wid, down, name, text, mods, e.repeatCount > 0)) ?: return false
val handled = KeyReply(r).handled
// Keys typing text type it, which the content takes as text.
if (!handled && down && editing && text.isNotEmpty() && keyNames[code] == null) {
edit(Event.textReplace(wid, false, 0, 0, text))
return true
}
return handled
}
override fun onKeyDown(code: Int, e: KeyEvent) = key(code, e, true) || super.onKeyDown(code, e)
override fun onKeyUp(code: Int, e: KeyEvent) = key(code, e, false) || super.onKeyUp(code, e)
override fun onCheckIsTextEditor() = editing
override fun onCreateInputConnection(info: EditorInfo): InputConnection? {
if (!editing) return null
val c = input
info.inputType = inputType(c)
info.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN or when (c.returnKey) {
"go" -> EditorInfo.IME_ACTION_GO
"next" -> EditorInfo.IME_ACTION_NEXT
"search" -> EditorInfo.IME_ACTION_SEARCH
"send" -> EditorInfo.IME_ACTION_SEND
"done" -> EditorInfo.IME_ACTION_DONE
else -> if (c.multiline) EditorInfo.IME_ACTION_NONE else EditorInfo.IME_ACTION_DONE
}
if (c.multiline && c.returnKey.isEmpty()) info.imeOptions = info.imeOptions or EditorInfo.IME_FLAG_NO_ENTER_ACTION
info.initialSelStart = c.selStart.toInt()
info.initialSelEnd = c.selEnd.toInt()
info.packageName = context.packageName
return Connection(this)
}
override fun getAccessibilityNodeProvider(): AccessibilityNodeProvider = Provider()
// Autofill: to the system, the input in focus is the one field of a
// form of its own. The window's surface draws it: only this says what
// it is, so that saved passwords and codes from SMS reach it.
override fun onProvideAutofillVirtualStructure(s: android.view.ViewStructure, flags: Int) {
s.setClassName(javaClass.name)
val c = input
val hint = autofillHint(c)
if (!editing || hint == null) return
val child = s.newChild(s.addChildCount(1))
child.setAutofillId(s.autofillId!!, autofillNode)
child.setClassName("android.widget.EditText")
child.setAutofillType(AUTOFILL_TYPE_TEXT)
child.setAutofillHints(arrayOf(hint))
child.setInputType(inputType(c))
child.setDataIsSensitive(c.secure)
child.setVisibility(VISIBLE)
child.setFocused(true)
child.setFocusable(true)
child.setEnabled(true)
child.setDimens((c.x * density).toInt(), (c.y * density).toInt(), 0, 0, (c.width * density).toInt(), (c.height * density).toInt())
child.setAutofillValue(android.view.autofill.AutofillValue.forText(wholeText(c)))
}
override fun autofill(values: android.util.SparseArray<android.view.autofill.AutofillValue>) {
val v = values.get(autofillNode) ?: return
if (!editing || !v.isText) return
edit(Event.textReplace(wid, true, 0, input.length, v.textValue.toString()))
}
}
/** The hint of Android's autofill for an input's traits, null for none. */
private fun autofillHint(c: SetTextInputCall): String? = when (c.autofill) {
"username" -> View.AUTOFILL_HINT_USERNAME
"password", "newPassword" -> View.AUTOFILL_HINT_PASSWORD
"oneTimeCode" -> "smsOTPCode" // androidx.autofill's HintConstants
"email" -> View.AUTOFILL_HINT_EMAIL_ADDRESS
"name" -> View.AUTOFILL_HINT_NAME
"phone" -> View.AUTOFILL_HINT_PHONE
"address" -> View.AUTOFILL_HINT_POSTAL_ADDRESS
"postalCode" -> View.AUTOFILL_HINT_POSTAL_CODE
"creditCard" -> View.AUTOFILL_HINT_CREDIT_CARD_NUMBER
else -> null
}
/** The input's whole text, which the host's copy may hold only part of. */
private fun wholeText(c: SetTextInputCall): String =
if (c.base == 0L && c.text.length.toLong() == c.length) c.text else document(0, c.length.toInt()).toString()
/** Tells the system's autofill what the input did, for those it knows of. */
private fun tellAutofill(was: SetTextInputCall, c: SetTextInputCall) {
val am = context.getSystemService(android.view.autofill.AutofillManager::class.java) ?: return
val had = was.active && autofillHint(was) != null
val has = c.active && autofillHint(c) != null
val another = c.serial != was.serial || !was.active
if (had && (!c.active || another)) {
am.notifyViewExited(surface, autofillNode)
// A form sent or left: the system may offer to save what it holds.
if (was.secure && was.length > 0 && !has) am.commit()
}
if (has && (!had || another)) {
val at = IntArray(2)
surface.getLocationOnScreen(at)
val x = at[0] + (c.x * density).toInt()
val y = at[1] + (c.y * density).toInt()
val r = Rect(x, y, x + (c.width * density).toInt(), y + (c.height * density).toInt())
surface.importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES
am.notifyViewEntered(surface, autofillNode, r)
}
}
/** The inputType of EditorInfo for an input's traits. */
private fun inputType(c: SetTextInputCall): Int {
var t = when (c.keyboard) {
"number" -> InputType.TYPE_CLASS_NUMBER
"decimal" -> InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED
"phone" -> InputType.TYPE_CLASS_PHONE
"email" -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
"url" -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
else -> InputType.TYPE_CLASS_TEXT
}
if (c.secure) {
t = if (t and InputType.TYPE_MASK_CLASS == InputType.TYPE_CLASS_NUMBER) {
InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
} else {
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
}
return t
}
if (t and InputType.TYPE_MASK_CLASS != InputType.TYPE_CLASS_TEXT) return t
if (c.multiline) t = t or InputType.TYPE_TEXT_FLAG_MULTI_LINE
val plain = c.keyboard.isEmpty() || c.keyboard == "search"
t = t or when (c.capitalize) {
"characters" -> InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS
"words" -> InputType.TYPE_TEXT_FLAG_CAP_WORDS
"sentences" -> InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
"none" -> 0
else -> if (plain) InputType.TYPE_TEXT_FLAG_CAP_SENTENCES else 0
}
t = t or when (c.autocorrect) {
"off" -> InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
"on" -> InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
else -> if (plain) InputType.TYPE_TEXT_FLAG_AUTO_CORRECT else 0
}
return t
}
/** The soft keyboard's edits, to Go. */
private inner class Connection(v: View) : BaseInputConnection(v, false) {
override fun commitText(t: CharSequence, newCursorPosition: Int): Boolean {
edit(Event.textReplace(wid, false, 0, 0, t.toString()))
placeCursor(t.length, newCursorPosition)
return true
}
override fun commitCompletion(c: android.view.inputmethod.CompletionInfo): Boolean {
c.text?.let { edit(Event.textReplace(wid, false, 0, 0, it.toString())) }
return true
}
override fun commitCorrection(c: android.view.inputmethod.CorrectionInfo): Boolean {
val at = c.offset.toLong()
edit(Event.textReplace(wid, true, at, at + c.oldText.length, c.newText.toString()))
return true
}
override fun setComposingText(t: CharSequence, newCursorPosition: Int): Boolean {
// The selection in the text composed, from the cursor Android
// places relative to it: past it, the common case, or before.
val n = t.length.toLong()
val at = if (newCursorPosition > 0) n else 0L
edit(Event.textMark(wid, false, 0, 0, t.toString(), at, at))
return true
}
override fun setComposingRegion(start: Int, end: Int): Boolean {
val a = minOf(start, end).coerceAtLeast(0)
val b = maxOf(start, end).coerceAtMost(input.length.toInt())
val text = document(a, b).toString()
val n = text.length.toLong()
edit(Event.textMark(wid, true, a.toLong(), b.toLong(), text, n, n))
return true
}
override fun finishComposingText(): Boolean {
edit(Event.textUnmark(wid))
return true
}
override fun deleteSurroundingText(before: Int, after: Int): Boolean {
edit(Event.textDelete(wid, before.toLong(), after.toLong()))
return true
}
override fun deleteSurroundingTextInCodePoints(before: Int, after: Int): Boolean {
// Units of the text around the selection.
val a = minOf(input.selStart, input.selEnd).toInt()
val b = maxOf(input.selStart, input.selEnd).toInt()
val head = document(maxOf(0, a - 2 * before), a).toString()
val tail = document(b, minOf(input.length.toInt(), b + 2 * after)).toString()
val units = head.length - head.offsetByCodePoints(head.length, -minOf(before, head.codePointCount(0, head.length)))
val unitsAfter = tail.offsetByCodePoints(0, minOf(after, tail.codePointCount(0, tail.length)))
edit(Event.textDelete(wid, units.toLong(), unitsAfter.toLong()))
return true
}
override fun setSelection(start: Int, end: Int): Boolean {
edit(Event.textSelect(wid, start.toLong(), end.toLong()))
return true
}
private fun placeCursor(committed: Int, newCursorPosition: Int) {
// Past the text, as nearly all input methods ask, is where the
// insertion leaves it.
if (newCursorPosition == 1) return
val end = input.selEnd.toInt()
val at = if (newCursorPosition > 0) end + newCursorPosition - 1 else end - committed + newCursorPosition
val p = at.coerceIn(0, input.length.toInt()).toLong()
edit(Event.textSelect(wid, p, p))
}
override fun sendKeyEvent(e: KeyEvent): Boolean {
if (e.action == KeyEvent.ACTION_DOWN) when (e.keyCode) {
KeyEvent.KEYCODE_DEL -> edit(Event.textCommand(wid, "deleteBackward"))
KeyEvent.KEYCODE_FORWARD_DEL -> edit(Event.textCommand(wid, "deleteForward"))
KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> edit(Event.textCommand(wid, "newline"))
KeyEvent.KEYCODE_TAB -> edit(Event.textCommand(wid, "tab"))
KeyEvent.KEYCODE_DPAD_LEFT -> edit(Event.textCommand(wid, "left"))
KeyEvent.KEYCODE_DPAD_RIGHT -> edit(Event.textCommand(wid, "right"))
KeyEvent.KEYCODE_DPAD_UP -> edit(Event.textCommand(wid, "up"))
KeyEvent.KEYCODE_DPAD_DOWN -> edit(Event.textCommand(wid, "down"))
else -> if (e.unicodeChar > 0) edit(Event.textReplace(wid, false, 0, 0, String(Character.toChars(e.unicodeChar))))
}
return true
}
override fun performEditorAction(action: Int): Boolean {
edit(Event.textCommand(wid, "newline"))
return true
}
override fun performContextMenuAction(action: Int): Boolean {
when (action) {
android.R.id.selectAll -> edit(Event.textCommand(wid, "selectAll"))
android.R.id.cut -> edit(Event.textCommand(wid, "cut"))
android.R.id.copy -> edit(Event.textCommand(wid, "copy"))
android.R.id.paste -> edit(Event.textCommand(wid, "paste"))
else -> return false
}
return true
}
override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence {
val a = minOf(input.selStart, input.selEnd).toInt()
return document(maxOf(0, a - n), a)
}
override fun getTextAfterCursor(n: Int, flags: Int): CharSequence {
val b = maxOf(input.selStart, input.selEnd).toInt()
return document(b, minOf(input.length.toInt(), b + n))
}
override fun getSelectedText(flags: Int): CharSequence? {
val a = minOf(input.selStart, input.selEnd).toInt()
val b = maxOf(input.selStart, input.selEnd).toInt()
return if (a == b) null else document(a, b)
}
override fun getExtractedText(req: android.view.inputmethod.ExtractedTextRequest?, flags: Int): android.view.inputmethod.ExtractedText {
val c = input
return android.view.inputmethod.ExtractedText().apply {
text = c.text
startOffset = c.base.toInt()
selectionStart = c.selStart.toInt() - c.base.toInt()
selectionEnd = c.selEnd.toInt() - c.base.toInt()
}
}
override fun getCursorCapsMode(reqModes: Int): Int {
val a = minOf(input.selStart, input.selEnd).toInt()
return android.text.TextUtils.getCapsMode(document(maxOf(0, a - 64), a).toString(), minOf(a, 64), reqModes)
}
}
/** The element TalkBack's cursor is on. */
private var accessFocus = View.NO_ID
private fun sendVirtual(id: Int, type: Int) {
val e = AccessibilityEvent(type)
e.packageName = context.packageName
e.setSource(surface, id)
(surface.parent as? android.view.ViewGroup)?.requestSendAccessibilityEvent(surface, e)
}
/** TalkBack's view of the elements of native UI, as virtual views. */
private inner class Provider : AccessibilityNodeProvider() {
override fun createAccessibilityNodeInfo(virtualId: Int): AccessibilityNodeInfo? {
val nodes = tree()
if (virtualId == View.NO_ID) {
val info = AccessibilityNodeInfo.obtain(surface)
surface.onInitializeAccessibilityNodeInfo(info)
for (n in nodes) info.addChild(surface, n.id.toInt())
return info
}
val n = nodes.firstOrNull { it.id.toInt() == virtualId } ?: return null
val info = AccessibilityNodeInfo.obtain(surface, virtualId)
info.setParent(surface)
info.packageName = context.packageName
info.className = n.className
if (n.role == 9L) {
// A text field: its text, under its name's hint, as EditText.
info.isEditable = true
info.text = n.value.ifEmpty { null }
info.hintText = n.label
info.isShowingHintText = n.value.isEmpty()
info.isPassword = n.states and 128 != 0L
} else {
info.text = n.label.ifEmpty { null }
if (n.value.isNotEmpty()) info.stateDescription = n.value
}
if (n.hint.isNotEmpty()) info.tooltipText = n.hint
val d = density
val box = Rect((n.x * d).toInt(), (n.y * d).toInt(), ((n.x + n.w) * d).toInt(), ((n.y + n.h) * d).toInt())
val loc = IntArray(2)
surface.getLocationOnScreen(loc)
box.offset(loc[0], loc[1])
info.setBoundsInScreen(box)
info.isEnabled = n.states and 2 == 0L
info.isChecked = n.states and 4 != 0L
info.isCheckable = n.role in longArrayOf(4, 5, 6, 31)
info.isSelected = n.states and 16 != 0L
info.isHeading = n.role == 43L
info.isVisibleToUser = true
info.isFocusable = true
info.isAccessibilityFocused = accessFocus == virtualId
info.addAction(if (accessFocus == virtualId) AccessibilityNodeInfo.AccessibilityAction.ACTION_CLEAR_ACCESSIBILITY_FOCUS
else AccessibilityNodeInfo.AccessibilityAction.ACTION_ACCESSIBILITY_FOCUS)
if (n.actions and 1 != 0L) {
info.isClickable = true
info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK)
}
if (n.actions and 4 != 0L) info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD)
if (n.actions and 8 != 0L) info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD)
return info
}
override fun performAction(virtualId: Int, action: Int, args: Bundle?): Boolean {
val name = when (action) {
AccessibilityNodeInfo.ACTION_CLICK -> "press"
AccessibilityNodeInfo.ACTION_SCROLL_FORWARD -> "increment"
AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD -> "decrement"
AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS -> {
if (accessFocus != virtualId) {
val old = accessFocus
accessFocus = virtualId
if (old != View.NO_ID) sendVirtual(old, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED)
sendVirtual(virtualId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED)
}
return true
}
AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS -> {
if (accessFocus == virtualId) {
accessFocus = View.NO_ID
sendVirtual(virtualId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED)
}
return true
}
else -> return false
}
val r = Go.ask(Event.accessibilityAction(wid, virtualId.toLong(), name)) ?: return false
return AccessibilityActionReply(r).handled
}
}
companion object {
private val keyNames = mapOf(
KeyEvent.KEYCODE_ENTER to "Enter", KeyEvent.KEYCODE_ESCAPE to "Escape", KeyEvent.KEYCODE_DEL to "Backspace",
KeyEvent.KEYCODE_TAB to "Tab", KeyEvent.KEYCODE_SPACE to "Space", KeyEvent.KEYCODE_FORWARD_DEL to "Delete",
KeyEvent.KEYCODE_MOVE_HOME to "Home", KeyEvent.KEYCODE_MOVE_END to "End", KeyEvent.KEYCODE_PAGE_UP to "PageUp",
KeyEvent.KEYCODE_PAGE_DOWN to "PageDown", KeyEvent.KEYCODE_DPAD_LEFT to "ArrowLeft",
KeyEvent.KEYCODE_DPAD_RIGHT to "ArrowRight", KeyEvent.KEYCODE_DPAD_UP to "ArrowUp", KeyEvent.KEYCODE_DPAD_DOWN to "ArrowDown",
)
}
}
/** An element of native UI, as Go encodes it (AccessibilityTree). */
class Node(
val id: Long, val parent: Long, val role: Long, val label: String, val value: String, val hint: String,
val x: Double, val y: Double, val w: Double, val h: Double, val states: Long, val actions: Long,
) {
val className: String
get() = when (role) {
2L, 31L, 40L, 18L -> "android.widget.Button"
4L -> "android.widget.CheckBox"
5L -> "android.widget.RadioButton"
6L -> "android.widget.Switch"
7L -> "android.widget.SeekBar"
8L -> "android.widget.ProgressBar"
9L -> "android.widget.EditText"
10L -> "android.widget.ImageView"
else -> "android.view.View"
}
companion object {
fun decode(b: ByteArray): List<Node> {
val r = WireReader(b)
val out = ArrayList<Node>()
while (true) {
val n = Node(r.int(), r.int(), r.int(), r.string(), r.string(), r.string(),
r.float(), r.float(), r.float(), r.float(), r.int(), r.int())
r.int() // the level
if (n.id == 0L) break
// Groups without a name hold others, which TalkBack reads.
if (n.role == 0L && n.label.isEmpty() && n.value.isEmpty()) continue
out.add(n)
}
return out
}
}
}
@@ -0,0 +1,182 @@
package dev.mygo
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.os.Build
import java.io.File
import java.nio.ByteBuffer
import kotlin.math.ceil
import kotlin.math.floor
/**
* Text of native UI, measured and drawn as a TextView measures and draws
* it: Minikin lays it out, Skia draws it. Go breaks lines itself and asks
* how wide words are (getTextRunAdvances) and what a cluster looks like
* (drawText).
*/
object Text {
private val registered = HashMap<String, Typeface>()
private val faces = HashMap<String, Typeface>()
private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG)
private val bounds = Rect()
private var bitmap: Bitmap? = null
/** The typeface of a CSS-like list of families, at a weight. */
private fun typeface(families: String, weight: Long, italic: Boolean): Typeface {
val key = "$families|$weight|$italic"
faces[key]?.let { return it }
var base: Typeface? = null
for (raw in families.split(',')) {
val f = raw.trim().trim('"', '\'')
base = registered[f] ?: when (f.lowercase()) {
"", "system-ui", "sans-serif", "ui-sans-serif", "-apple-system" -> Typeface.SANS_SERIF
"serif", "ui-serif" -> Typeface.SERIF
"monospace", "ui-monospace" -> Typeface.MONOSPACE
else -> Typeface.create(f, Typeface.NORMAL).takeIf { it != Typeface.DEFAULT }
}
if (base != null) break
}
val face = if (Build.VERSION.SDK_INT >= 28) {
Typeface.create(base ?: Typeface.SANS_SERIF, weight.toInt().coerceIn(1, 1000), italic)
} else {
Typeface.create(base ?: Typeface.SANS_SERIF, (if (weight >= 600) Typeface.BOLD else 0) or (if (italic) Typeface.ITALIC else 0))
}
if (faces.size > 256) faces.clear()
faces[key] = face
return face
}
private fun set(family: String, size: Double, weight: Long, italic: Boolean, noKern: Boolean = false): Paint {
paint.typeface = typeface(family, weight, italic)
paint.textSize = size.toFloat()
// Go draws clusters alone, which ligatures would join: "fl" would
// take the advance of both, and draw as an f before a gap.
paint.fontFeatureSettings = if (noKern) "'liga' 0, 'clig' 0, 'kern' 0" else "'liga' 0, 'clig' 0"
paint.color = Color.WHITE
return paint
}
@Synchronized
fun metrics(c: TextMetricsCall): TextMetricsReply {
val p = set(c.family, c.size, c.weight, c.italic)
val m = p.fontMetrics
val r = TextMetricsReply()
r.ascent = -m.ascent.toDouble()
r.descent = m.descent.toDouble()
p.getTextBounds("x", 0, 1, bounds)
r.xHeight = -bounds.top.toDouble()
if (Build.VERSION.SDK_INT >= 29) {
r.underlinePosition = p.underlinePosition.toDouble()
r.underlineThickness = p.underlineThickness.toDouble()
r.strikePosition = -p.strikeThruPosition.toDouble()
} else {
r.underlinePosition = c.size / 10
r.underlineThickness = maxOf(c.size / 14, 1.0)
r.strikePosition = r.xHeight / 2
}
return r
}
@Synchronized
fun measure(c: MeasureTextCall): MeasureTextReply {
val p = set(c.family, c.size, c.weight, c.italic, c.noKern)
val r = MeasureTextReply()
r.widths = DoubleArray(c.texts.size) { i ->
val t = c.texts[i]
p.getRunAdvance(t, 0, t.length, 0, t.length, false, t.length).toDouble()
}
return r
}
@Synchronized
fun advances(c: TextAdvancesCall): TextAdvancesReply {
val p = set(c.family, c.size, c.weight, c.italic, c.noKern)
val chars = c.text.toCharArray()
val out = FloatArray(chars.size)
p.getTextRunAdvances(chars, 0, chars.size, 0, chars.size, c.rtl, out, 0)
val r = TextAdvancesReply()
r.advances = DoubleArray(out.size) { out[it].toDouble() }
return r
}
@Synchronized
fun draw(c: DrawTextCall): DrawTextReply {
val r = DrawTextReply()
if (c.text.isBlank()) return r
// The font at the size text was measured at, the canvas scaled, as
// the measurements were made.
val p = set(c.family, c.size, c.weight, c.italic)
p.getTextBounds(c.text, 0, c.text.length, bounds)
val s = c.scale
val pad = 2
val left = floor(bounds.left * s + c.dx).toInt() - pad
val right = ceil(bounds.right * s + c.dx).toInt() + pad
val top = floor(bounds.top * s).toInt() - pad
val bottom = ceil(bounds.bottom * s).toInt() + pad
val w = right - left
val h = bottom - top
if (w <= 2 * pad || h <= 2 * pad || w > 2048 || h > 2048) return r
var bm = bitmap
if (bm == null || bm.width < w || bm.height < h) {
bm?.recycle()
bm = Bitmap.createBitmap(maxOf(w, bm?.width ?: 0, 64), maxOf(h, bm?.height ?: 0, 64), Bitmap.Config.ARGB_8888)
bitmap = bm
}
bm!!.eraseColor(Color.TRANSPARENT)
val canvas = Canvas(bm)
canvas.translate((c.dx - left).toFloat(), (-top).toFloat())
canvas.scale(s.toFloat(), s.toFloat())
canvas.drawText(c.text, 0f, 0f, p)
val buf = ByteBuffer.allocate(bm.byteCount)
bm.copyPixelsToBuffer(buf)
val px = buf.array()
val stride = bm.width * 4
// White text is as covered as it is opaque; other colors are an
// emoji's.
var color = false
loop@ for (y in 0 until h) for (x in 0 until w) {
val i = y * stride + x * 4
val a = px[i + 3].toInt() and 0xff
if (a > 32) {
val far = { v: Int -> v < a - 24 }
if (far(px[i].toInt() and 0xff) || far(px[i + 1].toInt() and 0xff) || far(px[i + 2].toInt() and 0xff)) {
color = true
break@loop
}
}
}
r.left = left.toLong()
r.top = top.toLong()
r.width = w.toLong()
r.height = h.toLong()
r.color = color
r.pixels = if (color) {
ByteArray(w * h * 4).also { out -> for (y in 0 until h) System.arraycopy(px, y * stride, out, y * w * 4, w * 4) }
} else {
ByteArray(w * h) { k -> px[(k / w) * stride + (k % w) * 4 + 3] }
}
return r
}
@Synchronized
fun register(c: RegisterFontCall): RegisterFontReply {
val r = RegisterFontReply()
try {
val f = File.createTempFile("font", ".ttf", HostImpl.app.cacheDir)
f.writeBytes(c.data)
val face = Typeface.createFromFile(f)
f.delete()
val family = c.family.ifEmpty { "font${registered.size + 1}" }
registered[family] = face
faces.clear()
r.family = family
} catch (e: Exception) {
r.error = "mygo: ${e.message}"
}
return r
}
}
@@ -0,0 +1,499 @@
// Windows showing web pages, in Android's WebView.
package dev.mygo
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.PermissionRequest
import android.webkit.RenderProcessGoneDetail
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.webkit.ScriptHandler
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
class WebWindow(context: Context, c: CreateWindowCall) : HostWindow(context, c.id) {
private val frame = FrameLayout(context)
override val view: View get() = frame
val web = WebView(context)
private val schemes = c.schemes.toSet()
private var scripts = ArrayList<ScriptHandler>()
private var defaultUA = ""
private var suffix = c.userAgentSuffix
private val ui = Handler(Looper.getMainLooper())
init {
val s = web.settings
s.javaScriptEnabled = true
s.domStorageEnabled = true
s.databaseEnabled = true
s.mediaPlaybackRequiresUserGesture = !c.autoplay
s.setSupportMultipleWindows(true)
s.javaScriptCanOpenWindowsAutomatically = true
s.setSupportZoom(c.pinchZoom)
s.builtInZoomControls = c.pinchZoom
s.displayZoomControls = false
defaultUA = s.userAgentString
setUserAgent(c.userAgent)
WebView.setWebContentsDebuggingEnabled(c.inspectable)
web.addJavascriptInterface(Bridge(this), "mygoAndroid")
web.webViewClient = Client()
web.webChromeClient = Chrome()
setScripts(c.scripts, c.scriptFlags)
if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
WebViewCompat.addDocumentStartJavaScript(web, Schemes.bodyScript, setOf("*"))
}
// The web view's own background, which the bars around it take,
// until the app gives one.
val dark = context.resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK ==
android.content.res.Configuration.UI_MODE_NIGHT_YES
fill = if (dark) 0xFF121212.toInt() else android.graphics.Color.WHITE
frame.addView(web, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
}
/** Lays the page out inside the system's bars and above the keyboard. */
override fun insetsChanged() {
val c = covered()
val lp = web.layoutParams as FrameLayout.LayoutParams
if (lp.leftMargin != c[1] || lp.topMargin != c[0] || lp.rightMargin != c[3] || lp.bottomMargin != maxOf(c[2], c[4])) {
lp.setMargins(c[1], c[0], c[3], maxOf(c[2], c[4]))
web.layoutParams = lp
}
reportSize()
}
override fun setBackground(argb: Int) {
frame.setBackgroundColor(argb)
web.setBackgroundColor(argb)
}
fun setUserAgent(ua: String) {
var v = ua.ifEmpty { defaultUA }
if (suffix.isNotEmpty()) v += " $suffix"
web.settings.userAgentString = v
}
fun setScripts(sources: List<String>, flags: List<String>) {
for (h in scripts) h.remove()
scripts = ArrayList()
if (!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) return
for ((i, src) in sources.withIndex()) {
val f = flags.getOrElse(i) { "" }
var js = src
if (f.contains('e')) js = "document.readyState==='loading'?document.addEventListener('DOMContentLoaded',function(){$js},{once:true}):(function(){$js})();"
if (!f.contains('a')) js = "if(window===window.top){$js}"
scripts.add(WebViewCompat.addDocumentStartJavaScript(web, js, setOf("*")))
}
}
fun load(url: String) {
web.loadUrl(url)
}
fun loadHTML(html: String, base: String) {
web.loadDataWithBaseURL(base.ifEmpty { null }, html, "text/html", "utf-8", null)
}
fun callAsync(req: Long, body: String) {
val js = "(function(){var r=$req;try{var F=Object.getPrototypeOf(async function(){}).constructor;" +
"new F(${JSONObject.quote(body)})().then(function(v){mygoAndroid.asyncResult(r,String(v),'')}," +
"function(e){mygoAndroid.asyncResult(r,'',String(e&&e.message||e))})}catch(e){mygoAndroid.asyncResult(r,'',String(e&&e.message||e))}})()"
web.evaluateJavascript(js, null)
}
fun capture(req: Long) {
if (web.width == 0 || web.height == 0) {
Go.send(Event.captured(req, ByteArray(0), "mygo: the page shows nothing"))
return
}
val bmp = Bitmap.createBitmap(web.width, web.height, Bitmap.Config.ARGB_8888)
web.draw(Canvas(bmp))
val out = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.PNG, 100, out)
bmp.recycle()
Go.send(Event.captured(req, out.toByteArray(), ""))
}
override fun close() {
web.stopLoading()
web.removeJavascriptInterface("mygoAndroid")
web.destroy()
}
private fun reportState() {
Go.send(Event.pageState(id, web.url ?: "", web.title ?: "", web.progress < 100, web.canGoBack(), web.canGoForward()))
HostImpl.updateBack()
}
/** Whether url is one of the app's schemes, served at https://<scheme>.localhost. */
private fun appHost(url: Uri): Boolean {
val host = url.host ?: return false
if (url.scheme != "https" || !host.endsWith(".localhost")) return false
val rest = host.removeSuffix(".localhost")
return schemes.any { rest == it || rest.endsWith(".$it") }
}
private class Bridge(val w: WebWindow) {
@JavascriptInterface
fun postMessage(text: String) = Go.send(Event.message(w.id, text))
@JavascriptInterface
fun asyncResult(req: Long, result: String, error: String) = Go.send(Event.asyncResult(req, result, error))
/** The body of a request to the app's schemes, which Android does not give shouldInterceptRequest. */
@JavascriptInterface
fun putBody(id: String, base64: String) = Schemes.putBody(id, base64)
}
private inner class Client : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, r: WebResourceRequest): Boolean {
val url = r.url
val scheme = url.scheme?.lowercase()
if (scheme != "http" && scheme != "https" && scheme != "about" && scheme != "data" && scheme != "blob" && scheme != "javascript") {
// mailto:, tel:, other apps' links.
try {
(HostImpl.activity ?: context).startActivity(Intent(Intent.ACTION_VIEW, url))
} catch (_: Exception) {
}
return true
}
if (!r.isForMainFrame) return false
val reply = Go.ask(Event.willNavigate(id, url.toString(), true, r.hasGesture(), r.isRedirect, false))
return reply != null && !WillNavigateReply(reply).allow
}
// Android's web view starts a page as it commits it: the page's
// scripts run after, and the core trusts them by the committed URL.
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
Go.send(Event.navigationStarted(id, url))
Go.send(Event.navigationCommitted(id, url))
reportState()
}
override fun onPageCommitVisible(view: WebView, url: String) {
HostImpl.drew = true
}
override fun onPageFinished(view: WebView, url: String) {
reportState()
Go.send(Event.loadFinished(id))
}
override fun doUpdateVisitedHistory(view: WebView, url: String, isReload: Boolean) = reportState()
override fun onReceivedError(view: WebView, r: WebResourceRequest, e: WebResourceError) {
if (r.isForMainFrame) Go.send(Event.loadFailed(id, r.url.toString(), e.errorCode.toLong(), e.description.toString()))
}
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
Go.send(Event.processGone(id, if (detail.didCrash()) "crashed" else "killed"))
return true
}
override fun shouldInterceptRequest(view: WebView, r: WebResourceRequest): WebResourceResponse? {
if (!appHost(r.url)) return null
return Schemes.request(id, r)
}
}
private inner class Chrome : WebChromeClient() {
override fun onReceivedTitle(view: WebView, title: String?) = reportState()
// The page's console, in the app's log, as the inspector shows it.
override fun onConsoleMessage(m: android.webkit.ConsoleMessage): Boolean {
val level = when (m.messageLevel()) {
android.webkit.ConsoleMessage.MessageLevel.ERROR -> android.util.Log.ERROR
android.webkit.ConsoleMessage.MessageLevel.WARNING -> android.util.Log.WARN
else -> android.util.Log.INFO
}
android.util.Log.println(level, "mygo", "console: ${m.message()} (${m.sourceId()}:${m.lineNumber()})")
return true
}
override fun onCreateWindow(view: WebView, dialog: Boolean, gesture: Boolean, msg: Message): Boolean {
// The page's new window: its URL comes with the first load of a
// web view made for it, which the app's window then takes.
val probe = WebView(view.context)
probe.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(v: WebView, r: WebResourceRequest): Boolean {
val url = r.url.toString()
val reply = Go.ask(Event.newWindow(id, url, gesture))
if (reply == null || !NewWindowReply(reply).handled) {
if (gesture) try {
(HostImpl.activity ?: context).startActivity(Intent(Intent.ACTION_VIEW, r.url))
} catch (_: Exception) {
}
}
v.destroy()
return true
}
}
(msg.obj as WebView.WebViewTransport).webView = probe
msg.sendToTarget()
return true
}
override fun onCloseWindow(window: WebView) {
Go.send(Event.closedByPage(id))
}
override fun onPermissionRequest(request: PermissionRequest) {
val kinds = request.resources.mapNotNull {
when (it) {
PermissionRequest.RESOURCE_VIDEO_CAPTURE -> "camera"
PermissionRequest.RESOURCE_AUDIO_CAPTURE -> "microphone"
else -> null
}
}
val reply = Go.ask(Event.permissionRequested(id, kinds, request.origin.toString()))
if (reply == null || !PermissionRequestedReply(reply).allow) {
request.deny()
return
}
// The system's permissions too, which the app's manifest declares.
val need = kinds.map { if (it == "camera") Manifest.permission.CAMERA else Manifest.permission.RECORD_AUDIO }
.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
val a = HostImpl.activity
if (need.isEmpty() || a == null) {
if (need.isEmpty()) request.grant(request.resources) else request.deny()
return
}
pendingPermission = request
a.requestPermissions(need.toTypedArray(), ASK_MEDIA)
}
// navigator.geolocation: the app's handler says, then the system's
// permission, which the app's manifest declares.
override fun onGeolocationPermissionsShowPrompt(origin: String, callback: android.webkit.GeolocationPermissions.Callback) {
val reply = Go.ask(Event.permissionRequested(id, listOf("geolocation"), origin))
if (reply == null || !PermissionRequestedReply(reply).allow) {
callback.invoke(origin, false, false)
return
}
PluginHost.requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)) {
callback.invoke(origin, it, false)
}
}
override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean {
val a = HostImpl.activity ?: return false
fileCallback?.onReceiveValue(null)
fileCallback = callback
return try {
@Suppress("DEPRECATION")
a.startActivityForResult(params.createIntent().putExtra(Intent.EXTRA_ALLOW_MULTIPLE, params.mode == FileChooserParams.MODE_OPEN_MULTIPLE), CHOOSE_FILE)
true
} catch (e: Exception) {
fileCallback = null
false
}
}
}
companion object {
private const val CHOOSE_FILE = 0x6d7b
private const val ASK_MEDIA = 0x6d7c
private var fileCallback: ValueCallback<Array<Uri>>? = null
private var pendingPermission: PermissionRequest? = null
fun activityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode != CHOOSE_FILE) return
fileCallback?.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data))
fileCallback = null
}
fun permissionsResult(requestCode: Int, results: IntArray) {
if (requestCode != ASK_MEDIA) return
val r = pendingPermission ?: return
pendingPermission = null
if (results.isNotEmpty() && results.all { it == PackageManager.PERMISSION_GRANTED }) r.grant(r.resources) else r.deny()
}
}
}
/**
* The app's schemes: Android's web view loads none of its own, so they
* are served at https://<scheme>.localhost, whose requests go to Go
* (shouldInterceptRequest, on a thread of the web view's), which answers
* with SchemeRespond, SchemeData and SchemeFinish. Android gives no body
* of a request: fetch and XMLHttpRequest put theirs aside (bodyScript).
*/
object Schemes {
private val next = AtomicLong()
private val pending = java.util.concurrent.ConcurrentHashMap<Long, Pending>()
private val bodies = java.util.concurrent.ConcurrentHashMap<String, ByteArray>()
private const val BODY_HEADER = "X-MyGo-Body"
fun putBody(id: String, base64: String) {
if (bodies.size > 64) bodies.clear() // bodies of requests that never came
bodies[id] = android.util.Base64.decode(base64, android.util.Base64.NO_WRAP)
}
/**
* Puts the bodies of fetch's and XMLHttpRequest's requests to the app's
* schemes (https URLs of the hosts under localhost) aside through putBody, and has the
* requests name them in a header, which request takes them back by.
*/
val bodyScript = """
(() => {
if (!window.mygoAndroid || window.__mygoBodies) return;
window.__mygoBodies = true;
const app = (u) => { try { const x = new URL(u, location.href); return x.protocol === 'https:' && x.hostname.endsWith('.localhost'); } catch (e) { return false; } };
const put = (buf) => {
const b = new Uint8Array(buf);
let s = '';
for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode.apply(null, b.subarray(i, i + 0x8000));
const id = Date.now().toString(36) + Math.random().toString(36).slice(2);
window.mygoAndroid.putBody(id, btoa(s));
return id;
};
const fetch0 = window.fetch;
window.fetch = async function (input, init) {
const req = new Request(input, init);
if (!app(req.url) || req.method === 'GET' || req.method === 'HEAD' || req.body === null) return fetch0.call(this, input, init);
const headers = new Headers(req.headers);
headers.set('$BODY_HEADER', put(await req.arrayBuffer()));
return fetch0.call(this, req.url, { method: req.method, headers, credentials: req.credentials, cache: req.cache,
redirect: req.redirect, referrer: req.referrer, signal: req.signal, mode: req.mode });
};
const open0 = XMLHttpRequest.prototype.open, send0 = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (method, url, async) {
this.__mygo = { method: String(method).toUpperCase(), url: String(url), async: async !== false };
return open0.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function (body) {
const m = this.__mygo;
if (!m || !m.async || body == null || m.method === 'GET' || m.method === 'HEAD' || !app(m.url)) return send0.call(this, body);
const r = new Response(body), type = r.headers.get('content-type');
r.arrayBuffer().then((buf) => {
if (type) try { this.setRequestHeader('Content-Type', type); } catch (e) {}
this.setRequestHeader('$BODY_HEADER', put(buf));
send0.call(this);
});
};
})();
"""
private class Pending {
val responded = CountDownLatch(1)
var status = 200
var header = HashMap<String, String>()
val body = BodyStream()
}
fun request(window: Long, r: WebResourceRequest): WebResourceResponse {
val req = next.incrementAndGet()
val p = Pending()
pending[req] = p
val header = ArrayList<String>()
var body: ByteArray? = null
for ((k, v) in r.requestHeaders) {
if (k.equals(BODY_HEADER, true)) {
body = bodies.remove(v)
continue
}
header.add(k)
header.add(v)
}
Go.send(Event.schemeRequest(window, req, r.method, r.url.toString(), header, body ?: ByteArray(0), body != null))
if (!p.responded.await(60, TimeUnit.SECONDS)) {
pending.remove(req)
Go.send(Event.schemeCancel(req))
return WebResourceResponse("text/plain", "utf-8", 504, "Gateway Timeout", emptyMap(), "".byteInputStream())
}
val type = p.header.entries.firstOrNull { it.key.equals("Content-Type", true) }?.value ?: "application/octet-stream"
val mime = type.substringBefore(';').trim()
val charset = Regex("charset=([^;]+)", RegexOption.IGNORE_CASE).find(type)?.groupValues?.get(1)?.trim()
// A WebResourceResponse takes no redirect.
val status = if (p.status in 300..399) 200 else p.status
return WebResourceResponse(mime, charset, status, reason(status), p.header, p.body)
}
private fun reason(status: Int) = when (status) {
200 -> "OK"; 204 -> "No Content"; 206 -> "Partial Content"; 304 -> "Not Modified"
400 -> "Bad Request"; 403 -> "Forbidden"; 404 -> "Not Found"; 500 -> "Internal Server Error"
else -> "Status $status"
}
fun respond(c: SchemeRespondCall) {
val p = pending[c.req] ?: return
p.status = c.status.toInt()
var i = 0
while (i + 1 < c.header.size) {
val k = c.header[i]
p.header[k] = p.header[k]?.let { it + ", " + c.header[i + 1] } ?: c.header[i + 1]
i += 2
}
p.responded.countDown()
}
fun data(req: Long, data: ByteArray) {
pending[req]?.body?.queue?.put(data)
}
fun finish(req: Long, error: String?) {
val p = pending.remove(req) ?: return
if (p.responded.count > 0) {
p.status = 500
p.responded.countDown()
}
p.body.queue.put(ByteArray(0))
}
/** The body of a response, as Go writes it; an empty piece ends it. */
private class BodyStream : InputStream() {
val queue = LinkedBlockingQueue<ByteArray>()
private var cur = ByteArray(0)
private var at = 0
private var done = false
private fun fill(): Boolean {
while (at >= cur.size) {
if (done) return false
cur = queue.take()
at = 0
if (cur.isEmpty()) {
done = true
return false
}
}
return true
}
override fun read(): Int = if (fill()) cur[at++].toInt() and 0xff else -1
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (len == 0) return 0
if (!fill()) return -1
val n = minOf(len, cur.size - at)
System.arraycopy(cur, at, b, off, n)
at += n
return n
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,5 @@
<paths>
<files-path name="files" path="." />
<cache-path name="cache" path="." />
<external-files-path name="external" path="." />
</paths>
@@ -0,0 +1,28 @@
// MyGo's Android host: the `mygo` library (the bridge to Go, the views,
// the web view, native modules' runtime), `app`, the shell app mygo build
// makes for each app, and the app's native modules' Kotlin.
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "mygo-android"
include(":mygo", ":app")
// The Kotlin of the app's native modules, a Gradle library each, which
// mygo build names (mygoNativeModules: name|directory|the modules it uses,
// by comma).
providers.gradleProperty("mygoNativeModules").orNull?.split(',')?.filter { it.isNotEmpty() }?.forEach {
val (name, dir) = it.split('|')
include(":$name")
project(":$name").projectDir = file(dir)
}
+448
View File
@@ -0,0 +1,448 @@
// Package mobile is the backend of phones and tablets: iOS, where the
// host is Swift and UIKit (ios/), and Android, where it is Kotlin and
// Android's views (android/). Both run Go the same way, so one backend
// serves them, and the host's language does what only it can: the views,
// the web view and its delegates, the keyboard, accessibility and the
// system's dialogs.
//
// The host owns the process's UI thread. Go runs on a thread of its own,
// which the core takes for the main thread: the backend's event loop
// (Run) handles there the events the host sends, and the host runs Go's
// calls on the UI thread (see transport), the messages of package wire.
// So Go can wait for an answer (await pumping Step) while the UI thread
// goes on, as the system needs it to; the browser backend works the same
// way. The Go code links into the host as a library, through the cgo of
// glue_ios.go and glue_android.go: the only cgo of MyGo, which phones'
// build modes need.
//
// Phones have one screen for the app: the window shown last fills it,
// above those shown before, and what desktops have that phones don't
// (menu bars, trays, the Dock, global shortcuts) does nothing, as in
// internal/unsupported.
package mobile
import (
"bytes"
"errors"
"os"
"runtime"
"strconv"
"sync"
"sync/atomic"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/internal/unsupported"
)
var errUnsupported = errors.New("mygo: " + runtime.GOOS + " does not support this")
// Backend is the backend of phones.
type Backend struct {
*unsupported.Backend
t *transport
h platform.AppHandler
mainID uint64
// notify wakes the event loop: for events, Signal or Wake.
notify chan struct{}
signaled atomic.Bool
woken atomic.Bool
quit atomic.Bool
mu sync.Mutex
events []event
stopped bool
// Main thread only.
windows map[int]*window
nextID int
reqs map[int]func(wire.Reader)
nextReq int
schemes map[int]*schemeRequest
tabs map[int]*tabBar
notes map[string]bool
// shown lists the windows on screen, the one in front last.
shown []*window
dark bool
// pluginEvents hears the events of plugins' native code.
pluginEvents func(plugin, name string, data []byte)
// ready is set once the core heard Ready, background while the app is
// in the background.
ready, background bool
// startedHidden says it started out of sight, until it first shows.
startedHidden bool
infoMu sync.Mutex
infoOK bool
info wire.AppInfoReply
}
type event struct {
msg []byte
done chan []byte // nil for an event the host does not wait for
}
// theHost is the host the glue started Go with.
var theHost host
// New returns the backend of the host the app runs in.
func New() *Backend {
b := &Backend{
Backend: unsupported.New(),
notify: make(chan struct{}, 1),
windows: map[int]*window{},
reqs: map[int]func(wire.Reader){},
schemes: map[int]*schemeRequest{},
tabs: map[int]*tabBar{},
notes: map[string]bool{},
}
if theHost != nil {
b.t = newTransport(theHost)
}
early.Lock()
b.events = early.events
early.events = nil
current.Store(b)
early.Unlock()
return b
}
// current is the backend events go to.
var current atomic.Pointer[Backend]
// early holds the events the host sent before the app made its backend,
// which takes them: a link the app was opened with is sent as it launches,
// while its main function may yet be setting up.
var early struct {
sync.Mutex
events []event
}
func goroutineID() uint64 {
var buf [64]byte
n := runtime.Stack(buf[:], false)
b := bytes.TrimPrefix(buf[:n], []byte("goroutine "))
b = b[:max(bytes.IndexByte(b, ' '), 0)]
id, _ := strconv.ParseUint(string(b), 10, 64)
return id
}
func (b *Backend) Name() string { return runtime.GOOS + "/mobile" }
func (b *Backend) call(m message, reply interface{ Decode(*wire.Reader) }) {
if b.t == nil {
return // no host: tests of the core, or a build that never started
}
b.t.call(m, reply)
}
func (b *Backend) Init(h platform.AppHandler, _ platform.AppOptions) error {
if b.t == nil {
return errors.New("mygo: the app runs outside its host; build it with mygo build -platform " + runtime.GOOS)
}
b.h = h
b.mainID = goroutineID()
var t wire.ThemeReply
b.call(&wire.Theme{}, &t)
b.dark = t.Dark
// Started for a background task: no frames until the user opens it.
b.background = b.appInfo().Background
b.startedHidden = b.background
return nil
}
// appInfo is what the host said of the app and the system, asked once.
func (b *Backend) appInfo() wire.AppInfoReply {
b.infoMu.Lock()
defer b.infoMu.Unlock()
if !b.infoOK {
b.call(&wire.AppInfo{}, &b.info)
b.infoOK = b.t != nil
}
return b.info
}
// forgetInfo makes appInfo ask again, as the system's settings changed.
func (b *Backend) forgetInfo() {
b.infoMu.Lock()
b.infoOK = false
b.infoMu.Unlock()
}
func (b *Backend) Run() error {
b.postReady()
for !b.quit.Load() {
<-b.notify
b.handleAll()
}
b.stopEvents()
return nil
}
// stopEvents answers what the host waits for, and all it will send: with the
// core's loop gone, no one would, and the UI thread would hang in it.
func (b *Backend) stopEvents() {
b.mu.Lock()
b.stopped = true
events := b.events
b.events = nil
b.mu.Unlock()
for _, e := range events {
if e.done != nil {
e.done <- nil
}
}
}
// postReady tells the core the app is ready once the loop runs, as the
// host started Go once it had launched.
func (b *Backend) postReady() {
b.mu.Lock()
// Before what the host sent while the app started.
b.events = append([]event{{msg: readyMsg}}, b.events...)
b.mu.Unlock()
b.wakeLoop()
}
var readyMsg = func() []byte {
var w wire.Writer
w.Uvarint(wire.EventReady)
return w.Buf
}()
// handleAll runs Dispatch if signaled, and the events that came.
func (b *Backend) handleAll() bool {
did := false
if b.signaled.Swap(false) {
b.h.Dispatch()
did = true
}
for {
b.mu.Lock()
if len(b.events) == 0 {
b.mu.Unlock()
break
}
e := b.events[0]
b.events = b.events[1:]
b.mu.Unlock()
reply := b.handle(e.msg)
if e.done != nil {
e.done <- reply
}
did = true
if b.signaled.Swap(false) {
b.h.Dispatch()
}
}
return did
}
func (b *Backend) wakeLoop() {
select {
case b.notify <- struct{}{}:
default:
}
}
func (b *Backend) Quit() {
// Phones don't quit apps: the system ends them. The loop stops for the
// core, which then finishes; the process stays until the system ends
// it.
b.quit.Store(true)
b.wakeLoop()
}
func (b *Backend) IsMainThread() bool { return b.mainID == 0 || goroutineID() == b.mainID }
func (b *Backend) Signal() {
b.signaled.Store(true)
b.wakeLoop()
}
func (b *Backend) Step() {
for {
if b.handleAll() || b.woken.Swap(false) || b.quit.Load() {
return
}
<-b.notify
}
}
func (b *Backend) Wake() {
b.woken.Store(true)
b.wakeLoop()
}
// deliver hands an event of the host to the event loop, and waits for its
// answer when the host waits for one. onUI tells whether the host sends
// it from the UI thread, which then runs Go's calls while it waits.
func deliver(msg []byte, onUI bool) []byte {
if len(msg) == 0 {
return nil
}
op := (&wire.Reader{Buf: msg}).Uvarint()
msg = bytes.Clone(msg)
b := current.Load()
if b == nil {
early.Lock()
b = current.Load()
if b == nil {
// What waits has no one to answer it yet.
if !wire.EventWaits(op) {
early.events = append(early.events, event{msg: msg})
}
early.Unlock()
return nil
}
early.Unlock()
}
if !wire.EventWaits(op) {
b.mu.Lock()
b.events = append(b.events, event{msg: msg})
b.mu.Unlock()
b.wakeLoop()
return nil
}
done := make(chan []byte, 1)
b.mu.Lock()
if b.stopped {
b.mu.Unlock()
return nil
}
b.events = append(b.events, event{msg: msg, done: done})
b.mu.Unlock()
b.wakeLoop()
if onUI && b.t != nil {
return b.t.wait(done)
}
return <-done
}
// request numbers an asynchronous answer, which an event brings with the
// number: fn decodes the rest of it. Main thread only.
func (b *Backend) request(fn func(r wire.Reader)) int {
b.nextReq++
b.reqs[b.nextReq] = fn
return b.nextReq
}
// answer runs the function waiting for the answer req of an event.
func (b *Backend) answer(req int, r wire.Reader) {
if fn := b.reqs[req]; fn != nil {
delete(b.reqs, req)
fn(r)
}
}
func (b *Backend) NewWindow(opts *platform.WindowOptions, h platform.WindowHandler) (platform.Window, error) {
return b.newWindow(opts, h)
}
// PopupMenu shows the system's menu at pos in w, and waits for the user's
// choice, handling events meanwhile, as menus do on desktops. What it
// chooses reaches the item's handlers through MenuItemClicked.
func (b *Backend) PopupMenu(m *platform.Menu, pw platform.Window, pos *platform.Point) {
w, _ := pw.(*window)
if w == nil {
w = b.front()
}
if w == nil || m == nil {
return
}
var enc wire.Writer
encodeMenu(&enc, m, "")
var x, y float64
if pos != nil {
x, y = float64(pos.X), float64(pos.Y)
}
picked, done := 0, false
req := b.request(func(r wire.Reader) {
var e wire.MenuPickedEvent
e.Decode(&r)
picked, done = e.Item, true
b.Wake()
})
b.call(&wire.PopupMenu{ID: w.id, Req: req, X: x, Y: y, Items: enc.Buf}, nil)
for !done && !b.quit.Load() {
b.Step()
}
if picked != 0 {
b.h.MenuItemClicked(picked)
}
}
// encodeMenu writes the items a phone's menu shows, in order, as the hosts
// read them: ID (0 for a separator), label, enabled, checked, destructive
// role. Phones' menus have one level: a submenu's items follow, under their
// labels.
func encodeMenu(w *wire.Writer, m *platform.Menu, prefix string) {
for _, it := range m.Items {
if !it.Visible {
continue
}
if it.Submenu != nil {
encodeMenu(w, it.Submenu, prefix+it.Label+" › ")
continue
}
if it.Type == platform.MenuItemSeparator {
w.Int(0)
w.String("")
w.Bool(false)
w.Bool(false)
continue
}
w.Int(it.ID)
w.String(prefix + it.Label)
w.Bool(it.Enabled)
w.Bool(it.Checked)
}
}
func (b *Backend) Network() platform.Network { return network{b: b} }
func (b *Backend) App() platform.AppController { return appController{b: b} }
func (b *Backend) Dialogs() platform.Dialogs { return dialogs{b: b} }
func (b *Backend) Clipboard() platform.Clipboard { return clipboard{b: b} }
func (b *Backend) Shell() platform.Shell { return shell{b: b} }
func (b *Backend) Screen() platform.Screen { return screen{b: b} }
func (b *Backend) Theme() platform.Theme { return theme{b: b} }
func (b *Backend) Power() platform.Power { return power{b: b} }
func (b *Backend) Secrets() platform.Secrets { return secrets{b: b} }
func (b *Backend) NotificationsSupported() bool { return true }
func (b *Backend) WebViewAvailable() bool { return true }
func (b *Backend) ReplaceFile(target, repl string) error { return os.Rename(repl, target) }
func (b *Backend) ShowNotification(n *platform.Notification, done func(error)) {
req := b.request(func(r wire.Reader) {
var e wire.NotifyDoneEvent
e.Decode(&r)
done(errorOf(e.Error))
})
b.call(&wire.Notify{Req: req, NotificationID: n.ID, Title: n.Title, Subtitle: n.Subtitle, Body: n.Body,
Group: n.Group, Silent: n.Silent}, nil)
}
func (b *Backend) RemoveNotification(id string) {
b.call(&wire.RemoveNotification{NotificationID: id}, nil)
}
func (b *Backend) RemoveAllNotifications() { b.call(&wire.RemoveAllNotifications{}, nil) }
// errorOf makes a host's message of an error an error, nil for none.
func errorOf(msg string) error {
if msg == "" {
return nil
}
return errors.New(msg)
}
// rgba packs a color as the host reads it: 0xRRGGBBAA.
func rgba(c platform.Color) int {
return int(c.R)<<24 | int(c.G)<<16 | int(c.B)<<8 | int(c.A)
}
func colorOf(v int) platform.Color {
return platform.Color{R: uint8(v >> 24), G: uint8(v >> 16), B: uint8(v >> 8), A: uint8(v)}
}
+84
View File
@@ -0,0 +1,84 @@
package mobile
import (
"encoding/base64"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
)
// What phones and tablets have that desktops don't (platform.DeviceBackend).
func (b *Backend) Haptic(kind string) { b.call(&wire.Haptic{Kind: kind}, nil) }
func (b *Backend) SetSystemBars(style string, hidden bool) {
b.call(&wire.SetSystemBars{Style: style, Hidden: hidden}, nil)
}
func (b *Backend) SetOrientations(mask uint32) { b.call(&wire.SetOrientations{Mask: int(mask)}, nil) }
func (b *Backend) Share(s platform.ShareRequest, done func(error)) {
req := b.request(func(r wire.Reader) {
var e wire.ShareResultEvent
e.Decode(&r)
done(errorOf(e.Error))
})
b.call(&wire.Share{Req: req, Text: s.Text, URL: s.URL, Paths: s.Paths, X: s.X, Y: s.Y}, nil)
}
func (b *Backend) SaveFile(path, name string, done func(string, error)) {
req := b.request(func(r wire.Reader) {
var e wire.FilesResultEvent
e.Decode(&r)
saved := ""
if len(e.Paths) > 0 {
saved = e.Paths[0]
}
done(saved, errorOf(e.Error))
})
b.call(&wire.SaveFile{Req: req, Path: path, Name: name}, nil)
}
func (b *Backend) Battery() platform.BatteryStatus {
var r wire.BatteryReply
b.call(&wire.Battery{}, &r)
return platform.BatteryStatus{Level: r.Level, Charging: r.Charging, LowPower: r.LowPower}
}
func (b *Backend) SetBarItems(pw platform.Window, items []platform.BarItem) {
w, ok := pw.(*window)
if !ok {
return
}
w.barItems = items
m := wire.SetBarItems{ID: w.id}
for _, it := range items {
m.Titles = append(m.Titles, it.Title)
m.Symbols = append(m.Symbols, it.Symbol)
m.Icons = append(m.Icons, base64.StdEncoding.EncodeToString(it.Icon))
}
b.call(&m, nil)
}
func (b *Backend) PluginCall(plugin, method string, args []byte, done func([]byte, error)) {
req := b.request(func(r wire.Reader) {
var e wire.PluginResultEvent
e.Decode(&r)
if e.Error != "" || e.Code != "" {
done(nil, &platform.PluginError{Code: e.Code, Message: e.Error})
return
}
done([]byte(e.Result), nil)
})
b.call(&wire.PluginCall{Req: req, Plugin: plugin, Method: method, Args: string(args)}, nil)
}
func (b *Backend) OnPluginEvent(fn func(plugin, name string, data []byte)) { b.pluginEvents = fn }
// StartedHidden reports whether the system started the app for something in the
// background, and it hasn't shown yet.
func (b *Backend) StartedHidden() bool { return b.startedHidden }
// WasEndedBySystem reports whether this launch follows the system ending the
// app, rather than the user.
func (b *Backend) WasEndedBySystem() bool { return b.appInfo().Restoring }
+12
View File
@@ -0,0 +1,12 @@
package mobile
import (
"os"
"syscall"
)
// dupOutput makes the descriptor of old (standard output or error) write
// to w, for the runtime's own writes (panics) to go there too.
func dupOutput(w, old *os.File) error {
return syscall.Dup3(int(w.Fd()), int(old.Fd()), 0)
}
+12
View File
@@ -0,0 +1,12 @@
package mobile
import (
"os"
"syscall"
)
// dupOutput makes the descriptor of old (standard output or error) write
// to w, for the runtime's own writes (panics) to go there too.
func dupOutput(w, old *os.File) error {
return syscall.Dup2(int(w.Fd()), int(old.Fd()))
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !ios && !android
package mobile
import (
"errors"
"os"
)
func dupOutput(_, _ *os.File) error { return errors.New("mygo: no host") }
func hostLog(bool, []byte) {}
+351
View File
@@ -0,0 +1,351 @@
package mobile
import (
"bytes"
"context"
"io"
"runtime"
"runtime/debug"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
)
// handle handles an event of the host on the main thread and returns the
// reply the host waits for, if any.
func (b *Backend) handle(msg []byte) []byte {
r := wire.Reader{Buf: msg}
op := r.Uvarint()
var w wire.Writer
win := func(id int) *window { return b.windows[id] }
switch op {
case wire.EventReady:
b.ready = true
b.h.Ready()
case wire.EventActive:
var e wire.ActiveEvent
e.Decode(&r)
if e.Active {
b.h.DidBecomeActive()
} else {
b.h.DidResignActive()
}
case wire.EventBackground:
var e wire.BackgroundEvent
e.Decode(&r)
switch {
case e.Background && !b.background:
b.background = true
b.h.PowerEvent("suspend")
case !e.Background && b.background:
// Coming back is the app opened again, as clicking its Dock
// icon is on macOS; launching is not.
b.background = false
for _, w := range b.windows {
if w.s != nil {
w.s.foreground()
}
}
// Started out of sight, as for a background task or by how iOS
// says it launches, it's no coming back.
if b.startedHidden {
b.startedHidden = false
break
}
b.h.PowerEvent("resume")
if b.ready {
b.h.Activated(b.front() != nil)
}
}
case wire.EventThemeChanged:
var t wire.ThemeReply
b.call(&wire.Theme{}, &t)
b.dark = t.Dark
b.h.ThemeChanged()
for _, w := range b.windows {
if w.s != nil {
w.s.themeChanged()
}
}
case wire.EventLocaleChanged:
b.forgetInfo()
b.h.LocaleChanged()
case wire.EventTimeZoneChanged:
var e wire.TimeZoneChangedEvent
e.Decode(&r)
setTimeZone(e.ID)
// What shows the time draws it again.
b.h.LocaleChanged()
case wire.EventOpenURLs:
var e wire.OpenURLsEvent
e.Decode(&r)
var urls, files []string
for _, u := range e.URLs {
if len(u) > 7 && u[:7] == "file://" {
files = append(files, u[7:])
} else {
urls = append(urls, u)
}
}
if len(urls) > 0 {
b.h.OpenURLs(urls)
}
if len(files) > 0 {
b.h.OpenFiles(files)
}
case wire.EventMemoryWarning:
b.h.MemoryWarning()
for _, w := range b.windows {
if w.s != nil {
w.s.lowMemory()
}
}
runtime.GC()
debug.FreeOSMemory()
case wire.EventTerminating:
b.h.Terminating()
case wire.EventResized:
var e wire.ResizedEvent
e.Decode(&r)
if w := win(e.ID); w != nil {
w.resized(&e)
}
case wire.EventBackPressed:
var e wire.BackPressedEvent
e.Decode(&r)
reply := wire.BackPressedReply{}
if w := win(e.ID); w != nil {
reply.Handled = w.back()
}
reply.Encode(&w)
case wire.EventMessage:
var e wire.MessageEvent
e.Decode(&r)
if w := win(e.ID); w != nil {
w.h.Message(e.Text)
}
case wire.EventWillNavigate:
var e wire.WillNavigateEvent
e.Decode(&r)
reply := wire.WillNavigateReply{Allow: true}
if win := win(e.ID); win != nil {
reply.Allow = win.h.WillNavigate(platform.Navigation{URL: win.appURL(e.URL), IsMainFrame: e.MainFrame,
UserInitiated: e.UserInitiated, Unasked: e.Unasked, Reload: e.Reload})
}
reply.Encode(&w)
case wire.EventNewWindow:
var e wire.NewWindowEvent
e.Decode(&r)
reply := wire.NewWindowReply{}
if win := win(e.ID); win != nil {
nw := win.h.NewWindow(platform.NewWindowRequest{URL: win.appURL(e.URL), UserInitiated: e.UserInitiated, Disposition: "new-window"})
if nw, ok := nw.(*window); ok && nw != nil {
// The app's window takes the page: phones show it in front.
nw.LoadURL(win.appURL(e.URL))
reply.Handled = true
}
}
reply.Encode(&w)
case wire.EventPageState:
var e wire.PageStateEvent
e.Decode(&r)
if w := win(e.ID); w != nil {
w.url, w.loading, w.canBack, w.canFwd = w.appURL(e.URL), e.Loading, e.CanGoBack, e.CanGoForward
if e.Title != w.pageTitle {
w.pageTitle = e.Title
w.h.TitleChanged(e.Title)
}
}
case wire.EventNavigationStarted:
var e wire.NavigationStartedEvent
e.Decode(&r)
if w := win(e.ID); w != nil {
w.loading = true
w.h.NavigationStarted(w.appURL(e.URL))
}
case wire.EventNavigationCommitted:
var e wire.NavigationCommittedEvent
e.Decode(&r)
if w := win(e.ID); w != nil {
w.url = w.appURL(e.URL)
w.h.NavigationCommitted(w.url)
}
case wire.EventLoadFinished:
var e wire.LoadFinishedEvent
e.Decode(&r)
if w := win(e.ID); w != nil {
w.loading = false
w.h.LoadFinished()
}
case wire.EventLoadFailed:
var e wire.LoadFailedEvent
e.Decode(&r)
if w := win(e.ID); w != nil {
w.loading = false
w.h.LoadFailed(w.appURL(e.URL), e.Code, e.Description)
}
case wire.EventWindowFront:
var e wire.WindowFrontEvent
e.Decode(&r)
old := b.front()
var w *window
if e.ID != 0 {
w = win(e.ID)
} else {
// The app's first scene: the last shown there.
for _, s := range b.shown {
if !s.opts.OwnScene {
w = s
}
}
}
if w != nil && w.visible {
b.unshow(w)
b.shown = append(b.shown, w)
b.refocus(old)
}
case wire.EventClosedByPage:
var e wire.ClosedByPageEvent
e.Decode(&r)
if w := win(e.ID); w != nil {
w.h.ClosedByPage()
}
case wire.EventProcessGone:
var e wire.ProcessGoneEvent
e.Decode(&r)
if w := win(e.ID); w != nil {
w.h.RenderProcessGone(e.Reason)
}
case wire.EventPermissionRequested:
var e wire.PermissionRequestedEvent
e.Decode(&r)
reply := wire.PermissionRequestedReply{}
if w := win(e.ID); w != nil {
reply.Allow = w.h.PermissionRequested(e.Kinds, w.appURL(e.Origin))
}
reply.Encode(&w)
case wire.EventSchemeRequest:
var e wire.SchemeRequestEvent
e.Decode(&r)
b.schemeRequest(&e)
case wire.EventSchemeCancel:
var e wire.SchemeCancelEvent
e.Decode(&r)
if s := b.schemes[e.Req]; s != nil {
delete(b.schemes, e.Req)
s.cancel()
}
case wire.EventPluginEvent:
var e wire.PluginEventEvent
e.Decode(&r)
if b.pluginEvents != nil {
b.pluginEvents(e.Plugin, e.Name, []byte(e.Data))
}
case wire.EventNetworkChanged:
var e wire.NetworkChangedEvent
e.Decode(&r)
b.h.NetworkChanged(platform.NetworkStatus{Online: e.Online, Metered: e.Metered})
case wire.EventAsyncResult, wire.EventCaptured, wire.EventMessageBoxResult, wire.EventFilesResult, wire.EventNotifyDone,
wire.EventShareResult, wire.EventMenuPicked, wire.EventPluginResult:
// Answers to a request: its number first, then the rest.
rest := r
req := r.Int()
b.answer(req, rest)
case wire.EventNotificationClicked:
var e wire.NotificationClickedEvent
e.Decode(&r)
b.h.NotificationClicked(e.NotificationID)
default:
if !b.handleNavigation(op, &r) {
b.handleSurface(op, &r, &w)
}
}
if !wire.EventWaits(op) {
return nil
}
if w.Buf == nil {
w.Buf = []byte{}
}
return w.Buf
}
// back handles Android's back for the window: its page goes back if it
// can, else the app's handlers may take it.
func (w *window) back() bool {
if w.s != nil {
return w.s.back()
}
if w.canBack {
w.GoBack()
return true
}
return false
}
// schemeRequest is a request of one of the app's schemes, which the core
// answers through it.
type schemeRequest struct {
b *Backend
req int
cancel context.CancelFunc
done bool
}
func (b *Backend) schemeRequest(e *wire.SchemeRequestEvent) {
w := b.windows[e.ID]
if w == nil {
b.call(&wire.SchemeFail{Req: e.Req, Message: "no window"}, nil)
return
}
ctx, cancel := context.WithCancel(context.Background())
s := &schemeRequest{b: b, req: e.Req, cancel: cancel}
b.schemes[e.Req] = s
header := map[string][]string{}
for i := 0; i+1 < len(e.Header); i += 2 {
header[e.Header[i]] = append(header[e.Header[i]], e.Header[i+1])
}
var body io.ReadCloser
if e.HasBody {
body = io.NopCloser(bytes.NewReader(e.Body))
}
w.h.SchemeRequest(&platform.SchemeRequest{Context: ctx, Method: e.Method, URL: w.appURL(e.URL), Header: header, Body: body, Responder: s})
}
func (s *schemeRequest) Respond(status int, header map[string][]string) {
var pairs []string
for k, vs := range header {
for _, v := range vs {
pairs = append(pairs, k, v)
}
}
s.b.call(&wire.SchemeRespond{Req: s.req, Status: status, Header: pairs}, nil)
}
func (s *schemeRequest) Write(p []byte) {
if len(p) > 0 && !s.done {
s.b.call(&wire.SchemeData{Req: s.req, Data: bytes.Clone(p)}, nil)
}
}
func (s *schemeRequest) Finish() {
if s.end() {
s.b.call(&wire.SchemeFinish{Req: s.req}, nil)
}
}
func (s *schemeRequest) Fail(err error) {
if s.end() {
s.b.call(&wire.SchemeFail{Req: s.req, Message: err.Error()}, nil)
}
}
func (s *schemeRequest) end() bool {
if s.done {
return false
}
s.done = true
delete(s.b.schemes, s.req)
s.cancel()
return true
}
+102
View File
@@ -0,0 +1,102 @@
//go:build android
package mobile
/*
#cgo LDFLAGS: -landroid -llog
#include <stdint.h>
#include <stdlib.h>
void mygo_android_call(uint8_t *msg, size_t len, uint8_t **reply, size_t *reply_len);
void mygo_android_call_here(uint8_t *msg, size_t len, uint8_t **reply, size_t *reply_len);
void mygo_android_post(void);
void mygo_android_log(int error, uint8_t *line, size_t len);
extern char **environ;
static char *mygo_environ(int i) { return environ[i]; }
*/
import "C"
import (
"os"
"runtime"
"strings"
"unsafe"
)
// cHost is the Kotlin host, through JNI (jni_android.c).
type cHost struct{}
func (cHost) call(msg []byte) []byte {
var reply *C.uint8_t
var n C.size_t
C.mygo_android_call((*C.uint8_t)(unsafe.Pointer(unsafe.SliceData(msg))), C.size_t(len(msg)), &reply, &n)
if reply == nil {
return nil
}
b := C.GoBytes(unsafe.Pointer(reply), C.int(n))
C.free(unsafe.Pointer(reply))
return b
}
// callHere calls the host on this thread, for what needs no UI thread.
func (cHost) callHere(msg []byte) []byte {
// The thread stays the JVM's, as it joined it, while it calls.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var reply *C.uint8_t
var n C.size_t
C.mygo_android_call_here((*C.uint8_t)(unsafe.Pointer(unsafe.SliceData(msg))), C.size_t(len(msg)), &reply, &n)
if reply == nil {
return nil
}
b := C.GoBytes(unsafe.Pointer(reply), C.int(n))
C.free(unsafe.Pointer(reply))
return b
}
func (cHost) post() { C.mygo_android_post() }
func hostLog(isErr bool, line []byte) {
e := C.int(0)
if isErr {
e = 1
}
C.mygo_android_log(e, (*C.uint8_t)(unsafe.Pointer(unsafe.SliceData(line))), C.size_t(len(line)))
}
//export mygo_start_android
func mygo_start_android() {
theHost = cHost{}
syncEnviron()
start()
}
// syncEnviron takes the variables the host set (HOME, TMPDIR, mygo dev's)
// into Go's environment, which Go copied as the library loaded, before
// the host set them.
func syncEnviron() {
for i := 0; ; i++ {
p := C.mygo_environ(C.int(i))
if p == nil {
return
}
if k, v, ok := strings.Cut(C.GoString(p), "="); ok && os.Getenv(k) != v {
os.Setenv(k, v)
}
}
}
//export mygo_event
func mygo_event(msg *C.uint8_t, n C.size_t, onUI C.int, reply **C.uint8_t, replyLen *C.size_t) {
r := deliver(unsafe.Slice((*byte)(unsafe.Pointer(msg)), int(n)), onUI != 0)
*reply, *replyLen = nil, 0
if r != nil {
p := C.malloc(C.size_t(max(len(r), 1)))
copy(unsafe.Slice((*byte)(p), len(r)), r)
*reply, *replyLen = (*C.uint8_t)(p), C.size_t(len(r))
}
}
//export mygo_drain
func mygo_drain() { drain() }
+77
View File
@@ -0,0 +1,77 @@
//go:build ios
package mobile
/*
#include <pthread.h>
#include <stdlib.h>
#include "ios/MyGo.h"
static mygo_host host;
static void mygo_set_host(mygo_host *h) { host = *h; }
static void mygo_host_call(const uint8_t *msg, size_t len, uint8_t **reply, size_t *reply_len) {
host.call(msg, len, reply, reply_len);
}
static void mygo_host_post(void) { host.post(); }
static void mygo_host_log(int error, const uint8_t *line, size_t len) { host.log(error, line, len); }
*/
import "C"
import "unsafe"
// cHost is the Swift host, through the functions it gave mygo_start.
type cHost struct{}
func (cHost) call(msg []byte) []byte {
var reply *C.uint8_t
var n C.size_t
C.mygo_host_call((*C.uint8_t)(unsafe.Pointer(unsafe.SliceData(msg))), C.size_t(len(msg)), &reply, &n)
if reply == nil {
return nil
}
b := C.GoBytes(unsafe.Pointer(reply), C.int(n))
C.free(unsafe.Pointer(reply))
return b
}
// callHere calls the host on this thread, for what needs no UI thread.
func (h cHost) callHere(msg []byte) []byte { return h.call(msg) }
func (cHost) post() { C.mygo_host_post() }
func hostLog(isErr bool, line []byte) {
e := C.int(0)
if isErr {
e = 1
}
C.mygo_host_log(e, (*C.uint8_t)(unsafe.Pointer(unsafe.SliceData(line))), C.size_t(len(line)))
}
//export mygo_start
func mygo_start(h *C.mygo_host) {
C.mygo_set_host(h)
theHost = cHost{}
start()
}
//export mygo_event
func mygo_event(msg *C.uint8_t, n C.size_t, onMain C.int, reply **C.uint8_t, replyLen *C.size_t) {
r := deliver(unsafe.Slice((*byte)(unsafe.Pointer(msg)), int(n)), onMain != 0)
*reply, *replyLen = nil, 0
if r != nil {
p := C.malloc(C.size_t(max(len(r), 1)))
copy(unsafe.Slice((*byte)(p), len(r)), r)
*reply, *replyLen = (*C.uint8_t)(p), C.size_t(len(r))
}
}
//export mygo_drain
func mygo_drain() { drain() }
//export mygo_free
func mygo_free(p *C.uint8_t) { C.free(unsafe.Pointer(p)) }
// onUIThread reports whether this is the UI thread, the process's main
// thread on iOS.
func onUIThread() bool { return C.pthread_main_np() != 0 }
+31
View File
@@ -0,0 +1,31 @@
// The C interface between MyGo's Go code (internal/mobile) and the Swift
// host. Messages are encoded as package wire encodes them.
#ifndef MYGO_H
#define MYGO_H
#include <stddef.h>
#include <stdint.h>
typedef struct {
// call runs an encoded call on the main thread and sets *reply to its
// encoded reply, malloc'd (Go frees it), or NULL for none.
void (*call)(const uint8_t *msg, size_t len, uint8_t **reply, size_t *reply_len);
// post asks the main thread to call mygo_drain soon. Any thread.
void (*post)(void);
// log writes a line of the app's output to the system's log. Any thread.
void (*log)(int error, const uint8_t *line, size_t len);
} mygo_host;
// mygo_start starts Go's main function on a thread of its own, once the
// app has launched. Main thread, once.
void mygo_start(mygo_host *host);
// mygo_event sends an encoded event. For an event Go answers, it waits for
// the answer and sets *reply to it, malloc'd (free it with mygo_free);
// on_main tells that the caller is the main thread, which runs Go's calls
// while it waits.
void mygo_event(uint8_t *msg, size_t len, int on_main, uint8_t **reply, size_t *reply_len);
// mygo_drain runs the calls Go made. Main thread.
void mygo_drain(void);
void mygo_free(uint8_t *p);
#endif
@@ -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
+12
View File
@@ -0,0 +1,12 @@
// Package ios holds the sources of the iOS host, Swift and UIKit, which
// mygo build compiles and links with the app's Go code. See
// internal/mobile for how the two work together.
package ios
import "embed"
// Files are the host's sources: MyGo.h, the C interface of the Go code,
// and Sources/MyGoHost, the Swift.
//
//go:embed MyGo.h Sources
var Files embed.FS
+256
View File
@@ -0,0 +1,256 @@
// The JNI side of the Android host: dev.mygo.MyGoNative's native methods
// call into Go, and Go's calls reach dev.mygo.Host on the UI thread. Go
// wakes the UI thread through a pipe its looper watches, so that the
// host's calls never attach a thread of Go's to the JVM. Native modules
// do: Go calls their Kotlin (dev.mygo.Native) on the calling thread, as
// it calls a Swift library's functions elsewhere.
#define _GNU_SOURCE
#include <jni.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <android/log.h>
#include <android/looper.h>
#include <android/native_window_jni.h>
#include "_cgo_export.h"
static JavaVM *vm;
static jclass host;
static jmethodID host_call;
static int wake[2] = {-1, -1};
// dev.mygo.Native, the runtime of native modules' Kotlin.
static jclass native;
static jmethodID native_init, native_invoke, native_direct, native_op;
JNIEXPORT jint JNI_OnLoad(JavaVM *v, void *reserved) {
vm = v;
JNIEnv *env;
if ((*v)->GetEnv(v, (void **)&env, JNI_VERSION_1_6) != JNI_OK) return JNI_ERR;
jclass c = (*env)->FindClass(env, "dev/mygo/Host");
if (c == NULL) return JNI_ERR;
host = (*env)->NewGlobalRef(env, c);
host_call = (*env)->GetStaticMethodID(env, host, "call", "([B)[B");
// Found here, with the app's class loader, which a thread of Go's that
// attaches later does not have.
jclass n = (*env)->FindClass(env, "dev/mygo/Native");
if (n == NULL) {
(*env)->ExceptionClear(env);
} else {
native = (*env)->NewGlobalRef(env, n);
native_init = (*env)->GetStaticMethodID(env, native, "init", "(Ljava/lang/String;Ljava/lang/String;J)Ljava/lang/String;");
native_invoke = (*env)->GetStaticMethodID(env, native, "invoke", "(Ljava/lang/String;Ljava/lang/String;J[BJ)[B");
native_direct = (*env)->GetStaticMethodID(env, native, "direct", "(Ljava/lang/String;Ljava/lang/String;J[J)J");
native_op = (*env)->GetStaticMethodID(env, native, "op", "(Ljava/lang/String;Ljava/lang/String;JJ[B)V");
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionClear(env);
native = NULL;
}
}
return JNI_VERSION_1_6;
}
static JNIEnv *ui_env(void) {
JNIEnv *env = NULL;
(*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6);
return env;
}
void mygo_android_call(uint8_t *msg, size_t len, uint8_t **reply, size_t *reply_len) {
JNIEnv *env = ui_env();
*reply = NULL;
*reply_len = 0;
jbyteArray a = (*env)->NewByteArray(env, (jsize)len);
(*env)->SetByteArrayRegion(env, a, 0, (jsize)len, (const jbyte *)msg);
jbyteArray r = (jbyteArray)(*env)->CallStaticObjectMethod(env, host, host_call, a);
(*env)->DeleteLocalRef(env, a);
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
return;
}
if (r == NULL) return;
jsize n = (*env)->GetArrayLength(env, r);
*reply = malloc(n > 0 ? n : 1);
(*env)->GetByteArrayRegion(env, r, 0, n, (jbyte *)*reply);
*reply_len = n;
(*env)->DeleteLocalRef(env, r);
}
// mygo_android_call_here calls the host on the thread of the caller, which
// joins the JVM the first time: the text of native UI, which measures and draws
// with its own objects, whatever the UI thread is doing.
void mygo_android_call_here(uint8_t *msg, size_t len, uint8_t **reply, size_t *reply_len) {
JNIEnv *env = NULL;
*reply = NULL;
*reply_len = 0;
if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK && (*vm)->AttachCurrentThreadAsDaemon(vm, &env, NULL) != JNI_OK) {
return;
}
mygo_android_call(msg, len, reply, reply_len);
}
void mygo_android_post(void) {
char c = 1;
write(wake[1], &c, 1);
}
void mygo_android_log(int error, uint8_t *line, size_t len) {
char *s = malloc(len + 1);
memcpy(s, line, len);
s[len] = 0;
__android_log_write(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "mygo", s);
free(s);
}
static int on_wake(int fd, int events, void *data) {
char buf[64];
while (read(fd, buf, sizeof buf) > 0) {
}
mygo_drain();
return 1;
}
JNIEXPORT void JNICALL Java_dev_mygo_MyGoNative_start(JNIEnv *env, jclass c) {
if (wake[0] >= 0) return;
pipe2(wake, O_NONBLOCK | O_CLOEXEC);
ALooper_addFd(ALooper_forThread(), wake[0], ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, on_wake, NULL);
mygo_start_android();
}
JNIEXPORT jlong JNICALL Java_dev_mygo_MyGoNative_nativeWindow(JNIEnv *env, jclass c, jobject surface) {
return (jlong)(intptr_t)ANativeWindow_fromSurface(env, surface);
}
JNIEXPORT void JNICALL Java_dev_mygo_MyGoNative_releaseNativeWindow(JNIEnv *env, jclass c, jlong window) {
if (window != 0) ANativeWindow_release((ANativeWindow *)(intptr_t)window);
}
JNIEXPORT jbyteArray JNICALL Java_dev_mygo_MyGoNative_event(JNIEnv *env, jclass c, jbyteArray msg, jboolean on_ui) {
jsize n = (*env)->GetArrayLength(env, msg);
jbyte *b = (*env)->GetByteArrayElements(env, msg, NULL);
uint8_t *reply = NULL;
size_t reply_len = 0;
mygo_event((uint8_t *)b, (size_t)n, on_ui ? 1 : 0, &reply, &reply_len);
(*env)->ReleaseByteArrayElements(env, msg, b, JNI_ABORT);
if (reply == NULL) return NULL;
jbyteArray r = (*env)->NewByteArray(env, (jsize)reply_len);
(*env)->SetByteArrayRegion(env, r, 0, (jsize)reply_len, (const jbyte *)reply);
free(reply);
return r;
}
JNIEXPORT void JNICALL Java_dev_mygo_MyGoNative_drain(JNIEnv *env, jclass c) { mygo_drain(); }
// Native modules.
// any_env is the JNIEnv of this thread, which joins the JVM the first
// time: Go calls a module from any of its threads.
static JNIEnv *any_env(void) {
JNIEnv *env = NULL;
if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK && (*vm)->AttachCurrentThreadAsDaemon(vm, &env, NULL) != JNI_OK) {
return NULL;
}
return env;
}
// failed reports, and clears, an exception the runtime let through.
static int failed(JNIEnv *env) {
if (!(*env)->ExceptionCheck(env)) return 0;
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
return 1;
}
static jbyteArray bytes(JNIEnv *env, const uint8_t *b, size_t n) {
jbyteArray a = (*env)->NewByteArray(env, (jsize)n);
if (a != NULL && n > 0) (*env)->SetByteArrayRegion(env, a, 0, (jsize)n, (const jbyte *)b);
return a;
}
// mygo_native_init loads a module's Kotlin, by the class of its generated
// object; it returns what went wrong, which the caller frees, or NULL.
char *mygo_native_init(const char *name, const char *cls, uint64_t base) {
if (native == NULL) return strdup("the app's host has no dev.mygo.Native: build it with mygo build -platform android");
JNIEnv *env = any_env();
if (env == NULL) return strdup("the thread could not join the JVM");
(*env)->PushLocalFrame(env, 8);
jstring msg = (jstring)(*env)->CallStaticObjectMethod(env, native, native_init, (*env)->NewStringUTF(env, name), (*env)->NewStringUTF(env, cls), (jlong)base);
char *r = NULL;
if (failed(env)) {
r = strdup("dev.mygo.Native.init threw");
} else if (msg != NULL) {
const char *c = (*env)->GetStringUTFChars(env, msg, NULL);
r = strdup(c);
(*env)->ReleaseStringUTFChars(env, msg, c);
}
(*env)->PopLocalFrame(env, NULL);
return r;
}
// mygo_native_invoke calls a function of a module's Kotlin. Its answer,
// which the caller frees, is the status and then the data; it returns 0
// when the call threw past the runtime.
int mygo_native_invoke(const char *name, const char *sym, uint64_t h, const uint8_t *args, size_t n, uint64_t call, uint8_t **reply, size_t *reply_len) {
*reply = NULL;
*reply_len = 0;
JNIEnv *env = any_env();
if (env == NULL || native == NULL) return 0;
(*env)->PushLocalFrame(env, 8);
jbyteArray r = (jbyteArray)(*env)->CallStaticObjectMethod(env, native, native_invoke, (*env)->NewStringUTF(env, name), (*env)->NewStringUTF(env, sym), (jlong)h, bytes(env, args, n), (jlong)call);
int ok = !failed(env);
if (ok && r != NULL) {
jsize k = (*env)->GetArrayLength(env, r);
*reply = malloc(k > 0 ? k : 1);
(*env)->GetByteArrayRegion(env, r, 0, k, (jbyte *)*reply);
*reply_len = k;
}
(*env)->PopLocalFrame(env, NULL);
return ok;
}
// mygo_native_direct calls a method of numbers.
uint64_t mygo_native_direct(const char *name, const char *sym, uint64_t h, const uint64_t *args, size_t n) {
JNIEnv *env = any_env();
if (env == NULL || native == NULL) return 0;
(*env)->PushLocalFrame(env, 8);
jlongArray a = (*env)->NewLongArray(env, (jsize)n);
if (n > 0) (*env)->SetLongArrayRegion(env, a, 0, (jsize)n, (const jlong *)args);
jlong r = (*env)->CallStaticLongMethod(env, native, native_direct, (*env)->NewStringUTF(env, name), (*env)->NewStringUTF(env, sym), (jlong)h, a);
if (failed(env)) r = 0;
(*env)->PopLocalFrame(env, NULL);
return (uint64_t)r;
}
// mygo_native_op releases an object, cancels a call, asks a stream for its
// next value, or resumes a continuation of Kotlin's.
void mygo_native_op(const char *name, const char *op, uint64_t a, int64_t status, const uint8_t *data, size_t n) {
JNIEnv *env = any_env();
if (env == NULL || native == NULL) return;
(*env)->PushLocalFrame(env, 8);
(*env)->CallStaticVoidMethod(env, native, native_op, (*env)->NewStringUTF(env, name), (*env)->NewStringUTF(env, op), (jlong)a, (jlong)status, data != NULL ? bytes(env, data, n) : NULL);
failed(env);
(*env)->PopLocalFrame(env, NULL);
}
// What Kotlin tells Go: the callback every module shares. The answer of a
// question is its status and then its data, null when there is none.
JNIEXPORT jbyteArray JNICALL Java_dev_mygo_Native_send(JNIEnv *env, jclass c, jlong kind, jlong id, jlong status, jbyteArray data) {
jsize n = data != NULL ? (*env)->GetArrayLength(env, data) : 0;
jbyte *b = data != NULL ? (*env)->GetByteArrayElements(env, data, NULL) : NULL;
uint8_t *reply = NULL;
size_t reply_len = 0;
int answered = mygo_native_handle((uint64_t)kind, (uint64_t)id, (int64_t)status, (uint8_t *)b, (size_t)n, &reply, &reply_len);
if (b != NULL) (*env)->ReleaseByteArrayElements(env, data, b, JNI_ABORT);
if (!answered) return NULL;
jbyteArray r = bytes(env, reply, reply_len);
free(reply);
return r;
}
// The memory of a *native.Buffer, which Kotlin reads and writes.
JNIEXPORT jobject JNICALL Java_dev_mygo_Native_buffer(JNIEnv *env, jclass c, jlong p, jlong n) {
return (*env)->NewDirectByteBuffer(env, (void *)(intptr_t)p, (jlong)n);
}
+262
View File
@@ -0,0 +1,262 @@
package mobile
import (
"sync"
"testing"
"time"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/internal/wait"
)
// fakeHost stands for the Swift or Kotlin host: its UI thread is a
// goroutine that runs what is posted to it, in turn.
type fakeHost struct {
t *testing.T
ui chan func()
mu sync.Mutex
calls []uint64
// answer, when set, answers waited calls by number.
answer func(op uint64, r *wire.Reader) []byte
b *Backend
}
func newFakeHost(t *testing.T) *fakeHost {
h := &fakeHost{t: t, ui: make(chan func(), 64)}
go func() {
for f := range h.ui {
f()
}
}()
t.Cleanup(func() { close(h.ui) })
return h
}
func (h *fakeHost) call(msg []byte) []byte {
r := wire.Reader{Buf: msg}
op := r.Uvarint()
h.mu.Lock()
h.calls = append(h.calls, op)
answer := h.answer
h.mu.Unlock()
if answer != nil {
if b := answer(op, &r); b != nil {
return b
}
}
return []byte{}
}
func (h *fakeHost) post() { h.ui <- func() { h.b.t.drain() } }
// onUI runs f on the host's UI thread and waits for it.
func (h *fakeHost) onUI(f func()) {
done := make(chan struct{})
h.ui <- func() { f(); close(done) }
<-done
}
func (h *fakeHost) called(op uint64) bool {
h.mu.Lock()
defer h.mu.Unlock()
for _, c := range h.calls {
if c == op {
return true
}
}
return false
}
// app is an AppHandler that records what it heard.
type app struct {
b *Backend
ready chan struct{}
mu sync.Mutex
posts []func()
}
func (a *app) Ready() { close(a.ready) }
func (a *app) Dispatch() {
a.mu.Lock()
posts := a.posts
a.posts = nil
a.mu.Unlock()
for _, f := range posts {
f()
}
}
func (a *app) QuitRequested() bool { return true }
func (a *app) Terminating() {}
func (a *app) HotkeyBound(int, string) {}
func (a *app) Activated(bool) {}
func (a *app) DidBecomeActive() {}
func (a *app) DidResignActive() {}
func (a *app) OpenURLs([]string) {}
func (a *app) OpenFiles([]string) {}
func (a *app) MenuItemClicked(int) {}
func (a *app) ThemeChanged() {}
func (a *app) DisplaysChanged() {}
func (a *app) LocaleChanged() {}
func (a *app) PowerEvent(string) {}
func (a *app) NetworkChanged(platform.NetworkStatus) {}
func (a *app) HotkeyPressed(int) {}
func (a *app) NotificationClicked(string) {}
func (a *app) MediaCommand(platform.MediaCommand, time.Duration) {}
func (a *app) MemoryWarning() {}
// startBackend runs a backend with a fake host, its loop on a goroutine of its
// own, the main thread, and returns them once the app is ready.
func startBackend(t *testing.T) (*Backend, *fakeHost) {
h := newFakeHost(t)
theHost = h
t.Cleanup(func() { theHost = nil })
b := New()
h.b = b
a := &app{b: b, ready: make(chan struct{})}
inited := make(chan error, 1)
go func() {
if err := b.Init(a, platform.AppOptions{}); err != nil {
inited <- err
return
}
inited <- nil
b.Run()
}()
if err := <-inited; err != nil {
t.Fatal(err)
}
wait.For(t, "the app to be ready", a.ready)
t.Cleanup(b.Quit)
return b, h
}
// onMain runs f on the backend's main thread and waits for it.
func onMain(b *Backend, f func()) {
a := b.h.(*app)
done := make(chan struct{})
a.mu.Lock()
a.posts = append(a.posts, func() { f(); close(done) })
a.mu.Unlock()
b.Signal()
<-done
}
// winHandler hears of a window; what a test does not set panics.
type winHandler struct {
platform.WindowHandler
willNavigate func(platform.Navigation) bool
scheme func(*platform.SchemeRequest)
}
func (w *winHandler) WillNavigate(n platform.Navigation) bool { return w.willNavigate(n) }
func (w *winHandler) SchemeRequest(r *platform.SchemeRequest) { w.scheme(r) }
func encodeEvent(f func(w *wire.Writer)) []byte {
var w wire.Writer
f(&w)
return w.Buf
}
// A handler of an event the UI thread waits for may make calls of the
// host, which the UI thread runs while it waits.
func TestCallWhileHostWaits(t *testing.T) {
b, h := startBackend(t)
h.answer = func(op uint64, r *wire.Reader) []byte {
switch op {
case wire.CallUserAgent:
var w wire.Writer
w.String("Agent/1")
return w.Buf
}
return nil
}
var ua string
wh := &winHandler{willNavigate: func(n platform.Navigation) bool {
ua = b.windows[1].UserAgent()
return n.URL == "https://allowed.example/"
}}
onMain(b, func() {
if _, err := b.NewWindow(&platform.WindowOptions{}, wh); err != nil {
t.Error(err)
}
})
for _, c := range []struct {
url string
allow bool
}{{"https://allowed.example/", true}, {"https://other.example/", false}} {
var reply []byte
h.onUI(func() {
reply = deliver(encodeEvent(func(w *wire.Writer) {
w.Uvarint(wire.EventWillNavigate)
w.Int(1)
w.String(c.url)
w.Bool(true)
w.Bool(true)
w.Bool(false)
w.Bool(false)
}), true)
})
if got := (&wire.Reader{Buf: reply}).Bool(); got != c.allow {
t.Errorf("WillNavigate(%s) = %v, want %v", c.url, got, c.allow)
}
}
if ua != "Agent/1" {
t.Errorf("UserAgent = %q, want the host's", ua)
}
}
// A request of the app's scheme is answered with calls of the host, in
// order.
func TestSchemeRequest(t *testing.T) {
b, h := startBackend(t)
wh := &winHandler{scheme: func(r *platform.SchemeRequest) {
if r.URL != "mygo://localhost/index.html" || r.Header["Accept"][0] != "text/html" {
t.Errorf("request %s %v", r.URL, r.Header)
}
r.Responder.Respond(200, map[string][]string{"Content-Type": {"text/html"}})
r.Responder.Write([]byte("<p>hi"))
r.Responder.Finish()
}}
onMain(b, func() { b.NewWindow(&platform.WindowOptions{}, wh) })
h.onUI(func() {
deliver(encodeEvent(func(w *wire.Writer) {
w.Uvarint(wire.EventSchemeRequest)
w.Int(1)
w.Int(7)
w.String("GET")
w.String("mygo://localhost/index.html")
w.Strings([]string{"Accept", "text/html"})
w.Bytes(nil)
w.Bool(false)
}), true)
})
wait.Until(t, "the response to finish", func() bool { return h.called(wire.CallSchemeFinish) })
for _, op := range []uint64{wire.CallSchemeRespond, wire.CallSchemeData} {
if !h.called(op) {
t.Errorf("no call %d", op)
}
}
}
// A message box answers once the host tells which button was chosen.
func TestMessageBox(t *testing.T) {
b, h := startBackend(t)
got := make(chan int, 1)
onMain(b, func() {
b.Dialogs().ShowMessageBox(nil, &platform.MessageBoxOptions{Message: "Sure?", Buttons: []string{"Yes", "No"}},
func(r platform.MessageBoxResult, err error) { got <- r.Response })
})
wait.Until(t, "the message box", func() bool { return h.called(wire.CallMessageBox) })
h.onUI(func() {
deliver(encodeEvent(func(w *wire.Writer) {
w.Uvarint(wire.EventMessageBoxResult)
w.Int(1) // the request
w.Int(1) // No
}), true)
})
if r := wait.For(t, "the answer", got); r != 1 {
t.Errorf("Response = %d, want 1", r)
}
}
+26
View File
@@ -0,0 +1,26 @@
//go:build ios || android
package mobile
import "github.com/egoist/mygo/internal/nativehost"
// Native modules' main-thread methods and views run on the UI thread, in
// order with Go's calls of the host.
func init() {
nativehost.OnUI = func(fn func()) {
b := current.Load()
if b == nil || b.t == nil || onUIThread() {
fn()
return
}
b.t.run(fn, true)
}
nativehost.PostUI = func(fn func()) {
b := current.Load()
if b == nil || b.t == nil {
fn()
return
}
b.t.run(fn, false)
}
}
+113
View File
@@ -0,0 +1,113 @@
//go:build android
package mobile
/*
#include <stdint.h>
#include <stdlib.h>
char *mygo_native_init(const char *name, const char *cls, uint64_t base);
int mygo_native_invoke(const char *name, const char *sym, uint64_t h, const uint8_t *args, size_t n, uint64_t call, uint8_t **reply, size_t *reply_len);
uint64_t mygo_native_direct(const char *name, const char *sym, uint64_t h, const uint64_t *args, size_t n);
void mygo_native_op(const char *name, const char *op, uint64_t a, int64_t status, const uint8_t *data, size_t n);
*/
import "C"
import (
"encoding/binary"
"runtime"
"sync"
"syscall"
"unsafe"
"github.com/egoist/mygo/internal/nativehost"
)
// Native modules' Kotlin, through JNI (jni_android.c): Go calls it on the
// calling thread, which joins the JVM the first time.
func init() {
nativehost.Kotlin = &nativehost.KotlinBridge{
Init: func(name, class string, idBase uint64) string {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
msg := C.mygo_native_init(cstr(name), cstr(class), C.uint64_t(idBase))
if msg == nil {
return ""
}
defer C.free(unsafe.Pointer(msg))
return C.GoString(msg)
},
Invoke: func(name, sym string, h uint64, args []byte, call uint64) []byte {
var reply *C.uint8_t
var n C.size_t
ok := C.mygo_native_invoke(cstr(name), cstr(sym), C.uint64_t(h), bytePtr(args), C.size_t(len(args)), C.uint64_t(call), &reply, &n)
if ok == 0 || reply == nil {
return nil
}
defer C.free(unsafe.Pointer(reply))
return C.GoBytes(unsafe.Pointer(reply), C.int(n))
},
Direct: func(name, sym string, h uint64, args []uint64) uint64 {
var p *C.uint64_t
if len(args) > 0 {
p = (*C.uint64_t)(unsafe.Pointer(&args[0]))
}
return uint64(C.mygo_native_direct(cstr(name), cstr(sym), C.uint64_t(h), p, C.size_t(len(args))))
},
Op: func(name, op string, a uint64, status int64, data []byte) {
C.mygo_native_op(cstr(name), cstr(op), C.uint64_t(a), C.int64_t(status), bytePtr(data), C.size_t(len(data)))
},
Malloc: func(n int) uintptr { return uintptr(C.malloc(C.size_t(n))) },
Free: func(p uintptr) { C.free(unsafe.Add(nil, p)) },
}
}
// cstrs are the C strings of the names of modules and their functions,
// made once each.
var cstrs sync.Map // string → *C.char
func cstr(s string) *C.char {
if p, ok := cstrs.Load(s); ok {
return p.(*C.char)
}
p, _ := cstrs.LoadOrStore(s, C.CString(s))
return p.(*C.char)
}
func bytePtr(b []byte) *C.uint8_t {
if len(b) == 0 {
return nil
}
return (*C.uint8_t)(unsafe.Pointer(unsafe.SliceData(b)))
}
// mygo_native_handle is what Kotlin tells Go (dev.mygo.Native.send). The
// answer of a question, which the caller frees, is its status and then
// its data.
//
//export mygo_native_handle
func mygo_native_handle(kind, id C.uint64_t, status C.int64_t, data *C.uint8_t, n C.size_t, reply **C.uint8_t, replyLen *C.size_t) C.int {
*reply, *replyLen = nil, 0
h := nativehost.Handle
if h == nil {
return 0
}
var b []byte
if data != nil {
b = C.GoBytes(unsafe.Pointer(data), C.int(n))
}
st, out, ok := h(uint64(kind), uint64(id), int64(status), b)
if !ok {
return 0
}
p := C.malloc(C.size_t(8 + len(out)))
r := unsafe.Slice((*byte)(p), 8+len(out))
binary.LittleEndian.PutUint64(r, uint64(st))
copy(r[8:], out)
*reply, *replyLen = (*C.uint8_t)(p), C.size_t(len(r))
return 1
}
// onUIThread reports whether this is the UI thread, the process's main
// thread on Android.
func onUIThread() bool { return syscall.Gettid() == syscall.Getpid() }
+119
View File
@@ -0,0 +1,119 @@
package mobile
import (
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
)
// The navigation of phones (platform.NavigationBackend): the host's tab
// bar, each tab a window, and stacks of windows pushed over others, under
// the host's navigation bar.
type tabBar struct {
b *Backend
id int
h platform.TabsHandler
}
func (b *Backend) NewTabs(tabs []platform.Tab, h platform.TabsHandler) (platform.TabBar, error) {
b.nextID++
t := &tabBar{b: b, id: b.nextID, h: h}
b.call(&wire.CreateTabs{ID: t.id}, nil)
old := b.front()
for i, tab := range tabs {
w := tab.Window.(*window)
w.visible = true
w.tabs, w.tabIndex = t, i
b.unshow(w)
b.shown = append(b.shown, w)
b.call(&wire.AddTab{ID: t.id, Window: w.id, Title: tab.Title, Symbol: tab.Symbol, Icon: tab.Icon}, nil)
}
// The first tab is in front.
first := tabs[0].Window.(*window)
b.unshow(first)
b.shown = append(b.shown, first)
b.tabs[t.id] = t
b.call(&wire.ShowTabs{ID: t.id}, nil)
b.refocus(old)
return t, nil
}
func (t *tabBar) Select(i int) {
t.fronted(i)
t.b.call(&wire.SelectTab{ID: t.id, Index: i}, nil)
}
// fronted makes the windows of tab i those in front, in the order they were.
func (t *tabBar) fronted(i int) {
b := t.b
old := b.front()
var mine, rest []*window
for _, w := range b.shown {
if w.tabs == t && w.tabIndex == i {
mine = append(mine, w)
} else {
rest = append(rest, w)
}
}
b.shown = append(rest, mine...)
b.refocus(old)
}
func (t *tabBar) SetBadge(i int, badge string) {
t.b.call(&wire.SetTabBadge{ID: t.id, Index: i, Badge: badge}, nil)
}
func (t *tabBar) Close() {
delete(t.b.tabs, t.id)
t.b.call(&wire.CloseTabs{ID: t.id}, nil)
}
func (b *Backend) PushWindow(parent, child platform.Window, animated bool) {
p, c := parent.(*window), child.(*window)
c.tabs, c.tabIndex = p.tabs, p.tabIndex
old := b.front()
c.visible = true
b.unshow(c)
b.shown = append(b.shown, c)
b.call(&wire.PushWindow{Parent: p.id, Child: c.id, Title: c.title, Animated: animated}, nil)
b.refocus(old)
}
func (b *Backend) PopWindow(w platform.Window, animated bool) {
b.call(&wire.PopWindow{ID: w.(*window).id, Animated: animated}, nil)
}
// handleNavigation handles the events of navigation, and reports whether
// op was one.
func (b *Backend) handleNavigation(op uint64, r *wire.Reader) bool {
switch op {
case wire.EventTabSelected:
var e wire.TabSelectedEvent
e.Decode(r)
if t := b.tabs[e.ID]; t != nil {
t.fronted(e.Index)
t.h.TabSelected(e.Index)
}
case wire.EventBarItemClicked:
var e wire.BarItemClickedEvent
e.Decode(r)
if w := b.windows[e.ID]; w != nil && e.Index >= 0 && e.Index < len(w.barItems) {
if fn := w.barItems[e.Index].OnClick; fn != nil {
fn()
}
}
case wire.EventPopped:
var e wire.PoppedEvent
e.Decode(r)
if w := b.windows[e.ID]; w != nil {
if h, ok := w.h.(platform.NavigationHandler); ok {
h.Popped()
} else {
w.Close()
}
}
default:
return false
}
return true
}
+333
View File
@@ -0,0 +1,333 @@
package mobile
import (
"bytes"
"sync"
"testing"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/internal/wait"
)
// textClient is a document of a text input, without its layout.
type textClient struct {
text string
sel, marked platform.TextRange
isMarked bool
}
func (c *textClient) TextForRange(r platform.TextRange) (string, platform.TextRange) {
a, z := min(r.Start, len(c.text)), min(r.End, len(c.text))
return c.text[a:z], platform.TextRange{Start: a, End: z}
}
func (c *textClient) Selection() platform.TextSelection { return platform.TextSelection{Range: c.sel} }
func (c *textClient) MarkedRange() (platform.TextRange, bool) {
return c.marked, c.isMarked
}
func (c *textClient) ReplaceText(r *platform.TextRange, s string) {
to := c.sel
if r != nil {
to = *r
} else if c.isMarked {
to = c.marked
}
c.text = c.text[:to.Start] + s + c.text[to.End:]
c.sel = platform.TextRange{Start: to.Start + len(s), End: to.Start + len(s)}
c.isMarked = false
}
func (c *textClient) SetMarkedText(r *platform.TextRange, s string, sel platform.TextRange) {
c.ReplaceText(r, s)
c.marked, c.isMarked = platform.TextRange{Start: c.sel.Start - len(s), End: c.sel.Start}, true
}
func (c *textClient) UnmarkText() { c.isMarked = false }
func (c *textClient) BoundsForRange(r platform.TextRange) (platform.RectF, platform.TextRange, bool) {
return platform.RectF{X: float64(r.Start) * 10, Y: 20, W: 2, H: 16}, r, true
}
func (c *textClient) IndexForPoint(x, y float64) (int, bool) { return int(x) / 10, true }
// surfaceEvents hears what a surface sends its content.
type surfaceEvents struct {
platform.WindowHandler
mu sync.Mutex
events []platform.SurfaceEvent
}
func (w *surfaceEvents) SurfaceEvent(ev platform.SurfaceEvent) bool {
w.mu.Lock()
defer w.mu.Unlock()
w.events = append(w.events, ev)
return false
}
func (w *surfaceEvents) kinds(k platform.SurfaceEventKind) int {
w.mu.Lock()
defer w.mu.Unlock()
n := 0
for _, e := range w.events {
if e.Kind == k {
n++
}
}
return n
}
// surfaceWindow makes a window of native UI, with a surface to draw on.
func surfaceWindow(t *testing.T, b *Backend, h *fakeHost) (*window, *surfaceEvents) {
t.Helper()
wh := &surfaceEvents{}
var w *window
onMain(b, func() {
pw, err := b.NewWindow(&platform.WindowOptions{Surface: true}, wh)
if err != nil {
t.Fatal(err)
}
w = pw.(*window)
w.s.handle = 1
w.width, w.height = 400, 800
})
return w, wh
}
// The keyboard edits the document through its client, by UTF-16 offsets, and
// gets the state after each edit in the answer.
func TestKeyboardEdits(t *testing.T) {
b, h := startBackend(t)
w, _ := surfaceWindow(t, b, h)
c := &textClient{text: "hello", sel: platform.TextRange{Start: 5, End: 5}}
onMain(b, func() {
w.s.SetTextInput(platform.TextInputState{Active: true, Client: c,
Traits: platform.TextTraits{Keyboard: platform.KeyboardEmail, Secure: true}})
})
wait.Until(t, "the host to hear of the input", func() bool { return h.called(wire.CallSetTextInput) })
ask := func(f func(w *wire.Writer)) wire.TextStateReply {
var reply []byte
h.onUI(func() { reply = deliver(encodeEvent(f), true) })
r := wire.Reader{Buf: reply}
return wire.TextStateReply{Text: r.String(), Base: r.Int(), Length: r.Int(), SelStart: r.Int(), SelEnd: r.Int(), MarkStart: r.Int(), MarkEnd: r.Int()}
}
st := ask(func(wr *wire.Writer) {
wr.Uvarint(wire.EventTextReplace)
wr.Int(w.id)
wr.Bool(false)
wr.Int(0)
wr.Int(0)
wr.String(" big")
})
if c.text != "hello big" || st.Text != "hello big" || st.SelStart != 9 || st.Length != 9 || st.MarkStart != -1 {
t.Errorf("typed: %q, state %+v", c.text, st)
}
st = ask(func(wr *wire.Writer) {
wr.Uvarint(wire.EventTextMark)
wr.Int(w.id)
wr.Bool(false)
wr.Int(0)
wr.Int(0)
wr.String("xy")
wr.Int(2)
wr.Int(2)
})
if st.MarkStart != 9 || st.MarkEnd != 11 {
t.Errorf("composing: state %+v", st)
}
st = ask(func(wr *wire.Writer) {
wr.Uvarint(wire.EventTextReplace)
wr.Int(w.id)
wr.Bool(false)
wr.Int(0)
wr.Int(0)
wr.String("!")
})
if c.text != "hello big!" || st.MarkStart != -1 {
t.Errorf("committed: %q, state %+v", c.text, st)
}
// A return typed is the key, not text.
st = ask(func(wr *wire.Writer) {
wr.Uvarint(wire.EventTextReplace)
wr.Int(w.id)
wr.Bool(false)
wr.Int(0)
wr.Int(0)
wr.String("\n")
})
if c.text != "hello big!" {
t.Errorf("return: %q", c.text)
}
if wh := w.h.(*surfaceEvents); wh.kinds(platform.KeyPressed) != 1 {
t.Errorf("return: %d keys", wh.kinds(platform.KeyPressed))
}
}
// A password's document does not show: what the keyboard deletes goes as keys.
func TestSecureDeletesByKeys(t *testing.T) {
b, h := startBackend(t)
w, wh := surfaceWindow(t, b, h)
onMain(b, func() {
w.s.SetTextInput(platform.TextInputState{Active: true, Client: &textClient{}, Traits: platform.TextTraits{Secure: true}})
})
h.onUI(func() {
deliver(encodeEvent(func(wr *wire.Writer) {
wr.Uvarint(wire.EventTextDelete)
wr.Int(w.id)
wr.Int(2)
wr.Int(0)
}), true)
})
if n := wh.kinds(platform.KeyPressed); n != 2 {
t.Errorf("%d keys", n)
}
}
// Frames stop in the background, where iOS ends apps that use the GPU, and the
// one held back draws as the app comes back.
func TestNoFramesInBackground(t *testing.T) {
b, h := startBackend(t)
w, wh := surfaceWindow(t, b, h)
frame := func() {
h.onUI(func() {
deliver(encodeEvent(func(wr *wire.Writer) {
wr.Uvarint(wire.EventFrame)
wr.Int(w.id)
}), true)
})
onMain(b, func() {})
}
bg := func(on bool) {
h.onUI(func() {
deliver(encodeEvent(func(wr *wire.Writer) {
wr.Uvarint(wire.EventBackground)
wr.Bool(on)
}), true)
})
}
frame()
if n := wh.kinds(platform.SurfaceFrame); n != 1 {
t.Fatalf("%d frames", n)
}
bg(true)
frame()
if n := wh.kinds(platform.SurfaceFrame); n != 1 {
t.Fatalf("in the background: %d frames", n)
}
h.mu.Lock()
h.calls = nil
h.mu.Unlock()
bg(false)
wait.Until(t, "the frame to be asked for", func() bool { return h.called(wire.CallRequestFrame) })
}
// A link the app is opened with, sent before the app made its backend, reaches
// it.
func TestEarlyEvents(t *testing.T) {
current.Store(nil)
deliver(encodeEvent(func(w *wire.Writer) {
w.Uvarint(wire.EventOpenURLs)
w.Strings([]string{"myapp://first"})
}), true)
b := New()
if len(b.events) != 1 {
t.Fatalf("%d events wait", len(b.events))
}
if !bytes.Contains(b.events[0].msg, []byte("myapp://first")) {
t.Errorf("event %q", b.events[0].msg)
}
early.events = nil
}
// A plugin's method answers through its request, or with its error.
func TestPluginCall(t *testing.T) {
b, h := startBackend(t)
type res struct {
data []byte
err error
}
got := make(chan res, 2)
call := func() {
onMain(b, func() {
b.PluginCall("location", "current", []byte("{}"), func(d []byte, err error) { got <- res{d, err} })
})
}
call()
wait.Until(t, "the call", func() bool { return h.called(wire.CallPluginCall) })
h.onUI(func() {
deliver(encodeEvent(func(w *wire.Writer) {
w.Uvarint(wire.EventPluginResult)
w.Int(1)
w.String(`{"a":1}`)
w.String("")
w.String("")
}), true)
})
r := wait.For(t, "the answer", got)
if string(r.data) != `{"a":1}` || r.err != nil {
t.Errorf("answer %q, %v", r.data, r.err)
}
call()
h.onUI(func() {
deliver(encodeEvent(func(w *wire.Writer) {
w.Uvarint(wire.EventPluginResult)
w.Int(2)
w.String("")
w.String("no")
w.String("Denied")
}), true)
})
r = wait.For(t, "the error", got)
if pe, ok := r.err.(*platform.PluginError); !ok || pe.Code != "Denied" {
t.Errorf("error %v", r.err)
}
}
// Web views close with the window that holds them, and hear nothing of it.
func TestHeldViews(t *testing.T) {
b, h := startBackend(t)
w, _ := surfaceWindow(t, b, h)
var v platform.WebView
onMain(b, func() {
var err error
v, err = w.s.NewWebView(&platform.WindowOptions{}, &winHandler{})
if err != nil {
t.Error(err)
}
w.s.PlaceWebViews([]platform.WebViewPlacement{{WebView: v, Clip: platform.RectF{W: 10, H: 10}, Frame: platform.RectF{W: 10, H: 10}}})
})
wait.Until(t, "the host to hear where it goes", func() bool { return h.called(wire.CallPlaceViews) })
child := v.(*window)
onMain(b, func() { v.Close() })
if !child.closed || len(w.children) != 0 {
t.Errorf("closed %v, children %d", child.closed, len(w.children))
}
}
// Four fingers open the inspector where developer tools are on, and do nothing
// in a release, whose apps may take them.
func TestFourFingers(t *testing.T) {
b, h := startBackend(t)
w, wh := surfaceWindow(t, b, h)
touch := func(pointer int) {
onMain(b, func() {
w.s.touch(&wire.TouchEvent{ID: w.id, Pointer: pointer, Phase: "down", Kind: "touch", X: float64(pointer) * 40, Y: 100})
})
}
lift := func(pointer int) {
onMain(b, func() {
w.s.touch(&wire.TouchEvent{ID: w.id, Pointer: pointer, Phase: "up", Kind: "touch", X: float64(pointer) * 40, Y: 100})
})
}
for p := 1; p <= 4; p++ {
touch(p)
}
if n := wh.kinds(platform.KeyPressed); n != 0 {
t.Errorf("without developer tools, %d keys", n)
}
for p := 1; p <= 4; p++ {
lift(p)
}
onMain(b, func() { w.devTools = true })
for p := 1; p <= 4; p++ {
touch(p)
}
if n := wh.kinds(platform.KeyPressed); n != 1 {
t.Errorf("with them, %d keys", n)
}
}
+330
View File
@@ -0,0 +1,330 @@
package mobile
import (
"errors"
"os"
"path/filepath"
"strings"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/internal/unsupported"
"github.com/egoist/mygo/transfer"
)
type appController struct {
unsupported.App
b *Backend
}
func (a appController) IsActive() bool { return a.b.front() != nil }
func (a appController) PreferredLanguages() []string {
if l := a.b.appInfo().Languages; len(l) > 0 {
return l
}
return []string{"en-US"}
}
func (a appController) Region() platform.Region {
i := a.b.appInfo()
return platform.Region{Locale: i.RegionLocale, FirstWeekday: i.FirstWeekday, HourCycle: i.HourCycle}
}
func (a appController) Package() (platform.PackageInfo, bool) {
i := a.b.appInfo()
if i.Identifier == "" {
return platform.PackageInfo{}, false
}
return platform.PackageInfo{Name: i.Name, Version: i.Version, Identifier: i.Identifier}, true
}
// URL schemes are the bundle's (Info.plist) and the manifest's: the
// system knows them as the app is installed.
func (a appController) RegisterURLScheme(string, string, string) error { return nil }
func (a appController) IsURLSchemeRegistered(string, string, string) bool { return true }
type dialogs struct {
unsupported.Dialogs
b *Backend
}
func (d dialogs) ShowMessageBox(_ platform.Window, o *platform.MessageBoxOptions, cb func(platform.MessageBoxResult, error)) {
buttons := o.Buttons
if len(buttons) == 0 {
buttons = []string{"OK"}
}
req := d.b.request(func(r wire.Reader) {
var e wire.MessageBoxResultEvent
e.Decode(&r)
cb(platform.MessageBoxResult{Response: e.Response, CheckboxChecked: o.CheckboxChecked}, nil)
})
d.b.call(&wire.MessageBox{Req: req, Type: o.Type, Title: o.Title, Message: o.Message, Detail: o.Detail,
Buttons: buttons, DefaultID: o.DefaultID, CancelID: o.CancelID}, nil)
}
// ShowOpenDialog shows the system's picker of documents, which gives the
// app copies of the files chosen, in its temporary directory: phones give
// apps no paths of other apps' files.
func (d dialogs) ShowOpenDialog(_ platform.Window, o *platform.OpenDialogOptions, cb func([]string, error)) {
var exts []string
for _, f := range o.Filters {
for _, e := range f.Extensions {
if e != "*" {
exts = append(exts, strings.TrimPrefix(e, "."))
}
}
}
req := d.b.request(func(r wire.Reader) {
var e wire.FilesResultEvent
e.Decode(&r)
cb(e.Paths, errorOf(e.Error))
})
d.b.call(&wire.OpenFiles{Req: req, Multiple: o.Multiple, Directories: o.OpenDirectories && !o.OpenFiles, Extensions: exts}, nil)
}
// ShowSaveDialog answers with a temporary file for the app to write, as phones
// have no paths of other apps' folders; DialogModule.SaveData has the user
// choose where a copy of it goes.
func (d dialogs) ShowSaveDialog(_ platform.Window, o *platform.SaveDialogOptions, cb func(string, error)) {
name := filepath.Base(o.DefaultPath)
if name == "." || name == "/" || name == "" {
name = "Untitled"
}
dir, err := os.MkdirTemp(d.b.appInfo().TempDir, "save")
if err != nil {
cb("", err)
return
}
cb(filepath.Join(dir, name), nil)
}
type clipboard struct {
unsupported.Clipboard
b *Backend
}
func (c clipboard) ReadImage() []byte {
var r wire.ClipboardImageReply
c.b.call(&wire.ClipboardImage{}, &r)
return r.PNG
}
func (c clipboard) WriteImage(png []byte) error {
c.b.call(&wire.SetClipboardImage{PNG: png}, nil)
return nil
}
func (c clipboard) ReadText() string {
var r wire.ClipboardTextReply
c.b.call(&wire.ClipboardText{}, &r)
return r.Text
}
func (c clipboard) WriteText(s string) { c.b.call(&wire.SetClipboardText{Text: s}, nil) }
func (c clipboard) Clear() { c.WriteText("") }
func (c clipboard) AvailableFormats() []string {
var out []string
if _, ok := c.text(); ok {
out = append(out, "text/plain")
}
if len(c.ReadImage()) > 0 {
out = append(out, "image/png")
}
return out
}
func (c clipboard) text() (string, bool) {
var r wire.ClipboardTextReply
c.b.call(&wire.ClipboardText{}, &r)
return r.Text, r.OK
}
func (c clipboard) Formats() []transfer.Format {
var out []transfer.Format
if _, ok := c.text(); ok {
out = append(out, transfer.Text)
}
if len(c.ReadImage()) > 0 {
out = append(out, transfer.PNG)
}
return out
}
func (c clipboard) ReadData(formats []transfer.Format) (transfer.Data, error) {
var reps []transfer.Representation
for _, f := range formats {
switch f {
case transfer.Text:
if s, ok := c.text(); ok {
reps = append(reps, transfer.Bytes(transfer.Text, []byte(s)))
}
case transfer.PNG:
if png := c.ReadImage(); len(png) > 0 {
reps = append(reps, transfer.Bytes(transfer.PNG, png))
}
}
}
if len(reps) == 0 {
return transfer.Data{}, nil
}
return transfer.New(transfer.NewItem(reps...)), nil
}
// WatchChanges is unsupported: neither system tells an app in the
// background of the clipboard's changes.
func (c clipboard) WatchChanges(func()) (func(), error) { return nil, platform.ErrUnsupported }
// WriteData writes d. Phones keep no concealed flag the app can set
// through these calls, so concealed is ignored.
func (c clipboard) WriteData(d transfer.Data, _ bool, _ func()) error {
wrote := false
if b, err := d.Read(transfer.PNG); err == nil {
c.WriteImage(b)
wrote = true
}
// The system's clipboard holds one or the other through these calls:
// text, what's pasted most, wins.
if b, err := d.Read(transfer.Text); err == nil {
c.WriteText(string(b))
wrote = true
}
if !wrote {
return errUnsupported
}
return nil
}
func (c clipboard) Flush() error { return nil }
type shell struct {
unsupported.Shell
b *Backend
}
func (s shell) OpenExternal(url string) error {
var r wire.OpenURLReply
s.b.call(&wire.OpenURL{URL: url}, &r)
if !r.OK {
return errors.New("mygo: no app opens " + url)
}
return nil
}
// OpenPath shares the file, as phones open another app's documents.
func (s shell) OpenPath(path string) error {
s.b.call(&wire.ShareFile{Path: path}, nil)
return nil
}
func (s shell) ShowItemInFolder(path string) { s.b.call(&wire.ShareFile{Path: path}, nil) }
// Phones have no trash, no Quick Look of the app's own and no default
// apps the app can ask for.
func (shell) TrashItemResult(string) (string, error) { return "", platform.ErrUnsupported }
func (shell) PreviewItem(string) error { return platform.ErrUnsupported }
func (shell) DefaultApp(string) (platform.Application, error) {
return platform.Application{}, platform.ErrUnsupported
}
func (s shell) Beep() { s.b.call(&wire.Haptic{Kind: "warning"}, nil) }
type screen struct {
unsupported.Screen
b *Backend
}
func (s screen) Displays() []platform.Display {
var r wire.ScreenReply
s.b.call(&wire.Screen{}, &r)
rect := platform.Rect{Width: int(r.Width + 0.5), Height: int(r.Height + 0.5)}
work := rect
if w := s.b.front(); w != nil {
work = platform.Rect{X: int(w.insets.Left), Y: int(w.insets.Top),
Width: int(r.Width - w.insets.Left - w.insets.Right), Height: int(r.Height - w.insets.Top - w.insets.Bottom)}
}
return []platform.Display{{ID: 1, Label: s.b.appInfo().Model, Bounds: rect, WorkArea: work, ScaleFactor: r.Scale,
Internal: true, Primary: true}}
}
type theme struct {
unsupported.Theme
b *Backend
}
func (t theme) IsDark() bool { return t.b.dark }
func (t theme) SetSource(source string) { t.b.call(&wire.SetAppearance{Source: source}, nil) }
func (t theme) Preferences() platform.Preferences {
var r wire.ThemeReply
t.b.call(&wire.Theme{}, &r)
return platform.Preferences{Accent: colorOf(r.Accent), ReduceMotion: r.ReduceMotion,
ReduceTransparency: r.ReduceTransparency, HighContrast: r.IncreaseContrast, TextScale: r.TextScale}
}
type power struct {
unsupported.Power
b *Backend
}
// KeepAwake keeps the screen on, as phones keep apps running while their
// screens show them.
// KeepRunning does nothing: the systems suspend an app in the
// background as they choose (plugins/background schedules work).
func (power) KeepRunning(string) func() { return func() {} }
func (p power) KeepAwake(_ bool, _ string) func() {
p.b.call(&wire.KeepAwake{On: true}, nil)
return func() { p.b.call(&wire.KeepAwake{On: false}, nil) }
}
func (p power) OnBattery() bool {
var r wire.BatteryReply
p.b.call(&wire.Battery{}, &r)
return !r.Charging
}
type network struct {
unsupported.Network
b *Backend
}
func (n network) Watch() { n.b.call(&wire.WatchNetwork{}, nil) }
func (n network) Status() platform.NetworkStatus {
var r wire.NetworkStatusReply
n.b.call(&wire.NetworkStatus{}, &r)
return platform.NetworkStatus{Online: r.Online, Metered: r.Metered}
}
type secrets struct {
unsupported.Secrets
b *Backend
}
func (s secrets) SetSecret(service, account string, value []byte) error {
var r wire.SecretSetReply
s.b.call(&wire.SecretSet{Service: service, Account: account, Value: value}, &r)
return errorOf(r.Error)
}
func (s secrets) Secret(service, account string) ([]byte, error) {
var r wire.SecretGetReply
s.b.call(&wire.SecretGet{Service: service, Account: account}, &r)
if err := errorOf(r.Error); err != nil {
return nil, err
}
if !r.Found {
return nil, platform.ErrSecretNotFound
}
return r.Value, nil
}
func (s secrets) DeleteSecret(service, account string) error {
var r wire.SecretDeleteReply
s.b.call(&wire.SecretDelete{Service: service, Account: account}, &r)
return errorOf(r.Error)
}
+87
View File
@@ -0,0 +1,87 @@
package mobile
import (
"bufio"
"bytes"
"os"
"runtime"
_ "unsafe" // go:linkname
)
// mainMain is the app's main function, which the build modes of phones
// (c-archive, c-shared) compile but don't run: start runs it.
//
//go:linkname mainMain main.main
func mainMain()
// start runs the app's main function on a thread of its own, Go's main
// thread, once the host is there.
func start() {
redirectOutput()
if h, ok := theHost.(interface{ callHere(msg []byte) []byte }); ok {
askTimeZone(h)
}
go func() {
runtime.LockOSThread()
mainMain()
}()
}
// drain runs the calls Go made of the host, on the UI thread.
func drain() {
if b := current.Load(); b != nil && b.t != nil {
b.t.drain()
}
}
// redirectOutput sends what the app writes to its standard output and
// error to the system's log, line by line, where phones show nothing of
// them.
func redirectOutput() {
for _, f := range []struct {
file **os.File
err bool
}{{&os.Stdout, false}, {&os.Stderr, true}} {
r, w, err := os.Pipe()
if err != nil {
continue
}
if dupOutput(w, *f.file) != nil {
r.Close()
w.Close()
continue
}
w.Close() // the standard descriptor writes to the pipe now
isErr := f.err
go func() {
s := bufio.NewScanner(r)
s.Buffer(make([]byte, 4096), 1<<20)
for s.Scan() {
if !chromiumLine(s.Bytes()) {
hostLog(isErr, s.Bytes())
}
}
}()
}
}
// chromiumLine reports whether line is a log line of Android's web view,
// which writes to the process's standard error too, as
// "[1031/124014.395252:INFO:file.cc:67] ...": it logs to the system's log
// itself.
func chromiumLine(line []byte) bool {
if len(line) < 2 || line[0] != '[' {
return false
}
end := bytes.IndexByte(line, ']')
if end < 0 {
return false
}
head := line[1:end]
for _, level := range []string{":INFO:", ":WARNING:", ":ERROR:", ":VERBOSE"} {
if bytes.Contains(head, []byte(level)) || bytes.HasPrefix(head, []byte(level[1:])) {
return true
}
}
return false
}
+673
View File
@@ -0,0 +1,673 @@
package mobile
import (
"math"
"runtime"
"strconv"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/transfer"
)
// surface is the drawing area of a window of native UI: a CAMetalLayer the
// Metal renderer draws into on iOS, an ANativeWindow an EGL context draws
// into on Android, which the host made (CreateWindow, SurfaceChanged).
// Frames come at the display's refreshes the content asks for
// (RequestFrame, Frame). A finger is the pointer while it touches the
// screen, and there is no pointer once it lifts (SurfaceEvent.Touch).
type surface struct {
w *window
handle uintptr
// refresh is how many times a second the display refreshes.
refresh float64
pending bool // a frame asked of the host
gone bool
// deferred is a frame the app in the background did not draw.
deferred bool
cursor platform.Cursor
// mouseButton is the button of a mouse that went down.
mouseButton int
// The fingers on the screen, by the host's numbers: the first is the
// pointer, two pinch.
primary int
touching bool
fingers map[int][2]float64
pinchDist float64
// pinchAngle is the line between two fingers, once pinchTurning.
pinchAngle float64
pinchTurning bool
// lastTap is where and when the last tap ended, for double taps.
lastTapX, lastTapY, lastTapTime float64
taps int
text platform.TextInputState
textSent wire.SetTextInput
// textSerial counts the inputs that took the keyboard.
textSerial int
marked string
access *platform.AccessTree
accessOn bool
}
func newSurface(w *window) *surface {
return &surface{w: w, refresh: 60, fingers: map[int][2]float64{}}
}
func (s *surface) send(ev platform.SurfaceEvent) bool {
if s.gone {
return false
}
return s.w.h.SurfaceEvent(ev)
}
// resized tells the content the window's new size, or that its insets
// changed, which moves what it lays out inside them.
func (s *surface) resized(size, insets bool) {
if size {
s.send(platform.SurfaceEvent{Kind: platform.SurfaceResize})
}
if size || insets {
s.RequestFrame()
}
}
func (s *surface) closed() {
s.gone = true
}
func (s *surface) themeChanged() { s.RequestFrame() }
// lowMemory has the content let go of what it can make again.
func (s *surface) lowMemory() { s.send(platform.SurfaceEvent{Kind: platform.SurfaceLowMemory}) }
// back hands Android's back to the content: Escape, which closes a menu
// or a dialog, then the Back key, as a mouse's back button, which a
// Router takes to go back. It reports whether the content took either.
func (s *surface) back() bool {
for _, k := range []platform.Key{platform.KeyEscape, platform.KeyBack} {
taken := s.send(platform.SurfaceEvent{Kind: platform.KeyPressed, Key: k})
s.send(platform.SurfaceEvent{Kind: platform.KeyReleased, Key: k})
if taken {
return true
}
}
return false
}
// Native is the CAMetalLayer of iOS, the ANativeWindow of Android.
func (s *surface) Native() platform.SurfaceNative {
if mapsSchemes { // Android
return platform.SurfaceNative{Window: s.handle}
}
return platform.SurfaceNative{Layer: s.handle}
}
func (s *surface) Size() (float64, float64, float64) { return s.w.width, s.w.height, s.w.scale }
// Insets are those of the system's bars, the cutout and the keyboard: the
// content lays out above the keyboard while it shows.
func (s *surface) Insets() platform.Insets {
in := s.w.insets
in.Bottom = max(in.Bottom, s.w.keyboard)
return in
}
func (s *surface) RequestFrame() {
if s.pending || s.gone {
return
}
s.pending = true
s.w.b.call(&wire.RequestFrame{ID: s.w.id}, nil)
}
func (s *surface) RefreshRate() float64 { return s.refresh }
// frame draws the frame the content asked for, at a refresh.
func (s *surface) frame() {
s.pending = false
if s.gone || s.handle == 0 || s.w.width == 0 {
return
}
// The GPU is not ours in the background, and iOS ends apps that use it
// there. The content draws again as the app comes back (surfaces asks).
if s.w.b.background {
s.deferred = true
return
}
s.send(platform.SurfaceEvent{Kind: platform.SurfaceFrame})
if s.text.Active {
s.syncText()
}
}
// foreground draws the frame the background held back.
func (s *surface) foreground() {
if s.deferred {
s.deferred = false
s.RequestFrame()
}
}
// PresentPixels has nothing to show frames drawn in memory on: phones
// draw with their GPUs.
func (s *surface) PresentPixels([]byte, int, int, int) {}
// SetCursor shows a mouse's or a trackpad's pointer, on an iPad or a Chromebook.
func (s *surface) SetCursor(c platform.Cursor) {
if c == s.cursor {
return
}
s.cursor = c
name := "default"
switch c {
case platform.CursorPointer:
name = "pointer"
case platform.CursorText, platform.CursorVerticalText:
name = "text"
case platform.CursorMove:
name = "move"
case platform.CursorResizeEW, platform.CursorResizeE, platform.CursorResizeW, platform.CursorResizeColumn:
name = "resizeX"
case platform.CursorResizeNS, platform.CursorResizeN, platform.CursorResizeS, platform.CursorResizeRow:
name = "resizeY"
case platform.CursorGrab:
name = "grab"
case platform.CursorGrabbing:
name = "grabbing"
case platform.CursorCrosshair:
name = "crosshair"
case platform.CursorNotAllowed:
name = "notAllowed"
case platform.CursorNone:
name = "none"
}
s.w.b.call(&wire.SetCursor{ID: s.w.id, Cursor: name}, nil)
}
// SetBackground tells the host the color the content's frames fill the
// window with, which the system's bars around it take on Android (its
// toolbar, its bottom navigation), for the screen to be of one color.
func (s *surface) SetBackground(c platform.Color) {
if c == s.w.bg {
return
}
s.w.bg = c
s.w.b.call(&wire.SetBackground{ID: s.w.id, Color: rgba(c)}, nil)
}
func (s *surface) UpdateAccessibility(tree *platform.AccessTree) {
old := s.access
s.access = tree
if !s.accessOn {
return
}
changed := old == nil || len(old.Nodes) != len(tree.Nodes) || old.Focus != tree.Focus
if !changed {
for i := range tree.Nodes {
a, b := &old.Nodes[i], &tree.Nodes[i]
if a.ID != b.ID || a.Label != b.Label || a.Value != b.Value || a.Bounds != b.Bounds || a.States != b.States ||
a.Now != b.Now || a.Min != b.Min || a.Max != b.Max || a.Actions != b.Actions || a.Description != b.Description {
changed = true
break
}
}
}
if changed {
s.w.b.call(&wire.AccessibilityChanged{ID: s.w.id, Focus: int(tree.Focus)}, nil)
}
for _, a := range tree.Announcements {
s.w.b.call(&wire.Announce{Text: a}, nil)
}
}
func (s *surface) Haptic(kind string) { s.w.b.Haptic(kind) }
func (s *surface) ShowEditMenu(x, y float64, actions []string) {
s.w.b.call(&wire.ShowMenu{ID: s.w.id, X: x, Y: y, Actions: actions}, nil)
}
func (s *surface) SetBackAvailable(on bool) {
s.w.b.call(&wire.SetBackAvailable{ID: s.w.id, On: on}, nil)
}
// CanStack: a window of its own scene, or one a surface holds, is in no stack.
func (s *surface) CanStack() bool { return !s.w.opts.OwnScene && s.w.parent == nil }
// StackMoves: UIKit's navigation controller moves its screens; Android's apps
// move their pages themselves.
func (s *surface) StackMoves() bool { return runtime.GOOS == "ios" }
func (s *surface) SetStack(screens []platform.StackScreen) {
c := wire.SetStack{ID: s.w.id, Titles: make([]string, len(screens)), Keys: make([]string, len(screens))}
for i, sc := range screens {
c.Titles[i], c.Keys[i] = sc.Title, strconv.FormatUint(sc.Key, 10)
}
s.w.b.call(&c, &wire.SetStackReply{})
}
func (s *surface) StackShown() { s.w.b.call(&wire.StackShown{ID: s.w.id}, nil) }
func (s *surface) ShowMagnifier(x, y float64) {
s.w.b.call(&wire.ShowMagnifier{ID: s.w.id, X: x, Y: y}, nil)
}
func (s *surface) HideMagnifier() { s.w.b.call(&wire.HideMagnifier{ID: s.w.id}, nil) }
func (s *surface) StartDataDrag(platform.DragRequest) {}
func (s *surface) CancelDataDrag() {}
func (s *surface) SetDropFormats([]transfer.Format) {}
// NewWebView makes a web view the host holds under the surface, hidden until
// PlaceWebViews shows it.
func (s *surface) NewWebView(o *platform.WindowOptions, h platform.WindowHandler) (platform.WebView, error) {
return s.w.b.makeWindow(o, h, s.w, "", "")
}
// NewPluginView makes a view of a plugin's native code, under the surface as a
// web view is (platform.PluginViewSurface).
func (s *surface) NewPluginView(viewType string, args []byte, h platform.WindowHandler) (platform.WebView, error) {
o := &platform.WindowOptions{}
return s.w.b.makeWindow(o, h, s.w, viewType, string(args))
}
// EmbedView shows a view of a native module's under the surface, as a
// plugin's view is (platform.ViewSurface): the host finds it by its
// handle, among the objects of the modules' Swift or Kotlin. It has no
// page to tell of: its handler is its host's, which hears nothing from it.
func (s *surface) EmbedView(view uintptr) (platform.WebView, error) {
return s.w.b.makeWindow(&platform.WindowOptions{}, s.w.h, s.w, nativeViewType, strconv.FormatUint(uint64(view), 10))
}
// nativeViewType is the type of plugin view of a native module's view.
const nativeViewType = "mygo.native"
// PlaceWebViews shows the views the surface holds where the content shows
// them; the frames are transparent there, and the host routes fingers to them
// but where the content painted over them.
func (s *surface) PlaceWebViews(views []platform.WebViewPlacement) {
var w wire.Writer
for _, p := range views {
v, ok := p.WebView.(*window)
if !ok || v.closed {
continue
}
w.Int(v.id)
for _, r := range []platform.RectF{p.Frame, p.Clip} {
w.Float(r.X)
w.Float(r.Y)
w.Float(r.W)
w.Float(r.H)
}
w.Int(len(p.Covers))
for _, r := range p.Covers {
w.Float(r.X)
w.Float(r.Y)
w.Float(r.W)
w.Float(r.H)
}
}
s.w.b.call(&wire.PlaceViews{ID: s.w.id, Places: w.Buf}, nil)
}
// FirstFrame tells the host that there's something to show: Android holds its
// splash until then, rather than showing a surface with nothing on it.
func (s *surface) FirstFrame() { s.w.b.call(&wire.FirstFrame{ID: s.w.id}, nil) }
// touch turns a finger, a pen or a mouse into pointer events: the first
// finger is the pointer, a second pinches, and a tap soon after another
// near it counts as a double tap.
func (s *surface) touch(e *wire.TouchEvent) {
if e.Kind != "touch" {
s.mouse(e)
return
}
switch e.Phase {
case "down":
s.fingers[e.Pointer] = [2]float64{e.X, e.Y}
if len(s.fingers) == 4 && s.w.devTools {
// Four fingers open the inspector, as F12 does: a phone has no such
// key, and the system and games keep fewer fingers to themselves.
s.send(platform.SurfaceEvent{Kind: platform.KeyPressed, Key: platform.KeyF12})
s.send(platform.SurfaceEvent{Kind: platform.KeyReleased, Key: platform.KeyF12})
return
}
if len(s.fingers) == 2 {
s.pinchDist = s.spread()
if s.touching {
// Pinching, not pressing: the press ends without a click.
s.cancel()
}
return
}
if len(s.fingers) > 1 {
return
}
s.primary, s.touching = e.Pointer, true
if e.Time-s.lastTapTime < 0.3 && math.Hypot(e.X-s.lastTapX, e.Y-s.lastTapY) < 24 {
s.taps++
} else {
s.taps = 1
}
s.send(platform.SurfaceEvent{Kind: platform.PointerMove, X: e.X, Y: e.Y, Touch: true})
s.send(platform.SurfaceEvent{Kind: platform.PointerDown, X: e.X, Y: e.Y, Clicks: s.taps, Touch: true})
case "move":
if _, ok := s.fingers[e.Pointer]; !ok {
return
}
s.fingers[e.Pointer] = [2]float64{e.X, e.Y}
if len(s.fingers) == 2 {
d := s.spread()
if s.pinchDist > 0 && d > 0 {
cx, cy := s.center()
s.send(platform.SurfaceEvent{Kind: platform.PointerMove, X: cx, Y: cy, Touch: true})
s.send(platform.SurfaceEvent{Kind: platform.PointerZoom, X: cx, Y: cy, Scale: d / s.pinchDist, Touch: true})
}
s.pinchDist = d
return
}
if s.touching && e.Pointer == s.primary {
s.send(platform.SurfaceEvent{Kind: platform.PointerMove, X: e.X, Y: e.Y, Touch: true})
}
case "up", "cancel":
delete(s.fingers, e.Pointer)
if len(s.fingers) < 2 {
s.pinchDist = 0
} else if len(s.fingers) == 2 {
s.pinchDist = s.spread() // from where the two left are now
}
if !s.touching || e.Pointer != s.primary {
return
}
s.touching = false
if e.Phase == "cancel" {
s.cancel()
return
}
s.send(platform.SurfaceEvent{Kind: platform.PointerUp, X: e.X, Y: e.Y, Clicks: s.taps, Touch: true})
s.send(platform.SurfaceEvent{Kind: platform.PointerLeave, Touch: true})
s.lastTapX, s.lastTapY, s.lastTapTime = e.X, e.Y, e.Time
}
}
// cancel ends the finger's press without a click: it lets go far outside
// what it pressed.
func (s *surface) cancel() {
s.touching = false
s.send(platform.SurfaceEvent{Kind: platform.PointerUp, X: -1e6, Y: -1e6, Touch: true, Canceled: true})
s.send(platform.SurfaceEvent{Kind: platform.PointerLeave, Touch: true})
s.taps = 0
}
// spread is how far apart two fingers are. Map order would swap them, so
// they go by their numbers.
func (s *surface) spread() float64 {
a, b, ok := s.twoFingers()
if !ok {
return 0
}
return math.Hypot(a[0]-b[0], a[1]-b[1])
}
func (s *surface) twoFingers() (a, b [2]float64, ok bool) {
lo, hi := -1, -1
for id := range s.fingers {
switch {
case lo < 0 || id < lo:
lo, hi = id, lo
case hi < 0 || id < hi:
hi = id
}
}
if lo < 0 || hi < 0 {
return a, b, false
}
return s.fingers[lo], s.fingers[hi], true
}
// turned is how far two fingers turned since it was last asked, in radians
// clockwise, the way the shorter way round.
func (s *surface) turned() float64 {
a, b, ok := s.twoFingers()
if !ok {
return 0
}
angle := math.Atan2(b[1]-a[1], b[0]-a[0])
d := angle - s.pinchAngle
first := !s.pinchTurning
s.pinchAngle, s.pinchTurning = angle, true
if first {
return 0
}
for d > math.Pi {
d -= 2 * math.Pi
}
for d < -math.Pi {
d += 2 * math.Pi
}
return d
}
func (s *surface) center() (float64, float64) {
var x, y float64
for _, f := range s.fingers {
x += f[0]
y += f[1]
}
n := float64(len(s.fingers))
return x / n, y / n
}
// mouse handles a mouse's or a trackpad's pointer, as on an iPad with one,
// which hovers.
func (s *surface) mouse(e *wire.TouchEvent) {
button := 0
if e.Buttons&2 != 0 {
button = 1
}
switch e.Phase {
case "down":
s.mouseButton = button
s.send(platform.SurfaceEvent{Kind: platform.PointerDown, X: e.X, Y: e.Y, Button: button, Clicks: 1})
case "up":
// The one that went down: a release tells of none held any more.
s.send(platform.SurfaceEvent{Kind: platform.PointerUp, X: e.X, Y: e.Y, Button: s.mouseButton, Clicks: 1})
case "cancel":
s.send(platform.SurfaceEvent{Kind: platform.PointerLeave})
default:
s.send(platform.SurfaceEvent{Kind: platform.PointerMove, X: e.X, Y: e.Y})
}
}
// keys maps the names the hosts give a hardware keyboard's keys.
var keys = map[string]platform.Key{
"Enter": platform.KeyEnter, "Escape": platform.KeyEscape, "Backspace": platform.KeyBackspace, "Tab": platform.KeyTab,
"Space": platform.KeySpace, "Delete": platform.KeyDelete, "Home": platform.KeyHome, "End": platform.KeyEnd,
"PageUp": platform.KeyPageUp, "PageDown": platform.KeyPageDown, "ArrowLeft": platform.KeyLeft,
"ArrowRight": platform.KeyRight, "ArrowUp": platform.KeyUp, "ArrowDown": platform.KeyDown,
}
func keyOf(name string) platform.Key {
if k, ok := keys[name]; ok {
return k
}
if len(name) == 1 {
c := name[0] | 0x20
switch {
case c >= 'a' && c <= 'z':
return platform.KeyA + platform.Key(c-'a')
case name[0] >= '0' && name[0] <= '9':
return platform.Key0 + platform.Key(name[0]-'0')
}
}
return platform.KeyUnknown
}
// accessTree encodes the content's accessible elements for the host,
// asking the content for them first if it was not giving them yet.
func (s *surface) accessTree() []byte {
if !s.accessOn {
s.accessOn = true
// The content gives its tree at once (UpdateAccessibility).
s.send(platform.SurfaceEvent{Kind: platform.AccessibilityOn})
}
var w wire.Writer
if s.access == nil {
return w.Buf
}
for i := range s.access.Nodes {
n := &s.access.Nodes[i]
w.Int(int(n.ID))
parent := 0
if n.Parent >= 0 && n.Parent < len(s.access.Nodes) {
parent = int(s.access.Nodes[n.Parent].ID)
}
w.Int(parent)
w.Int(int(n.Role))
w.String(n.Label)
value := n.Value
if n.Role.Ranged() && value == "" && n.Max > n.Min {
value = strconv.Itoa(int(math.Round(100*(n.Now-n.Min)/(n.Max-n.Min)))) + "%"
}
w.String(value)
w.String(n.Description)
w.Float(n.Bounds.X)
w.Float(n.Bounds.Y)
w.Float(n.Bounds.W)
w.Float(n.Bounds.H)
w.Int(int(n.States))
w.Int(int(n.Actions))
w.Int(n.Level)
}
return w.Buf
}
// accessAction performs an assistive technology's action on an element.
func (s *surface) accessAction(node int, action string) bool {
kinds := map[string]platform.AccessActionKind{
"press": platform.AccessPress, "focus": platform.AccessFocus, "increment": platform.AccessIncrement,
"decrement": platform.AccessDecrement, "scrollIntoView": platform.AccessScrollIntoView,
"expand": platform.AccessExpand, "collapse": platform.AccessCollapse,
}
k, ok := kinds[action]
if !ok {
return false
}
s.send(platform.SurfaceEvent{Kind: platform.AccessAction, ID: uint64(node), Action: k})
return true
}
// handleSurface handles the events of surfaces, and reports whether op
// was one.
func (b *Backend) handleSurface(op uint64, r *wire.Reader, w *wire.Writer) bool {
sf := func(id int) *surface {
if win := b.windows[id]; win != nil {
return win.s
}
return nil
}
switch op {
case wire.EventFrame:
var e wire.FrameEvent
e.Decode(r)
if s := sf(e.ID); s != nil {
s.frame()
}
case wire.EventSurfaceChanged:
var e wire.SurfaceChangedEvent
e.Decode(r)
if s := sf(e.ID); s != nil {
old := s.handle
s.handle = uintptr(e.Handle)
if e.Refresh > 0 {
s.refresh = e.Refresh
}
if old != 0 && s.handle != old {
s.send(platform.SurfaceEvent{Kind: platform.SurfaceRenew})
}
if s.handle != 0 {
s.RequestFrame()
}
}
case wire.EventSurfaceDestroyed:
var e wire.SurfaceDestroyedEvent
e.Decode(r)
if s := sf(e.ID); s != nil && s.handle != 0 {
s.handle = 0
// The content lets go of its renderer at once.
s.send(platform.SurfaceEvent{Kind: platform.SurfaceRenew})
}
case wire.EventTouch:
var e wire.TouchEvent
e.Decode(r)
if s := sf(e.ID); s != nil {
s.touch(&e)
}
case wire.EventScroll:
var e wire.ScrollEvent
e.Decode(r)
if s := sf(e.ID); s != nil {
s.send(platform.SurfaceEvent{Kind: platform.PointerScroll, X: e.X, Y: e.Y, DX: e.DX, DY: e.DY,
Precise: e.Precise, Momentum: e.Phase == "momentum"})
}
case wire.EventKey:
var e wire.KeyEvent
e.Decode(r)
reply := wire.KeyReply{}
if s := sf(e.ID); s != nil {
kind := platform.KeyPressed
if !e.Down {
kind = platform.KeyReleased
}
k := keyOf(e.Key)
reply.Handled = s.send(platform.SurfaceEvent{Kind: kind, Key: k, PhysicalKey: k, Mods: platform.Modifiers(e.Mods), Repeat: e.Repeated})
}
reply.Encode(w)
case wire.EventBackGesture:
var e wire.BackGestureEvent
e.Decode(r)
if s := sf(e.ID); s != nil {
s.send(platform.SurfaceEvent{Kind: platform.SurfaceBackGesture, Text: e.Phase, Scale: e.Progress})
}
case wire.EventStackPopped:
var e wire.StackPoppedEvent
e.Decode(r)
if s := sf(e.ID); s != nil {
s.send(platform.SurfaceEvent{Kind: platform.SurfaceStackPopped, To: e.Depth})
}
case wire.EventStatusBarTapped:
if w := b.front(); w != nil && w.s != nil {
w.s.send(platform.SurfaceEvent{Kind: platform.SurfaceScrollToTop})
}
case wire.EventViewPressed:
var e wire.ViewPressedEvent
e.Decode(r)
if s := sf(e.ID); s != nil {
s.send(platform.SurfaceEvent{Kind: platform.WebViewPress, X: e.X, Y: e.Y})
}
case wire.EventTextReplace, wire.EventTextMark, wire.EventTextUnmark, wire.EventTextDelete, wire.EventTextSelect,
wire.EventTextCommand, wire.EventTextState, wire.EventTextRange, wire.EventTextBounds, wire.EventTextIndexAt, wire.EventTextInputEnded:
b.textEvent(op, r, w)
case wire.EventAccessibilityTree:
var e wire.AccessibilityTreeEvent
e.Decode(r)
reply := wire.AccessibilityTreeReply{}
if s := sf(e.ID); s != nil {
reply.Nodes = s.accessTree()
}
reply.Encode(w)
case wire.EventAccessibilityAction:
var e wire.AccessibilityActionEvent
e.Decode(r)
reply := wire.AccessibilityActionReply{}
if s := sf(e.ID); s != nil {
reply.Handled = s.accessAction(e.Node, e.Action)
}
reply.Encode(w)
default:
return false
}
return true
}
+108
View File
@@ -0,0 +1,108 @@
package mobile
import "github.com/egoist/mygo/internal/mobile/wire"
// The text of native UI on Android, which the host's Paint measures and
// draws (internal/text's engine): any goroutine but the UI thread. It goes
// straight to the host on the caller's thread: a screen of new text is
// hundreds of calls, which must not wait for the UI thread each.
func textCall(m message, reply interface{ Decode(*wire.Reader) }) bool {
b := current.Load()
if b == nil || b.t == nil {
return false
}
if !callHere(b, m, reply) {
b.t.call(m, reply)
}
return true
}
// callHere calls the host on the caller's thread, where the host's glue can.
func callHere(b *Backend, m message, reply interface{ Decode(*wire.Reader) }) bool {
h, ok := b.t.h.(interface{ callHere(msg []byte) []byte })
if !ok {
return false
}
var w wire.Writer
m.Encode(&w)
out := h.callHere(w.Buf)
if reply != nil {
reply.Decode(&wire.Reader{Buf: out})
}
return true
}
// The sound's output: blocking calls of the host on the audio's own thread,
// which must not wait for the UI thread, nor the UI thread for it.
// AudioOpen opens the output.
func AudioOpen(rate, aheadMS int) error {
b := current.Load()
if b == nil || b.t == nil {
return errUnsupported
}
var r wire.AudioOpenReply
if !callHere(b, &wire.AudioOpen{Rate: rate, Ahead: aheadMS}, &r) {
return errUnsupported
}
return errorOf(r.Error)
}
// AudioWrite plays samples after those written.
func AudioWrite(samples []byte) error {
b := current.Load()
if b == nil || b.t == nil {
return errUnsupported
}
var r wire.AudioWriteReply
if !callHere(b, &wire.AudioWrite{Samples: samples}, &r) {
return errUnsupported
}
return errorOf(r.Error)
}
// AudioClose closes the output.
func AudioClose() {
if b := current.Load(); b != nil && b.t != nil {
callHere(b, &wire.AudioClose{}, nil)
}
}
// TextMetrics returns the metrics of a font.
func TextMetrics(family string, size float64, weight int, italic bool) (r wire.TextMetricsReply, ok bool) {
ok = textCall(&wire.TextMetrics{Family: family, Size: size, Weight: weight, Italic: italic}, &r)
return r, ok
}
// MeasureText returns how wide each text is in a font.
func MeasureText(family string, size float64, weight int, italic, noKern bool, texts []string) []float64 {
var r wire.MeasureTextReply
textCall(&wire.MeasureText{Family: family, Size: size, Weight: weight, Italic: italic, NoKern: noKern, Texts: texts}, &r)
return r.Widths
}
// TextAdvances returns the advance of each UTF-16 unit of text laid out
// as a whole.
func TextAdvances(family string, size float64, weight int, italic, noKern bool, text string, rtl bool) []float64 {
var r wire.TextAdvancesReply
textCall(&wire.TextAdvances{Family: family, Size: size, Weight: weight, Italic: italic, NoKern: noKern, Text: text, RTL: rtl}, &r)
return r.Advances
}
// DrawText draws text in white, as DrawText's reply tells.
func DrawText(family string, size float64, weight int, italic bool, text string, scale, dx float64) wire.DrawTextReply {
var r wire.DrawTextReply
textCall(&wire.DrawText{Family: family, Size: size, Weight: weight, Italic: italic, Text: text, Scale: scale, DX: dx}, &r)
return r
}
// RegisterFont adds a font file under family, or its own, and returns the
// family.
func RegisterFont(data []byte, family string) (string, error) {
var r wire.RegisterFontReply
if !textCall(&wire.RegisterFont{Data: data, Family: family}, &r) {
return "", errUnsupported
}
return r.Family, errorOf(r.Error)
}
+307
View File
@@ -0,0 +1,307 @@
package mobile
import (
"math"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
)
// The keyboard edits the document of the input with the focus through its
// TextInputClient, by UTF-16 offsets, which are what UITextInput and
// InputConnection count in. The host keeps a copy of the text around the
// selection, for the keyboard's many questions, and gets it afresh with the
// answer to each of its edits, and from SetTextInput when the content
// changes it.
// textWindow is how many UTF-16 units either side of the selection the host
// gets: a document may be large, and a keyboard reads around the caret.
const textWindow = 1 << 12
// The hosts' names of what platform.TextTraits numbers.
var (
keyboardNames = [...]string{"", "email", "number", "decimal", "phone", "url", "search"}
returnNames = [...]string{"", "done", "go", "next", "search", "send"}
capitalizeNames = [...]string{"", "none", "words", "sentences", "characters"}
autocorrectNames = [...]string{"", "on", "off"}
autofillNames = [...]string{"", "username", "password", "newPassword", "oneTimeCode", "email", "name", "phone", "address", "postalCode", "creditCard"}
)
// SetTextInput shows the keyboard while an element takes text, and gives the
// host its traits and the text around the caret.
func (s *surface) SetTextInput(t platform.TextInputState) {
if !t.Active && s.text.Active {
s.marked = ""
}
if t.Client != s.text.Client {
s.textSerial++ // another input: keyboards forget what they knew
}
s.text = t
s.syncText()
}
// syncText tells the host the state of the text input, if it changed.
func (s *surface) syncText() {
t := s.text
st := s.snapshot()
m := wire.SetTextInput{ID: s.w.id, Active: t.Active, Show: int(t.ShowKeyboard), Serial: s.textSerial, Document: t.Client != nil,
X: st.X, Y: st.Y, Width: st.Width, Height: st.Height,
Multiline: t.Traits.Multiline, Secure: t.Traits.Secure, Keyboard: keyboardNames[t.Traits.Keyboard], ReturnKey: returnNames[t.Traits.ReturnKey],
Capitalize: capitalizeNames[t.Traits.Capitalize], Autocorrect: autocorrectNames[t.Traits.Autocorrect], Autofill: autofillNames[t.Traits.Autofill],
Text: st.Text, Base: st.Base, Length: st.Length, SelStart: st.SelStart, SelEnd: st.SelEnd, MarkStart: st.MarkStart, MarkEnd: st.MarkEnd}
if m == s.textSent {
return
}
s.textSent = m
s.w.b.call(&m, nil)
}
// snapshot is the input's state now, as the host takes it.
func (s *surface) snapshot() wire.TextStateReply {
t := s.text
r := wire.TextStateReply{MarkStart: -1, MarkEnd: -1, X: t.Caret.X, Y: t.Caret.Y, Width: t.Caret.W, Height: t.Caret.H}
c := t.Client
if !t.Active || c == nil {
return r
}
sel := c.Selection().Range
r.SelStart, r.SelEnd = sel.Start, sel.End
if m, ok := c.MarkedRange(); ok {
r.MarkStart, r.MarkEnd = m.Start, m.End
}
// A range past the document's end is taken back to it.
_, end := c.TextForRange(platform.TextRange{Start: math.MaxInt32, End: math.MaxInt32})
r.Length = end.End
var around platform.TextRange
r.Text, around = c.TextForRange(platform.TextRange{Start: max(0, sel.Start-textWindow), End: sel.End + textWindow})
r.Base = around.Start
caret := sel.End
if b, _, ok := c.BoundsForRange(platform.TextRange{Start: caret, End: caret}); ok {
r.X, r.Y, r.Width, r.Height = b.X, b.Y, b.W, b.H
}
return r
}
// typed hands the keyboard's text to the content without a document, or a
// new line or a tab as its key, which submits a field or moves the focus.
func (s *surface) typed(text string) {
if s.marked != "" {
s.marked = ""
s.send(platform.SurfaceEvent{Kind: platform.TextComposition})
}
s.send(platform.SurfaceEvent{Kind: platform.TextInput, Text: text})
}
func (s *surface) key(k platform.Key) {
s.send(platform.SurfaceEvent{Kind: platform.KeyPressed, Key: k, PhysicalKey: k})
s.send(platform.SurfaceEvent{Kind: platform.KeyReleased, Key: k, PhysicalKey: k})
}
// replace puts text in a range of the document, or in place of the marked
// text or the selection. A return or a tab typed is its key, as desktop
// keyboards send them.
func (s *surface) replace(r *platform.TextRange, text string) {
c := s.text.Client
if r == nil {
marked := false
if c != nil {
_, marked = c.MarkedRange()
}
switch {
case text == "\n" && !marked:
s.key(platform.KeyEnter)
return
case text == "\t" && !marked:
s.key(platform.KeyTab)
return
}
}
if c != nil {
c.ReplaceText(r, text)
return
}
if text != "" {
s.typed(text)
}
}
// deleteAround deletes units before and after the selection, which only
// keys reach where the document does not show the host: a password's text.
func (s *surface) deleteAround(before, after int) {
c := s.text.Client
if c == nil || s.text.Traits.Secure {
for range before {
s.key(platform.KeyBackspace)
}
for range after {
s.key(platform.KeyDelete)
}
return
}
sel := c.Selection().Range
if after > 0 {
c.ReplaceText(&platform.TextRange{Start: sel.End, End: sel.End + after}, "")
}
if before > 0 {
c.ReplaceText(&platform.TextRange{Start: max(0, sel.Start-before), End: sel.Start}, "")
}
}
func (s *surface) command(cmd string) {
switch cmd {
case "newline":
s.key(platform.KeyEnter)
case "tab":
s.key(platform.KeyTab)
case "deleteBackward":
s.key(platform.KeyBackspace)
case "deleteForward":
s.key(platform.KeyDelete)
case "left":
s.key(platform.KeyLeft)
case "right":
s.key(platform.KeyRight)
case "up":
s.key(platform.KeyUp)
case "down":
s.key(platform.KeyDown)
default:
s.send(platform.SurfaceEvent{Kind: platform.SurfaceCommand, Text: cmd})
}
}
func rangeOf(has bool, start, end int) *platform.TextRange {
if !has {
return nil
}
return &platform.TextRange{Start: start, End: end}
}
// textEvent handles an event of the keyboard. Those that edit answer with
// the state after the edit, which the keyboard goes on to read.
func (b *Backend) textEvent(op uint64, r *wire.Reader, w *wire.Writer) {
sf := func(id int) *surface {
if win := b.windows[id]; win != nil {
return win.s
}
return nil
}
state := func(s *surface) {
if !wire.EventWaits(op) {
return
}
var st wire.TextStateReply
if s != nil {
st = s.snapshot()
s.acknowledge(st)
}
st.Encode(w)
}
switch op {
case wire.EventTextReplace:
var e wire.TextReplaceEvent
e.Decode(r)
s := sf(e.ID)
if s != nil {
s.replace(rangeOf(e.HasRange, e.Start, e.End), e.Text)
}
state(s)
case wire.EventTextMark:
var e wire.TextMarkEvent
e.Decode(r)
s := sf(e.ID)
if s != nil {
if c := s.text.Client; c != nil {
c.SetMarkedText(rangeOf(e.HasRange, e.Start, e.End), e.Text, platform.TextRange{Start: e.SelStart, End: e.SelEnd})
} else {
s.marked = e.Text
s.send(platform.SurfaceEvent{Kind: platform.TextComposition, Text: e.Text, Caret: platform.RunesInUTF16(e.Text, e.SelEnd)})
}
}
state(s)
case wire.EventTextUnmark:
var e wire.TextUnmarkEvent
e.Decode(r)
s := sf(e.ID)
if s != nil {
if c := s.text.Client; c != nil {
c.UnmarkText()
} else if s.marked != "" {
text := s.marked
s.marked = ""
s.send(platform.SurfaceEvent{Kind: platform.TextComposition})
s.typed(text)
}
}
state(s)
case wire.EventTextDelete:
var e wire.TextDeleteEvent
e.Decode(r)
s := sf(e.ID)
if s != nil {
s.deleteAround(e.Before, e.After)
}
state(s)
case wire.EventTextSelect:
var e wire.TextSelectEvent
e.Decode(r)
s := sf(e.ID)
if s != nil {
if c, ok := s.text.Client.(platform.TextSelectionSetter); ok {
c.SetTextSelection(platform.TextRange{Start: e.Start, End: e.End})
}
}
state(s)
case wire.EventTextCommand:
var e wire.TextCommandEvent
e.Decode(r)
s := sf(e.ID)
if s != nil {
s.command(e.Command)
}
state(s)
case wire.EventTextState:
var e wire.TextStateEvent
e.Decode(r)
state(sf(e.ID))
case wire.EventTextRange:
var e wire.TextRangeEvent
e.Decode(r)
reply := wire.TextRangeReply{}
if s := sf(e.ID); s != nil && s.text.Client != nil {
var got platform.TextRange
reply.Text, got = s.text.Client.TextForRange(platform.TextRange{Start: e.Start, End: e.End})
reply.Start, reply.End = got.Start, got.End
}
reply.Encode(w)
case wire.EventTextBounds:
var e wire.TextBoundsEvent
e.Decode(r)
reply := wire.TextBoundsReply{}
if s := sf(e.ID); s != nil && s.text.Client != nil {
if b, got, ok := s.text.Client.BoundsForRange(platform.TextRange{Start: e.Start, End: e.End}); ok {
reply.OK, reply.X, reply.Y, reply.Width, reply.Height, reply.End = true, b.X, b.Y, b.W, b.H, got.End
}
}
reply.Encode(w)
case wire.EventTextIndexAt:
var e wire.TextIndexAtEvent
e.Decode(r)
reply := wire.TextIndexAtReply{}
if s := sf(e.ID); s != nil && s.text.Client != nil {
reply.Index, reply.OK = s.text.Client.IndexForPoint(e.X, e.Y)
}
reply.Encode(w)
case wire.EventTextInputEnded:
// The content keeps its selection and the focus as the keyboard goes,
// as UIKit's text fields do until the app ends editing.
}
}
// acknowledge notes the state the host gets with an answer, which the next
// frame need not send again.
func (s *surface) acknowledge(st wire.TextStateReply) {
m := &s.textSent
m.Text, m.Base, m.Length, m.SelStart, m.SelEnd, m.MarkStart, m.MarkEnd = st.Text, st.Base, st.Length, st.SelStart, st.SelEnd, st.MarkStart, st.MarkEnd
m.X, m.Y, m.Width, m.Height = st.X, st.Y, st.Width, st.Height
}
+33
View File
@@ -0,0 +1,33 @@
package mobile
import (
"time"
"github.com/egoist/mygo/internal/mobile/wire"
)
// Go finds no local time zone on phones, whose /etc/localtime it can't reach
// or doesn't look at, and has every time in UTC: time.Local comes from the
// host, and follows it as the phone changes zone. Go's own files of zones
// aren't there either (timezone_phone.go embeds them).
// setTimeZone makes the zone named by id, as "Asia/Shanghai", time.Local. What
// Go doesn't know stays as it was.
func setTimeZone(id string) {
if id == "" {
return
}
if loc, err := time.LoadLocation(id); err == nil {
time.Local = loc
}
}
// askTimeZone sets the zone before the app's main function runs, on the
// thread that starts Go. The host may answer on any thread.
func askTimeZone(h interface{ callHere(msg []byte) []byte }) {
var w wire.Writer
(&wire.TimeZone{}).Encode(&w)
var r wire.TimeZoneReply
r.Decode(&wire.Reader{Buf: h.callHere(w.Buf)})
setTimeZone(r.ID)
}
+5
View File
@@ -0,0 +1,5 @@
//go:build ios || android
package mobile
import _ "time/tzdata" // Go's database of zones: phones have it in no form Go reads
+161
View File
@@ -0,0 +1,161 @@
package mobile
import (
"sync"
"github.com/egoist/mygo/internal/mobile/wire"
)
// A host is the native side of the app: the Swift host on iOS, the Kotlin
// host on Android. It runs calls on the UI thread, where the system's
// views live, and sends events. Go runs on a thread of its own, its main
// thread (the one the core calls the main thread), so that it can wait
// (Step) while the UI thread goes on.
type host interface {
// call runs an encoded call and returns its encoded reply, nil for a
// call not waited for. UI thread only.
call(msg []byte) []byte
// post asks the UI thread to call transport.drain soon. Any thread.
post()
}
// transport carries calls from Go's threads to the UI thread, which runs
// them in order: when it next drains them (post), or at once while it
// waits for Go to answer an event, so that neither side waits for the
// other: an event handler the UI thread waits for may make calls.
type transport struct {
h host
mu sync.Mutex
pending []request
posted bool
// waiting counts the events the UI thread waits in, nested; kick
// wakes it to run calls meanwhile.
waiting int
kick chan struct{}
}
type request struct {
msg []byte
// fn, when set, runs on the UI thread in place of a call of the host:
// a native module's main-thread method, or its view.
fn func()
reply chan []byte // nil for a call not waited for
}
func newTransport(h host) *transport {
return &transport{h: h, kick: make(chan struct{}, 1)}
}
// message is a call of package wire.
type message interface {
Encode(w *wire.Writer)
Wait() bool
}
// call sends m to the UI thread, and when m is waited for, decodes its
// reply into reply. Any thread but the UI thread.
func (t *transport) call(m message, reply interface{ Decode(*wire.Reader) }) {
var w wire.Writer
m.Encode(&w)
req := request{msg: w.Buf}
if m.Wait() {
req.reply = make(chan []byte, 1)
}
b := t.send(req)
if b != nil && reply != nil {
reply.Decode(&wire.Reader{Buf: *b})
}
}
// run runs fn on the UI thread, in order with the calls, and when wait,
// waits for it. Any thread but the UI thread when wait.
func (t *transport) run(fn func(), wait bool) {
req := request{fn: fn}
if wait {
req.reply = make(chan []byte, 1)
}
t.send(req)
}
// send queues req for the UI thread and waits for its reply, if it has
// one to wait for.
func (t *transport) send(req request) *[]byte {
t.mu.Lock()
t.pending = append(t.pending, req)
post := false
if t.waiting > 0 {
select {
case t.kick <- struct{}{}:
default:
}
} else if !t.posted {
t.posted, post = true, true
}
t.mu.Unlock()
if post {
t.h.post()
}
if req.reply == nil {
return nil
}
b := <-req.reply
return &b
}
// drain runs the calls sent so far. UI thread only.
func (t *transport) drain() {
for {
// One at a time: a call may wait for Go (wait), which runs the calls
// after it meanwhile, one of which Go may be waiting for.
t.mu.Lock()
if len(t.pending) == 0 {
t.posted = false
t.mu.Unlock()
return
}
r := t.pending[0]
t.pending = t.pending[1:]
t.mu.Unlock()
var b []byte
if r.fn != nil {
r.fn()
} else {
b = t.h.call(r.msg)
}
if r.reply != nil {
r.reply <- b
}
}
}
// wait waits for done, an answer of Go's main thread to an event of the
// UI thread, running the calls Go makes meanwhile. UI thread only.
func (t *transport) wait(done chan []byte) []byte {
t.mu.Lock()
t.waiting++
t.mu.Unlock()
defer func() {
t.mu.Lock()
t.waiting--
// A call that came as it stopped waiting only kicked it.
post := t.waiting == 0 && len(t.pending) > 0 && !t.posted
if post {
t.posted = true
}
t.mu.Unlock()
if post {
t.h.post()
}
}()
for {
t.drain()
select {
case b := <-done:
// Calls sent before the answer run before the UI thread goes on.
t.drain()
return b
case <-t.kick:
}
}
}
+114
View File
@@ -0,0 +1,114 @@
package mobile
import (
"sync"
"testing"
"time"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/internal/wait"
)
// rawCall is a call by its first byte.
type rawCall struct {
id byte
reply bool
}
func (c rawCall) Encode(w *wire.Writer) { w.Buf = append(w.Buf, c.id) }
func (c rawCall) Wait() bool { return c.reply }
// loopHost hears the calls the test's UI thread runs.
type loopHost struct {
onCall func(id byte)
}
func (h *loopHost) call(msg []byte) []byte {
h.onCall(msg[0])
return nil
}
func (h *loopHost) post() {}
// A call that waits for Go runs the calls after it meanwhile, among which may
// be the one Go waits for before it answers.
func TestWaitRunsCallsBehindIt(t *testing.T) {
var tr *transport
done := make(chan []byte, 1)
h := &loopHost{}
h.onCall = func(id byte) {
if id == 1 {
tr.wait(done) // as closing a window asks Go something
}
}
tr = newTransport(h)
var wg sync.WaitGroup
wg.Add(1)
tr.call(rawCall{id: 1}, nil)
queued := make(chan struct{})
go func() {
defer wg.Done()
close(queued)
tr.call(rawCall{id: 2, reply: true}, nil)
done <- nil
}()
<-queued
// The UI thread: both calls may be queued by now, in one batch or not.
ran := make(chan struct{})
go func() {
tr.drain()
close(ran)
}()
wait.For(t, "the calls to run", ran)
wg.Wait()
}
// Once the core's loop is gone, the host's events are answered at once: no one
// is left to, and the UI thread would hang.
func TestEventsAfterQuit(t *testing.T) {
b, h := startBackend(t)
var held []byte
stopped := make(chan struct{})
h.onUI(func() {
b.Quit()
wait.Until(t, "the loop to stop", func() bool {
b.mu.Lock()
defer b.mu.Unlock()
return b.stopped
})
held = deliver(encodeEvent(func(w *wire.Writer) { w.Uvarint(wire.EventBackground) }), true)
close(stopped)
})
wait.For(t, "the event to be answered", stopped)
if held != nil {
t.Errorf("answered %v", held)
}
}
// What a keyboard composes counts UTF-16 units, its caret in runes on our side.
func TestRunesInUTF16(t *testing.T) {
for _, c := range []struct {
s string
units int
want int
}{{"abc", 2, 2}, {"a😀b", 3, 2}, {"a😀b", 4, 3}, {"中文", 1, 1}, {"", 3, 0}} {
if got := platform.RunesInUTF16(c.s, c.units); got != c.want {
t.Errorf("%q, %d: %d, want %d", c.s, c.units, got, c.want)
}
}
}
// The phone's zone is time.Local, and what Go doesn't know of leaves it.
func TestTimeZone(t *testing.T) {
defer func(l *time.Location) { time.Local = l }(time.Local)
setTimeZone("Asia/Tokyo")
if name, off := time.Now().Zone(); name != "JST" || off != 9*3600 {
t.Errorf("in Tokyo: %s %d", name, off)
}
setTimeZone("Nowhere/Land")
setTimeZone("")
if time.Local.String() != "Asia/Tokyo" {
t.Errorf("after an unknown zone: %v", time.Local)
}
}
+12
View File
@@ -0,0 +1,12 @@
//go:build android
package mobile
import (
"github.com/egoist/mygo/internal/inotify"
"github.com/egoist/mygo/internal/platform"
)
func (*Backend) NewFileWatch(notify func(platform.FileWatchNotice)) (platform.FileWatch, error) {
return inotify.New(notify)
}
+12
View File
@@ -0,0 +1,12 @@
//go:build ios
package mobile
import (
"github.com/egoist/mygo/internal/kqueue"
"github.com/egoist/mygo/internal/platform"
)
func (*Backend) NewFileWatch(notify func(platform.FileWatchNotice)) (platform.FileWatch, error) {
return kqueue.New(notify)
}
+434
View File
@@ -0,0 +1,434 @@
package mobile
import (
"runtime"
"slices"
"github.com/egoist/mygo/internal/mobile/wire"
"github.com/egoist/mygo/internal/platform"
"github.com/egoist/mygo/internal/schemehost"
)
// mapsSchemes tells that the web view loads no custom scheme, as
// Android's: the app's schemes are served at https://<scheme>.localhost
// (package schemehost), which pages and the core never see.
var mapsSchemes = runtime.GOOS == "android"
// webURL is the URL the web view loads for url.
func (w *window) webURL(url string) string {
if !mapsSchemes || url == "" {
return url
}
return schemehost.WebURLOf(url, "https", w.hasScheme)
}
// appURL is the URL of the app's that the web view's url stands for.
func (w *window) appURL(url string) string {
if !mapsSchemes || url == "" {
return url
}
return schemehost.AppURLOf(url, "https", w.hasScheme)
}
func (w *window) hasScheme(s string) bool { return slices.Contains(w.opts.Schemes, s) }
// window is a screen of the app: a web view, or a surface for native UI,
// filling the screen while it is the window in front. Its size is the
// screen's, which the host reports (Resized) with the insets of what
// covers its edges, the system's bars and the keyboard among them.
// Main thread only, as the core uses it.
type window struct {
b *Backend
id int
h platform.WindowHandler
opts platform.WindowOptions
s *surface
title string
visible bool
closed bool
focused bool
bg platform.Color
// What the host said of the page (PageState).
url, pageTitle string
loading, canBack, canFwd bool
zoom float64
userAgent string
muted bool
// The size the host reported (Resized), in DIPs, and its insets.
width, height, scale float64
insets platform.Insets
keyboard float64
barItems []platform.BarItem
// tabs is the bar of tabs the window is on, in tab tabIndex.
tabs *tabBar
tabIndex int
// devTools says its developer tools are on, in a development build.
devTools bool
// parent is the surface's window this one shows under, as a web view in
// native UI, and children those it holds.
parent *window
children []*window
}
// scriptsOf encodes user scripts as CreateWindow and SetUserScripts take
// them: the sources, and for each its flags, "e" to inject it at the
// document's end, "a" into every frame.
func scriptsOf(scripts []platform.UserScript) (src, flags []string) {
for _, s := range scripts {
f := ""
if s.AtDocumentEnd {
f += "e"
}
if s.AllFrames {
f += "a"
}
src = append(src, s.Source)
flags = append(flags, f)
}
return src, flags
}
func (b *Backend) newWindow(opts *platform.WindowOptions, h platform.WindowHandler) (*window, error) {
return b.makeWindow(opts, h, nil, "", "")
}
// makeWindow makes a window, within parent if any: a web view, or with a
// viewType a plugin's native view.
func (b *Backend) makeWindow(opts *platform.WindowOptions, h platform.WindowHandler, parent *window, viewType, viewArgs string) (*window, error) {
b.nextID++
w := &window{b: b, id: b.nextID, h: h, opts: *opts, title: opts.Title, zoom: 1, scale: 1, parent: parent, devTools: opts.DevTools}
if opts.Zoom > 0 {
w.zoom = opts.Zoom
}
src, flags := scriptsOf(opts.UserScripts)
c := wire.CreateWindow{
ID: w.id, Surface: opts.Surface, OwnScene: opts.OwnScene, Schemes: opts.Schemes, Scripts: src, ScriptFlags: flags,
UserAgent: opts.UserAgent, UserAgentSuffix: opts.UserAgentSuffix, Inspectable: opts.DevTools,
Autoplay: opts.Autoplay, SwipeNavigation: opts.SwipeNavigation, PinchZoom: opts.PinchZoom,
ViewType: viewType, ViewArgs: viewArgs,
}
if parent != nil {
c.Parent = parent.id
parent.children = append(parent.children, w)
}
if opts.BackgroundColor != nil {
c.Background, c.HasBackground = rgba(*opts.BackgroundColor), true
w.bg = *opts.BackgroundColor
}
var r wire.CreateWindowReply
b.call(&c, &r)
if err := errorOf(r.Error); err != nil {
return nil, err
}
if opts.Surface {
w.s = newSurface(w)
w.s.handle = uintptr(r.Layer) // iOS's layer; Android's window comes with SurfaceChanged
}
b.windows[w.id] = w
if w.zoom != 1 && !opts.Surface {
b.call(&wire.SetZoom{ID: w.id, Factor: w.zoom}, nil)
}
return w, nil
}
// front is the window on screen, nil for none.
func (b *Backend) front() *window {
if len(b.shown) == 0 {
return nil
}
return b.shown[len(b.shown)-1]
}
// setFront makes the window in front w (nil for none) and tells the
// windows whose focus that changes.
func (b *Backend) refocus(old *window) {
now := b.front()
if old == now {
return
}
if old != nil && old.focused {
old.focused = false
old.h.Blurred()
}
if now != nil && !now.focused {
now.focused = true
now.h.Focused()
}
}
func (w *window) Handle() uintptr { return uintptr(w.id) }
// ViewID is the number the host knows the window by, which a plugin's native
// code knows its views by.
func (w *window) ViewID() int { return w.id }
func (w *window) Surface() platform.Surface {
if w.s == nil {
return nil
}
return w.s
}
func (w *window) SetTitle(t string) {
if t != w.title {
w.title = t
w.b.call(&wire.SetTitle{ID: w.id, Title: t}, nil)
}
}
func (w *window) Title() string { return w.title }
func (w *window) SetRepresentedFile(string) {}
func (w *window) SetDocumentEdited(bool) {}
func (w *window) SetBounds(platform.Rect) {}
func (w *window) SetContentBounds(platform.Rect) {}
func (w *window) SetMinimumSize(platform.Size) {}
func (w *window) SetMaximumSize(platform.Size) {}
func (w *window) SetResizable(bool) {}
func (w *window) IsResizable() bool { return false }
func (w *window) SetMovable(bool) {}
func (w *window) IsMovable() bool { return false }
func (w *window) SetMinimizable(bool) {}
func (w *window) IsMinimizable() bool { return false }
func (w *window) SetMaximizable(bool) {}
func (w *window) IsMaximizable() bool { return false }
func (w *window) SetClosable(bool) {}
func (w *window) IsClosable() bool { return true }
func (w *window) SetAlwaysOnTop(bool) {}
func (w *window) IsAlwaysOnTop() bool { return false }
func (w *window) Minimize() {}
func (w *window) IsMinimized() bool { return false }
func (w *window) Maximize() {}
func (w *window) Unmaximize() {}
func (w *window) IsMaximized() bool { return true }
func (w *window) Restore() {}
func (w *window) SetFullScreen(bool) {}
func (w *window) IsFullScreen() bool { return true }
func (w *window) Center() {}
func (w *window) SetOpacity(float64) {}
func (w *window) Opacity() float64 { return 1 }
func (w *window) SetHasShadow(bool) {}
func (w *window) HasShadow() bool { return false }
func (w *window) SetIgnoreMouseEvents(bool) {}
func (w *window) IgnoresMouseEvents() bool { return false }
func (w *window) SetVibrancyTint(*platform.Color) {}
func (w *window) SetContentProtection(bool) {}
func (w *window) SetVibrancy(string) {}
func (w *window) SetActiveAppearance(bool) {}
func (w *window) SetWindowButtonsTheme(string) {}
func (w *window) SetProgressBar(string, float64) {}
func (w *window) FlashFrame(bool) {}
func (w *window) SetSkipTaskbar(bool) {}
func (w *window) SetVisibleOnAllWorkspaces(bool) {}
func (w *window) SetIcon([]byte) error { return nil }
func (w *window) SetMenu(*platform.Menu) {}
func (w *window) SetAutoHideMenu(bool) {}
func (w *window) TitleBar() platform.TitleBar { return platform.TitleBar{} }
func (w *window) StartDrag() {}
func (w *window) TitleBarDoubleClicked() {}
func (w *window) PlaceFlyout(platform.Flyout, platform.Size) {}
// Bounds is the screen's, as the window fills it.
func (w *window) Bounds() platform.Rect {
return platform.Rect{Width: int(w.width + 0.5), Height: int(w.height + 0.5)}
}
func (w *window) ContentBounds() platform.Rect { return w.Bounds() }
func (w *window) Show() {
if w.closed {
return
}
old := w.b.front()
w.b.unshow(w)
w.b.shown = append(w.b.shown, w)
w.visible = true
w.b.call(&wire.ShowWindow{ID: w.id}, nil)
w.b.refocus(old)
}
func (w *window) ShowInactive() { w.Show() }
// unshow takes w out of the windows on screen.
func (b *Backend) unshow(w *window) {
for i, s := range b.shown {
if s == w {
b.shown = append(b.shown[:i], b.shown[i+1:]...)
return
}
}
}
func (w *window) Hide() {
if !w.visible || w.closed {
return
}
old := w.b.front()
w.b.unshow(w)
w.visible = false
w.b.call(&wire.HideWindow{ID: w.id}, nil)
w.b.refocus(old)
}
func (w *window) IsVisible() bool { return w.visible }
func (w *window) Focus() {
if w.parent == nil && w.visible && w.b.front() != w {
w.Show()
}
w.b.call(&wire.Focus{ID: w.id}, nil)
}
func (w *window) Blur() {}
func (w *window) IsFocused() bool { return w.focused }
// CornerRadius is 0: the screen's corners are the system's, which it does
// not tell.
func (w *window) CornerRadius() float64 { return 0 }
func (w *window) SetBackgroundColor(c platform.Color) {
w.bg = c
w.b.call(&wire.SetBackground{ID: w.id, Color: rgba(c)}, nil)
}
func (w *window) Close() {
if w.closed {
return
}
for _, c := range append([]*window(nil), w.children...) {
c.Close()
}
if p := w.parent; p != nil {
// A web view: its handler hears no more of it.
p.children = slices.DeleteFunc(p.children, func(c *window) bool { return c == w })
w.closed = true
w.b.call(&wire.CloseWindow{ID: w.id}, nil)
delete(w.b.windows, w.id)
return
}
old := w.b.front()
w.b.unshow(w)
w.closed, w.visible = true, false
w.b.call(&wire.CloseWindow{ID: w.id}, nil)
delete(w.b.windows, w.id)
if w.s != nil {
w.s.closed()
}
w.b.refocus(old)
w.h.Closed()
}
// TabInto gives a web view the keyboard: phones' keyboards have no Tab to
// come in with.
func (w *window) TabInto(bool) { w.b.call(&wire.Focus{ID: w.id}, nil) }
// resized takes the size the host reported.
func (w *window) resized(e *wire.ResizedEvent) {
changed := e.Width != w.width || e.Height != w.height || e.Scale != w.scale
w.width, w.height, w.scale = e.Width, e.Height, e.Scale
insets := platform.Insets{Top: e.SafeTop, Left: e.SafeLeft, Bottom: e.SafeBottom, Right: e.SafeRight}
inset := insets != w.insets || e.Keyboard != w.keyboard
w.insets, w.keyboard = insets, e.Keyboard
if w.s != nil {
w.s.resized(changed, inset)
}
if changed {
w.h.Resized()
}
}
// Page.
func (w *window) WebViewHandle() uintptr { return uintptr(w.id) }
func (w *window) LoadURL(url string) {
w.url = url
w.b.call(&wire.LoadURL{ID: w.id, URL: w.webURL(url)}, nil)
}
func (w *window) LoadHTML(html, baseURL string) {
w.b.call(&wire.LoadHTML{ID: w.id, HTML: html, BaseURL: w.webURL(baseURL)}, nil)
}
func (w *window) LoadFile(path, _ string) { w.LoadURL("file://" + path) }
func (w *window) Reload(ignoreCache bool) {
w.b.call(&wire.Reload{ID: w.id, IgnoreCache: ignoreCache}, nil)
}
func (w *window) StopLoading() { w.b.call(&wire.StopLoading{ID: w.id}, nil) }
func (w *window) GoBack() { w.b.call(&wire.GoBack{ID: w.id}, nil) }
func (w *window) GoForward() { w.b.call(&wire.GoForward{ID: w.id}, nil) }
func (w *window) CanGoBack() bool { return w.canBack }
func (w *window) CanGoForward() bool { return w.canFwd }
func (w *window) URL() string { return w.url }
func (w *window) IsLoading() bool { return w.loading }
func (w *window) Eval(js string) { w.b.call(&wire.Eval{ID: w.id, JS: js}, nil) }
func (w *window) SetUserScripts(scripts []platform.UserScript) {
src, flags := scriptsOf(scripts)
w.b.call(&wire.SetUserScripts{ID: w.id, Scripts: src, ScriptFlags: flags}, nil)
}
func (w *window) SetContentRules([]any) {}
func (w *window) CallAsyncFunction(body string, cb func(string, error)) {
req := w.b.request(func(r wire.Reader) {
var e wire.AsyncResultEvent
e.Decode(&r)
cb(e.Result, errorOf(e.Error))
})
w.b.call(&wire.CallAsync{ID: w.id, Req: req, Body: body}, nil)
}
func (w *window) SetZoom(f float64) {
w.zoom = f
w.b.call(&wire.SetZoom{ID: w.id, Factor: f}, nil)
}
func (w *window) Zoom() float64 { return w.zoom }
func (w *window) SetUserAgent(ua string) {
w.userAgent = ua
w.b.call(&wire.SetUserAgent{ID: w.id, UserAgent: ua}, nil)
}
func (w *window) UserAgent() string {
var r wire.UserAgentReply
w.b.call(&wire.UserAgent{ID: w.id}, &r)
return r.UserAgent
}
func (w *window) ProcessID() int { return 0 }
func (w *window) GPUProcessID() int { return 0 }
func (w *window) IsAudible() bool { return false }
func (w *window) SetAudioMuted(m bool) { w.muted = m }
func (w *window) IsAudioMuted() bool { return false }
func (w *window) CaptureState(platform.CaptureKind) platform.CaptureState {
return platform.CaptureNone
}
func (w *window) SetCaptureState(platform.CaptureKind, platform.CaptureState) {}
func (w *window) TogglePictureInPicture() {}
func (w *window) PictureInPictureActive(cb func(bool)) { cb(false) }
func (w *window) SessionState() []byte { return nil }
func (w *window) RestoreSessionState([]byte) bool { return false }
func (w *window) OpenDevTools() {}
func (w *window) CloseDevTools() {}
func (w *window) IsDevToolsOpened() bool { return false }
func (w *window) DroppedFiles() []string { return nil }
func (w *window) Print() {}
func (w *window) CapturePage(cb func([]byte, error)) {
req := w.b.request(func(r wire.Reader) {
var e wire.CapturedEvent
e.Decode(&r)
cb(e.PNG, errorOf(e.Error))
})
w.b.call(&wire.CapturePage{ID: w.id, Req: req}, nil)
}
func (w *window) PrintToPDF(_ platform.PDFOptions, cb func([]byte, error)) {
cb(nil, platform.ErrUnsupported)
}
+468
View File
@@ -0,0 +1,468 @@
// Command gen writes the messages of spec.go for the three sides: Go
// (../msgs.go), Swift (the iOS host's Wire.swift) and Kotlin (the Android
// host's Wire.kt).
package main
import (
"bytes"
"fmt"
"go/format"
"log"
"os"
"path/filepath"
"strings"
"unicode"
)
// Paths from internal/mobile/wire, where go generate runs.
const (
goOut = "msgs.go"
swiftOut = "../ios/Sources/MyGoHost/Wire.swift"
kotlinOut = "../android/mygo/src/main/java/dev/mygo/Wire.kt"
)
func main() {
out := map[string][]byte{goOut: goSource(), swiftOut: swiftSource(), kotlinOut: kotlinSource()}
for path, b := range out {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
log.Fatal(err)
}
if err := os.WriteFile(path, b, 0o644); err != nil {
log.Fatal(err)
}
}
}
// lower makes a Go name the Swift and Kotlin one: ID → id, URLs → urls,
// SafeTop → safeTop, HTMLText → htmlText, BaseURL → baseURL.
func lower(s string) string {
r := []rune(s)
i := 0
for i < len(r) && unicode.IsUpper(r[i]) {
i++
}
switch {
case i == len(r) || string(r[i:]) == "s":
return strings.ToLower(s)
case i > 1:
i-- // the last capital starts the next word
}
return strings.ToLower(string(r[:i])) + string(r[i:])
}
const header = "Code generated by internal/mobile/wire/gen from spec.go; DO NOT EDIT."
// ---- Go
var goTypes = map[string]string{"int": "int", "float": "float64", "bool": "bool", "string": "string", "bytes": "[]byte", "strings": "[]string", "floats": "[]float64"}
var goRW = map[string]string{"int": "Int", "float": "Float", "bool": "Bool", "string": "String", "bytes": "Bytes", "strings": "Strings", "floats": "Floats"}
func goSource() []byte {
var b bytes.Buffer
fmt.Fprintf(&b, "// %s\n\npackage wire\n\n", header)
b.WriteString("// Numbers of calls.\nconst (\n")
for i, m := range calls {
fmt.Fprintf(&b, "\tCall%s = %d\n", m.name, i+1)
}
b.WriteString(")\n\n// Numbers of events.\nconst (\n")
for i, m := range events {
fmt.Fprintf(&b, "\tEvent%s = %d\n", m.name, i+1)
}
b.WriteString(")\n\n")
goStruct := func(name, doc string, fs []field) {
if doc != "" {
fmt.Fprintf(&b, "// %s is %s.\n", name, doc)
}
fmt.Fprintf(&b, "type %s struct {\n", name)
for _, f := range fs {
fmt.Fprintf(&b, "\t%s %s\n", f.name, goTypes[f.typ])
}
b.WriteString("}\n\n")
}
enc := func(recv string, op string, fs []field) {
fmt.Fprintf(&b, "func (m *%s) Encode(w *Writer) {\n", recv)
if op != "" {
fmt.Fprintf(&b, "\tw.Uvarint(%s)\n", op)
}
for _, f := range fs {
fmt.Fprintf(&b, "\tw.%s(m.%s)\n", goRW[f.typ], f.name)
}
b.WriteString("}\n\n")
}
dec := func(recv string, fs []field) {
fmt.Fprintf(&b, "func (m *%s) Decode(r *Reader) {\n", recv)
for _, f := range fs {
fmt.Fprintf(&b, "\tm.%s = r.%s()\n", f.name, goRW[f.typ])
}
b.WriteString("}\n\n")
}
for _, m := range calls {
goStruct(m.name, m.doc, m.args)
enc(m.name, "Call"+m.name, m.args)
fmt.Fprintf(&b, "// Wait reports whether the caller waits for the host to run it.\nfunc (*%s) Wait() bool { return %v }\n\n", m.name, m.wait)
if m.wait {
goStruct(m.name+"Reply", "", m.reply)
dec(m.name+"Reply", m.reply)
}
}
for _, m := range events {
goStruct(m.name+"Event", m.doc, m.args)
dec(m.name+"Event", m.args)
if m.wait {
goStruct(m.name+"Reply", "", m.reply)
enc(m.name+"Reply", "", m.reply)
}
}
b.WriteString("// EventWaits reports whether the host waits for the reply of event op.\nfunc EventWaits(op uint64) bool {\n\tswitch op {\n\tcase ")
var waits []string
for _, m := range events {
if m.wait {
waits = append(waits, "Event"+m.name)
}
}
b.WriteString(strings.Join(waits, ", "))
b.WriteString(":\n\t\treturn true\n\t}\n\treturn false\n}\n")
src, err := format.Source(b.Bytes())
if err != nil {
log.Fatalf("%v\n%s", err, b.Bytes())
}
return src
}
// ---- Swift
var swiftTypes = map[string]string{"int": "Int", "float": "Double", "bool": "Bool", "string": "String", "bytes": "[UInt8]", "strings": "[String]", "floats": "[Double]"}
var swiftZero = map[string]string{"int": "0", "float": "0", "bool": "false", "string": `""`, "bytes": "[]", "strings": "[]", "floats": "[]"}
const swiftCodec = `
/// Writes the values of a message, as package wire encodes them.
public struct WireWriter {
public var buf: [UInt8] = []
public init() {}
mutating func uvarint(_ v: UInt64) {
var v = v
while v >= 0x80 { buf.append(UInt8(v & 0x7f) | 0x80); v >>= 7 }
buf.append(UInt8(v))
}
mutating func int(_ v: Int) { uvarint(UInt64(bitPattern: Int64((v << 1) ^ (v >> 63)))) }
mutating func bool(_ v: Bool) { buf.append(v ? 1 : 0) }
mutating func float(_ v: Double) { withUnsafeBytes(of: v.bitPattern.littleEndian) { buf.append(contentsOf: $0) } }
mutating func string(_ v: String) { let u = Array(v.utf8); uvarint(UInt64(u.count)); buf.append(contentsOf: u) }
mutating func bytes(_ v: [UInt8]) { uvarint(UInt64(v.count)); buf.append(contentsOf: v) }
mutating func strings(_ v: [String]) { uvarint(UInt64(v.count)); for s in v { string(s) } }
mutating func floats(_ v: [Double]) { uvarint(UInt64(v.count)); for f in v { float(f) } }
}
/// Reads the values of a message; past its end they read as zero.
public struct WireReader {
let buf: UnsafeRawBufferPointer
var at = 0
public init(_ buf: UnsafeRawBufferPointer) { self.buf = buf }
mutating func uvarint() -> UInt64 {
var v: UInt64 = 0, shift: UInt64 = 0
while at < buf.count {
let c = buf[at]; at += 1
v |= UInt64(c & 0x7f) << shift
if c < 0x80 { return v }
shift += 7
}
return 0
}
mutating func int() -> Int { let u = uvarint(); return Int(Int64(bitPattern: (u >> 1) ^ (0 &- (u & 1)))) }
mutating func bool() -> Bool { guard at < buf.count else { return false }; at += 1; return buf[at - 1] != 0 }
mutating func float() -> Double {
guard at + 8 <= buf.count else { at = buf.count; return 0 }
var bits: UInt64 = 0
for i in 0..<8 { bits |= UInt64(buf[at + i]) << (8 * UInt64(i)) }
at += 8
return Double(bitPattern: bits)
}
mutating func bytes() -> [UInt8] {
let n = Int(uvarint())
guard n >= 0, at + n <= buf.count else { at = buf.count; return [] }
defer { at += n }
return Array(buf[at..<at + n])
}
mutating func string() -> String { String(decoding: bytes(), as: UTF8.self) }
mutating func strings() -> [String] {
let n = Int(uvarint())
var s: [String] = []
for _ in 0..<min(n, buf.count - at) { s.append(string()) }
return s
}
mutating func floats() -> [Double] {
let n = Int(uvarint())
var f: [Double] = []
for _ in 0..<min(n, (buf.count - at) / 8) { f.append(float()) }
return f
}
}
`
func swiftSource() []byte {
var b bytes.Buffer
fmt.Fprintf(&b, "// %s\n\n// swiftlint:disable all\n", header)
b.WriteString(swiftCodec)
str := func(name string, fs []field, decode, encode bool) {
fmt.Fprintf(&b, "\npublic struct %s {\n", name)
for _, f := range fs {
fmt.Fprintf(&b, " public var %s: %s = %s\n", lower(f.name), swiftTypes[f.typ], swiftZero[f.typ])
}
b.WriteString(" public init() {}\n")
if decode {
b.WriteString(" init(_ r: inout WireReader) {\n")
for _, f := range fs {
fmt.Fprintf(&b, " %s = r.%s()\n", lower(f.name), f.typ)
}
b.WriteString(" }\n")
}
if encode {
b.WriteString(" func encode(_ w: inout WireWriter) {\n")
for _, f := range fs {
fmt.Fprintf(&b, " w.%s(%s)\n", f.typ, lower(f.name))
}
b.WriteString(" }\n")
}
b.WriteString("}\n")
}
// Calls: the host decodes them and encodes their replies.
for _, m := range calls {
if len(m.args) > 0 {
str(m.name+"Call", m.args, true, false)
}
if m.wait {
str(m.name+"Reply", m.reply, false, true)
}
}
b.WriteString("\n/// The calls Go makes of the host, on the main thread.\npublic protocol HostCalls: AnyObject {\n")
for _, m := range calls {
sig := "func " + lower(m.name) + "("
if len(m.args) > 0 {
sig += "_ c: " + m.name + "Call"
}
sig += ")"
if m.wait {
sig += " -> " + m.name + "Reply"
}
if m.doc != "" {
fmt.Fprintf(&b, " /// %s\n", m.doc)
}
fmt.Fprintf(&b, " %s\n", sig)
}
b.WriteString("}\n\n/// Runs a call on h and encodes its reply, nil for a call not waited for.\npublic func dispatchCall(_ h: HostCalls, _ buf: UnsafeRawBufferPointer) -> [UInt8]? {\n var r = WireReader(buf)\n var w = WireWriter()\n switch r.uvarint() {\n")
for i, m := range calls {
fmt.Fprintf(&b, " case %d:\n", i+1)
arg := ""
if len(m.args) > 0 {
arg = m.name + "Call(&r)"
}
if m.wait {
fmt.Fprintf(&b, " h.%s(%s).encode(&w)\n return w.buf\n", lower(m.name), arg)
} else {
fmt.Fprintf(&b, " h.%s(%s)\n return nil\n", lower(m.name), arg)
}
}
b.WriteString(" default:\n return nil\n }\n}\n")
// Events: the host encodes them and decodes their replies.
b.WriteString("\n/// Encodes the events the host sends Go.\npublic enum Event {\n")
for i, m := range events {
if m.doc != "" {
fmt.Fprintf(&b, " /// %s\n", m.doc)
}
var params []string
for _, f := range m.args {
params = append(params, lower(f.name)+": "+swiftTypes[f.typ])
}
fmt.Fprintf(&b, " public static func %s(%s) -> [UInt8] {\n var w = WireWriter()\n w.uvarint(%d)\n", lower(m.name), strings.Join(params, ", "), i+1)
for _, f := range m.args {
fmt.Fprintf(&b, " w.%s(%s)\n", f.typ, lower(f.name))
}
b.WriteString(" return w.buf\n }\n")
}
b.WriteString("}\n")
for _, m := range events {
if m.wait {
str(m.name+"Reply", m.reply, true, false)
}
}
return b.Bytes()
}
// ---- Kotlin
var kotlinTypes = map[string]string{"int": "Long", "float": "Double", "bool": "Boolean", "string": "String", "bytes": "ByteArray", "strings": "List<String>", "floats": "DoubleArray"}
var kotlinZero = map[string]string{"int": "0L", "float": "0.0", "bool": "false", "string": `""`, "bytes": "ByteArray(0)", "strings": "emptyList()", "floats": "DoubleArray(0)"}
const kotlinCodec = `
/** Writes the values of a message, as package wire encodes them. */
class WireWriter {
private var buf = ByteArray(64)
var size = 0
private set
private fun room(n: Int) {
if (size + n > buf.size) buf = buf.copyOf(maxOf(buf.size * 2, size + n))
}
fun uvarint(v: Long) {
room(10)
var x = v
while (x and 0x7fL.inv() != 0L) {
buf[size++] = ((x and 0x7f) or 0x80).toByte()
x = x ushr 7
}
buf[size++] = x.toByte()
}
fun int(v: Long) = uvarint((v shl 1) xor (v shr 63))
fun bool(v: Boolean) { room(1); buf[size++] = if (v) 1 else 0 }
fun float(v: Double) {
room(8)
val bits = java.lang.Double.doubleToRawLongBits(v)
for (i in 0 until 8) buf[size++] = (bits ushr (8 * i)).toByte()
}
fun bytes(v: ByteArray) { uvarint(v.size.toLong()); room(v.size); v.copyInto(buf, size); size += v.size }
fun string(v: String) = bytes(v.toByteArray(Charsets.UTF_8))
fun strings(v: List<String>) { uvarint(v.size.toLong()); for (s in v) string(s) }
fun floats(v: DoubleArray) { uvarint(v.size.toLong()); for (f in v) float(f) }
fun toByteArray(): ByteArray = buf.copyOf(size)
}
/** Reads the values of a message; past its end they read as zero. */
class WireReader(private val buf: ByteArray) {
private var at = 0
/** Whether all of the message was read. */
fun done() = at >= buf.size
fun uvarint(): Long {
var v = 0L
var shift = 0
while (at < buf.size) {
val c = buf[at++].toInt() and 0xff
v = v or ((c and 0x7f).toLong() shl shift)
if (c < 0x80) return v
shift += 7
}
return 0
}
fun int(): Long { val u = uvarint(); return (u ushr 1) xor -(u and 1) }
fun bool(): Boolean = if (at < buf.size) buf[at++].toInt() != 0 else false
fun float(): Double {
if (at + 8 > buf.size) { at = buf.size; return 0.0 }
var bits = 0L
for (i in 0 until 8) bits = bits or ((buf[at + i].toLong() and 0xff) shl (8 * i))
at += 8
return java.lang.Double.longBitsToDouble(bits)
}
fun bytes(): ByteArray {
val n = uvarint().toInt()
if (n < 0 || at + n > buf.size) { at = buf.size; return ByteArray(0) }
val b = buf.copyOfRange(at, at + n)
at += n
return b
}
fun string(): String = String(bytes(), Charsets.UTF_8)
fun strings(): List<String> {
val n = uvarint().toInt()
val s = ArrayList<String>(minOf(n, buf.size - at).coerceAtLeast(0))
for (i in 0 until minOf(n, buf.size - at)) s.add(string())
return s
}
fun floats(): DoubleArray {
val n = minOf(uvarint().toInt(), (buf.size - at) / 8).coerceAtLeast(0)
return DoubleArray(n) { float() }
}
}
`
func kotlinSource() []byte {
var b bytes.Buffer
fmt.Fprintf(&b, "// %s\n\n@file:Suppress(\"unused\", \"MemberVisibilityCanBePrivate\")\n\npackage dev.mygo\n", header)
b.WriteString(kotlinCodec)
class := func(name string, fs []field, decode, encode bool) {
fmt.Fprintf(&b, "\nclass %s(", name)
var ps []string
for _, f := range fs {
ps = append(ps, fmt.Sprintf("\n @JvmField var %s: %s = %s", lower(f.name), kotlinTypes[f.typ], kotlinZero[f.typ]))
}
b.WriteString(strings.Join(ps, ","))
if len(fs) > 0 {
b.WriteString(",\n")
}
b.WriteString(") {\n")
if decode {
b.WriteString(" constructor(r: WireReader) : this() {\n")
for _, f := range fs {
fmt.Fprintf(&b, " %s = r.%s()\n", lower(f.name), f.typ)
}
b.WriteString(" }\n")
}
if encode {
b.WriteString(" fun encode(w: WireWriter) {\n")
for _, f := range fs {
fmt.Fprintf(&b, " w.%s(%s)\n", f.typ, lower(f.name))
}
b.WriteString(" }\n")
}
b.WriteString("}\n")
}
for _, m := range calls {
if len(m.args) > 0 {
class(m.name+"Call", m.args, true, false)
}
if m.wait {
class(m.name+"Reply", m.reply, false, true)
}
}
b.WriteString("\n/** The calls Go makes of the host, on the UI thread. */\ninterface HostCalls {\n")
for _, m := range calls {
sig := "fun " + lower(m.name) + "("
if len(m.args) > 0 {
sig += "c: " + m.name + "Call"
}
sig += ")"
if m.wait {
sig += ": " + m.name + "Reply"
}
if m.doc != "" {
fmt.Fprintf(&b, " /** %s */\n", m.doc)
}
fmt.Fprintf(&b, " %s\n", sig)
}
b.WriteString("}\n\n/** Runs a call on h and encodes its reply, null for a call not waited for. */\nfun dispatchCall(h: HostCalls, buf: ByteArray): ByteArray? {\n val r = WireReader(buf)\n val w = WireWriter()\n when (r.uvarint().toInt()) {\n")
for i, m := range calls {
arg := ""
if len(m.args) > 0 {
arg = m.name + "Call(r)"
}
if m.wait {
fmt.Fprintf(&b, " %d -> { h.%s(%s).encode(w); return w.toByteArray() }\n", i+1, lower(m.name), arg)
} else {
fmt.Fprintf(&b, " %d -> h.%s(%s)\n", i+1, lower(m.name), arg)
}
}
b.WriteString(" }\n return null\n}\n\n/** Encodes the events the host sends Go. */\nobject Event {\n")
for i, m := range events {
if m.doc != "" {
fmt.Fprintf(&b, " /** %s */\n", m.doc)
}
var ps []string
for _, f := range m.args {
ps = append(ps, lower(f.name)+": "+kotlinTypes[f.typ])
}
fmt.Fprintf(&b, " @JvmStatic fun %s(%s): ByteArray {\n val w = WireWriter()\n w.uvarint(%d)\n", lower(m.name), strings.Join(ps, ", "), i+1)
for _, f := range m.args {
fmt.Fprintf(&b, " w.%s(%s)\n", f.typ, lower(f.name))
}
b.WriteString(" return w.toByteArray()\n }\n")
}
b.WriteString("}\n")
for _, m := range events {
if m.wait {
class(m.name+"Reply", m.reply, true, false)
}
}
return b.Bytes()
}
+30
View File
@@ -0,0 +1,30 @@
package main
import (
"bytes"
"os"
"path/filepath"
"testing"
)
// The generated files are what the spec makes: run go generate in
// internal/mobile/wire after changing it.
func TestUpToDate(t *testing.T) {
for path, want := range map[string][]byte{goOut: goSource(), swiftOut: swiftSource(), kotlinOut: kotlinSource()} {
got, err := os.ReadFile(filepath.Join("..", path))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Errorf("%s is out of date: run go generate ./internal/mobile/wire", path)
}
}
}
func TestLower(t *testing.T) {
for in, want := range map[string]string{"ID": "id", "URLs": "urls", "SafeTop": "safeTop", "HTMLText": "htmlText", "BaseURL": "baseURL", "PNG": "png"} {
if got := lower(in); got != want {
t.Errorf("lower(%q) = %q, want %q", in, got, want)
}
}
}
+272
View File
@@ -0,0 +1,272 @@
package main
// field is a field of a message: its name, in Go's form, and its type:
// int, float, bool, string, bytes or strings.
type field struct{ name, typ string }
// msg is a message. A call goes from Go to the host, which runs it on the
// UI thread; an event from the host to Go, which handles it on its main
// thread. reply lists what the receiver answers: a message without one
// is not waited for (wait false), so that a call or an event costs its
// sender nothing; one with wait set is, even with no fields to answer.
type msg struct {
name string
doc string
args []field
reply []field
wait bool
}
func f(name, typ string) field { return field{name, typ} }
// calls go from Go to the host.
var calls = []msg{
{name: "AppInfo", doc: "the app's bundle and the system's settings, asked once at start", wait: true, reply: []field{
f("Name", "string"), f("Version", "string"), f("Identifier", "string"),
f("FilesDir", "string"), f("CacheDir", "string"), f("TempDir", "string"), f("DocumentsDir", "string"),
f("ResourcesDir", "string"),
f("Languages", "strings"), f("RegionLocale", "string"), f("FirstWeekday", "int"), f("HourCycle", "int"),
f("System", "string"), f("SystemVersion", "string"), f("Model", "string"), f("Restoring", "bool"), f("Background", "bool"),
}},
{name: "TimeZone", doc: "the name of the system's time zone; any thread", wait: true, reply: []field{f("ID", "string")}},
{name: "Theme", doc: "the appearance and the accessibility preferences", wait: true, reply: []field{
f("Dark", "bool"), f("Accent", "int"), f("ReduceMotion", "bool"), f("ReduceTransparency", "bool"),
f("IncreaseContrast", "bool"), f("TextScale", "float"),
}},
{name: "SetAppearance", doc: `the appearance the app asks for: "light", "dark" or "system"`, args: []field{f("Source", "string")}},
{name: "Screen", doc: "the screen's size in DIPs and scale", wait: true, reply: []field{
f("Width", "float"), f("Height", "float"), f("Scale", "float"),
}},
{name: "Log", doc: "a line the app wrote to its standard output or error", args: []field{f("Error", "bool"), f("Line", "string")}},
{name: "CreateWindow", doc: "the screen's content: a web view, or a surface for native UI", wait: true,
args: []field{
f("ID", "int"), f("Surface", "bool"), f("OwnScene", "bool"), f("Background", "int"), f("HasBackground", "bool"),
f("Schemes", "strings"), f("Scripts", "strings"), f("ScriptFlags", "strings"),
f("UserAgent", "string"), f("UserAgentSuffix", "string"), f("Inspectable", "bool"),
f("Autoplay", "bool"), f("SwipeNavigation", "bool"), f("PinchZoom", "bool"),
f("Parent", "int"), f("ViewType", "string"), f("ViewArgs", "string"),
},
reply: []field{f("Error", "string"), f("Layer", "int")}},
{name: "FirstFrame", doc: "the window's content presented its first frame", args: []field{f("ID", "int")}},
{name: "PlaceViews", doc: "where a surface shows the windows it holds (Parent), under it, in the order painted; the others hide. Places: encoded by Go (encodePlaces)",
args: []field{f("ID", "int"), f("Places", "bytes")}},
{name: "ShowWindow", args: []field{f("ID", "int")}},
{name: "HideWindow", args: []field{f("ID", "int")}},
{name: "CloseWindow", args: []field{f("ID", "int")}},
{name: "SetBackground", args: []field{f("ID", "int"), f("Color", "int")}},
{name: "Focus", args: []field{f("ID", "int")}},
{name: "SetTitle", doc: "the window's title, which a navigation bar shows", args: []field{f("ID", "int"), f("Title", "string")}},
{name: "CreateTabs", doc: "a bar of tabs, whose tabs AddTab adds before ShowTabs shows it", args: []field{f("ID", "int")}},
{name: "AddTab", args: []field{f("ID", "int"), f("Window", "int"), f("Title", "string"), f("Symbol", "string"), f("Icon", "bytes")}},
{name: "ShowTabs", args: []field{f("ID", "int")}},
{name: "SelectTab", args: []field{f("ID", "int"), f("Index", "int")}},
{name: "SetTabBadge", args: []field{f("ID", "int"), f("Index", "int"), f("Badge", "string")}},
{name: "CloseTabs", args: []field{f("ID", "int")}},
{name: "PushWindow", doc: "shows Child over Parent in Parent's stack, under a bar with its Title and a back button",
args: []field{f("Parent", "int"), f("Child", "int"), f("Title", "string"), f("Animated", "bool")}},
{name: "PopWindow", args: []field{f("ID", "int"), f("Animated", "bool")}},
{name: "SetStack", doc: "a router's pages as the window's stack of screens, its first page and those deeper (Titles, told apart by Keys): the screens of the keys the stack shows stay, the others are pushed, popped or replaced; none take the stack away. Answered once the screen going out of sight holds what the surface shows, as the surface is about to show the page coming",
wait: true, args: []field{f("ID", "int"), f("Titles", "strings"), f("Keys", "strings")}},
{name: "StackShown", doc: "the surface shows the page of the stack's last screen, after SetStack or StackPopped", args: []field{f("ID", "int")}},
{name: "LoadURL", args: []field{f("ID", "int"), f("URL", "string")}},
{name: "LoadHTML", args: []field{f("ID", "int"), f("HTML", "string"), f("BaseURL", "string")}},
{name: "Reload", args: []field{f("ID", "int"), f("IgnoreCache", "bool")}},
{name: "StopLoading", args: []field{f("ID", "int")}},
{name: "GoBack", args: []field{f("ID", "int")}},
{name: "GoForward", args: []field{f("ID", "int")}},
{name: "Eval", args: []field{f("ID", "int"), f("JS", "string")}},
{name: "CallAsync", doc: "runs Body as an async function's; AsyncResult answers", args: []field{f("ID", "int"), f("Req", "int"), f("Body", "string")}},
{name: "SetZoom", args: []field{f("ID", "int"), f("Factor", "float")}},
{name: "SetUserAgent", args: []field{f("ID", "int"), f("UserAgent", "string")}},
{name: "SetUserScripts", args: []field{f("ID", "int"), f("Scripts", "strings"), f("ScriptFlags", "strings")}},
{name: "CapturePage", doc: "a PNG of the page; Captured answers", args: []field{f("ID", "int"), f("Req", "int")}},
{name: "UserAgent", wait: true, args: []field{f("ID", "int")}, reply: []field{f("UserAgent", "string")}},
{name: "SchemeRespond", doc: "the status and headers of a SchemeRequest (Header: names and values in turn)",
args: []field{f("Req", "int"), f("Status", "int"), f("Header", "strings")}},
{name: "SchemeData", args: []field{f("Req", "int"), f("Data", "bytes")}},
{name: "SchemeFinish", args: []field{f("Req", "int")}},
{name: "SchemeFail", args: []field{f("Req", "int"), f("Message", "string")}},
{name: "MessageBox", doc: "an alert; MessageBoxResult answers",
args: []field{f("Req", "int"), f("Type", "string"), f("Title", "string"), f("Message", "string"),
f("Detail", "string"), f("Buttons", "strings"), f("DefaultID", "int"), f("CancelID", "int")}},
{name: "OpenFiles", doc: "the system's picker of documents; FilesResult answers with copies the app may read",
args: []field{f("Req", "int"), f("Multiple", "bool"), f("Directories", "bool"), f("Extensions", "strings")}},
{name: "ShareFile", doc: "the share sheet of a file, as the place to save it", args: []field{f("Path", "string")}},
{name: "ClipboardText", wait: true, reply: []field{f("Text", "string"), f("OK", "bool")}},
{name: "SetClipboardText", args: []field{f("Text", "string")}},
{name: "OpenURL", doc: "opens a URL in the app the system has for it", wait: true, args: []field{f("URL", "string")}, reply: []field{f("OK", "bool")}},
{name: "SecretGet", wait: true, args: []field{f("Service", "string"), f("Account", "string")},
reply: []field{f("Value", "bytes"), f("Found", "bool"), f("Error", "string")}},
{name: "SecretSet", wait: true, args: []field{f("Service", "string"), f("Account", "string"), f("Value", "bytes")},
reply: []field{f("Error", "string")}},
{name: "SecretDelete", wait: true, args: []field{f("Service", "string"), f("Account", "string")},
reply: []field{f("Error", "string")}},
{name: "Notify", doc: "a local notification; NotifyDone answers once the system has it",
args: []field{f("Req", "int"), f("NotificationID", "string"), f("Title", "string"), f("Subtitle", "string"),
f("Body", "string"), f("Group", "string"), f("Silent", "bool")}},
{name: "RemoveNotification", args: []field{f("NotificationID", "string")}},
{name: "RemoveAllNotifications"},
{name: "KeepAwake", doc: "keeps the screen on while the app shows", args: []field{f("On", "bool")}},
{name: "NetworkStatus", wait: true, reply: []field{f("Online", "bool"), f("Metered", "bool")}},
{name: "WatchNetwork", doc: "starts NetworkChanged"},
{name: "Battery", wait: true, reply: []field{f("Level", "float"), f("Charging", "bool"), f("LowPower", "bool")}},
{name: "SetSystemBars", doc: `the icons of the system's bars ("auto", "light" or "dark"), and whether the bars hide`,
args: []field{f("Style", "string"), f("Hidden", "bool")}},
{name: "SetOrientations", doc: "the orientations the screen may take: 1 portrait, 2 upside down, 4 landscape left, 8 landscape right; 0 any",
args: []field{f("Mask", "int")}},
{name: "Share", doc: "the share sheet of text, a link and files; ShareResult answers", args: []field{f("Req", "int"), f("Text", "string"),
f("URL", "string"), f("Paths", "strings"), f("X", "float"), f("Y", "float")}},
{name: "SaveFile", doc: "the system's picker of where to keep a copy of Path under Name; FilesResult answers with the place, empty when dismissed",
args: []field{f("Req", "int"), f("Path", "string"), f("Name", "string")}},
{name: "ClipboardImage", wait: true, reply: []field{f("PNG", "bytes")}},
{name: "SetClipboardImage", args: []field{f("PNG", "bytes")}},
{name: "PopupMenu", doc: "the system's menu at a point of the window: Items are encoded by Go (encodeMenu); MenuPicked answers with the item's ID, 0 when dismissed",
args: []field{f("ID", "int"), f("Req", "int"), f("X", "float"), f("Y", "float"), f("Items", "bytes")}},
{name: "SetBarItems", doc: "the buttons at the end of the window's navigation bar; BarItemClicked tells which: titles, symbols and icons by index",
args: []field{f("ID", "int"), f("Titles", "strings"), f("Symbols", "strings"), f("Icons", "strings")}},
{name: "PluginCall", doc: "a call of a plugin's native code: Args and PluginResult's Result are JSON", args: []field{f("Req", "int"),
f("Plugin", "string"), f("Method", "string"), f("Args", "string")}},
{name: "AudioOpen", doc: "opens the sound's output: stereo at Rate frames a second, holding about Ahead milliseconds; on the caller's thread", wait: true,
args: []field{f("Rate", "int"), f("Ahead", "int")}, reply: []field{f("Error", "string")}},
{name: "AudioWrite", doc: "plays interleaved stereo float32 samples after those written, waiting while the output holds enough; on the caller's thread", wait: true,
args: []field{f("Samples", "bytes")}, reply: []field{f("Error", "string")}},
{name: "AudioClose", wait: true},
{name: "Haptic", doc: `"selection", "light", "medium", "heavy", "success", "warning" or "error"`, args: []field{f("Kind", "string")}},
// Native UI.
{name: "RequestFrame", doc: "asks for a Frame at the next refresh of the display", args: []field{f("ID", "int")}},
{name: "SetTextInput", doc: "whether the keyboard shows and what for: the input's traits (platform.TextTraits), and its text. Show counts the requests to show the keyboard again. Offsets are UTF-16 units of the document, of which Text is the part around the selection, from Base; MarkStart is -1 without marked text. A window without Document takes text without one, as a terminal: the keyboard sees none",
args: []field{f("ID", "int"), f("Active", "bool"), f("Show", "int"), f("Serial", "int"), f("X", "float"), f("Y", "float"), f("Width", "float"), f("Height", "float"),
f("Document", "bool"), f("Multiline", "bool"), f("Secure", "bool"), f("Keyboard", "string"), f("ReturnKey", "string"),
f("Capitalize", "string"), f("Autocorrect", "string"), f("Autofill", "string"),
f("Text", "string"), f("Base", "int"), f("Length", "int"), f("SelStart", "int"), f("SelEnd", "int"), f("MarkStart", "int"), f("MarkEnd", "int")}},
{name: "SetCursor", doc: "the pointer's shape, for a mouse or a trackpad", args: []field{f("ID", "int"), f("Cursor", "string")}},
{name: "AccessibilityChanged", doc: "the tree of accessible elements changed; Focus names the one with the focus",
args: []field{f("ID", "int"), f("Focus", "int")}},
{name: "Announce", args: []field{f("Text", "string")}},
{name: "ShowMenu", doc: "the system's edit menu at a point, with the actions given (cut, copy, paste, selectAll); TextCommand answers",
args: []field{f("ID", "int"), f("X", "float"), f("Y", "float"), f("Actions", "strings")}},
{name: "SetBackAvailable", doc: "whether the content takes the system's back", args: []field{f("ID", "int"), f("On", "bool")}},
{name: "ShowMagnifier", doc: "the system's magnifier of what is at a point", args: []field{f("ID", "int"), f("X", "float"), f("Y", "float")}},
{name: "HideMagnifier", args: []field{f("ID", "int")}},
{name: "TextMetrics", doc: "the metrics of a font (Android's Paint): ascent and descent, x-height, underline and strikethrough", wait: true,
args: []field{f("Family", "string"), f("Size", "float"), f("Weight", "int"), f("Italic", "bool")},
reply: []field{f("Ascent", "float"), f("Descent", "float"), f("XHeight", "float"), f("UnderlinePosition", "float"),
f("UnderlineThickness", "float"), f("StrikePosition", "float")}},
{name: "MeasureText", doc: "how wide each of Texts is in a font, kerned unless NoKern", wait: true,
args: []field{f("Family", "string"), f("Size", "float"), f("Weight", "int"), f("Italic", "bool"), f("NoKern", "bool"),
f("Texts", "strings")},
reply: []field{f("Widths", "floats")}},
{name: "TextAdvances", doc: "the advance of each UTF-16 unit of Text laid out as a whole (getTextRunAdvances)", wait: true,
args: []field{f("Family", "string"), f("Size", "float"), f("Weight", "int"), f("Italic", "bool"), f("NoKern", "bool"),
f("Text", "string"), f("RTL", "bool")},
reply: []field{f("Advances", "floats")}},
{name: "DrawText", doc: "draws Text in white at Scale pixels per DIP, its pen DX pixels right of a pixel's edge: its ink's box from the pen and its pixels, a byte of coverage each, or premultiplied RGBA when Color", wait: true,
args: []field{f("Family", "string"), f("Size", "float"), f("Weight", "int"), f("Italic", "bool"), f("Text", "string"),
f("Scale", "float"), f("DX", "float")},
reply: []field{f("Left", "int"), f("Top", "int"), f("Width", "int"), f("Height", "int"), f("Color", "bool"), f("Pixels", "bytes")}},
{name: "RegisterFont", doc: "adds a font file under Family, or its own family when empty", wait: true,
args: []field{f("Data", "bytes"), f("Family", "string")}, reply: []field{f("Family", "string"), f("Error", "string")}},
}
// events go from the host to Go.
var events = []msg{
{name: "Ready", doc: "the app finished launching"},
{name: "Active", doc: "the app is in front, or no longer", args: []field{f("Active", "bool")}},
{name: "Background", doc: "the app goes to the background (true) or came back. The host waits: iOS ends apps that use the GPU in the background, so that frames stop before it returns", wait: true, args: []field{f("Background", "bool")}},
{name: "ThemeChanged"},
{name: "LocaleChanged"},
{name: "TimeZoneChanged", args: []field{f("ID", "string")}},
{name: "OpenURLs", args: []field{f("URLs", "strings")}},
{name: "MemoryWarning"},
{name: "Terminating", doc: "the process ends once Go answers", wait: true},
{name: "Resized", doc: "the window's size in DIPs, the scale, and the insets of what covers it: the system's bars, the cutout, the keyboard",
args: []field{f("ID", "int"), f("Width", "float"), f("Height", "float"), f("Scale", "float"),
f("SafeTop", "float"), f("SafeLeft", "float"), f("SafeBottom", "float"), f("SafeRight", "float"), f("Keyboard", "float")}},
{name: "BackGesture", doc: `the system's gesture of going back, as it goes: Phase is "started", "progress" or "cancelled"`,
args: []field{f("ID", "int"), f("Phase", "string"), f("Progress", "float")}},
{name: "StatusBarTapped", doc: "a tap on iOS's status bar"},
{name: "ViewPressed", doc: "a finger went down on a view a surface holds, which takes it", args: []field{f("ID", "int"), f("X", "float"), f("Y", "float")}},
{name: "PluginResult", args: []field{f("Req", "int"), f("Result", "string"), f("Error", "string"), f("Code", "string")}},
{name: "PluginEvent", doc: "an event of a plugin's native code: Data is JSON", args: []field{f("Plugin", "string"), f("Name", "string"), f("Data", "string")}},
{name: "NetworkChanged", args: []field{f("Online", "bool"), f("Metered", "bool")}},
{name: "ShareResult", args: []field{f("Req", "int"), f("Error", "string")}},
{name: "MenuPicked", args: []field{f("Req", "int"), f("Item", "int")}},
{name: "BarItemClicked", args: []field{f("ID", "int"), f("Index", "int")}},
{name: "TabSelected", doc: "the user chose tab Index", args: []field{f("ID", "int"), f("Index", "int")}},
{name: "StackPopped", doc: "the user took screens off a window's stack (SetStack): Depth stay", args: []field{f("ID", "int"), f("Depth", "int")}},
{name: "Popped", doc: "the window left its stack: the back button, a swipe, Android's back, or PopWindow", args: []field{f("ID", "int")}},
{name: "BackPressed", doc: "Android's back: whether the app took it", wait: true, args: []field{f("ID", "int")}, reply: []field{f("Handled", "bool")}},
{name: "Message", doc: "a message the page's bridge posted", args: []field{f("ID", "int"), f("Text", "string")}},
{name: "WillNavigate", wait: true,
args: []field{f("ID", "int"), f("URL", "string"), f("MainFrame", "bool"), f("UserInitiated", "bool"), f("Unasked", "bool"), f("Reload", "bool")},
reply: []field{f("Allow", "bool")}},
{name: "NewWindow", doc: "window.open or a link to _blank: whether the app opened it", wait: true,
args: []field{f("ID", "int"), f("URL", "string"), f("UserInitiated", "bool")}, reply: []field{f("Handled", "bool")}},
{name: "PageState", doc: "what the page is at, after any change of it",
args: []field{f("ID", "int"), f("URL", "string"), f("Title", "string"), f("Loading", "bool"), f("CanGoBack", "bool"), f("CanGoForward", "bool")}},
{name: "NavigationStarted", args: []field{f("ID", "int"), f("URL", "string")}},
{name: "NavigationCommitted", args: []field{f("ID", "int"), f("URL", "string")}},
{name: "LoadFinished", args: []field{f("ID", "int")}},
{name: "LoadFailed", args: []field{f("ID", "int"), f("URL", "string"), f("Code", "int"), f("Description", "string")}},
{name: "ClosedByPage", args: []field{f("ID", "int")}},
{name: "WindowFront", doc: "the user went to a window of its own scene, or (0) to the app's first", args: []field{f("ID", "int")}},
{name: "ProcessGone", args: []field{f("ID", "int"), f("Reason", "string")}},
{name: "PermissionRequested", wait: true, args: []field{f("ID", "int"), f("Kinds", "strings"), f("Origin", "string")}, reply: []field{f("Allow", "bool")}},
{name: "SchemeRequest", doc: "a request of one of the app's schemes (Header: names and values in turn)",
args: []field{f("ID", "int"), f("Req", "int"), f("Method", "string"), f("URL", "string"), f("Header", "strings"),
f("Body", "bytes"), f("HasBody", "bool")}},
{name: "SchemeCancel", args: []field{f("Req", "int")}},
{name: "AsyncResult", args: []field{f("Req", "int"), f("Result", "string"), f("Error", "string")}},
{name: "Captured", args: []field{f("Req", "int"), f("PNG", "bytes"), f("Error", "string")}},
{name: "MessageBoxResult", args: []field{f("Req", "int"), f("Response", "int")}},
{name: "FilesResult", args: []field{f("Req", "int"), f("Paths", "strings"), f("Error", "string")}},
{name: "NotifyDone", args: []field{f("Req", "int"), f("Error", "string")}},
{name: "NotificationClicked", args: []field{f("NotificationID", "string")}},
// Native UI.
{name: "Frame", doc: "the display refreshes: draw a frame if one was asked for", args: []field{f("ID", "int")}},
{name: "SurfaceChanged", doc: "the native surface to draw on (a CAMetalLayer, an ANativeWindow), 0 when gone",
args: []field{f("ID", "int"), f("Handle", "int"), f("Width", "float"), f("Height", "float"), f("Scale", "float"), f("Refresh", "float")}},
{name: "SurfaceDestroyed", doc: "the native surface goes: the host waits for Go to let go of it", wait: true, args: []field{f("ID", "int")}},
{name: "Touch", doc: `a finger, a pen or a mouse: Phase is "down", "move", "up" or "cancel", Kind "touch", "pen" or "mouse"`,
args: []field{f("ID", "int"), f("Pointer", "int"), f("Phase", "string"), f("Kind", "string"), f("X", "float"), f("Y", "float"),
f("Pressure", "float"), f("Buttons", "int"), f("Time", "float")}},
{name: "Scroll", doc: "a mouse's or a trackpad's scrolling, in DIPs", args: []field{f("ID", "int"), f("X", "float"), f("Y", "float"),
f("DX", "float"), f("DY", "float"), f("Precise", "bool"), f("Phase", "string")}},
{name: "Key", doc: "a hardware keyboard's key: Down, its name (as ui names keys) and the text it types",
args: []field{f("ID", "int"), f("Down", "bool"), f("Key", "string"), f("Text", "string"), f("Mods", "int"), f("Repeated", "bool")},
reply: []field{f("Handled", "bool")}, wait: true},
{name: "TextReplace", doc: "the keyboard put Text in Start to End of the document, or with no range in place of the marked text or the selection; answers TextStateReply", wait: true,
args: []field{f("ID", "int"), f("HasRange", "bool"), f("Start", "int"), f("End", "int"), f("Text", "string")}},
{name: "TextMark", doc: "the input method composes Text over Start to End, or with no range over the marked text or the selection; SelStart and SelEnd are in Text; answers TextStateReply", wait: true,
args: []field{f("ID", "int"), f("HasRange", "bool"), f("Start", "int"), f("End", "int"), f("Text", "string"), f("SelStart", "int"), f("SelEnd", "int")}},
{name: "TextUnmark", doc: "the marked text stays as text; answers TextStateReply", wait: true, args: []field{f("ID", "int")}},
{name: "TextDelete", doc: "the keyboard deleted Before units before the selection and After after it; answers TextStateReply", wait: true,
args: []field{f("ID", "int"), f("Before", "int"), f("After", "int")}},
{name: "TextSelect", doc: "the keyboard moved the selection; answers TextStateReply", wait: true, args: []field{f("ID", "int"), f("Start", "int"), f("End", "int")}},
{name: "TextCommand", doc: `an editing action of the keyboard or the edit menu: "newline", "tab", "deleteBackward", "deleteForward", "cut", "copy", "paste", "selectAll", "left", …; answers TextStateReply`, wait: true,
args: []field{f("ID", "int"), f("Command", "string")}},
{name: "TextState", doc: "the text around the selection, and the selection", wait: true,
args: []field{f("ID", "int")}, reply: []field{f("Text", "string"), f("Base", "int"), f("Length", "int"), f("SelStart", "int"), f("SelEnd", "int"),
f("MarkStart", "int"), f("MarkEnd", "int"), f("X", "float"), f("Y", "float"), f("Width", "float"), f("Height", "float")}},
{name: "TextRange", doc: "a part of the document outside the text the host has", wait: true,
args: []field{f("ID", "int"), f("Start", "int"), f("End", "int")}, reply: []field{f("Text", "string"), f("Start", "int"), f("End", "int")}},
{name: "TextBounds", doc: "where the range is on screen: its first line's rectangle", wait: true,
args: []field{f("ID", "int"), f("Start", "int"), f("End", "int")}, reply: []field{f("OK", "bool"), f("X", "float"), f("Y", "float"), f("Width", "float"), f("Height", "float"), f("End", "int")}},
{name: "TextIndexAt", doc: "the offset nearest a point of the window", wait: true,
args: []field{f("ID", "int"), f("X", "float"), f("Y", "float")}, reply: []field{f("OK", "bool"), f("Index", "int")}},
{name: "TextInputEnded", doc: "the keyboard went away", args: []field{f("ID", "int")}},
{name: "AccessibilityTree", doc: "the accessible elements, encoded as Nodes: for each, its ID, parent, role, label, value, hint, frame and actions", wait: true,
args: []field{f("ID", "int")}, reply: []field{f("Nodes", "bytes")}},
{name: "AccessibilityAction", doc: `an assistive technology's action on an element: "press", "increment", "decrement", "focus", "scrollForward", …`, wait: true,
args: []field{f("ID", "int"), f("Node", "int"), f("Action", "string")}, reply: []field{f("Handled", "bool")}},
}
File diff suppressed because it is too large. Load diff
+172
View File
@@ -0,0 +1,172 @@
// Package wire encodes the messages the backend of phones (internal/mobile)
// and its hosts exchange: the Swift host on iOS, the Kotlin host on
// Android. A message is its number and then its fields, in the order the
// spec (gen/spec.go) lists them; replies are their fields alone.
//
// Integers are zigzag varints, floats 8 bytes little endian, booleans a
// byte, strings and bytes a uvarint length and their bytes, lists of
// strings a uvarint count and the strings, lists of floats a count and
// the floats. msgs.go, Wire.swift and
// Wire.kt are generated from the spec (go generate), so the three sides
// agree on every message.
package wire
import (
"encoding/binary"
"errors"
"math"
)
//go:generate go run ./gen
// ErrShort is the error of a Reader that ran out of bytes.
var ErrShort = errors.New("wire: message too short")
// Writer appends encoded values to its buffer.
type Writer struct{ Buf []byte }
// Reset empties the buffer, keeping its memory.
func (w *Writer) Reset() { w.Buf = w.Buf[:0] }
func (w *Writer) Uvarint(v uint64) { w.Buf = binary.AppendUvarint(w.Buf, v) }
func (w *Writer) Int(v int) { w.Buf = binary.AppendVarint(w.Buf, int64(v)) }
func (w *Writer) Bool(v bool) {
if v {
w.Buf = append(w.Buf, 1)
} else {
w.Buf = append(w.Buf, 0)
}
}
func (w *Writer) Float(v float64) {
w.Buf = binary.LittleEndian.AppendUint64(w.Buf, math.Float64bits(v))
}
func (w *Writer) String(s string) {
w.Uvarint(uint64(len(s)))
w.Buf = append(w.Buf, s...)
}
func (w *Writer) Bytes(b []byte) {
w.Uvarint(uint64(len(b)))
w.Buf = append(w.Buf, b...)
}
func (w *Writer) Floats(f []float64) {
w.Uvarint(uint64(len(f)))
for _, v := range f {
w.Float(v)
}
}
func (w *Writer) Strings(s []string) {
w.Uvarint(uint64(len(s)))
for _, v := range s {
w.String(v)
}
}
// Reader reads values from a message. A value past its end reads as zero
// and sets Err, which the caller checks once it read the message.
type Reader struct {
Buf []byte
Err error
}
func (r *Reader) fail() {
if r.Err == nil {
r.Err = ErrShort
}
r.Buf = nil
}
func (r *Reader) Uvarint() uint64 {
v, n := binary.Uvarint(r.Buf)
if n <= 0 {
r.fail()
return 0
}
r.Buf = r.Buf[n:]
return v
}
func (r *Reader) Int() int {
v, n := binary.Varint(r.Buf)
if n <= 0 {
r.fail()
return 0
}
r.Buf = r.Buf[n:]
return int(v)
}
func (r *Reader) Bool() bool {
if len(r.Buf) < 1 {
r.fail()
return false
}
v := r.Buf[0] != 0
r.Buf = r.Buf[1:]
return v
}
func (r *Reader) Float() float64 {
if len(r.Buf) < 8 {
r.fail()
return 0
}
v := math.Float64frombits(binary.LittleEndian.Uint64(r.Buf))
r.Buf = r.Buf[8:]
return v
}
// raw returns the next n bytes, aliasing the message.
func (r *Reader) raw() []byte {
n := r.Uvarint()
if uint64(len(r.Buf)) < n {
r.fail()
return nil
}
b := r.Buf[:n:n]
r.Buf = r.Buf[n:]
return b
}
func (r *Reader) String() string { return string(r.raw()) }
// Bytes returns a copy of the next bytes, which outlives the message.
func (r *Reader) Bytes() []byte {
b := r.raw()
if b == nil {
return nil
}
return append([]byte(nil), b...)
}
func (r *Reader) Strings() []string {
n := r.Uvarint()
if n > uint64(len(r.Buf)) {
r.fail()
return nil
}
s := make([]string, 0, n)
for range n {
s = append(s, r.String())
}
return s
}
func (r *Reader) Floats() []float64 {
n := r.Uvarint()
if n > uint64(len(r.Buf))/8 {
r.fail()
return nil
}
f := make([]float64, n)
for i := range f {
f[i] = r.Float()
}
return f
}
+38
View File
@@ -0,0 +1,38 @@
package wire
import (
"slices"
"testing"
)
func TestRoundTrip(t *testing.T) {
m := CreateWindow{ID: 3, Surface: true, Background: 0xff8000ff, Schemes: []string{"mygo", "app"},
UserAgent: "ünïcode", Inspectable: true}
var w Writer
m.Encode(&w)
r := Reader{Buf: w.Buf}
if op := r.Uvarint(); op != CallCreateWindow {
t.Fatalf("op = %d", op)
}
got := CreateWindow{ID: r.Int(), Surface: r.Bool(), OwnScene: r.Bool(), Background: r.Int(), HasBackground: r.Bool(), Schemes: r.Strings(),
Scripts: r.Strings(), ScriptFlags: r.Strings(), UserAgent: r.String(), UserAgentSuffix: r.String(), Inspectable: r.Bool()}
if r.Err != nil || got.ID != 3 || !got.Surface || got.Background != 0xff8000ff || !slices.Equal(got.Schemes, m.Schemes) ||
got.UserAgent != m.UserAgent || !got.Inspectable {
t.Errorf("decoded %+v (%v)", got, r.Err)
}
var f Writer
f.Float(-1.5)
f.Int(-7)
fr := Reader{Buf: f.Buf}
if v, n := fr.Float(), fr.Int(); v != -1.5 || n != -7 {
t.Errorf("Float, Int = %v, %v", v, n)
}
}
// A message cut short reads as zeros and reports it.
func TestShort(t *testing.T) {
r := Reader{Buf: []byte{5}}
if s := r.String(); s != "" || r.Err != ErrShort {
t.Errorf("String = %q, %v", s, r.Err)
}
}