diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index c419c673e6..fe5be38ee1 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -534,6 +534,10 @@ class FrontEndActivity : ComponentActivity() { android.widget.Toast.makeText(this, R.string.main_wait_runtime, android.widget.Toast.LENGTH_SHORT).show() return } + SessionState.installing != null && !SessionState.running -> { + android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() + return + } compat -> Unit pkgStage != null -> { android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() @@ -559,12 +563,12 @@ class FrontEndActivity : ComponentActivity() { } private fun launchFlooded(f: PendingFlood) { - if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null || - ProtonExtras.installInProgress || pkgStage != null) { + if (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || + protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) { flood = null floodProgress = 0f com.droiddeck.launcher.ui.LaunchOrigin.flooding = null - if (!busy && !LinuxRuntimeInstaller.isBusy() && + if (!busy && !LinuxRuntimeInstaller.isBusy() && !(SessionState.installing != null && !SessionState.running) && (protons.protonBusyId != null || ProtonExtras.installInProgress)) { compatFlood = com.droiddeck.launcher.ui.Themes.byId(theme).signal waitForCompat(f.intent) @@ -598,7 +602,7 @@ class FrontEndActivity : ComponentActivity() { } if (!compatLaunchVisible) { ui.postDelayed(this, 250); return } val problem = protons.protonProblem.takeIf { waiting.menuInstall } - if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || pkgStage != null)) { + if (problem == null && (busy || LinuxRuntimeInstaller.isBusy() || (SessionState.installing != null && !SessionState.running) || pkgStage != null)) { waiting.loading.say(pkgStage ?: stage.takeIf { it.isNotBlank() } ?: getString(R.string.main_wait_runtime), com.droiddeck.launcher.session.LoadingState.Topic.RUNTIME, readable = true) waiting.loading.percent = if (pkgStage != null) pkgPercent else percent @@ -2437,6 +2441,10 @@ class FrontEndActivity : ComponentActivity() { private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean { if (busy || LinuxRuntimeInstaller.isBusy()) return false + if (SessionState.installing != null && !SessionState.running) { + android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() + return false + } if (com.droiddeck.launcher.storage.StorageState.cleaning) { android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show() return false diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 13dd33579a..6159d45ca9 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -489,6 +489,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { finish() return } + // A cancelled install keeps its thread until the download stops; a new launch would reuse its stop flag and close itself. + if (savedInstanceState == null && SessionState.installing != null && !SessionState.running) { + runtimeRemovalBlocked = true + android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() + finish() + return + } if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) { val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty() @@ -1666,12 +1673,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } - @Volatile private var installingRuntime = false + private var localInstalling = false + private val installingRuntime get() = localInstalling || SessionState.installing != null private var repairOffered by mutableStateOf(false) private fun installThenStart(runtime: Boolean, desktop: Boolean, proton: Boolean = false, resume: Boolean = false) { if (SessionState.stopRequested) return - installingRuntime = true + val worker = Any() + activeInstallWorker = worker + localInstalling = true SessionState.installing = if (runtime) "runtime" else if (resume) "package" else if (desktop) "desktop" else "proton" SessionEvents.transition( SessionPhase.INSTALLING_RUNTIME, @@ -1689,30 +1699,39 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (problem == null) SessionEvents.record("runtime.ready") else failedComponent = "runtime" } if (problem == null && resume && !SessionState.stopRequested) { - SessionState.installing = "package" + if (activeInstallWorker === worker) SessionState.installing = "package" SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "package.resuming", mapOf("component" to "package")) - problem = com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, progressAsIs()) - ?.let { getString(R.string.session_package_resume_failed, it) } + val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested } + SessionState.installCancellation = cancellation + problem = try { + com.droiddeck.launcher.runtime.DesktopCatalog.resumeInterrupted(this, cancellation, progressAsIs()) + ?.let { getString(R.string.session_package_resume_failed, it) } + } finally { + if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null + } if (problem == null) SessionEvents.record("package.ready") else failedComponent = "package" } if (problem == null && desktop && !SessionState.stopRequested) { - SessionState.installing = "desktop" + if (activeInstallWorker === worker) SessionState.installing = "desktop" SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "desktop.installing", mapOf("component" to "desktop")) problem = installDesktop() if (problem == null) SessionEvents.record("desktop.ready") else failedComponent = "desktop" } if (problem == null && proton && !SessionState.stopRequested) { - SessionState.installing = "proton" + if (activeInstallWorker === worker) SessionState.installing = "proton" SessionEvents.transition(SessionPhase.INSTALLING_RUNTIME, "proton.installing", mapOf("component" to "proton")) val protonProblem = installProton() if (protonProblem == null) SessionEvents.record("proton.ready") else SessionEvents.record("proton.skipped", mapOf("reason" to protonProblem)) } uiHandler.post { - installingRuntime = false - SessionState.installing = null + localInstalling = false + if (activeInstallWorker === worker) { + activeInstallWorker = null + SessionState.installing = null + } if (SessionState.stopRequested) { - SessionState.stopRequested = false + if (activeInstallWorker == null) SessionState.stopRequested = false SessionEvents.transition(SessionPhase.IDLE, "session.cancelled") collectStartArtifacts("session start cancelled") finish() @@ -1790,17 +1809,29 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun installDesktop(): String? { uiHandler.post { loading.percent = -1; loading.say(getString(DESKTOP_LINES.downloading), DESKTOP_LINES.topic, readable = true) } val entry = com.droiddeck.launcher.runtime.DesktopCatalog.desktopEntry(this) - val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry, - progressFor(DESKTOP_LINES, entry.size / 1_000_000)) - return problem?.let { getString(R.string.session_desktop_install_failed, it) } + val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested } + SessionState.installCancellation = cancellation + return try { + val problem = com.droiddeck.launcher.runtime.DesktopCatalog.install(this, entry, cancellation, + progressFor(DESKTOP_LINES, entry.size / 1_000_000)) + problem?.let { getString(R.string.session_desktop_install_failed, it) } + } finally { + if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null + } } private fun installProton(): String? { uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) } val catalog = com.droiddeck.launcher.runtime.DesktopCatalog - val entry = catalog.fetch(catalog.STEAM_SEED_URL)?.firstOrNull { it.id == catalog.PROTON_SEED_ID } - ?: return "catalog unreachable" - return catalog.install(this, entry, progressFor(PROTON_LINES, entry.size / 1_000_000)) + val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested } + SessionState.installCancellation = cancellation + return try { + val entry = catalog.fetch(catalog.STEAM_SEED_URL, cancellation)?.firstOrNull { it.id == catalog.PROTON_SEED_ID } + ?: return if (cancellation.asBoolean) "cancelled" else "catalog unreachable" + catalog.install(this, entry, cancellation, progressFor(PROTON_LINES, entry.size / 1_000_000)) + } finally { + if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null + } } override fun surfaceCreated(holder: SurfaceHolder) { @@ -3876,6 +3907,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private const val PAUSED_FRAME_REDRAW_MS = 150L private const val TAG = "SessionActivity" private var startedScreens = 0 + @Volatile private var activeInstallWorker: Any? = null private const val FEX_MISSING = "droiddeck-fex: x86 Linux programs need" private const val UNBUFFERED_SOURCES = InputDevice.SOURCE_CLASS_JOYSTICK or InputDevice.SOURCE_CLASS_TRACKBALL or InputDevice.SOURCE_CLASS_POSITION private const val CURSOR_PAD_HOLD_MS = 1200L diff --git a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java index 98e41ab6f6..31e8f45f55 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/Downloader.java +++ b/app/src/main/java/com/droiddeck/launcher/core/Downloader.java @@ -16,20 +16,83 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; public final class Downloader { private static final String TAG = "Downloader"; private static final int CONNECT_TIMEOUT_MS = 10_000; private static final int STALL_TIMEOUT_MS = 15_000; private static final int HTTP_RANGE_NOT_SATISFIABLE = 416; + private static final java.util.concurrent.ExecutorService CANCEL_EXECUTOR = + java.util.concurrent.Executors.newCachedThreadPool(r -> { + Thread thread = new Thread(r, "download-cancel"); + thread.setDaemon(true); + return thread; + }); private Downloader() {} + public static final class Cancellation implements java.util.function.BooleanSupplier { + private final AtomicBoolean cancelled = new AtomicBoolean(); + private final AtomicReference connection = new AtomicReference<>(); + private final AtomicReference input = new AtomicReference<>(); + private final java.util.function.BooleanSupplier external; + + public Cancellation() { this(null); } + public Cancellation(java.util.function.BooleanSupplier external) { this.external = external; } + + public void cancel() { + cancelled.set(true); + HttpURLConnection active = connection.get(); + if (active != null) disconnectAsync(active); + InputStream activeInput = input.get(); + if (activeInput != null) closeAsync(activeInput); + } + + private static void disconnectAsync(HttpURLConnection active) { + CANCEL_EXECUTOR.execute(() -> { + try { active.disconnect(); } catch (RuntimeException ignored) { } + }); + } + + private static void closeAsync(InputStream active) { + CANCEL_EXECUTOR.execute(() -> { + try { active.close(); } catch (IOException ignored) { } + }); + } + + @Override public boolean getAsBoolean() { + return cancelled.get() || (external != null && external.getAsBoolean()); + } + + private void attach(HttpURLConnection active) { + connection.set(active); + if (getAsBoolean()) disconnectAsync(active); + } + + private void detach(HttpURLConnection active) { connection.compareAndSet(active, null); } + + private void attach(InputStream active) { + input.set(active); + if (getAsBoolean()) closeAsync(active); + } + + private void detach(InputStream active) { input.compareAndSet(active, null); } + } + public static String downloadString(String url) { + return downloadString(url, null); + } + + public static String downloadString(String url, java.util.function.BooleanSupplier cancelled) { List sources = DownloadSource.INSTANCE.candidates(url); for (int i = 0; i < sources.size(); i++) { + if (isCancelled(cancelled)) return null; if (i > 0) Log.i(TAG, "retrying " + url + " via " + sources.get(i)); - Fetch fetch = fetch(sources.get(i)); + Fetch fetch = fetch(sources.get(i), cancelled); + // A cancelled fetch says nothing about the source, so it must not count as a failure. + if (isCancelled(cancelled)) return null; if (fetch.body != null) { DownloadSource.INSTANCE.succeeded(sources.get(i)); return fetch.body; @@ -53,30 +116,52 @@ public final class Downloader { /** Verify each candidate before accepting it, so a bad mirror can fall back. */ public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256, java.util.function.Consumer progress) { + return downloadFile(url, destination, resume, expectedSha256, null, progress); + } + + /** {@code cancelled} is polled while bytes arrive; a cancel stops at once and leaves the partial file for the caller. */ + public static boolean downloadFile(String url, File destination, boolean resume, String expectedSha256, + java.util.function.BooleanSupplier cancelled, + java.util.function.Consumer progress) { if (expectedSha256 != null && !expectedSha256.matches("(?i)[0-9a-f]{64}")) throw new IllegalArgumentException("Expected SHA-256 must be 64 hex characters"); - return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, progress); + return downloadCandidates(url, sources(url, expectedSha256), destination, resume, expectedSha256, cancelled, progress); } /** A third-party mirror may only serve bytes that can be checked against a digest from a direct source. */ static List sources(String url, String expectedSha256) { return expectedSha256 == null ? java.util.Collections.singletonList(url) : DownloadSource.INSTANCE.candidates(url); + } // Package-private for the local multi-source HTTP test. static boolean downloadCandidates(String original, List sources, File destination, boolean resume, String expectedSha256, java.util.function.Consumer progress) { + return downloadCandidates(original, sources, destination, resume, expectedSha256, null, progress); + } + + static boolean downloadCandidates(String original, List sources, File destination, boolean resume, + String expectedSha256, java.util.function.BooleanSupplier cancelled, + java.util.function.Consumer progress) { Identity identity = loadIdentity(destination, resume, expectedSha256); for (int i = 0; i < sources.size(); i++) { String source = sources.get(i); + if (isCancelled(cancelled)) return false; if (i > 0) Log.i(TAG, "retrying " + original + " via " + source); - Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, progress); + Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, cancelled, progress); + // A cancel is not a source failure: no other mirror, and no DownloadSource.failed(). + if (outcome == Outcome.CANCELLED) return false; if (outcome == Outcome.DONE) { - if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) { - Log.w(TAG, "checksum mismatch from " + source + "; trying another source"); - if (!discardPartial(destination, identity)) return false; - continue; + if (expectedSha256 != null) { + String actualSha256 = Hashes.sha256(destination); + if (isCancelled(cancelled)) return false; + if (!expectedSha256.equalsIgnoreCase(actualSha256)) { + Log.w(TAG, "checksum mismatch from " + source + "; trying another source"); + if (!discardPartial(destination, identity)) return false; + continue; + } } + if (isCancelled(cancelled)) return false; resumeFile(destination).delete(); DownloadSource.INSTANCE.succeeded(source); if (progress != null) progress.accept(1f); @@ -88,7 +173,11 @@ public final class Downloader { return false; } - private enum Outcome { DONE, RETRY, FATAL } + private enum Outcome { DONE, RETRY, FATAL, CANCELLED } + + private static boolean isCancelled(java.util.function.BooleanSupplier cancelled) { + return cancelled != null && cancelled.getAsBoolean(); + } private static final class Identity { private String source; @@ -156,7 +245,9 @@ public final class Downloader { } private static Outcome attempt(String url, File destination, boolean resume, Identity identity, - String expectedSha256, java.util.function.Consumer progress) { + String expectedSha256, java.util.function.BooleanSupplier cancelled, + java.util.function.Consumer progress) { + if (isCancelled(cancelled)) return Outcome.CANCELLED; HttpURLConnection connection = null; long have = resume && destination.isFile() ? destination.length() : 0; try { @@ -166,6 +257,7 @@ public final class Downloader { have = 0; } connection = open(url, STALL_TIMEOUT_MS); + if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(connection); if (have > 0) { connection.setRequestProperty("Range", "bytes=" + have + "-"); connection.setRequestProperty("If-Range", identity.etag); @@ -174,7 +266,7 @@ public final class Downloader { if (have > 0 && code == HTTP_RANGE_NOT_SATISFIABLE) { connection.disconnect(); if (!discardPartial(destination, identity)) return Outcome.RETRY; - return attempt(url, destination, false, identity, expectedSha256, progress); + return attempt(url, destination, false, identity, expectedSha256, cancelled, progress); } if (code / 100 != 2) { Log.w(TAG, url + " -> HTTP " + code); @@ -185,13 +277,13 @@ public final class Downloader { if (appending && !rangeStartsAt(connection.getHeaderField("Content-Range"), have)) { connection.disconnect(); if (!discardPartial(destination, identity)) return Outcome.RETRY; - return attempt(url, destination, false, identity, expectedSha256, progress); + return attempt(url, destination, false, identity, expectedSha256, cancelled, progress); } String etag = connection.getHeaderField("ETag"); if (have > 0 && appending && (!strongETag(etag) || !etag.equals(identity.etag))) { connection.disconnect(); if (!discardPartial(destination, identity)) return Outcome.RETRY; - return attempt(url, destination, false, identity, expectedSha256, progress); + return attempt(url, destination, false, identity, expectedSha256, cancelled, progress); } if (!appending && have > 0) { // If-Range may legitimately return full 200 when representation changed. @@ -208,26 +300,36 @@ public final class Downloader { identity.etag = strongETag(etag) ? etag : null; saveIdentity(destination, identity, expectedSha256); long written = have; - try (InputStream in = new BufferedInputStream(connection.getInputStream(), 1 << 16); + InputStream input = connection.getInputStream(); + if (cancelled instanceof Cancellation) ((Cancellation) cancelled).attach(input); + try (InputStream in = new BufferedInputStream(input, 1 << 16); OutputStream out = new FileOutputStream(destination, appending)) { byte[] buffer = new byte[1 << 16]; long lastReport = 0; for (int read = in.read(buffer); read > 0; read = in.read(buffer)) { out.write(buffer, 0, read); written += read; + if (isCancelled(cancelled)) return Outcome.CANCELLED; if (progress != null && written - lastReport > (1 << 20)) { lastReport = written; progress.accept(total > 0 ? written / (float) total : -1f); } } + } finally { + if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(input); } + if (isCancelled(cancelled)) return Outcome.CANCELLED; if (total > 0 && written < total) return Outcome.RETRY; return Outcome.DONE; } catch (Exception e) { + if (isCancelled(cancelled)) return Outcome.CANCELLED; Log.w(TAG, "download " + url, e); return Outcome.RETRY; } finally { - if (connection != null) connection.disconnect(); + if (connection != null) { + if (cancelled instanceof Cancellation) ((Cancellation) cancelled).detach(connection); + connection.disconnect(); + } } } @@ -256,9 +358,15 @@ public final class Downloader { } private static Fetch fetch(String url) { + return fetch(url, null); + } + + private static Fetch fetch(String url, java.util.function.BooleanSupplier cancelled) { HttpURLConnection connection = null; + Cancellation token = cancelled instanceof Cancellation ? (Cancellation) cancelled : null; try { connection = open(url, STALL_TIMEOUT_MS); + if (token != null) token.attach(connection); int code = connection.getResponseCode(); if (code / 100 != 2) { Log.w(TAG, url + " -> HTTP " + code); @@ -270,10 +378,14 @@ public final class Downloader { return new Fetch(new String(out.toByteArray(), StandardCharsets.UTF_8), false); } } catch (Exception e) { + if (isCancelled(cancelled)) return new Fetch(null, false); Log.w(TAG, "GET " + url, e); return new Fetch(null, false); } finally { - if (connection != null) connection.disconnect(); + if (connection != null) { + if (token != null) token.detach(connection); + connection.disconnect(); + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt index 20714b552c..094564f5c7 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt @@ -22,8 +22,8 @@ object DesktopCatalog { val icon: String, val category: String, ) - fun fetch(url: String = CATALOG_URL): List? { - val body = Downloader.downloadString(url) ?: return null + fun fetch(url: String = CATALOG_URL, cancelled: java.util.function.BooleanSupplier? = null): List? { + val body = Downloader.downloadString(url, cancelled) ?: return null return try { val json = JSONObject(body) val arr = json.getJSONArray("packages") @@ -71,9 +71,22 @@ object DesktopCatalog { } fun resumeInterrupted(context: Context, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) { + resumeInterrupted(context, null, listener) + } + + fun resumeInterrupted( + context: Context, + cancelled: Downloader.Cancellation?, + listener: LinuxRuntimeInstaller.ProgressListener?, + ): String? = synchronized(installLock) { for (entry in interrupted(context)) { Log.w(TAG, "finishing the interrupted install of ${entry.id} ${entry.version}") - install(context, entry, listener)?.let { return it } + val problem = if (cancelled == null) { + install(context, entry, listener) + } else { + install(context, entry, cancelled, listener) + } + if (problem != null) return problem } null } @@ -144,10 +157,16 @@ object DesktopCatalog { } fun install(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) { - installLocked(context, entry, listener) + installLocked(context, entry, null, listener) } - private fun installLocked(context: Context, entry: Entry, listener: LinuxRuntimeInstaller.ProgressListener?): String? { + fun install(context: Context, entry: Entry, cancelled: Downloader.Cancellation, + listener: LinuxRuntimeInstaller.ProgressListener?): String? = synchronized(installLock) { + installLocked(context, entry, cancelled, listener) + } + + private fun installLocked(context: Context, entry: Entry, cancelled: Downloader.Cancellation?, + listener: LinuxRuntimeInstaller.ProgressListener?): String? { val root = LinuxRuntime.rootDir(context) if (!root.isDirectory) return context.getString(R.string.deskpkg_runtime_missing) if (entry.sha256.isEmpty()) return context.getString(R.string.deskpkg_no_checksum, entry.name) @@ -166,14 +185,20 @@ object DesktopCatalog { if (!downloaded(download, entry)) { val downloading = context.getString(R.string.user_apps_downloading, entry.name) report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, 0) - val ok = Downloader.downloadFile(entry.url, download, true, entry.sha256) { f -> + val progress = java.util.function.Consumer { f -> report.onProgress(LinuxRuntimeInstaller.Step.DOWNLOADING, downloading, if (f < 0) -1 else Math.round(f * 100f)) } - if (!ok) return context.getString(R.string.user_apps_download_failed) + val ok = if (cancelled == null) { + Downloader.downloadFile(entry.url, download, true, entry.sha256, progress) + } else { + Downloader.downloadFile(entry.url, download, true, entry.sha256, cancelled, progress) + } + if (!ok || cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed) report.onProgress(LinuxRuntimeInstaller.Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1) val actual = Hashes.sha256(download) if (!entry.sha256.equals(actual, ignoreCase = true)) return context.getString(R.string.deskpkg_checksum_mismatch) } + if (cancelled?.getAsBoolean() == true) return context.getString(R.string.user_apps_download_failed) report.onProgress(context.getString(R.string.deskpkg_installing, entry.name), -1) when (entry.kind) { "appimage" -> { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 101fb82a15..5ddf9924e9 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -2178,6 +2178,7 @@ class SessionService : Service() { fun stop(context: Context) { if (!SessionState.running) { SessionState.stopRequested = true + SessionState.installCancellation?.cancel() return } context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP)) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index 5f3ae0154a..f29c73042c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -37,6 +37,9 @@ object SessionState { @Volatile var installing: String? = null + @Volatile + var installCancellation: com.droiddeck.launcher.core.Downloader.Cancellation? = null + @Volatile var stopRequested = false diff --git a/app/src/test/java/com/droiddeck/launcher/core/DownloaderResumeTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DownloaderResumeTest.kt index 73fd0161c6..f0c1002eb0 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/DownloaderResumeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/DownloaderResumeTest.kt @@ -6,6 +6,9 @@ import java.net.Socket import java.nio.file.Files import java.security.MessageDigest import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit import org.junit.After import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals @@ -29,6 +32,9 @@ class DownloaderResumeTest { @Volatile private var misbehave = false @Volatile private var etag: String? = "\"v1\"" @Volatile private var corrupt = false + @Volatile private var holdAfterFirstChunk = false + private var bodyStarted = CountDownLatch(1) + private var continueBody = CountDownLatch(1) @Before fun setUp() { dir = Files.createTempDirectory("downloader-resume").toFile() @@ -70,8 +76,15 @@ class DownloaderResumeTest { val start = if (from == null) "200 OK" else "206 Partial Content" val extra = if (from == null) "" else "Content-Range: bytes 0-${data.size - 1}/${data.size}\r\n" out.write("HTTP/1.1 $start\r\n${extra}${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray()) - out.write(content) - out.flush() + if (holdAfterFirstChunk) { + out.write(content, 0, 1024) + out.flush() + bodyStarted.countDown() + continueBody.await(5, TimeUnit.SECONDS) + } else { + out.write(content) + out.flush() + } } else if (from == null) { out.write("HTTP/1.1 200 OK\r\n${validator}Content-Length: ${data.size}\r\nConnection: close\r\n\r\n".toByteArray()) out.write(content, 0, cutAt) @@ -168,6 +181,48 @@ class DownloaderResumeTest { } + @Test fun cancelStopsTheTransferWithoutTryingAnotherSource() { + val first = "http://127.0.0.1:${server.localPort}/first" + val second = "http://127.0.0.1:${server.localPort}/second" + val target = File(dir, "runtime.tar.zst") + misbehave = true + val polls = java.util.concurrent.atomic.AtomicInteger() + // candidate selection and attempt each check once before the request; later checks follow chunks + val cancelled = java.util.function.BooleanSupplier { polls.incrementAndGet() > 2 } + assertFalse(Downloader.downloadCandidates(first, listOf(first, second), target, true, null, cancelled, null)) + assertEquals("a cancel must not fall back to the next source", listOf(null), requests.toList()) + assertTrue("the transfer stopped early (kept=${target.length()})", target.length() in 1 until data.size) + } + + @Test fun cancellationDisconnectsAStalledTransfer() { + val url = "http://127.0.0.1:${server.localPort}/first" + val target = File(dir, "runtime.tar.zst") + misbehave = true + holdAfterFirstChunk = true + val cancellation = Downloader.Cancellation() + val executor = Executors.newSingleThreadExecutor() + val cancelExecutor = Executors.newSingleThreadExecutor() + try { + val result = executor.submit { Downloader.downloadFile(url, target, true, null, cancellation, null) } + assertTrue("server sent the first chunk", bodyStarted.await(2, TimeUnit.SECONDS)) + val cancelled = cancelExecutor.submit { cancellation.cancel() } + cancelled.get(10, TimeUnit.SECONDS) + assertFalse("cancelled download", result.get(10, TimeUnit.SECONDS)) + assertEquals(listOf(null), requests.toList()) + } finally { + continueBody.countDown() + executor.shutdownNow() + cancelExecutor.shutdownNow() + } + } + + @Test fun aCancelBeforeTheFirstRequestSendsNothing() { + val url = "http://127.0.0.1:${server.localPort}/runtime.tar.zst" + val target = File(dir, "runtime.tar.zst") + assertFalse(Downloader.downloadFile(url, target, true, null, { true }, null)) + assertEquals(emptyList(), requests.toList()) + } + @Test fun withoutADigestOnlyTheOriginalUrlIsTried() { val url = "https://github.com/owner/repo/releases/download/v1/app.AppImage" assertEquals(listOf(url), Downloader.sources(url, null))