feat: port the client to Flutter (0.3.0)
Replace the MyGo/Go app with a Flutter client that keeps the feature set: - servers: saved servers, passwordless and password login, HTTP/SOCKS5 proxy via dart:io, self-signed certificates and pinning, tokens in flutter_secure_storage (Keystore) - sessions: list with live events, search, new/rename/archive/delete, instance sheet - chat: streaming Markdown (flutter_markdown), reasoning and tool rows, image previews, context usage ring and sheet, model/agent switching, fork/revert, attachments (file_picker), permissions - Android 7.0 (API 24)+, plain http:// works in release (Dart dials sockets directly) - build: China mirrors for Gradle/NDK, Aliyun Maven repositories, and the Gradle distribution pre-seeded; release signed with the test keystore Read-aloud is dropped as requested. Version 0.3.0.
This commit is contained in:
1 parent
24a311f234
commit
aee560172c
2616 files changed
+5810
-672083
No files matched your search
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
#Wed Nov 18 12:18:36 CST 2026
|
||||
gradle.version=8.14.3
|
||||
Binary file not shown.
Binary file not shown.
Whitespace-only changes.
@@ -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) }
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
BIN
Binary file not shown.
@@ -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
@@ -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,6 @@
|
||||
// Written by mygo build: the plugins the app's packages name.
|
||||
package dev.mygo
|
||||
|
||||
internal fun registerPlugins() {
|
||||
PluginHost.register("tts", TTSPlugin())
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package dev.mygo
|
||||
|
||||
import android.speech.tts.TextToSpeech
|
||||
import org.json.JSONObject
|
||||
import java.util.Locale
|
||||
|
||||
class TTSPlugin : MyGoPlugin {
|
||||
private var engine: TextToSpeech? = null
|
||||
private var ready = false
|
||||
private var pending: Pair<String, PluginReply>? = null
|
||||
|
||||
override fun call(method: String, args: JSONObject, reply: PluginReply) {
|
||||
when (method) {
|
||||
"speak" -> {
|
||||
val text = args.optString("text").ifEmpty { return reply.failure(PluginFailure("Empty", "no text")) }
|
||||
if (ready) {
|
||||
engine?.speak(text, TextToSpeech.QUEUE_FLUSH, null, "openchamber")
|
||||
reply.success(null)
|
||||
} else {
|
||||
pending = text to reply
|
||||
init()
|
||||
}
|
||||
}
|
||||
"stop" -> {
|
||||
engine?.stop()
|
||||
reply.success(null)
|
||||
}
|
||||
else -> reply.failure(PluginFailure("NoMethod", method))
|
||||
}
|
||||
}
|
||||
|
||||
private fun init() {
|
||||
if (engine != null) return
|
||||
engine = TextToSpeech(PluginHost.context) { status ->
|
||||
if (status == TextToSpeech.SUCCESS) {
|
||||
engine?.setLanguage(Locale.getDefault())
|
||||
ready = true
|
||||
val p = pending
|
||||
pending = null
|
||||
if (p != null) {
|
||||
engine?.speak(p.first, TextToSpeech.QUEUE_FLUSH, null, "openchamber")
|
||||
p.second.success(null)
|
||||
}
|
||||
} else {
|
||||
val p = pending
|
||||
pending = null
|
||||
if (p != null) p.second.failure(PluginFailure("Init", "text-to-speech is unavailable"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user