From 0247831c7e579716f703f9f392aecdf73a7473c0 Mon Sep 17 00:00:00 2001 From: K11MCH1 <81425424+K11MCH1@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:46:59 +0900 Subject: [PATCH] Make File Manager cancellation stop active file I/O Description: - Pass the active coroutine job into copy, move, and delete operations so synchronous file I/O observes cancellation while it is running. - Check for cancellation between copy chunks and recursive delete entries. Remove a newly created partial copy, and stage overwrites so cancelling a copy or move preserves the previous destination and move source. - Add focused tests for cancelling a copy, move fallback, and recursive delete. Why it was needed: - Accept cancelled the Compose coroutine, but FileOps continued its synchronous I/O work. The confirmation could therefore wait for a large copy or delete to finish instead of stopping it. - Copy and move must avoid replacing an existing destination with partial data when cancellation occurs. Copy and move safeguards adapted from upstream commit a74ff3d6 (#1029). Added and adjusted: - Added cancellation checks between file transfer chunks and recursive delete entries, including single-file and batch operations. - Adjusted FileManagerScreen to pass the active job to FileOps and check it during copy progress. Accept now waits for the file operation to stop before Exit, Return, or Back proceeds. - Adjusted overwrite handling to use a temporary file so cancellation preserves the previous destination; an incomplete new destination is removed and a move source remains intact. - Added tests for cancelling a new copy, a move fallback with an existing destination, and a recursive delete. The focused debug unit tests passed. Localization already included on this branch: - The earlier File Manager update added translations for Exit, Return to start, and the unavailable starting-folder message. - It also translated the cancel-operation title and warning, plus the Accept and Decline buttons, across all 32 supported locale resource sets alongside the English defaults. - These strings let localized users understand the navigation controls and the consequences of cancelling an in-progress operation. They were added in the preceding commit 7928effd; this commit makes Accept actually stop the file I/O. --- .../launcher/files/FileManagerScreen.kt | 13 ++- .../com/droiddeck/launcher/files/FileOps.kt | 79 ++++++++++++++++--- .../launcher/files/FileOpsCancellationTest.kt | 55 +++++++++++++ 3 files changed, 130 insertions(+), 17 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/files/FileOpsCancellationTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt index 2ce9a1c47b..20bc975d63 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -93,6 +93,7 @@ import androidx.compose.ui.unit.sp import com.droiddeck.launcher.session.SessionPrefs import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File @@ -316,7 +317,8 @@ fun FileManagerScreen( operationJob = scope.launch { isOperationRunning = true operationLabel = context.getString(R.string.fm_op_deleting) - val ok = withContext(Dispatchers.IO) { FileOps.delete(file) } + val job = coroutineContext[Job] + val ok = withContext(Dispatchers.IO) { FileOps.delete(file) { job?.isActive == false } } isOperationRunning = false operationJob = null loadDirectory(currentDir, resetScroll = false) @@ -342,6 +344,7 @@ fun FileManagerScreen( operationDeterminate = true operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying) isOperationRunning = true + val job = coroutineContext[Job] var applyToAll: ConflictChoice? = null var failed = 0 @@ -377,6 +380,7 @@ fun FileManagerScreen( } var lastPct = -1 val onProgress = FileOps.ProgressCallback { copied, total -> + job?.ensureActive() val pct = if (total > 0) ((copied * 100) / total).toInt() else 100 if (pct != lastPct) { lastPct = pct @@ -385,8 +389,8 @@ fun FileManagerScreen( } val target = dst val ok = withContext(Dispatchers.IO) { - if (cut) FileOps.moveWithProgress(src, target, onProgress) - else FileOps.copyWithProgress(src, target, onProgress) + if (cut) FileOps.moveWithProgress(src, target, onProgress) { job?.isActive == false } + else FileOps.copyWithProgress(src, target, onProgress) { job?.isActive == false } } if (ok) done++ else failed++ } @@ -561,10 +565,11 @@ fun FileManagerScreen( selectedPaths = emptySet() operationJob = scope.launch { isOperationRunning = true + val job = coroutineContext[Job] var failed = 0 victims.forEachIndexed { i, f -> operationLabel = context.getString(R.string.fm_op_deleting_batch, i + 1, victims.size, f.name) - if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++ + if (!withContext(Dispatchers.IO) { FileOps.delete(f) { job?.isActive == false } }) failed++ } isOperationRunning = false operationJob = null diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt b/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt index 04b83abaa2..6105411cfa 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt @@ -9,6 +9,7 @@ import java.io.FileOutputStream import java.io.IOException import java.nio.file.Files import java.util.Locale +import java.util.concurrent.CancellationException object FileOps { private const val TAG = "FileOps" @@ -24,18 +25,20 @@ object FileOps { fun isSymlink(file: File): Boolean = try { Files.isSymbolicLink(file.toPath()) } catch (e: Exception) { false } - fun delete(target: File?): Boolean { + fun delete(target: File?, isCancelled: () -> Boolean = { false }): Boolean { + if (isCancelled()) throw CancellationException("Delete cancelled: $target") if (target == null) return false if (target.isDirectory && !isSymlink(target)) { - if (!clear(target)) return false + if (!clear(target, isCancelled)) return false } + if (isCancelled()) throw CancellationException("Delete cancelled: $target") return target.delete() } - fun clear(dir: File): Boolean { + fun clear(dir: File, isCancelled: () -> Boolean = { false }): Boolean { val children = dir.listFiles() ?: return true var ok = true - for (child in children) if (!delete(child)) ok = false + for (child in children) if (!delete(child, isCancelled)) ok = false return ok } @@ -45,22 +48,25 @@ object FileOps { return f.length() } - fun moveWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean { + fun moveWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean { if (sameFile(src, dst)) return true + if (isCancelled()) return false if (!dst.exists() && src.renameTo(dst)) { progress?.onProgress(1, 1) return true } - if (!copyWithProgress(src, dst, progress)) return false + if (!copyWithProgress(src, dst, progress, isCancelled)) return false + if (isCancelled()) return false return delete(src) } - fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean { + fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean { val total = maxOf(totalSize(src), 1L) - return copyWithProgress(src, dst, longArrayOf(0), total, progress) + return copyWithProgress(src, dst, longArrayOf(0), total, progress, isCancelled) } - private fun copyWithProgress(src: File, dst: File, done: LongArray, total: Long, progress: ProgressCallback?): Boolean { + private fun copyWithProgress(src: File, dst: File, done: LongArray, total: Long, progress: ProgressCallback?, isCancelled: () -> Boolean): Boolean { + if (isCancelled()) throw CancellationException("Copy cancelled: $src") if (isSymlink(src)) return true if (sameFile(src, dst)) return true if (src.isDirectory && isWithin(dst, src)) { @@ -71,7 +77,7 @@ object FileOps { if (!dst.exists() && !dst.mkdirs()) return false var allOk = true src.list()?.forEach { name -> - if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress)) { + if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) { Log.e(TAG, "Failed to copy: ${File(src, name)}") allOk = false } @@ -81,13 +87,42 @@ object FileOps { val parent = dst.parentFile if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false val chunk = 4L * 1024 * 1024 + var staging: File? = null + var created = false + var output: java.nio.channels.FileChannel? = null try { + output = try { + java.nio.channels.FileChannel.open(dst.toPath(), java.nio.file.StandardOpenOption.WRITE, java.nio.file.StandardOpenOption.CREATE_NEW) + .also { created = true } + } catch (e: java.nio.file.FileAlreadyExistsException) { + null + } + val target = if (!created && isSymlink(dst)) dst.canonicalFile else dst + var permissions: Set? = null + if (output == null) { + if (isSymlink(target) || target.parentFile?.isDirectory != true) { + throw IOException("Destination symlink target is not a writable directory entry: $dst") + } + if (target.isDirectory) throw IOException("Destination is a directory: $target") + permissions = try { + Files.getPosixFilePermissions(target.toPath()) + } catch (e: java.nio.file.NoSuchFileException) { + null + } catch (e: UnsupportedOperationException) { + null + } + if (target.exists() && !target.canWrite()) throw IOException("Destination is not writable: $target") + val directory = Files.createTempDirectory(checkNotNull(target.absoluteFile.parentFile).toPath(), ".droiddeck-copy-") + staging = directory.toFile() + output = FileOutputStream(File(staging, "file")).channel + } FileInputStream(src).channel.use { input -> - FileOutputStream(dst).channel.use { output -> + checkNotNull(output).use { channel -> val size = input.size() var position = 0L while (position < size) { - val transferred = input.transferTo(position, minOf(chunk, size - position), output) + if (isCancelled()) throw CancellationException("Copy cancelled: $src") + val transferred = input.transferTo(position, minOf(chunk, size - position), channel) if (transferred <= 0) break position += transferred done[0] += transferred @@ -96,11 +131,29 @@ object FileOps { if (position < size) throw IOException("Incomplete copy: $position/$size bytes") } } + if (isCancelled()) throw CancellationException("Copy cancelled: $src") + staging?.let { directory -> + val copied = File(directory, "file").toPath() + if (permissions != null && Files.getPosixFilePermissions(copied) != permissions) { + Files.setPosixFilePermissions(copied, permissions) + } + if (isCancelled()) throw CancellationException("Copy cancelled: $src") + Files.move(copied, target.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE) + } return true + } catch (e: CancellationException) { + if (created) dst.delete() + throw e } catch (e: IOException) { Log.e(TAG, "Failed to copy file: $src to $dst", e) - dst.delete() + if (created) dst.delete() return false + } finally { + output?.close() + staging?.let { directory -> + File(directory, "file").delete() + directory.delete() + } } } diff --git a/app/src/test/java/com/droiddeck/launcher/files/FileOpsCancellationTest.kt b/app/src/test/java/com/droiddeck/launcher/files/FileOpsCancellationTest.kt new file mode 100644 index 0000000000..30c50558a5 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/FileOpsCancellationTest.kt @@ -0,0 +1,55 @@ +package com.droiddeck.launcher.files + +import java.io.File +import java.util.concurrent.CancellationException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class FileOpsCancellationTest { + @get:Rule val tmp = TemporaryFolder() + + @Test fun cancellingCopyRemovesAnIncompleteNewFile() { + val source = tmp.newFile("source").apply { writeBytes(ByteArray(5 * 1024 * 1024)) } + val destination = File(tmp.root, "destination") + + assertThrows(CancellationException::class.java) { + FileOps.copyWithProgress(source, destination, { _, _ -> throw CancellationException("cancel") }) + } + + assertTrue(source.exists()) + assertFalse(destination.exists()) + } + + @Test fun cancellingMoveFallbackPreservesTheSourceAndExistingDestination() { + val source = tmp.newFile("source").apply { writeText("replacement") } + val destination = tmp.newFile("destination").apply { writeText("original") } + + assertThrows(CancellationException::class.java) { + FileOps.moveWithProgress(source, destination, { _, _ -> throw CancellationException("cancel") }) + } + + assertEquals("replacement", source.readText()) + assertEquals("original", destination.readText()) + } + + @Test fun cancellingRecursiveDeleteStopsBeforeTheNextFile() { + val directory = tmp.newFolder("directory") + repeat(3) { File(directory, "file-$it").writeText("content") } + var checks = 0 + + assertThrows(CancellationException::class.java) { + FileOps.delete(directory) { ++checks > 3 } + } + + assertTrue(directory.exists()) + assertEquals(2, directory.listFiles()?.size) + } +}