Android: Hex Preview, an APK outside Google Play that updates itself (#2531)

* Android: Hex Preview, an APK outside Google Play that updates itself

Adds a preview build type: the release build (R8, resource shrinking, arm64-v8a,
Android 12+) as ly.anoma.hex.preview, named Hex Preview in the launcher and the
keyboard list, signed with its own key from ~/.config/hex-android-preview (or
HEX_ANDROID_PREVIEW_KEYSTORE_PROPERTIES), never the Play upload key. Its version
code is -PhexPreviewBuild (the release script passes dev's commit count) and its
name <versionName>-preview.<build>; -PhexPreviewChannel bakes the channel address.

The updater lives only in app/src/preview: it reads latest.json from the channel
when the app opens and at most once a day when the keyboard opens (never in a
password field), shows a card on Home and one dismissible line in the strip,
downloads only after Update (size first on mobile data), checks size, SHA-256
and the signing certificate, then installs through PackageInstaller with
REQUEST_INSTALL_PACKAGES and UPDATE_PACKAGES_WITHOUT_USER_ACTION. Settings gets
Check for updates automatically and Check now; the preview's privacy text says
what the check sends. Strings in English and Simplified Chinese.

Play builds (debug, release) compile app/src/play's empty Updates, inlined away.
Main code gains only the hooks: StripNotice and the strip's notice row,
Updates.appOpened in MainActivity.onResume, Updates.keyboardShown in
onStartInputView, the two cards on Home, and HexSettings' Label/Card/Rule/Entry/
Toggle/Action made internal for the preview's cards.

Verified on anomastudio: testDebugUnitTest and assemblePreview pass; the
release bundle requests only RECORD_AUDIO and INTERNET, has no receiver, no
PackageInstaller reference, no updater string or resource and no
ly.anoma.hex.updates class in its R8 mapping; the preview APK is signed with
the preview certificate. Hex 0.2.2 (upload-signed) and Hex Preview install side
by side on the API 36 and API 31 emulators with separate keyboards and settings.

* Android: preview-release.sh publishes Hex Preview builds; README section

android/scripts/preview-release.sh builds the preview APK on the builder Mac
(anomastudio by default) from one commit, numbered by git rev-list --count,
checks its signing certificate and version before anything is published,
creates a pre-release (never latest) tagged android-preview-<build> at that
commit with the APK and its SHA-256, confirms the asset serves those bytes,
then fast-forwards the channel branch (android-preview) to a commit holding
only latest.json and the README people land on. It refuses a commit not on
dev for the real channel, an existing tag, or a build not newer than the
channel's. --repo and --channel point it at a test channel (a fork).

android/README.md gains a Hex Preview section: the build type, the key and
its certificate SHA-256, where the updater lives and how builds are numbered.

Verified: bash -n; the end-to-end run against a fork follows in this PR.

* preview-release.sh: Java for apksigner on the builder; no shell backticks in the release body

apksigner needs a JDK on the builder's PATH, which ferry's login shell lacks; the
build and the signature check now share one JAVA_HOME/PATH prefix. The release
body was written by a bash-expanded heredoc, so its backticks ran the SHA-256 as
a command and dropped both hashes from the body; Python now adds them.

Verified: build 2305 published to the R44VC0RP/hex-preview-test fork (channel
android-preview-test) with this script; its latest.json and README rendered as
expected, and the 2305 release body was corrected by hand.

* Hex Preview: a strip line that fits, and Version 0.2.2, build N in Check now

The strip's update line was cut off on a Pixel 8 (A Hex Preview update is
availa…); it now reads Hex Preview update available. Check now named the build
twice (Version 0.2.2-preview.2305 · build 2305); it now shows the version
without the preview suffix, then the build.

Verified from emulator screenshots of build 2305 on API 36.

* preview-release.sh: build detached on the builder, so a dropped ferry connection can't stop it

A publish of build 2308 died when ferry's connection to the loaded Studio broke
mid-build (ferry stops the remote process tree when the caller goes away). The
build now runs with ferry sh --detach, writes its exit code to build.exit, and
the script polls for it (15 s, up to an hour), printing the log's tail on failure.

Verified: build 2308 then published to the test channel on the fork.

* Hex Preview: say that updating closes the keyboard for a moment

On the API 31 emulator, an update installed while the keyboard was open in
another app closed that keyboard, and it stayed closed until the field was
tapped again (API 36: until another field took focus). Hex Preview stays the
selected keyboard throughout. The update card now says so under Update and
while installing, in English and Simplified Chinese.

Verified: compilePreviewKotlin on anomastudio; the behaviour itself on the
API 31 emulator with build 2308.

* preview-release.sh: retry the builder steps when ferry's connection drops

Under heavy load on the Studio, ferry's pipe to it broke on several steps of a
publish (copy, signature check, fetching the APK). Each builder step is safe to
repeat, so they now retry up to five times, and the detached build is not
started twice if its log already exists.

Verified: build 2310 published to the fork's test channel with this script.
This commit is contained in:
Ryan Vogel
2026-11-23 11:37:51 -05:00
committed by GitHub
parent ae1cdf71b9
commit f1d965ae5c
15 changed files with 820 additions and 10 deletions
+8
View File
@@ -81,4 +81,12 @@ On the headless Studio, start an ARM64 AVD with `-audio none -grpc 8566 -grpc-us
For the upload bundle, run `./gradlew :app:bundleRelease`. Release packaging requires a private properties file at `~/.config/hex-android/keystore.properties` or the path in `HEX_ANDROID_KEYSTORE_PROPERTIES`. It must contain `storeFile` (relative to that file, or absolute), `keyAlias`, `storePassword` and `keyPassword`. Release uses R8 and resource shrinking and never falls back to the debug key. Gradle writes `app/build/outputs/bundle/release/app-release.aab`.
## Hex Preview (outside Google Play)
Hex Preview is the `preview` build type: the release build as an APK, application id `ly.anoma.hex.preview`, named Hex Preview in the launcher and in Android's keyboard list, so it installs beside Hex from Google Play with its own settings, words and speech model. It is signed with its own key (never the Play upload key), read from `~/.config/hex-android-preview/keystore.properties` or `HEX_ANDROID_PREVIEW_KEYSTORE_PROPERTIES`; every build must be, because Android refuses an update signed with any other. The certificate's SHA-256 is `13:35:68:F6:F0:61:4F:E5:7B:C8:8D:AE:CA:32:AF:A7:2C:6A:B7:40:20:26:29:F7:52:FA:A0:33:BE:35:D9:8E`.
Its updater lives only in `app/src/preview` (code, permissions, strings); debug and release build `app/src/play`'s empty `Updates`, which is inlined away, because Google Play forbids an app updating itself. It reads `latest.json` on the `android-preview` branch when the app opens and at most once a day when the keyboard opens (never in a password field; Settings › Check for updates automatically). An update downloads only after Update is tapped, and goes to `PackageInstaller` only once its size, SHA-256 and signing certificate match.
[`scripts/preview-release.sh`](scripts/preview-release.sh) publishes a build: the build number is the count of commits up to the built commit of `dev`, the version name `<versionName>-preview.<build>`, the tag `android-preview-<build>` (a pre-release, never moved), and the channel branch `android-preview` holds only `latest.json` and the README people land on.
**Scope:** Android 12+ (min API 31), target 36, ARM64, four typing models and four dictation languages. See the [Play release evidence, listing drafts, phone screenshots and real-device checklist](play/README.md). The Studio also exercised offline fallback, all four styles, per-dictation translation, both appearances and insertion into a separate app with music playing in earlier phases.
+45
View File
@@ -60,6 +60,26 @@ val requireUploadKey by tasks.registering {
}
}
// Hex Preview (the `preview` build type) is signed with its own key, never the Play upload key, read the same way.
val previewProperties = providers.environmentVariable("HEX_ANDROID_PREVIEW_KEYSTORE_PROPERTIES").orNull
?.let(::file) ?: File(System.getProperty("user.home"), ".config/hex-android-preview/keystore.properties")
val previewKey = Properties().apply {
if (previewProperties.isFile) previewProperties.inputStream().use(::load)
}
val requirePreviewKey by tasks.registering {
doLast {
check(listOf("storeFile", "storePassword", "keyAlias", "keyPassword").all { !previewKey.getProperty(it).isNullOrBlank() } &&
previewProperties.parentFile.resolve(previewKey.getProperty("storeFile")).isFile) {
"Hex Preview packaging requires the preview keystore and its keystore.properties."
}
}
}
// A Hex Preview build's number: android/scripts/preview-release.sh passes the count of dev's commits up to the
// commit it builds, which only grows. A local build without it is build 1 and updates to any published one.
val previewBuild = providers.gradleProperty("hexPreviewBuild").orNull?.toInt() ?: 1
val previewChannel = providers.gradleProperty("hexPreviewChannel").orNull
?: "https://raw.githubusercontent.com/anomalyco/hex/android-preview/latest.json"
android {
namespace = "ly.anoma.hex"
compileSdk = 36
@@ -88,6 +108,12 @@ android {
keyAlias = upload.getProperty("keyAlias")
keyPassword = upload.getProperty("keyPassword")
}
create("preview") {
storeFile = previewKey.getProperty("storeFile")?.let { previewProperties.parentFile.resolve(it) }
storePassword = previewKey.getProperty("storePassword")
keyAlias = previewKey.getProperty("keyAlias")
keyPassword = previewKey.getProperty("keyPassword")
}
}
buildTypes {
release {
@@ -98,7 +124,18 @@ android {
signingConfig = signingConfigs.getByName("upload")
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
// Hex Preview: the release build as an APK outside Google Play, beside the Play app, with its own updater
// (src/preview). Play builds get src/play's empty one: Google Play forbids an app updating itself.
create("preview") {
initWith(getByName("release"))
applicationIdSuffix = ".preview"
signingConfig = signingConfigs.getByName("preview")
matchingFallbacks += "release"
resValue("string", "update_channel", previewChannel)
}
}
sourceSets["debug"].java.srcDir("src/play/java")
sourceSets["release"].java.srcDir("src/play/java")
packaging.resources.excludes += "DebugProbesKt.bin"
buildFeatures { compose = true }
androidResources { noCompress += listOf("bin", "hextm", "valid", "capitals") }
@@ -111,9 +148,17 @@ android {
}
}
androidComponents {
onVariants(selector().withBuildType("preview")) { variant ->
val name = "${android.defaultConfig.versionName}-preview.$previewBuild"
variant.outputs.forEach { it.versionCode.set(previewBuild); it.versionName.set(name) }
}
}
kotlin.compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) }
tasks.matching { it.name in setOf("packageRelease", "packageReleaseBundle", "signReleaseBundle", "bundleRelease", "assembleRelease") }
.configureEach { dependsOn(requireUploadKey) }
tasks.matching { it.name in setOf("packagePreview", "assemblePreview") }.configureEach { dependsOn(requirePreviewKey) }
// Unmodified InterVariable.ttf from rsms/inter v4.1, stored locally for offline builds.
val verifyInter by tasks.registering {
val font = file("src/main/res/font/inter_variable.ttf")
@@ -38,6 +38,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import ly.anoma.hex.speech.*
import ly.anoma.hex.typing.TypingPreferences
import ly.anoma.hex.updates.Updates
private enum class Page(val title: Int) {
Home(R.string.app_name), Dictation(R.string.settings_dictation), Keyboard(R.string.settings_keyboard), Privacy(R.string.settings_privacy),
@@ -163,6 +164,7 @@ internal fun HexSettings(setup: Setup, speech: SpeechPreferences, typing: Typing
}
}
if (notice != null) Label(notice, muted = true, size = 14, lines = 3)
Updates.HomeCard()
Card {
listOf(Page.Dictation, Page.Keyboard, Page.Privacy).forEachIndexed { i, dest ->
if (i != 0) Rule()
@@ -173,6 +175,7 @@ internal fun HexSettings(setup: Setup, speech: SpeechPreferences, typing: Typing
Entry(stringResource(R.string.home_keyboard_settings), value = "↗", action = systemSettings)
Rule(); Entry(stringResource(R.string.home_run_setup), action = { setupPage(0) })
}
Updates.SettingsCard()
}
Page.Dictation -> {
Card {
@@ -286,7 +289,7 @@ internal fun HexSettings(setup: Setup, speech: SpeechPreferences, typing: Typing
}
}
@Composable private fun Label(text: String, size: Int = 16, weight: FontWeight = FontWeight.Normal,
@Composable internal fun Label(text: String, size: Int = 16, weight: FontWeight = FontWeight.Normal,
muted: Boolean = false, inverted: Boolean = false, lines: Int = 1, mod: Modifier = Modifier) {
BasicText(text, mod, style = TextStyle(fontFamily = inter, fontWeight = weight, fontSize = size.sp,
lineHeight = (size + 5).sp, color = colorResource(if (inverted) R.color.page else if (muted) R.color.quiet else R.color.ink)),
@@ -312,14 +315,14 @@ private fun reflow(lines: List<String>) = buildString {
append(if (ends) "\n" else " ")
}
}
@Composable private fun Action(text: String, onClick: () -> Unit) {
@Composable internal fun Action(text: String, onClick: () -> Unit) {
Box(Modifier.heightIn(min = 48.dp).clickable(role = Role.Button, onClick = onClick).padding(horizontal = 12.dp),
contentAlignment = Alignment.Center) { Label(text, weight = FontWeight.Medium, size = 15) }
}
@Composable private fun Card(content: @Composable ColumnScope.() -> Unit) {
@Composable internal fun Card(content: @Composable ColumnScope.() -> Unit) {
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(colorResource(R.color.sheet)), content = content)
}
@Composable private fun Rule() {
@Composable internal fun Rule() {
Spacer(Modifier.fillMaxWidth().padding(start = 16.dp).height(1.dp).background(colorResource(R.color.rule)))
}
@Composable private fun RowScope.RowTitle(title: String, note: String?) {
@@ -328,7 +331,7 @@ private fun reflow(lines: List<String>) = buildString {
if (note != null) Label(note, size = 13, muted = true, lines = 2)
}
}
@Composable private fun Entry(title: String, note: String? = null, value: String = "›", action: (() -> Unit)? = null) {
@Composable internal fun Entry(title: String, note: String? = null, value: String = "›", action: (() -> Unit)? = null) {
val click = if (action != null) Modifier.clickable(role = Role.Button, onClick = action) else Modifier
Row(Modifier.fillMaxWidth().then(click).heightIn(min = 52.dp).padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
@@ -336,7 +339,7 @@ private fun reflow(lines: List<String>) = buildString {
if (action != null && value.isNotEmpty()) Label(value, muted = true, size = if (value == "›") 22 else 15)
}
}
@Composable private fun Toggle(title: String, note: String, on: Boolean, enabled: Boolean = true, change: (Boolean) -> Unit) {
@Composable internal fun Toggle(title: String, note: String, on: Boolean, enabled: Boolean = true, change: (Boolean) -> Unit) {
Row(Modifier.fillMaxWidth().toggleable(on, enabled = enabled, role = Role.Switch, onValueChange = change)
.heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
@@ -43,6 +43,7 @@ import kotlinx.coroutines.delay
import ly.anoma.hex.keyboard.speechNote
import ly.anoma.hex.speech.*
import ly.anoma.hex.typing.TypingPreferences
import ly.anoma.hex.updates.Updates
internal data class Setup(val mic: Boolean = false, val enabled: Boolean = false, val chosen: Boolean = false,
val micNeedsSettings: Boolean = false) {
@@ -122,7 +123,7 @@ class MainActivity : ComponentActivity() {
permission.launch(Manifest.permission.RECORD_AUDIO)
}
}
override fun onResume() { super.onResume(); refresh() }
override fun onResume() { super.onResume(); refresh(); Updates.appOpened(this) }
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (!hasFocus) return
@@ -24,6 +24,7 @@ import ly.anoma.hex.typing.PersonalWords
import ly.anoma.hex.typing.SpatialDecoder
import ly.anoma.hex.typing.TypingModel
import ly.anoma.hex.typing.TypingPreferences
import ly.anoma.hex.updates.Updates
/** The input method: the editor's lifecycle, the views and dictation. Typing lives in [KeyboardEngine]. */
/** Dictation's notes arrive from MicCapture as English sentences: the ones a person sees, in the phone's
@@ -89,6 +90,8 @@ class HexKeyboard : InputMethodService() {
if (typeChanged) view?.closeMenu(configure = false)
engine.configureTyping()
view?.status(capture.phase, idleHint())
// Hex Preview's update line (Play builds have none); never in a password field.
Updates.keyboardShown(this, engine.secure) { view?.notice(it) }
}
override fun onUpdateSelection(oldSelStart: Int, oldSelEnd: Int, newSelStart: Int, newSelEnd: Int,
candidatesStart: Int, candidatesEnd: Int) {
@@ -53,6 +53,7 @@ internal class KeyboardView(context: Context, private val ime: HexKeyboard) : Li
}
override fun suggestions(slots: List<Suggestion>) = strip.suggestions(slots)
override fun undoDictation(shown: Boolean) = strip.undo(shown)
fun notice(notice: StripNotice?) = strip.notice(notice)
/** Emoji in place of the strip and the keys, the window's height unchanged (Gboard's panel
* replaces its toolbar too); ABC brings both back. */
@@ -0,0 +1,5 @@
package ly.anoma.hex.keyboard
/** One line the strip shows in place of the hint and suggestions until the person types, taps it or its ✕.
* Only Hex Preview's updater uses it (src/preview); Play builds never show one. */
internal class StripNotice(val text: String, val dismissLabel: String, val tap: () -> Unit, val dismiss: () -> Unit)
@@ -54,6 +54,11 @@ internal class StripView(context: Context, private val ime: HexKeyboard, private
// Undo dictation, in the slots' place after a dictation (iPhone Hex's chip).
private val undoChip = TextView(context)
private var undoing = false
// A dismissible line in the hint's place (Hex Preview's update): it goes for this field once typing starts.
private val noticeRow = LinearLayout(context)
private val noticeText = TextView(context)
private val noticeClose = FrameLayout(context)
private var notice: StripNotice? = null
private val well = FrameLayout(context)
private val scope = DotScopeView(context)
@@ -94,6 +99,20 @@ internal class StripView(context: Context, private val ime: HexKeyboard, private
setOnClickListener { if (choosing) host.backInMenu() }
}
idleRow.addView(statusText, LinearLayout.LayoutParams(0, -1, 1f))
noticeText.apply {
useInter(500); setTextColor(ink); textSize = 14f; maxLines = 1; ellipsize = TextUtils.TruncateAt.END
gravity = Gravity.CENTER_VERTICAL; setPadding(dp(10), 0, dp(4), 0); isFocusable = true
setOnClickListener { notice?.let { notice = null; update(); it.tap() } }
}
noticeClose.apply {
isFocusable = true
addView(icon(R.drawable.ic_cancel), LayoutParams(dp(16), dp(16), Gravity.CENTER))
setOnClickListener { notice?.let { notice = null; update(); it.dismiss() } }
}
noticeRow.addView(noticeText, LinearLayout.LayoutParams(0, -1, 1f))
noticeRow.addView(noticeClose, LinearLayout.LayoutParams(dp(40), -1))
noticeRow.visibility = GONE
idleRow.addView(noticeRow, LinearLayout.LayoutParams(0, -1, 1f))
for (i in 0..2) {
if (i > 0) slotRow.addView(dividers[i - 1].apply { setBackgroundColor(color(R.color.rule)) },
LinearLayout.LayoutParams(maxOf(1, dp(1) / 2 + 1), dp(20)).apply { gravity = Gravity.CENTER_VERTICAL })
@@ -199,6 +218,8 @@ internal class StripView(context: Context, private val ime: HexKeyboard, private
* in quotes on the left, then the fix (in a chip) or the likeliest word in the middle. Without it,
* the likeliest word takes the middle, the next the left, as Gboard and iPhone place them. */
fun suggestions(slots: List<Suggestion>) {
// Typing started: the suggestions matter more than the notice, which comes back in the next field.
if (slots.any { it.kind == Suggestion.Kind.Typed }) notice = null
val shown = arrayOfNulls<Suggestion>(3)
if (slots.any { it.kind == Suggestion.Kind.Typed }) slots.take(3).forEachIndexed { i, slot -> shown[i] = slot }
else { shown[1] = slots.getOrNull(0); shown[0] = slots.getOrNull(1); shown[2] = slots.getOrNull(2) }
@@ -226,12 +247,21 @@ internal class StripView(context: Context, private val ime: HexKeyboard, private
}
/** Undo dictation shows in the slots' place, or goes. */
fun undo(shown: Boolean) { undoing = shown; update() }
/** Shows [notice] (or none) in the hint's place until typing starts, a tap or its ✕. */
fun notice(notice: StripNotice?) {
this.notice = notice
noticeText.text = notice?.text; noticeText.contentDescription = notice?.text
noticeClose.contentDescription = notice?.dismissLabel
update()
}
fun update() {
val undo = idle && !choosing && undoing
val show = idle && !choosing && !undo && offered.any { it != null }
val noted = idle && !choosing && notice != null
val undo = idle && !choosing && undoing && !noted
val show = idle && !choosing && !undo && !noted && offered.any { it != null }
noticeRow.visibility = if (noted) VISIBLE else GONE
(undoChip.parent as View).visibility = if (undo) VISIBLE else GONE
slotRow.visibility = if (show) VISIBLE else GONE
statusText.visibility = if (idle && !show && !undo) VISIBLE else GONE
statusText.visibility = if (idle && !show && !undo && !noted) VISIBLE else GONE
menuKey.text = context.getString(when { choosing -> R.string.keyboard_menu_done; show -> R.string.keyboard_menu_more; else -> R.string.keyboard_menu_open })
menuKey.contentDescription = context.getString(if (choosing) R.string.keyboard_menu_done else R.string.keyboard_menu)
}
@@ -0,0 +1,16 @@
package ly.anoma.hex.updates
import android.content.Context
import androidx.compose.runtime.Composable
import ly.anoma.hex.keyboard.StripNotice
/** Play builds (debug and release) have no update system: Google Play updates them, and Play forbids an app
* updating itself any other way. Hex Preview's updater is in src/preview. These do nothing and are inlined
* where they are called, so not even this object reaches the Play build's code. */
@Suppress("NOTHING_TO_INLINE", "UNUSED_PARAMETER")
internal object Updates {
inline fun appOpened(context: Context) = Unit
inline fun keyboardShown(context: Context, secure: Boolean, show: (StripNotice?) -> Unit) = Unit
@Composable inline fun HomeCard() = Unit
@Composable inline fun SettingsCard() = Unit
}
@@ -0,0 +1,13 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- Hex Preview only: installing its own updates (each after the person taps Update) and saying the
download's size first on mobile data. The Play build has none of these. -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.UPDATE_PACKAGES_WITHOUT_USER_ACTION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application>
<receiver android:name="ly.anoma.hex.updates.UpdateReceiver" android:exported="false" />
<!-- As in release: baseline profiles still install; the shell's benchmark receiver is unnecessary. -->
<receiver android:name="androidx.profileinstaller.ProfileInstallReceiver" tools:node="remove" />
</application>
</manifest>
@@ -0,0 +1,149 @@
package ly.anoma.hex.updates
import android.content.Context
import android.content.pm.PackageManager
import org.json.JSONArray
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import javax.net.ssl.HttpsURLConnection
import ly.anoma.hex.R
/** One published Hex Preview build, as latest.json describes it. */
internal data class Release(val code: Long, val name: String, val version: String, val url: String, val size: Long,
val sha256: String, val minSdk: Int, val date: String, val notes: List<String>) {
fun json(): String = JSONObject().put("versionCode", code).put("versionName", name).put("version", version)
.put("minSdk", minSdk).put("published", date).put("notes", JSONArray(notes))
.put("apk", JSONObject().put("url", url).put("size", size).put("sha256", sha256)).toString()
companion object {
/** Null for anything that isn't a sane Hex Preview release: a GitHub HTTPS address, a SHA-256, a size. */
fun parse(text: String): Release? = runCatching {
val o = JSONObject(text)
val apk = o.getJSONObject("apk")
val notes = o.optJSONArray("notes")
Release(o.getLong("versionCode"), o.getString("versionName"), o.optString("version", o.getString("versionName")),
apk.getString("url"), apk.getLong("size"), apk.getString("sha256").lowercase(), o.optInt("minSdk", 31),
o.optString("published"), List(minOf(notes?.length() ?: 0, 8)) { notes!!.getString(it).take(200) })
}.getOrNull()?.takeIf {
it.code > 0 && it.size in 1..400_000_000 && it.sha256.matches(Regex("[0-9a-f]{64}")) && allowed(URL(it.url))
}
}
}
/** What Hex Preview fetches: latest.json from its channel and the APK it names, only from GitHub over HTTPS.
* The requests carry nothing about the person: no identifiers, no settings, a fixed user agent. */
internal object Channel {
class Failure(val problem: Updates.Problem) : Exception()
fun latest(context: Context): Release {
val text = open(URL(context.getString(R.string.update_channel))).use { http ->
http.inputStream.use { it.readLimited(64 * 1024) }
}
return Release.parse(text) ?: throw Failure(Updates.Problem.Server)
}
/** Downloads [release] into the cache, checking its size and SHA-256 as it arrives; anything else is deleted. */
fun download(context: Context, release: Release, progress: (Int) -> Unit): File {
val dir = File(context.cacheDir, "updates").apply { mkdirs() }
val done = File(dir, "${release.code}.apk")
dir.listFiles()?.forEach { if (it != done) it.delete() }
if (done.length() == release.size && sha256(done) == release.sha256) return done
val part = File(dir, "${release.code}.part")
try {
if (dir.usableSpace < release.size + 20_000_000) throw Failure(Updates.Problem.Space)
val digest = MessageDigest.getInstance("SHA-256")
var total = 0L
open(URL(release.url)).use { http ->
http.inputStream.use { input ->
part.outputStream().use { out ->
val buffer = ByteArray(128 * 1024)
while (true) {
val n = input.read(buffer)
if (n < 0) break
total += n
if (total > release.size) throw Failure(Updates.Problem.Mismatch)
digest.update(buffer, 0, n); out.write(buffer, 0, n)
progress((total * 100 / release.size).toInt())
}
out.fd.sync()
}
}
}
if (total != release.size || hex(digest.digest()) != release.sha256) throw Failure(Updates.Problem.Mismatch)
if (!part.renameTo(done)) throw Failure(Updates.Problem.Space)
return done
} catch (e: Failure) { part.delete(); throw e
} catch (e: IOException) { part.delete(); throw Failure(Updates.Problem.Connection) }
}
/** The APK must be Hex Preview itself, the build latest.json named, newer than what runs, and signed with
* exactly the running app's key. */
fun verify(context: Context, file: File, release: Release) {
val pm = context.packageManager
val flags = PackageManager.GET_SIGNING_CERTIFICATES
val archive = pm.getPackageArchiveInfo(file.path, flags) ?: throw Failure(Updates.Problem.Mismatch)
val running = pm.getPackageInfo(context.packageName, flags)
if (archive.packageName != context.packageName || archive.longVersionCode != release.code ||
archive.longVersionCode <= running.longVersionCode) throw Failure(Updates.Problem.Mismatch)
val theirs = signers(archive.signingInfo)
if (theirs.isEmpty() || theirs != signers(running.signingInfo)) throw Failure(Updates.Problem.Signature)
}
private fun signers(info: android.content.pm.SigningInfo?): Set<String> {
info ?: return emptySet()
val certs = if (info.hasMultipleSigners()) info.apkContentsSigners.toList() else info.signingCertificateHistory.orEmpty().takeLast(1)
return certs.map { hex(MessageDigest.getInstance("SHA-256").digest(it.toByteArray())) }.toSet()
}
private fun sha256(file: File): String = file.inputStream().use { input ->
val digest = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(128 * 1024)
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
hex(digest.digest())
}
private fun hex(bytes: ByteArray) = bytes.joinToString("") { "%02x".format(it) }
private fun open(start: URL): HttpsURLConnection {
var target = start
repeat(6) {
if (!allowed(target)) throw Failure(Updates.Problem.Server)
val http = target.openConnection() as HttpsURLConnection
try {
http.instanceFollowRedirects = false
http.connectTimeout = 15_000; http.readTimeout = 45_000
http.useCaches = false
// Android's default user agent names the phone and its build.
http.setRequestProperty("User-Agent", "HexPreviewUpdater/1")
http.setRequestProperty("Accept-Encoding", "identity")
when (http.responseCode) {
200 -> return http
301, 302, 303, 307, 308 -> target = URL(target, http.getHeaderField("Location") ?: throw Failure(Updates.Problem.Server))
else -> throw Failure(Updates.Problem.Server)
}
} catch (e: IOException) { http.disconnect(); throw Failure(Updates.Problem.Connection)
} catch (e: Failure) { http.disconnect(); throw e }
http.disconnect()
}
throw Failure(Updates.Problem.Server)
}
private fun InputStream.readLimited(limit: Int): String {
val out = ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val n = read(buffer); if (n < 0) break
out.write(buffer, 0, n); if (out.size() > limit) throw Failure(Updates.Problem.Server)
}
return out.toString("UTF-8")
}
}
private val hosts = setOf("github.com", "raw.githubusercontent.com", "objects.githubusercontent.com", "release-assets.githubusercontent.com")
private fun allowed(url: URL) = url.protocol == "https" && url.userInfo == null && url.port in listOf(-1, 443) && url.host.lowercase() in hosts
private inline fun <T : HttpURLConnection, R> T.use(block: (T) -> R): R = try { block(this) } finally { disconnect() }
@@ -0,0 +1,317 @@
package ly.anoma.hex.updates
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.text.format.Formatter
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import ly.anoma.hex.Action
import ly.anoma.hex.Card
import ly.anoma.hex.Entry
import ly.anoma.hex.Label
import ly.anoma.hex.MainActivity
import ly.anoma.hex.R
import ly.anoma.hex.Rule
import ly.anoma.hex.Toggle
import ly.anoma.hex.keyboard.StripNotice
import java.io.File
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.concurrent.Executors
/** Hex Preview's own updates, from its channel on GitHub (Play builds have none: src/play). It looks when the
* app opens and at most once a day from the keyboard; nothing downloads or installs until the person taps
* Update, and then only an APK whose size, SHA-256 and signing key are right goes to Android's installer. */
internal object Updates {
enum class Problem { Connection, Server, Space, Mismatch, Signature, Install }
sealed interface State {
data object Idle : State
data object Checking : State
data object Current : State
data class CheckFailed(val problem: Problem) : State
data class Available(val release: Release) : State
/** On mobile data the size comes first. */
data class Confirm(val release: Release) : State
data class Downloading(val release: Release, val percent: Int) : State
data class Verifying(val release: Release) : State
/** Android's one-time "Install unknown apps" switch for Hex Preview is off. */
data class NeedsPermission(val release: Release, val file: File) : State
data class Installing(val release: Release) : State
data class Failed(val release: Release, val problem: Problem) : State
}
private val flow = MutableStateFlow<State>(State.Idle)
val state = flow.asStateFlow()
private val worker = Executors.newSingleThreadExecutor { Thread(it, "Hex Preview updates") }
private val main = Handler(Looper.getMainLooper())
private const val HOUR = 3_600_000L
private const val DAY = 24 * HOUR
private var loaded = false
private var checking = false
private var checkedThisRun = false
/** The keyboard's field now: where a check's answer goes, unless it is a password field. */
private var keyboard: ((StripNotice?) -> Unit)? = null
private fun prefs(c: Context) = c.getSharedPreferences("updates", Context.MODE_PRIVATE)
private fun automatic(c: Context) = prefs(c).getBoolean("automatic", true)
private fun installed(c: Context) = c.packageManager.getPackageInfo(c.packageName, 0)
private fun release(s: State) = when (s) {
is State.Available -> s.release; is State.Confirm -> s.release; is State.Downloading -> s.release
is State.Verifying -> s.release; is State.NeedsPermission -> s.release; is State.Installing -> s.release
is State.Failed -> s.release; else -> null
}
private fun busy(s: State) = s is State.Confirm || s is State.Downloading || s is State.Verifying ||
s is State.NeedsPermission || s is State.Installing
@Synchronized private fun load(c: Context) {
if (loaded) return
loaded = true
val saved = prefs(c).getString("release", null)?.let(Release::parse)
if (saved != null && saved.code > installed(c).longVersionCode) flow.value = State.Available(saved)
else { prefs(c).edit().remove("release").apply(); worker.execute { File(c.cacheDir, "updates").deleteRecursively() } }
}
fun appOpened(context: Context) {
val c = context.applicationContext
load(c)
// Back from Android's "Install unknown apps" page: carry on with the update the person asked for.
(flow.value as? State.NeedsPermission)?.let { if (c.packageManager.canRequestPackageInstalls()) install(c, it.release, it.file) }
if (automatic(c) && (!checkedThisRun || System.currentTimeMillis() - prefs(c).getLong("checked", 0) > HOUR)) check(c, false)
}
fun keyboardShown(context: Context, secure: Boolean, show: (StripNotice?) -> Unit) {
if (secure) { keyboard = null; show(null); return }
val c = context.applicationContext
load(c)
keyboard = show
show(notice(c))
if (automatic(c) && System.currentTimeMillis() - prefs(c).getLong("checked", 0) >= DAY) check(c, false)
}
private fun notice(c: Context): StripNotice? {
val r = (flow.value as? State.Available)?.release ?: return null
if (prefs(c).getLong("stripDismissed", 0) >= r.code) return null
val gone = { prefs(c).edit().putLong("stripDismissed", r.code).apply() }
return StripNotice(c.getString(R.string.updates_strip), c.getString(R.string.updates_strip_dismiss), tap = {
gone()
c.startActivity(Intent(c, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP))
}, dismiss = gone)
}
fun checkNow(context: Context) = check(context.applicationContext, true)
private fun check(c: Context, manual: Boolean) {
synchronized(this) {
if (checking || busy(flow.value)) return
checking = true
}
if (manual) flow.value = State.Checking
worker.execute {
val outcome = try { Result.success(Channel.latest(c)) } catch (e: Channel.Failure) { Result.failure(e) }
prefs(c).edit().putLong("checked", System.currentTimeMillis()).apply()
main.post {
checking = false; checkedThisRun = true
val r = outcome.getOrNull()
val now = flow.value
when {
busy(now) -> Unit
r != null && r.code > installed(c).longVersionCode && r.minSdk <= Build.VERSION.SDK_INT -> {
prefs(c).edit().putString("release", r.json()).apply()
if (now !is State.Failed || now.release.code != r.code) flow.value = State.Available(r)
}
r != null -> { prefs(c).edit().remove("release").apply(); flow.value = State.Current }
manual || now == State.Checking -> flow.value = State.CheckFailed((outcome.exceptionOrNull() as Channel.Failure).problem)
}
keyboard?.invoke(notice(c))
}
}
}
/** The person tapped Update (or Download after the mobile-data note, or Try again). */
fun update(context: Context, confirmed: Boolean = false) {
val c = context.applicationContext
val r = release(flow.value) ?: return
if (flow.value is State.Downloading || flow.value is State.Verifying || flow.value is State.Installing) return
if (!confirmed && c.getSystemService(ConnectivityManager::class.java).isActiveNetworkMetered) { flow.value = State.Confirm(r); return }
flow.value = State.Downloading(r, 0)
worker.execute {
try {
var shown = -1
val file = Channel.download(c, r) { if (it != shown) { shown = it; flow.value = State.Downloading(r, it) } }
flow.value = State.Verifying(r)
try { Channel.verify(c, file, r) } catch (e: Channel.Failure) { file.delete(); throw e }
main.post { install(c, r, file) }
} catch (e: Channel.Failure) { flow.value = State.Failed(r, e.problem) }
}
}
fun notNow() { (flow.value as? State.Confirm)?.let { flow.value = State.Available(it.release) } }
private fun install(c: Context, r: Release, file: File) {
if (!c.packageManager.canRequestPackageInstalls()) { flow.value = State.NeedsPermission(r, file); return }
flow.value = State.Installing(r)
worker.execute {
try {
val installer = c.packageManager.packageInstaller
val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
setAppPackageName(c.packageName); setSize(file.length())
setInstallReason(PackageManager.INSTALL_REASON_USER)
// Android 12+: a later update by the app that installed the last one may go without its dialog.
setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)
}
val id = installer.createSession(params)
installer.openSession(id).use { session ->
file.inputStream().use { input ->
session.openWrite("hex-preview.apk", 0, file.length()).use { out -> input.copyTo(out); session.fsync(out) }
}
val result = Intent(c, UpdateReceiver::class.java).putExtra("code", r.code)
val flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
session.commit(PendingIntent.getBroadcast(c, id, result, flags).intentSender)
}
record(c, "committed")
} catch (e: Exception) { record(c, "session failed"); flow.value = State.Failed(r, Problem.Install) }
}
}
/** Android's answer for the session: its confirmation to show, or how it ended. */
fun installStatus(c: Context, intent: Intent) {
val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)
record(c, "status $status " + intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE).orEmpty())
when (status) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
@Suppress("DEPRECATION")
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
else intent.getParcelableExtra(Intent.EXTRA_INTENT)
confirm?.let { c.startActivity(it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
PackageInstaller.STATUS_SUCCESS -> {
prefs(c).edit().remove("release").apply(); flow.value = State.Current
}
else -> release(flow.value)?.let { flow.value = State.Failed(it, Problem.Install) }
}
}
/** The last few installer outcomes, kept on the phone only, for anyone debugging an update. */
private fun record(c: Context, line: String) {
val p = prefs(c)
val log = (p.getString("log", "").orEmpty().lines().filter { it.isNotBlank() } + "${System.currentTimeMillis()} $line").takeLast(10)
p.edit().putString("log", log.joinToString("\n")).apply()
}
@Composable fun HomeCard() {
val c = LocalContext.current
val s = state.collectAsState().value
val r = release(s) ?: return
Card {
Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Label(stringResource(R.string.updates_available, r.version, r.code), weight = FontWeight.SemiBold, lines = 2)
Label(listOfNotNull(Formatter.formatShortFileSize(c, r.size), date(r.date)).joinToString(" · "), muted = true, size = 14)
r.notes.forEach { Label(it, size = 14, lines = 4) }
Spacer(Modifier.height(4.dp))
when (s) {
is State.Available -> {
Primary(stringResource(R.string.updates_update)) { update(c) }
// Android closes an open keyboard while it replaces the app; Hex Preview stays the chosen one.
Label(stringResource(R.string.updates_keyboard_note), muted = true, size = 13, lines = 3)
}
is State.Confirm -> {
Label(stringResource(R.string.updates_metered, Formatter.formatShortFileSize(c, r.size)), size = 14, lines = 3)
Row(verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.weight(1f)) { Primary(stringResource(R.string.updates_download)) { update(c, confirmed = true) } }
Action(stringResource(R.string.updates_not_now), ::notNow)
}
}
is State.Downloading -> {
Label(stringResource(R.string.updates_downloading, s.percent), muted = true, size = 14)
LinearProgressIndicator(progress = { s.percent / 100f }, modifier = Modifier.fillMaxWidth(),
color = colorResource(R.color.ink), trackColor = colorResource(R.color.rule))
}
is State.Verifying -> Label(stringResource(R.string.updates_verifying), muted = true, size = 14)
is State.Installing -> {
Label(stringResource(R.string.updates_installing), muted = true, size = 14)
Label(stringResource(R.string.updates_keyboard_note), muted = true, size = 13, lines = 3)
}
is State.NeedsPermission -> {
Label(stringResource(R.string.updates_permission), size = 14, lines = 6)
Primary(stringResource(R.string.updates_open_settings)) {
c.startActivity(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + c.packageName)))
}
}
is State.Failed -> {
Label(stringResource(problem(s.problem)), size = 14, lines = 3)
Primary(stringResource(R.string.updates_retry)) { update(c, confirmed = true) }
}
else -> Unit
}
}
}
}
@Composable fun SettingsCard() {
val c = LocalContext.current
val s = state.collectAsState().value
var auto by remember { mutableStateOf(automatic(c)) }
val info = remember { installed(c) }
Card {
Toggle(stringResource(R.string.updates_auto), stringResource(R.string.updates_auto_detail), auto) {
auto = it; prefs(c).edit().putBoolean("automatic", it).apply()
}
Rule()
Entry(stringResource(R.string.updates_check_now), stringResource(R.string.updates_installed, info.versionName.orEmpty().substringBefore("-preview."), info.longVersionCode),
when (s) {
State.Checking -> stringResource(R.string.updates_checking)
State.Current -> stringResource(R.string.updates_current)
is State.CheckFailed -> stringResource(R.string.updates_check_failed)
State.Idle -> ""
else -> stringResource(R.string.updates_ready)
}, { checkNow(c) })
}
}
private fun problem(p: Problem) = when (p) {
Problem.Connection -> R.string.updates_failed_connection
Problem.Server -> R.string.updates_failed_server
Problem.Space -> R.string.updates_failed_space
Problem.Mismatch -> R.string.updates_failed_mismatch
Problem.Signature -> R.string.updates_failed_signature
Problem.Install -> R.string.updates_failed_install
}
private fun date(iso: String) = runCatching {
LocalDate.parse(iso.take(10)).format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))
}.getOrNull()
@Composable private fun Primary(text: String, onClick: () -> Unit) {
Box(Modifier.fillMaxWidth().height(48.dp).clip(RoundedCornerShape(12.dp)).background(colorResource(R.color.ink))
.clickable(role = Role.Button, onClick = onClick), contentAlignment = Alignment.Center) {
Label(text, inverted = true, weight = FontWeight.SemiBold)
}
}
}
/** Where Android reports an update session's progress: the confirmation to show, or how it ended. */
class UpdateReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) = Updates.installStatus(context.applicationContext, intent)
}
@@ -0,0 +1,31 @@
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
<string name="settings_privacy_detail">Hex 在这台手机上将语音转换为文字,绝不上传你的声音或输入的内容,也不保存任何按键记录或转录内容。为了查找更新,Hex Preview 会在你打开它时,以及每天最多一次在键盘上,向 GitHub 询问最新版本。这个请求不包含任何关于你或你输入内容的信息,不过和访问任何网站一样,GitHub 会看到你的网络地址。可以用“自动检查更新”关闭。</string>
<string name="updates_available">Hex Preview %1$s(版本号 %2$d)已可更新</string>
<string name="updates_update">更新</string>
<string name="updates_keyboard_note">更新时键盘会暂时关闭,点按文本框即可重新打开。</string>
<string name="updates_metered">你正在使用移动数据。这次下载需要 %1$s。</string>
<string name="updates_download">下载</string>
<string name="updates_not_now">以后再说</string>
<string name="updates_downloading">正在下载… %1$d%%</string>
<string name="updates_verifying">正在检查下载内容…</string>
<string name="updates_installing">正在安装…</string>
<string name="updates_permission">Android 会询问一次是否允许 Hex Preview 安装自己的更新。请打开“允许来自此来源的应用”,然后回到这里。</string>
<string name="updates_open_settings">打开设置</string>
<string name="updates_failed_connection">下载已中断。请检查网络连接后重试。</string>
<string name="updates_failed_server">GitHub 的回应不正常。请稍后重试。</string>
<string name="updates_failed_space">可用空间不足,无法下载。</string>
<string name="updates_failed_mismatch">下载的内容与发布的不一致,所以没有安装任何东西。</string>
<string name="updates_failed_signature">下载的内容不是用 Hex Preview 的密钥签名的,所以没有安装任何东西。</string>
<string name="updates_failed_install">Android 没有安装这次更新。</string>
<string name="updates_retry">重试</string>
<string name="updates_auto">自动检查更新</string>
<string name="updates_auto_detail">打开 Hex Preview 时,以及每天一次从键盘检查</string>
<string name="updates_check_now">立即检查</string>
<string name="updates_installed">版本 %1$s,版本号 %2$d</string>
<string name="updates_checking">正在检查…</string>
<string name="updates_current">已是最新版本</string>
<string name="updates_check_failed">无法检查</string>
<string name="updates_ready">有可用更新</string>
<string name="updates_strip">Hex Preview 有可用更新</string>
<string name="updates_strip_dismiss">关闭</string>
</resources>
@@ -0,0 +1,34 @@
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
<!-- Hex Preview only (the APK outside Google Play): its name, its privacy note and its updater. Every
translatable string here has a Simplified Chinese one in values-zh-rCN. -->
<string name="app_name" translatable="false">Hex Preview</string>
<string name="settings_privacy_detail">Hex turns speech into text on this phone and never uploads your voice or what you type. It keeps no keystrokes or transcripts. To find updates, Hex Preview asks GitHub for its latest version when you open it and at most once a day from the keyboard. That request carries nothing about you or what you type, though GitHub sees your internet address, as with any website. Turn it off with Check for updates automatically.</string>
<string name="updates_available">Hex Preview %1$s (build %2$d) is available</string>
<string name="updates_update">Update</string>
<string name="updates_keyboard_note">Updating closes the keyboard for a moment. Tap a text field to bring it back.</string>
<string name="updates_metered">You’re on mobile data. This download uses %1$s.</string>
<string name="updates_download">Download</string>
<string name="updates_not_now">Not now</string>
<string name="updates_downloading">Downloading… %1$d%%</string>
<string name="updates_verifying">Checking the download…</string>
<string name="updates_installing">Installing…</string>
<string name="updates_permission">Android asks once whether Hex Preview may install its own updates. Turn on Allow from this source, then come back here.</string>
<string name="updates_open_settings">Open settings</string>
<string name="updates_failed_connection">The download stopped. Check your connection and try again.</string>
<string name="updates_failed_server">GitHub didn’t answer as expected. Try again later.</string>
<string name="updates_failed_space">There isn’t enough free space for the download.</string>
<string name="updates_failed_mismatch">The download didn’t match what was published, so nothing was installed.</string>
<string name="updates_failed_signature">The download wasn’t signed with Hex Preview’s key, so nothing was installed.</string>
<string name="updates_failed_install">Android didn’t install the update.</string>
<string name="updates_retry">Try again</string>
<string name="updates_auto">Check for updates automatically</string>
<string name="updates_auto_detail">When you open Hex Preview, and once a day from the keyboard</string>
<string name="updates_check_now">Check now</string>
<string name="updates_installed">Version %1$s, build %2$d</string>
<string name="updates_checking">Checking…</string>
<string name="updates_current">Up to date</string>
<string name="updates_check_failed">Couldn’t check</string>
<string name="updates_ready">Update available</string>
<string name="updates_strip">Hex Preview update available</string>
<string name="updates_strip_dismiss">Dismiss</string>
</resources>
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env bash
# Publishes one Hex Preview build: the preview APK (outside Google Play, ly.anoma.hex.preview) built from one
# commit of dev on a build Mac, as its own GitHub pre-release with its own tag at that commit, then points the
# channel (a branch holding only latest.json and README.md) at it. Hex Preview reads that latest.json to update.
#
# android/scripts/preview-release.sh --notes notes.txt [--commit <sha>] the real channel
# android/scripts/preview-release.sh --repo you/fork --channel android-preview-test --commit <sha> --notes notes.txt
#
# --commit what to build (default: origin/dev's head). The real channel takes only commits on dev.
# --repo where the release and the channel live (default anomalyco/hex). A test channel is a fork.
# --channel the channel branch (default android-preview). The APK is built to read this branch's latest.json.
# --notes what changed, one short line each: the app shows them above Update, and the release body lists them.
# --builder the ferry machine with the Android SDK, NDK and JDK 21 (default anomastudio; android/README.md).
#
# Build numbers are the count of commits up to the built commit (git rev-list --count), so they only grow along
# dev; a build whose tag exists, or that isn't newer than the channel's, is refused. Tags are never moved or reused.
# Every build is signed with the Hex Preview key: Android refuses an update signed with any other. The key and its
# keystore.properties stay outside the repository, in ~/.config/hex-android-preview on this Mac and the builder.
set -euo pipefail
# ferry's connection to a busy builder can drop; every step it retries is safe to repeat.
retry() { for _ in 1 2 3 4; do "$@" && return 0; sleep 5; done; "$@"; }
repo=anomalyco/hex channel=android-preview commit="" notes="" builder=anomastudio
while [ $# -gt 0 ]; do
case "$1" in
--repo) repo=$2; shift 2 ;;
--channel) channel=$2; shift 2 ;;
--commit) commit=$2; shift 2 ;;
--notes) notes=$2; shift 2 ;;
--builder) builder=$2; shift 2 ;;
*) echo "unknown option: $1" >&2; exit 2 ;;
esac
done
# The Hex Preview certificate's SHA-256 (the key itself never leaves ~/.config/hex-android-preview).
fingerprint=133568F6F0614FE57BC88DAECA32AFA72C6AB740202629F752FAA033BE35D98E
root=$(git rev-parse --show-toplevel)
key=~/.config/hex-android-preview
real=$([ "$repo" = anomalyco/hex ] && [ "$channel" = android-preview ] && echo yes || echo no)
[ -n "$notes" ] && [ -s "$notes" ] || { echo "--notes <file> with one line per change is required" >&2; exit 2; }
[ -f "$key/keystore.properties" ] && [ -f "$key/preview.jks" ] || { echo "missing $key (the Hex Preview key)" >&2; exit 1; }
git -C "$root" fetch -q origin dev
commit=$(git -C "$root" rev-parse --verify "${commit:-origin/dev}^{commit}")
if [ "$real" = yes ] && ! git -C "$root" merge-base --is-ancestor "$commit" origin/dev; then
echo "$commit is not on dev; the real channel takes only dev's commits" >&2; exit 1
fi
build=$(git -C "$root" rev-list --count "$commit")
tag=android-preview-$build
version=$(git -C "$root" show "$commit:android/app/build.gradle.kts" | sed -n 's/^ *versionName = "\(.*\)"$/\1/p' | head -1)
minsdk=$(git -C "$root" show "$commit:android/app/build.gradle.kts" | sed -n 's/^ *minSdk = \([0-9]*\)$/\1/p' | head -1)
name=$version-preview.$build
raw=https://raw.githubusercontent.com/$repo/$channel/latest.json
echo "Hex Preview $name from ${commit:0:12} -> $repo $tag, channel $channel"
if gh api "repos/$repo/git/ref/tags/$tag" >/dev/null 2>&1; then echo "tag $tag already exists; tags are never reused" >&2; exit 1; fi
current=$(curl -fsSL "https://api.github.com/repos/$repo/contents/latest.json?ref=$channel" -H 'Accept: application/vnd.github.raw' 2>/dev/null \
| python3 -c 'import json,sys; print(json.load(sys.stdin)["versionCode"])' 2>/dev/null || echo 0)
[ "$build" -gt "$current" ] || { echo "build $build is not newer than the channel's $current" >&2; exit 1; }
# Build on the builder from exactly that commit's android/ folder.
work=$(mktemp -d); trap 'rm -rf "$work"' EXIT
git -C "$root" archive "$commit" android | tar -x -C "$work"
remote=dev/hex-preview-build/$build
retry ferry sh "$builder" "rm -rf ~/$remote && mkdir -p ~/$remote ~/.config/hex-android-preview && chmod 700 ~/.config/hex-android-preview"
ferry sh "$builder" '[ -f ~/.config/hex-android-preview/preview.jks ] && [ -f ~/.config/hex-android-preview/keystore.properties ]' || {
retry ferry cp "$key/preview.jks" "$builder:.config/hex-android-preview/preview.jks" >/dev/null
retry ferry cp "$key/keystore.properties" "$builder:.config/hex-android-preview/keystore.properties" >/dev/null
retry ferry sh "$builder" 'chmod 600 ~/.config/hex-android-preview/*'
}
retry ferry cp "$work/android" "$builder:$remote/" >/dev/null
jdk='export JAVA_HOME=/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home ANDROID_HOME=$HOME/Library/Android/sdk; export PATH=$JAVA_HOME/bin:$PATH;'
# Detached, so a dropped connection to the builder doesn't stop the build; the exit code lands in a file.
retry ferry sh "$builder" --detach "[ -f ~/$remote/build.log ] && exit 0; $jdk cd ~/$remote/android && ./gradlew --no-daemon -q :app:assemblePreview -PhexPreviewBuild=$build \
-PhexPreviewChannel=$raw > ~/$remote/build.log 2>&1; echo \$? > ~/$remote/build.exit" >/dev/null
for _ in $(seq 1 240); do ferry sh "$builder" "test -f ~/$remote/build.exit" 2>/dev/null && break; sleep 15; done
if [ "$(retry ferry sh "$builder" "cat ~/$remote/build.exit")" != 0 ]; then
ferry sh "$builder" "tail -40 ~/$remote/build.log" >&2; echo "the build failed on $builder" >&2; exit 1
fi
apk=HexPreview-$name.apk
out=$root/android/build/preview/$build; mkdir -p "$out"
retry ferry cp "$builder:$remote/android/app/build/outputs/apk/preview/app-preview.apk" "$out/$apk" >/dev/null
# Check what was built before anything is published.
tools=$(retry ferry sh "$builder" 'ls -d ~/Library/Android/sdk/build-tools/36.0.0')
signer=$(retry ferry sh "$builder" "$jdk $tools/apksigner verify --print-certs ~/$remote/android/app/build/outputs/apk/preview/app-preview.apk" | sed -n 's/.*SHA-256 digest: //p' | tr a-f A-F)
badging=$(retry ferry sh "$builder" "$tools/aapt2 dump badging ~/$remote/android/app/build/outputs/apk/preview/app-preview.apk" | head -1)
[ "$signer" = "$fingerprint" ] || { echo "APK is signed with $signer, not the Hex Preview key" >&2; exit 1; }
case "$badging" in *"name='ly.anoma.hex.preview' versionCode='$build' versionName='$name'"*) ;; *) echo "unexpected APK: $badging" >&2; exit 1 ;; esac
sha=$(shasum -a 256 "$out/$apk" | cut -d' ' -f1); size=$(stat -f %z "$out/$apk")
echo "$sha $apk" > "$out/$apk.sha256"
url=https://github.com/$repo/releases/download/$tag/$apk
python3 - "$notes" "$out" <<PY
import json, sys, datetime
notes = [l.strip() for l in open(sys.argv[1]) if l.strip()]
latest = {"versionCode": $build, "versionName": "$name", "version": "$version", "minSdk": $minsdk,
"published": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d"), "commit": "$commit",
"apk": {"url": "$url", "size": $size, "sha256": "$sha"}, "notes": notes}
open(sys.argv[2] + "/latest.json", "w").write(json.dumps(latest, indent=2, ensure_ascii=False) + "\n")
tick = chr(96) # a literal backtick: this heredoc is expanded by bash
body = "\n".join("- " + n for n in notes) + "\n\nHex Preview for Android, built from ${commit:0:12}. Install it outside Google Play; it updates itself from [the channel](https://github.com/$repo/tree/$channel).\n\nAPK SHA-256: " + tick + "$sha" + tick + " \nSigning certificate SHA-256: " + tick + "$fingerprint" + tick + "\n"
open(sys.argv[2] + "/release.md", "w").write(body)
PY
gh release create "$tag" --repo "$repo" --target "$commit" --prerelease --latest=false \
--title "Hex Preview $version (build $build)" --notes-file "$out/release.md" "$out/$apk" "$out/$apk.sha256"
# The asset must serve exactly what was checked before the channel points at it.
curl -fsSL "$url" | shasum -a 256 | grep -q "^$sha " || { echo "the published APK doesn't match; channel left as it was" >&2; exit 1; }
# Point the channel at it: one commit on the channel branch, fast-forward only.
ch=$(mktemp -d)
git -C "$ch" init -q
git -C "$ch" remote add origin "https://github.com/$repo.git"
if git -C "$ch" fetch -q --depth 1 origin "$channel" 2>/dev/null; then git -C "$ch" checkout -q -b "$channel" FETCH_HEAD
else git -C "$ch" checkout -q --orphan "$channel"; fi
cp "$out/latest.json" "$ch/latest.json"
fp=$(echo "$fingerprint" | sed 's/../&:/g; s/:$//')
cat > "$ch/README.md" <<MD
# Hex Preview for Android
**[Download Hex Preview $version (build $build)]($url)** · $(( size / 1000000 )) MB · Android 12 or later · $(date -u +%Y-%m-%d)
Hex Preview is the [Hex keyboard](https://anoma.ly/hex) for Android, before it reaches Google Play. It installs as its own app beside Hex from Google Play, and it updates itself: it checks this page's \`latest.json\` when you open it and at most once a day from the keyboard, shows what changed, and installs a new build only when you tap Update.
## Install
1. Open the download link above on your phone and download the APK.
2. Open it. Android asks whether your browser or Files app may install apps: tap **Settings**, turn on **Allow from this source**, then go back and tap **Install**.
3. Open Hex Preview and follow its setup: the microphone, Hex Preview as your keyboard, and the 190 MB speech model.
The first update asks the same once for Hex Preview itself.
## Check a download
- APK SHA-256: \`$sha\`
- Signing certificate SHA-256: \`$fp\`
Every Hex Preview build is signed with this certificate; Android refuses an update signed with any other. Check with \`apksigner verify --print-certs\` or \`keytool -printcert -jarfile\`.
## What changed
$(sed '/^[[:space:]]*$/d; s/^/- /' "$notes")
Earlier builds are on the [releases page](https://github.com/$repo/releases?q=android-preview) (tags \`android-preview-<build>\`). Typing and dictation stay on the phone; the update check asks GitHub for this file and carries nothing about you.
MD
git -C "$ch" add latest.json README.md
git -C "$ch" -c user.name="$(git -C "$root" config user.name)" -c user.email="$(git -C "$root" config user.email)" \
commit -q -m "Hex Preview $name (${commit:0:12})"
git -C "$ch" push -q origin "HEAD:refs/heads/$channel"
rm -rf "$ch"
echo "published $url"
echo "channel https://github.com/$repo/tree/$channel"
echo "latest $raw (GitHub's raw cache keeps an old copy up to 5 minutes)"