Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

0.1.2: robust updates on both devices, reconnecting after updates and restarts

Bee0f90ad0c56d2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0151e34..9f634ce 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,46 @@ All notable changes to Nectarlink. Versions follow
[semantic versioning](https://semver.org); before 1.0, a minor version may
change things that need a step from you, and its notes say so.
+## 0.1.2 (2026-10-15)
+
+A smoother update on both devices, and the phone reconnects on its own after
+an update or a restart.
+
+### Downloads
+
+| Download | For | Needs |
+|---|---|---|
+| [Nectarlink-0.1.2-x64-setup.exe](https://github.com/thtbee/nectarlink/releases/download/v0.1.2/Nectarlink-0.1.2-x64-setup.exe) | Windows | Windows 11, 64-bit |
+| [Nectarlink-0.1.2-android.apk](https://github.com/thtbee/nectarlink/releases/download/v0.1.2/Nectarlink-0.1.2-android.apk) | Android | Android 8.0 or newer |
+
+Both are listed with their SHA-256 hashes in [SHA256SUMS.txt](https://github.com/thtbee/nectarlink/releases/download/v0.1.2/SHA256SUMS.txt).
+Installed copies update themselves.
+
+### Fixed
+
+- **The phone reconnects after an update or a restart.** Android closes an
+ app while it updates, and nothing brought Nectarlink's connection back until
+ the app was opened again, so the PC showed the phone as gone. The connection
+ now comes back on its own, after an update and after the phone restarts. A
+ notification says the update is done; tapping it opens the app.
+- **Check for updates in the phone's Settings shows what it found**: that
+ Nectarlink is up to date, or the update with its **Update** button and
+ progress, or why it couldn't check. Before, the button greyed out and nothing
+ appeared.
+- **Allowing installs continues the update.** When Android first asks to let
+ Nectarlink install updates, coming back from that screen now carries on with
+ the update instead of staying on **Allow**.
+- **Phone downloads resume.** A dropped or changed connection no longer fails
+ the update: the download waits for the network and continues where it
+ stopped, also after the app restarts. Progress shows the size downloaded.
+- **Updates keep going in the background.** Leaving the screen no longer stops
+ a phone update that's downloading. Saying no to Android's install prompt
+ leaves the update ready to install instead of reporting an error.
+- **The PC app comes to the front after updating.** It reopened behind other
+ windows; now it comes forward and a notification says it's updated. The same
+ fix brings the window forward when Nectarlink is opened while already
+ running.
+
## 0.1.1 (2026-10-15)
Fewer steps when sharing from the phone, clearer setup on phones that hold
diff --git a/Cargo.lock b/Cargo.lock
index dc70ea2..3ea8597 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2318,7 +2318,7 @@ dependencies = [
[[package]]
name = "nectarlink-adb"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"thiserror 2.0.21",
"tokio",
@@ -2328,7 +2328,7 @@ dependencies = [
[[package]]
name = "nectarlink-cli"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"anyhow",
"clap",
@@ -2347,7 +2347,7 @@ dependencies = [
[[package]]
name = "nectarlink-core"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"blake3",
"bytes",
@@ -2380,7 +2380,7 @@ dependencies = [
[[package]]
name = "nectarlink-desktop"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"anyhow",
"blake3",
@@ -2409,7 +2409,7 @@ dependencies = [
[[package]]
name = "nectarlink-ffi"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"nectarlink-core",
"paranoid-android",
@@ -2422,7 +2422,7 @@ dependencies = [
[[package]]
name = "nectarlink-protocol"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"ciborium",
"data-encoding",
@@ -2437,7 +2437,7 @@ dependencies = [
[[package]]
name = "nectarlink-vcam"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"ab_glyph",
"embed-resource",
@@ -5064,7 +5064,7 @@ dependencies = [
[[package]]
name = "xtask"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"anyhow",
"serde_json",
diff --git a/Cargo.toml b/Cargo.toml
index d169a53..9dcda5a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
-version = "0.1.1"
+version = "0.1.2"
edition = "2024"
rust-version = "1.97"
authors = ["The Nectarlink contributors"]
@@ -25,10 +25,10 @@ repository = "https://github.com/thtbee/nectarlink"
name = "Pollen"
[workspace.dependencies]
-nectarlink-adb = { path = "core/nectarlink-adb", version = "0.1.1" }
-nectarlink-protocol = { path = "core/nectarlink-protocol", version = "0.1.1" }
-nectarlink-core = { path = "core/nectarlink-core", version = "0.1.1" }
-nectarlink-vcam = { path = "desktop/vcam", version = "0.1.1" }
+nectarlink-adb = { path = "core/nectarlink-adb", version = "0.1.2" }
+nectarlink-protocol = { path = "core/nectarlink-protocol", version = "0.1.2" }
+nectarlink-core = { path = "core/nectarlink-core", version = "0.1.2" }
+nectarlink-vcam = { path = "desktop/vcam", version = "0.1.2" }
anyhow = "1"
ciborium = "0.2"
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 80dd01e..4b65198 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -14,6 +14,8 @@
<!-- Staying reachable in the background. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
+ <!-- Reconnecting after the phone restarts. -->
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Sharing the screen with a PC (each time, after Android's prompt). -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<!-- Keeping the phone awake while mirroring its screen to a PC. -->
@@ -191,6 +193,16 @@
android:name=".update.AppUpdater$InstallResult"
android:exported="false" />
+ <!-- Reconnects after the phone restarts or Nectarlink updates. -->
+ <receiver
+ android:name=".service.StartupReceiver"
+ android:exported="false">
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
+ </intent-filter>
+ </receiver>
+
<!-- The PC media notification's buttons (Android 12 and earlier). -->
<receiver
android:name=".media.PcMedia$CommandReceiver"
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/StartupReceiver.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/StartupReceiver.kt
new file mode 100644
index 0000000..81a99b5
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/StartupReceiver.kt
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.service
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import app.nectarlink.android.NectarlinkApplication
+import app.nectarlink.android.core.CoreStatus
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeoutOrNull
+
+/**
+ * Brings the connection back after the phone restarts or Nectarlink is
+ * updated, without waiting for the app to be opened. Starting the core starts
+ * the connection service when a PC is paired (Core.start). After an update,
+ * the new version also says so in a notification.
+ */
+class StartupReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ val updated = when (intent.action) {
+ Intent.ACTION_MY_PACKAGE_REPLACED -> true
+ Intent.ACTION_BOOT_COMPLETED -> false
+ else -> return
+ }
+ val app = context.applicationContext as NectarlinkApplication
+ val pending = goAsync()
+ CoroutineScope(Dispatchers.Default).launch {
+ try {
+ app.core.start()
+ // Kept alive until the core is up, so the service starts inside the
+ // window Android allows after these broadcasts.
+ withTimeoutOrNull(START_WAIT_MS) { app.core.state.first { it.status !is CoreStatus.Starting } }
+ if (updated) app.updater.onUpdated()
+ } finally {
+ pending.finish()
+ }
+ }
+ }
+
+ private companion object {
+ const val START_WAIT_MS = 8_000L
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
index 2030211..3a37d82 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
@@ -222,7 +222,11 @@ class MainActivity : ComponentActivity() {
if (app.core.state.value.status is CoreStatus.Ready) {
app.core.refreshNotificationAccess()
}
- if (app.updater.enabled) lifecycleScope.launch { app.updater.updateIfDue() }
+ if (app.updater.enabled) {
+ // Back from allowing installs: the update the user started carries on.
+ app.updater.onAppResumed()
+ lifecycleScope.launch { app.updater.updateIfDue() }
+ }
}
override fun onNewIntent(intent: Intent) {
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/update/AppUpdater.kt b/android/app/src/main/kotlin/app/nectarlink/android/update/AppUpdater.kt
index 4aa2645..78af91c 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/update/AppUpdater.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/update/AppUpdater.kt
@@ -10,7 +10,10 @@ 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.NetworkCapabilities
import android.os.Build
+import android.os.SystemClock
import android.provider.Settings
import android.util.Log
import androidx.core.app.NotificationCompat
@@ -20,14 +23,21 @@ import androidx.core.net.toUri
import app.nectarlink.android.BuildConfig
import app.nectarlink.android.NectarlinkApplication
import app.nectarlink.android.R
+import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.File
+import java.io.FileOutputStream
+import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
@@ -38,12 +48,19 @@ import java.security.MessageDigest
* Android only installs it over this app when it's signed with the same
* key, so only release builds update themselves (debug builds are signed
* differently).
+ *
+ * Downloads resume where they stopped: across a dropped or changed network
+ * (it waits for one to come back), and across restarts of the app.
*/
@androidx.compose.runtime.Stable
class AppUpdater(context: Context) {
private val context = context.applicationContext
internal val prefs = context.getSharedPreferences("updates", Context.MODE_PRIVATE)
+ /** Installs outlive the screen that started them. */
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ private val busy = Mutex()
+
/** A newer release. */
@androidx.compose.runtime.Immutable
data class Update(val version: String, val notesUrl: String, internal val apkUrl: String, internal val apkName: String, internal val sumsUrl: String)
@@ -51,14 +68,23 @@ class AppUpdater(context: Context) {
sealed interface State {
data object Idle : State
data object Checking : State
+
+ /** A check found nothing newer. */
+ data object UpToDate : State
data class Available(val update: Update) : State
- data class Downloading(val update: Update) : State
+
+ /** Waiting for the user to let Nectarlink install apps; continues when they have. */
+ data class NeedsPermission(val update: Update) : State
+
+ /** `total` is 0 until the size is known. */
+ data class Downloading(val update: Update, val done: Long, val total: Long, val waitingForNetwork: Boolean) : State
+
/** Waiting for Android (and the user) to install it. */
data class Installing(val update: Update) : State
data class Failed(val update: Update?, val reason: Reason) : State
}
- enum class Reason { Offline, Damaged, NotAllowed, Install }
+ enum class Reason { Offline, Damaged, Install }
private val _state = MutableStateFlow<State>(State.Idle)
val state: StateFlow<State> = _state.asStateFlow()
@@ -82,9 +108,7 @@ class AppUpdater(context: Context) {
* itself before; otherwise a notification asks for one tap.
*/
suspend fun updateIfDue() {
- if (!enabled) return
- // Not while one is already on its way.
- if (_state.value is State.Downloading || _state.value is State.Installing) return
+ if (!enabled || isBusy()) return
checkIfDue()
val available = (_state.value as? State.Available)?.update ?: return
if (_autoInstall.value && canInstall()) install(available, automatic = true)
@@ -97,21 +121,30 @@ class AppUpdater(context: Context) {
check()
}
- /** Checks now; returns whether an update is available. */
+ /** Checks now; returns whether an update is available. Leaves an install in progress alone. */
suspend fun check(): Boolean {
- if (!enabled) return false
+ if (!enabled || isBusy()) return _state.value is State.Available
_state.value = State.Checking
val found = withContext(Dispatchers.IO) {
runCatching { latest() }.onFailure { Log.i(TAG, "couldn't check for updates", it) }
}
prefs.edit { putLong(LAST_CHECK, System.currentTimeMillis()) }
_state.value = found.fold(
- onSuccess = { update -> update?.let { State.Available(it) } ?: State.Idle },
+ onSuccess = { update -> update?.let { State.Available(it) } ?: State.UpToDate },
onFailure = { State.Failed(null, Reason.Offline) },
)
return _state.value is State.Available
}
+ /** Checks now, from a button. */
+ fun checkNow() {
+ scope.launch { check() }
+ }
+
+ private fun isBusy(): Boolean = _state.value.let {
+ it is State.Downloading || it is State.Installing || it is State.Checking
+ }
+
private fun latest(): Update? {
val body = try {
get(LATEST, 1 shl 20)
@@ -151,55 +184,173 @@ class AppUpdater(context: Context) {
Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, "package:${context.packageName}".toUri())
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- /** Downloads, checks and hands the update to Android's installer. */
- suspend fun install(update: Update, automatic: Boolean = false) {
- prefs.edit { putBoolean(LAST_AUTOMATIC, automatic) }
+ /**
+ * The user tapped Update. Starts the install, or, when Android first needs
+ * the user to allow installs, returns the screen for that; the update then
+ * continues by itself once they come back ([onAppResumed]).
+ */
+ fun requestInstall(update: Update): Intent? {
if (!canInstall()) {
- _state.value = State.Failed(update, Reason.NotAllowed)
- return
- }
- _state.value = State.Downloading(update)
- val apk = withContext(Dispatchers.IO) { runCatching { download(update) } }.getOrElse {
- Log.w(TAG, "update download failed", it)
- _state.value = State.Failed(update, if (it is DamagedException) Reason.Damaged else Reason.Offline)
- return
+ _state.value = State.NeedsPermission(update)
+ return allowInstallsIntent()
}
- _state.value = State.Installing(update)
- withContext(Dispatchers.IO) { runCatching { commit(apk) } }.onFailure {
- Log.w(TAG, "couldn't start the install", it)
- _state.value = State.Failed(update, Reason.Install)
+ scope.launch { install(update) }
+ return null
+ }
+
+ /** The app is in front again: carries on an update the user was allowing. */
+ fun onAppResumed() {
+ val waiting = (_state.value as? State.NeedsPermission)?.update ?: return
+ if (canInstall()) scope.launch { install(waiting) }
+ }
+
+ /** Downloads, checks and hands the update to Android's installer. */
+ suspend fun install(update: Update, automatic: Boolean = false) {
+ if (!busy.tryLock()) return
+ try {
+ prefs.edit { putBoolean(LAST_AUTOMATIC, automatic) }
+ if (!canInstall()) {
+ _state.value = State.NeedsPermission(update)
+ return
+ }
+ _state.value = State.Downloading(update, 0, 0, waitingForNetwork = false)
+ val apk = withContext(Dispatchers.IO) { runCatching { download(update) } }.getOrElse {
+ Log.w(TAG, "update download failed", it)
+ _state.value = State.Failed(update, if (it is DamagedException) Reason.Damaged else Reason.Offline)
+ return
+ }
+ _state.value = State.Installing(update)
+ withContext(Dispatchers.IO) { runCatching { commit(apk) } }.onFailure {
+ Log.w(TAG, "couldn't start the install", it)
+ _state.value = State.Failed(update, Reason.Install)
+ }
+ } finally {
+ busy.unlock()
}
}
private class DamagedException : Exception("checksum mismatch")
- private fun download(update: Update): File {
- val sums = String(get(update.sumsUrl, 64 * 1024))
+ /**
+ * The verified APK. Kept under a name taken from its expected hash, so a
+ * partial download only ever continues into the same file.
+ */
+ private suspend fun download(update: Update): File {
+ val sums = retrying(update) { String(get(update.sumsUrl, 64 * 1024)) }
val expected = listedHash(sums, update.apkName) ?: throw DamagedException()
- val dir = File(context.cacheDir, "updates").apply { deleteRecursively(); mkdirs() }
- // A fixed name: the release's asset name is not trusted as a path.
- val file = File(dir, "update.apk")
- val digest = MessageDigest.getInstance("SHA-256")
- open(update.apkUrl).inputStream.use { input ->
- file.outputStream().use { output ->
- val buffer = ByteArray(256 * 1024)
- var total = 0L
- while (true) {
- val read = input.read(buffer)
- if (read < 0) break
- total += read
- if (total > MAX_APK) throw DamagedException()
- digest.update(buffer, 0, read)
- output.write(buffer, 0, read)
- }
+ val dir = File(context.cacheDir, UPDATES_DIR).apply { mkdirs() }
+ val name = "nectarlink-${expected.take(16)}.apk"
+ val apk = File(dir, name)
+ val part = File(dir, "$name.part")
+ dir.listFiles()?.filter { it != apk && it != part }?.forEach { it.deleteRecursively() }
+ if (apk.isFile && sha256(apk) == expected) return apk
+ apk.delete()
+
+ retrying(update) { fetchInto(update, part) }
+ if (sha256(part) != expected) {
+ part.delete()
+ throw DamagedException()
+ }
+ if (!part.renameTo(apk)) throw IOException("can't keep the download")
+ return apk
+ }
+
+ /**
+ * Runs [block], and after a network error waits for a connection and
+ * tries again. Gives up after [MAX_ATTEMPTS] tries in a row that got
+ * nowhere; any progress resets the count.
+ */
+ private suspend fun <T> retrying(update: Update, block: suspend () -> T): T {
+ var failures = 0
+ var lastDone = downloaded()
+ while (true) {
+ try {
+ return block()
+ } catch (e: DamagedException) {
+ throw e
+ } catch (e: HttpStatus) {
+ if (e.code in 400..499 && e.code != 408 && e.code != 429) throw e
+ failures = nextFailure(failures, lastDone).also { lastDone = downloaded() }
+ if (failures > MAX_ATTEMPTS) throw e
+ } catch (e: IOException) {
+ failures = nextFailure(failures, lastDone).also { lastDone = downloaded() }
+ if (failures > MAX_ATTEMPTS) throw e
}
+ setWaiting(update, true)
+ awaitNetwork()
+ delay(BACKOFF_MS[(failures - 1).coerceIn(0, BACKOFF_MS.lastIndex)])
+ setWaiting(update, false)
}
- val actual = digest.digest().joinToString("") { "%02x".format(it) }
- if (actual != expected) {
- file.delete()
- throw DamagedException()
+ }
+
+ private fun downloaded(): Long = (_state.value as? State.Downloading)?.done ?: 0
+
+ private fun nextFailure(failures: Int, lastDone: Long): Int = if (downloaded() > lastDone) 1 else failures + 1
+
+ private fun setWaiting(update: Update, waiting: Boolean) {
+ _state.update { s ->
+ if (s is State.Downloading && s.update == update) s.copy(waitingForNetwork = waiting) else s
+ }
+ }
+
+ /** Waits (up to two minutes) for a network that reaches the internet. */
+ private suspend fun awaitNetwork() {
+ val manager = context.getSystemService(ConnectivityManager::class.java) ?: return
+ val deadline = SystemClock.elapsedRealtime() + NETWORK_WAIT_MS
+ while (SystemClock.elapsedRealtime() < deadline) {
+ val caps = manager.getNetworkCapabilities(manager.activeNetwork)
+ if (caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) == true) return
+ delay(1_000)
}
- return file
+ }
+
+ /** Downloads into `part`, continuing from what it already holds. */
+ private fun fetchInto(update: Update, part: File) {
+ val have = part.length()
+ val connection = connect(update.apkUrl, from = have)
+ try {
+ val append = when (val code = connection.responseCode) {
+ HttpURLConnection.HTTP_PARTIAL -> true
+ HttpURLConnection.HTTP_OK -> false
+ // Asked for bytes past the end: it's all here already.
+ 416 -> return
+ else -> throw HttpStatus(code)
+ }
+ val total = if (append) {
+ rangeTotal(connection.getHeaderField("Content-Range")) ?: (have + connection.contentLengthLong)
+ } else {
+ connection.contentLengthLong
+ }
+ if (total > MAX_APK) throw DamagedException()
+ var done = if (append) have else 0L
+ var lastReport = 0L
+ report(update, done, total)
+ FileOutputStream(part, append).use { output ->
+ connection.inputStream.use { input ->
+ val buffer = ByteArray(256 * 1024)
+ while (true) {
+ val read = input.read(buffer)
+ if (read < 0) break
+ done += read
+ if (done > MAX_APK) throw DamagedException()
+ output.write(buffer, 0, read)
+ val now = SystemClock.elapsedRealtime()
+ if (now - lastReport > PROGRESS_EVERY_MS) {
+ lastReport = now
+ report(update, done, total)
+ }
+ }
+ }
+ }
+ report(update, done, total)
+ if (total > 0 && done < total) throw IOException("download ended early")
+ } finally {
+ connection.disconnect()
+ }
+ }
+
+ private fun report(update: Update, done: Long, total: Long) {
+ _state.value = State.Downloading(update, done, maxOf(total, 0), waitingForNetwork = false)
}
private fun commit(apk: File) {
@@ -231,6 +382,7 @@ class AppUpdater(context: Context) {
/** Android's answer: ask the user to confirm, or it's done (or failed). */
class InstallResult : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
+ val updater = (context.applicationContext as NectarlinkApplication).updater
when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val confirm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
@@ -239,35 +391,41 @@ class AppUpdater(context: Context) {
@Suppress("DEPRECATION")
intent.getParcelableExtra(Intent.EXTRA_INTENT)
}?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ?: return
- val updater = (context.applicationContext as NectarlinkApplication).updater
// Started by the user: Android's prompt opens now. In the background it
// can't, so a notification waits for the tap.
if (updater.prefs.getBoolean(LAST_AUTOMATIC, false)) {
updater.notifyReady(confirm)
} else {
- context.startActivity(confirm)
+ runCatching { context.startActivity(confirm) }.onFailure { updater.notifyReady(confirm) }
}
}
- PackageInstaller.STATUS_SUCCESS -> Unit // The new version starts fresh.
+ // This process is replaced; the new version says it's updated (onUpdated).
+ PackageInstaller.STATUS_SUCCESS -> Unit
+ // The user said no to Android's prompt: the update is still there to install.
+ PackageInstaller.STATUS_FAILURE_ABORTED -> updater.installCancelled()
else -> {
Log.w(TAG, "install failed: ${intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)}")
- (context.applicationContext as NectarlinkApplication).updater.installFailed()
+ updater.installFailed()
}
}
}
}
- /** "Nectarlink 0.2.0 is ready", opening Android's install prompt when tapped. */
- internal fun notifyReady(confirm: Intent) {
- if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
- PackageManager.PERMISSION_GRANTED
- ) {
- return
- }
- val manager = context.getSystemService(NotificationManager::class.java)
+ private fun channel(manager: NotificationManager) {
manager.createNotificationChannel(
NotificationChannel(CHANNEL, context.getString(R.string.channel_updates), NotificationManager.IMPORTANCE_DEFAULT),
)
+ }
+
+ private fun mayNotify(): Boolean =
+ Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
+ ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
+
+ /** "Nectarlink 0.2.0 is ready", opening Android's install prompt when tapped. */
+ internal fun notifyReady(confirm: Intent) {
+ if (!mayNotify()) return
+ val manager = context.getSystemService(NotificationManager::class.java)
+ channel(manager)
val version = (_state.value as? State.Installing)?.update?.version.orEmpty()
val tap = PendingIntent.getActivity(context, READY_ID, confirm, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(context, CHANNEL)
@@ -280,53 +438,119 @@ class AppUpdater(context: Context) {
manager.notify(READY_ID, notification)
}
+ /**
+ * The new version's first run after an update (StartupReceiver): clears
+ * the download and says so. Android doesn't let an app open its own window
+ * from the background, so the notification opens it.
+ */
+ fun onUpdated() {
+ runCatching { File(context.cacheDir, UPDATES_DIR).deleteRecursively() }
+ if (!mayNotify()) return
+ val manager = context.getSystemService(NotificationManager::class.java)
+ channel(manager)
+ manager.cancel(READY_ID)
+ val launch = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return
+ val tap = PendingIntent.getActivity(
+ context,
+ UPDATED_ID,
+ launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ val notification = NotificationCompat.Builder(context, CHANNEL)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(context.getString(R.string.update_done_title, BuildConfig.VERSION_NAME))
+ .setContentText(context.getString(R.string.update_done_text))
+ .setContentIntent(tap)
+ .setAutoCancel(true)
+ .setOnlyAlertOnce(true)
+ .build()
+ manager.notify(UPDATED_ID, notification)
+ }
+
/** Android didn't install it. */
internal fun installFailed() {
_state.update { s -> State.Failed((s as? State.Installing)?.update, Reason.Install) }
}
+ internal fun installCancelled() {
+ _state.update { s -> (s as? State.Installing)?.update?.let { State.Available(it) } ?: s }
+ }
+
companion object {
private const val TAG = "AppUpdater"
private const val LATEST = "https://api.github.com/repos/thtbee/nectarlink/releases/latest"
private const val LAST_CHECK = "lastCheck"
private const val AUTO_INSTALL = "autoInstall"
private const val LAST_AUTOMATIC = "lastAutomatic"
+ private const val UPDATES_DIR = "updates"
private const val CHANNEL = "updates"
private const val READY_ID = 0x0D47
+ private const val UPDATED_ID = 0x0D48
private const val CHECK_EVERY_MS = 24L * 3600 * 1000
private const val MAX_APK = 300L * 1024 * 1024
+ private const val MAX_ATTEMPTS = 6
+ private const val NETWORK_WAIT_MS = 2L * 60 * 1000
+ private const val PROGRESS_EVERY_MS = 150L
+ private val BACKOFF_MS = longArrayOf(1_000, 2_000, 4_000, 8_000, 15_000, 30_000)
- /** A response other than 200 OK. */
- private class HttpStatus(val code: Int) : java.io.IOException("HTTP $code")
+ /** A response other than the one expected. */
+ private class HttpStatus(val code: Int) : IOException("HTTP $code")
- private fun open(url: String): HttpURLConnection {
- if (!url.startsWith("https://")) throw java.io.IOException("only https")
+ /** A connection for `url`, asking for the bytes from `from` on when that's past 0. */
+ private fun connect(url: String, from: Long = 0): HttpURLConnection {
+ if (!url.startsWith("https://")) throw IOException("only https")
return (URL(url).openConnection() as HttpURLConnection).apply {
- connectTimeout = 10_000
- readTimeout = 60_000
+ connectTimeout = 15_000
+ // A stalled connection fails soon, so the download resumes on a fresh one.
+ readTimeout = 20_000
instanceFollowRedirects = true
setRequestProperty("User-Agent", "Nectarlink/${BuildConfig.VERSION_NAME} (Android)")
setRequestProperty("Accept", "application/vnd.github+json, application/octet-stream")
- if (responseCode != 200) throw HttpStatus(responseCode)
+ if (from > 0) setRequestProperty("Range", "bytes=$from-")
// Redirects stay on https (HttpURLConnection never follows one to another
// protocol); checked again in case that ever changes.
- if (this.url.protocol != "https") throw java.io.IOException("only https")
+ responseCode
+ if (this.url.protocol != "https") throw IOException("only https")
}
}
/** The body, up to `limit` bytes; never buffers more than that. */
- private fun get(url: String, limit: Int): ByteArray =
- open(url).inputStream.use { input ->
- val out = java.io.ByteArrayOutputStream()
- val buffer = ByteArray(16 * 1024)
+ private fun get(url: String, limit: Int): ByteArray {
+ val connection = connect(url)
+ try {
+ if (connection.responseCode != HttpURLConnection.HTTP_OK) throw HttpStatus(connection.responseCode)
+ return connection.inputStream.use { input ->
+ val out = java.io.ByteArrayOutputStream()
+ val buffer = ByteArray(16 * 1024)
+ while (true) {
+ val read = input.read(buffer)
+ if (read < 0) break
+ if (out.size() + read > limit) throw IOException("too large")
+ out.write(buffer, 0, read)
+ }
+ out.toByteArray()
+ }
+ } finally {
+ connection.disconnect()
+ }
+ }
+
+ private fun sha256(file: File): String {
+ val digest = MessageDigest.getInstance("SHA-256")
+ file.inputStream().use { input ->
+ val buffer = ByteArray(256 * 1024)
while (true) {
val read = input.read(buffer)
if (read < 0) break
- if (out.size() + read > limit) throw java.io.IOException("too large")
- out.write(buffer, 0, read)
+ digest.update(buffer, 0, read)
}
- out.toByteArray()
}
+ return digest.digest().joinToString("") { "%02x".format(it) }
+ }
+
+ /** The full size from a `Content-Range: bytes 100-199/200` header. */
+ fun rangeTotal(header: String?): Long? =
+ header?.substringAfterLast('/', "")?.trim()?.toLongOrNull()?.takeIf { it > 0 }
/** The SHA-256 a sums file lists for `name` (`<hex> <name>` lines). */
fun listedHash(sums: String, name: String): String? = sums.lineSequence().firstNotNullOfOrNull { line ->
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.kt b/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.kt
index 9971535..80e3655 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/update/UpdateCard.kt
@@ -2,12 +2,15 @@
package app.nectarlink.android.update
import android.content.Intent
+import android.text.format.Formatter
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
@@ -17,10 +20,6 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-import androidx.compose.runtime.rememberCoroutineScope
-import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
@@ -28,23 +27,33 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import app.nectarlink.android.BuildConfig
import app.nectarlink.android.R
import app.nectarlink.android.ui.theme.LocalReducedMotion
-import kotlinx.coroutines.launch
-/** "Nectarlink 0.2.0 is available", while there's an update to talk about. */
+/** The update a state is about, if any. */
+private val AppUpdater.State.update: AppUpdater.Update?
+ get() = when (this) {
+ is AppUpdater.State.Available -> update
+ is AppUpdater.State.NeedsPermission -> update
+ is AppUpdater.State.Downloading -> update
+ is AppUpdater.State.Installing -> update
+ is AppUpdater.State.Failed -> update
+ else -> null
+ }
+
+/** "Nectarlink 0.2.0 is available" on Home, while there's an update to talk about. */
@Composable
fun UpdateCard(updater: AppUpdater, modifier: Modifier = Modifier) {
val state by updater.state.collectAsStateWithLifecycle()
- val update = when (val s = state) {
- is AppUpdater.State.Available -> s.update
- is AppUpdater.State.Downloading -> s.update
- is AppUpdater.State.Installing -> s.update
- is AppUpdater.State.Failed -> s.update
- else -> null
- } ?: return
+ val update = state.update ?: return
+ UpdatePanel(updater, state, update, modifier)
+}
+
+/** One update's status, progress and actions, for the Home card and Settings. */
+@Composable
+private fun UpdatePanel(updater: AppUpdater, state: AppUpdater.State, update: AppUpdater.Update, modifier: Modifier = Modifier) {
val context = LocalContext.current
- val scope = rememberCoroutineScope()
val failure = (state as? AppUpdater.State.Failed)?.reason
Surface(
shape = MaterialTheme.shapes.extraLarge,
@@ -54,42 +63,48 @@ fun UpdateCard(updater: AppUpdater, modifier: Modifier = Modifier) {
) {
Column(Modifier.fillMaxWidth().padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(stringResource(R.string.update_title, update.version), style = MaterialTheme.typography.titleMedium)
- Text(
- stringResource(
- when {
- state is AppUpdater.State.Downloading -> R.string.update_downloading
- state is AppUpdater.State.Installing -> R.string.update_installing
- failure == AppUpdater.Reason.NotAllowed -> R.string.update_not_allowed
- failure == AppUpdater.Reason.Damaged -> R.string.update_damaged
- failure == AppUpdater.Reason.Install -> R.string.update_install_failed
- failure != null -> R.string.update_offline
- else -> R.string.update_text
- },
- ),
- style = MaterialTheme.typography.bodyMedium,
- )
- if (state is AppUpdater.State.Downloading || state is AppUpdater.State.Installing) {
- if (LocalReducedMotion.current) {
- LinearProgressIndicator(progress = { 0.5f }, modifier = Modifier.fillMaxWidth())
- } else {
- LinearProgressIndicator(Modifier.fillMaxWidth())
- }
+ val status = when {
+ state is AppUpdater.State.Downloading && state.waitingForNetwork -> stringResource(R.string.update_waiting_network)
+ state is AppUpdater.State.Downloading && state.total > 0 -> stringResource(
+ R.string.update_downloading_progress,
+ Formatter.formatShortFileSize(context, state.done),
+ Formatter.formatShortFileSize(context, state.total),
+ )
+ state is AppUpdater.State.Downloading -> stringResource(R.string.update_downloading)
+ state is AppUpdater.State.Installing -> stringResource(R.string.update_installing)
+ state is AppUpdater.State.NeedsPermission -> stringResource(R.string.update_not_allowed)
+ failure == AppUpdater.Reason.Damaged -> stringResource(R.string.update_damaged)
+ failure == AppUpdater.Reason.Install -> stringResource(R.string.update_install_failed)
+ failure != null -> stringResource(R.string.update_offline)
+ else -> stringResource(R.string.update_text)
+ }
+ Text(status, style = MaterialTheme.typography.bodyMedium)
+ when {
+ state is AppUpdater.State.Downloading && state.total > 0 && !state.waitingForNetwork -> LinearProgressIndicator(
+ progress = { (state.done.toFloat() / state.total).coerceIn(0f, 1f) },
+ modifier = Modifier.fillMaxWidth(),
+ )
+ state is AppUpdater.State.Downloading || state is AppUpdater.State.Installing ->
+ if (LocalReducedMotion.current) {
+ LinearProgressIndicator(progress = { 0.5f }, modifier = Modifier.fillMaxWidth())
+ } else {
+ LinearProgressIndicator(Modifier.fillMaxWidth())
+ }
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- if (failure == AppUpdater.Reason.NotAllowed && !updater.canInstall()) {
- Button(onClick = { context.startActivity(updater.allowInstallsIntent()) }) {
+ when (state) {
+ is AppUpdater.State.NeedsPermission -> Button(onClick = { context.startActivity(updater.allowInstallsIntent()) }) {
Text(stringResource(R.string.action_allow))
}
- } else {
- Button(
- enabled = state is AppUpdater.State.Available || state is AppUpdater.State.Failed,
- onClick = { scope.launch { updater.install(update) } },
- ) {
- Text(stringResource(R.string.action_update))
+ is AppUpdater.State.Available, is AppUpdater.State.Failed -> Button(onClick = {
+ updater.requestInstall(update)?.let(context::startActivity)
+ }) {
+ Text(stringResource(if (failure != null) R.string.action_try_again else R.string.action_update))
}
+ else -> Unit
}
TextButton(onClick = {
- context.startActivity(Intent(Intent.ACTION_VIEW, update.notesUrl.toUri()))
+ runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, update.notesUrl.toUri())) }
}) {
Text(stringResource(R.string.update_whats_new))
}
@@ -98,11 +113,10 @@ fun UpdateCard(updater: AppUpdater, modifier: Modifier = Modifier) {
}
}
-/** "Check for updates" in Settings, with what it found, and automatic updates on or off. */
+/** Updates in Settings: automatic installs on or off, a check, and what it found. */
@Composable
fun CheckForUpdates(updater: AppUpdater) {
if (!updater.enabled) return
- val scope = rememberCoroutineScope()
val state by updater.state.collectAsStateWithLifecycle()
val auto by updater.autoInstall.collectAsStateWithLifecycle()
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
@@ -120,24 +134,24 @@ fun CheckForUpdates(updater: AppUpdater) {
colors = app.nectarlink.android.ui.theme.nectarSwitchColors(),
)
}
- var checked by remember { mutableStateOf(false) }
- OutlinedButton(
- enabled = state !is AppUpdater.State.Checking && state !is AppUpdater.State.Downloading,
- onClick = {
- scope.launch {
- updater.check()
- checked = true
- }
- },
- ) {
- Text(stringResource(R.string.update_check))
+ val update = state.update
+ if (update != null) {
+ UpdatePanel(updater, state, update, Modifier.fillMaxWidth())
+ return
}
- if (checked) {
- val text = when (state) {
- AppUpdater.State.Idle -> R.string.update_up_to_date
- is AppUpdater.State.Failed -> R.string.update_check_failed
- else -> null
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ OutlinedButton(enabled = state !is AppUpdater.State.Checking, onClick = updater::checkNow) {
+ Text(stringResource(R.string.update_check))
}
- text?.let { Text(stringResource(it), style = MaterialTheme.typography.bodySmall) }
+ if (state is AppUpdater.State.Checking) {
+ CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
+ }
+ }
+ val result = when (state) {
+ AppUpdater.State.Checking -> stringResource(R.string.update_checking)
+ AppUpdater.State.UpToDate -> stringResource(R.string.update_up_to_date_version, BuildConfig.VERSION_NAME)
+ is AppUpdater.State.Failed -> stringResource(R.string.update_check_failed)
+ else -> stringResource(R.string.update_current_version, BuildConfig.VERSION_NAME)
}
+ Text(result, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index e213592..c035a29 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -233,14 +233,18 @@
<string name="update_title">Nectarlink %1$s is available</string>
<string name="update_text">Get the latest improvements and fixes.</string>
<string name="update_downloading">Downloading…</string>
+ <string name="update_downloading_progress">Downloading · %1$s of %2$s</string>
+ <string name="update_waiting_network">Waiting for a connection. The download continues where it stopped.</string>
<string name="update_installing">Installing. Android may ask you to confirm.</string>
- <string name="update_not_allowed">Allow Nectarlink to install its updates, then come back and tap Update.</string>
+ <string name="update_not_allowed">Allow Nectarlink to install its updates. The update continues when you come back.</string>
<string name="update_damaged">The download was damaged, so it wasn’t installed. Try again.</string>
<string name="update_offline">The update couldn’t be downloaded. Try again when you’re online.</string>
<string name="update_install_failed">Android didn’t install the update. Try again.</string>
<string name="update_whats_new">What’s new</string>
<string name="update_check">Check for updates</string>
- <string name="update_up_to_date">Nectarlink is up to date.</string>
+ <string name="update_checking">Checking for updates…</string>
+ <string name="update_up_to_date_version">Nectarlink %1$s is up to date.</string>
+ <string name="update_current_version">You have Nectarlink %1$s.</string>
<string name="update_check_failed">Couldn’t check for updates. Check your internet connection.</string>
<string name="action_lock_pc">Lock PC</string>
<string name="action_sleep_pc">Sleep</string>
@@ -1248,6 +1252,8 @@
<string name="channel_updates">Updates</string>
<string name="update_ready_title">Nectarlink %1$s is ready</string>
<string name="update_ready_text">Tap to install the update.</string>
+ <string name="update_done_title">Nectarlink is updated to %1$s</string>
+ <string name="update_done_text">Tap to open it. Your PCs reconnect on their own.</string>
<string name="update_auto_title">Install updates automatically</string>
<string name="update_auto_text">New versions from GitHub install in the background.</string>
</resources>
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/update/AppUpdaterTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/update/AppUpdaterTest.kt
index 08fdd2f..a32d990 100644
--- a/android/app/src/test/kotlin/app/nectarlink/android/update/AppUpdaterTest.kt
+++ b/android/app/src/test/kotlin/app/nectarlink/android/update/AppUpdaterTest.kt
@@ -27,4 +27,12 @@ class AppUpdaterTest {
assertNull(AppUpdater.listedHash(sums, "missing.apk"))
assertEquals("c".repeat(64), AppUpdater.listedHash("${"C".repeat(64)} *x.apk", "x.apk"))
}
+
+ @Test
+ fun readsTheFullSizeFromContentRange() {
+ assertEquals(49_362_916L, AppUpdater.rangeTotal("bytes 1048576-49362915/49362916"))
+ assertNull(AppUpdater.rangeTotal("bytes 0-99/*"))
+ assertNull(AppUpdater.rangeTotal(null))
+ assertNull(AppUpdater.rangeTotal("garbage"))
+ }
}
diff --git a/desktop/app/cpp/native_window.cpp b/desktop/app/cpp/native_window.cpp
index 0ac4933..cd67548 100644
--- a/desktop/app/cpp/native_window.cpp
+++ b/desktop/app/cpp/native_window.cpp
@@ -142,8 +142,24 @@ void NativeWindow::bringToFront()
showNormal();
raise();
requestActivate();
- if (handle())
- SetForegroundWindow(hwndOf(this));
+ if (!handle())
+ return;
+ const HWND hwnd = hwndOf(this);
+ if (SetForegroundWindow(hwnd) || GetForegroundWindow() == hwnd)
+ return;
+ // Windows only lets the process the user is working in change the
+ // foreground window, so a copy opened from the background (after an
+ // update, or by another instance) would stay behind. Sharing the
+ // foreground thread's input state for a moment lets it come forward.
+ const HWND foreground = GetForegroundWindow();
+ const DWORD foregroundThread = foreground ? GetWindowThreadProcessId(foreground, nullptr) : 0;
+ const DWORD thisThread = GetCurrentThreadId();
+ const bool attached = foregroundThread != 0 && foregroundThread != thisThread
+ && AttachThreadInput(thisThread, foregroundThread, TRUE);
+ BringWindowToTop(hwnd);
+ SetForegroundWindow(hwnd);
+ if (attached)
+ AttachThreadInput(thisThread, foregroundThread, FALSE);
}
void NativeWindow::flash()
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 24147c9..404569f 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -198,6 +198,8 @@ struct Options {
data_dir: Option<PathBuf>,
/// Start in the tray without opening the window (autostart).
minimized: bool,
+ /// Started by the updater's relauncher, as the new version.
+ updated: bool,
/// `--send-to <device> <files…>`: Explorer's "Send to" menu.
send_to: Option<(String, Vec<PathBuf>)>,
/// `--share <targets…>`: Windows Share sheet or CLI share invocation.
@@ -272,6 +274,10 @@ fn parse_options_from<I: IntoIterator<Item = std::ffi::OsString>>(iter: I) -> Op
in_share = false;
options.update_service = true;
}
+ Some(updater::UPDATED_ARG) => {
+ in_share = false;
+ options.updated = true;
+ }
Some(win::vcam::REGISTER_ARG) => {
in_share = false;
options.register_vcam = true;
@@ -545,6 +551,10 @@ fn main() -> ExitCode {
updater::set_auto(settings.auto_update);
updater::set_auto_install(settings.install_updates);
updater::start();
+ let previous = updater::note_running_version(&data_dir);
+ if previous.is_some() || options.updated {
+ updater::announce_update(previous, !options.minimized);
+ }
}
// Requests left while no instance was running, then this launch's own.
for waiting in launch::drain(&data_dir) {
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index 59dfd26..4cbbe25 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -443,6 +443,9 @@ pub fn on_toast(event: ToastEvent) {
return crate::bridge::app::install_update_in_background();
}
ToastEvent::Dismissed { device, .. } if device == crate::updater::TOAST_GROUP => return,
+ ToastEvent::Opened { device, .. } if device == crate::updater::TOAST_GROUP => {
+ return crate::bridge::app::request_activation();
+ }
// New photos: open, save or copy one.
ToastEvent::Opened { device, key } if device == crate::photos::TOAST_GROUP => {
return crate::photos::on_toast(key, None);
diff --git a/desktop/app/src/updater.rs b/desktop/app/src/updater.rs
index b786bb9..e9ee23c 100644
--- a/desktop/app/src/updater.rs
+++ b/desktop/app/src/updater.rs
@@ -352,8 +352,8 @@ fn spawn_relauncher(exe: &Path, version: &str, shown: bool) -> Result<(), String
if !version.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) {
return Err("unusual version".into());
}
- let arguments = if shown { "" } else { "--minimized" };
- let script = relauncher_script(exe, version, arguments);
+ let arguments = if shown { UPDATED_ARG.to_owned() } else { format!("--minimized {UPDATED_ARG}") };
+ let script = relauncher_script(exe, version, &arguments);
let encoded: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-EncodedCommand"])
@@ -544,6 +544,56 @@ fn install_with_prompt() -> Result<(), String> {
Ok(())
}
+/// The flag the relauncher passes to the new version.
+pub const UPDATED_ARG: &str = "--updated";
+
+/// The file that remembers which version last ran, to notice an update
+/// however it was installed (the task, the installer, or setup by hand).
+const LAST_VERSION_FILE: &str = "last-version";
+
+/// Records this version as the one that ran, and returns the one before it
+/// when this one is newer: the app was just updated.
+pub fn note_running_version(data_dir: &Path) -> Option<String> {
+ let path = data_dir.join(LAST_VERSION_FILE);
+ let previous = std::fs::read_to_string(&path).ok().map(|v| v.trim().to_owned());
+ let current = env!("CARGO_PKG_VERSION");
+ if previous.as_deref() != Some(current)
+ && let Err(e) = std::fs::write(&path, current)
+ {
+ tracing::warn!(error = %e, "can't note the running version");
+ }
+ previous.filter(|p| is_newer(current, p))
+}
+
+/// Just updated: says so, and when the window was asked for, brings it to
+/// the front. Started from the background, Windows would otherwise leave
+/// the new window behind whatever the user has open.
+pub fn announce_update(previous: Option<String>, shown: bool) {
+ let current = env!("CARGO_PKG_VERSION");
+ tracing::info!(from = previous.as_deref().unwrap_or("?"), to = current, "updated");
+ std::thread::spawn(move || {
+ // Once the window exists.
+ std::thread::sleep(Duration::from_millis(1500));
+ if shown {
+ crate::bridge::app::request_activation();
+ }
+ toast::show(toast::Toast {
+ device: TOAST_GROUP.into(),
+ key: "updated".into(),
+ title: format!("Nectarlink is updated to {current}"),
+ body: "Your phone reconnects on its own.".into(),
+ attribution: "Nectarlink".into(),
+ icon: None,
+ image: None,
+ actions: Vec::new(),
+ reply: None,
+ silent: true,
+ progress: None,
+ call: false,
+ });
+ });
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -581,17 +631,37 @@ mod tests {
#[test]
fn the_relauncher_waits_for_the_version_then_opens_the_app() {
- let script =
- relauncher_script(r"C:\Program Files\Nectarlink\nectarlink-desktop.exe", "0.2.0", "--minimized");
+ let script = relauncher_script(
+ r"C:\Program Files\Nectarlink\nectarlink-desktop.exe",
+ "0.2.0",
+ "--minimized --updated",
+ );
assert!(script.contains("$installed -eq '0.2.0'"));
assert!(script.contains("Nectarlink-*-setup"));
assert!(script.contains(
- r"Start-Process -FilePath 'C:\Program Files\Nectarlink\nectarlink-desktop.exe' -ArgumentList '--minimized'"
+ r"Start-Process -FilePath 'C:\Program Files\Nectarlink\nectarlink-desktop.exe' -ArgumentList '--minimized --updated'"
));
let shown = relauncher_script(r"C:\Program Files\Nectarlink\nectarlink-desktop.exe", "0.2.0", "");
assert!(!shown.contains("-ArgumentList"));
}
+ #[test]
+ fn notices_a_newer_version_once() {
+ let dir = tempfile::tempdir().unwrap();
+ let current = env!("CARGO_PKG_VERSION");
+ // A first run, then the same version again: no update.
+ assert_eq!(note_running_version(dir.path()), None);
+ assert_eq!(note_running_version(dir.path()), None);
+ // An older version ran before this one: updated, said once.
+ std::fs::write(dir.path().join(LAST_VERSION_FILE), "0.0.1\n").unwrap();
+ assert_eq!(note_running_version(dir.path()).as_deref(), Some("0.0.1"));
+ assert_eq!(note_running_version(dir.path()), None);
+ assert_eq!(std::fs::read_to_string(dir.path().join(LAST_VERSION_FILE)).unwrap(), current);
+ // Going back to an older build isn't an update.
+ std::fs::write(dir.path().join(LAST_VERSION_FILE), "999.0.0").unwrap();
+ assert_eq!(note_running_version(dir.path()), None);
+ }
+
#[test]
fn the_relauncher_refuses_paths_and_versions_that_could_break_its_quotes() {
let odd = Path::new(r"C:\Program Files\it's\nectarlink-desktop.exe");