From cb153ece872485a5f46ee630af1a13e571b8d1fd Mon Sep 17 00:00:00 2001 From: K11MCH1 <81425424+K11MCH1@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:29:18 +0900 Subject: [PATCH] Guard File Manager jobs and clean up cancelled copies Description: - Reject bulk delete while another operation is active. Check current operation state at action time, and clear operationJob on completion only when the finishing coroutine still owns it. - Retain the requested Return directory even when it is unavailable, so Return can display the existing unavailable-directory message while browsing starts from the valid fallback. - Observe cancellation during the recursive size scan before copying. Remove destination directories created by a cancelled copy, while preserving existing destination directories and ordinary copy-failure behavior. - After a move's copy commits, finish deleting the source instead of reporting cancellation with both copies left behind. Preserve cancellation before copying and the existing copy-failure path. - Log permission-restoration failures in staged copies and continue publishing the copied file. - Exercise cancellation signals during transfers and size scans, directory cleanup, preservation of existing directories, and committed move completion without leftover staging entries. Why it was needed: - Overlapping operations could replace the tracked job, and an older completion could clear that reference, allowing navigation before the remaining work stopped. - Cancellation could leave new partial directory trees or wait through the size scan. Late move cancellation could leave the source behind after publishing its replacement. - A missing launch directory suppressed Return entirely, and a permission-restoration error could prevent an otherwise successful overwrite. Validation: - Debug Kotlin compilation passed with skipRust=true. - Focused FileOps cancellation, copy, and link suites: 17 passed, 10 platform-dependent cases skipped on Windows, no failures. - git diff --check passed. --- .../launcher/files/FileManagerScreen.kt | 28 ++++---- .../com/droiddeck/launcher/files/FileOps.kt | 43 ++++++++---- .../launcher/files/FileOpsCancellationTest.kt | 70 ++++++++++++++++++- .../launcher/files/FileOpsCopyTest.kt | 14 ++-- 4 files changed, 119 insertions(+), 36 deletions(-) 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 72398b63f0..be804fd0a5 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -128,7 +128,7 @@ fun FileManagerScreen( initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0") } val launchDir = remember(initialDir, pickMode) { - initialDir?.takeIf { it.isDirectory && !pickMode } + initialDir?.takeIf { !pickMode } } var currentDir by remember { mutableStateOf(rootDir) } val initialRoot = remember(rootDir) { @@ -236,7 +236,8 @@ fun FileManagerScreen( LaunchedEffect(Unit) { loadDirectory(rootDir) } val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true - val operationActive = isOperationRunning || operationJob?.isCompleted == false || cancelledJob?.isCompleted == false + fun isOperationActive() = isOperationRunning || operationJob?.isCompleted == false || cancelledJob?.isCompleted == false + val operationActive = isOperationActive() fun navigate(action: FileManagerNavigation) { when (action) { @@ -252,7 +253,7 @@ fun FileManagerScreen( fun requestNavigation(action: FileManagerNavigation) { if (cancellingNavigation) return - if (operationActive) pendingNavigation = action else navigate(action) + if (isOperationActive()) pendingNavigation = action else navigate(action) } BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot) { @@ -313,14 +314,14 @@ fun FileManagerScreen( } fun performDelete(file: File) { - if (operationActive) return + if (isOperationActive()) return operationJob = scope.launch { isOperationRunning = true operationLabel = context.getString(R.string.fm_op_deleting) val job = coroutineContext[Job] val ok = withContext(Dispatchers.IO) { FileOps.delete(file) { job?.isActive == false } } isOperationRunning = false - operationJob = null + if (operationJob === job) operationJob = null loadDirectory(currentDir, resetScroll = false) if (!ok) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_SHORT).show() } @@ -335,7 +336,7 @@ fun FileManagerScreen( fun performPaste() { val sources = clipboardFiles - if (sources.isEmpty() || isOperationRunning || operationJob?.isActive == true || cancelledJob?.isCompleted == false) return + if (sources.isEmpty() || isOperationActive()) return val dstDir = currentDir val cut = isCutOperation @@ -397,7 +398,7 @@ fun FileManagerScreen( isOperationRunning = false operationDeterminate = false - operationJob = null + if (operationJob === job) operationJob = null clipboardFiles = emptyList() isCutOperation = false selectionMode = false @@ -415,36 +416,38 @@ fun FileManagerScreen( } fun performRename(file: File, newName: String) { - if (operationActive) return + if (isOperationActive()) return val target = File(file.parentFile, newName) if (target.exists()) { Toast.makeText(context, context.getString(R.string.fm_already_exists, newName), Toast.LENGTH_SHORT).show() return } operationJob = scope.launch { + val job = coroutineContext[Job] isOperationRunning = true operationLabel = context.getString(R.string.fm_op_renaming) val ok = withContext(Dispatchers.IO) { file.renameTo(target) } isOperationRunning = false - operationJob = null + if (operationJob === job) operationJob = null loadDirectory(currentDir, resetScroll = false) if (!ok) Toast.makeText(context, R.string.fm_rename_failed, Toast.LENGTH_SHORT).show() } } fun createFolder(parent: File, name: String) { - if (operationActive) return + if (isOperationActive()) return val target = File(parent, name) if (target.exists()) { Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show() return } operationJob = scope.launch { + val job = coroutineContext[Job] isOperationRunning = true operationLabel = context.getString(R.string.fm_op_creating_folder) val ok = withContext(Dispatchers.IO) { target.mkdirs() } isOperationRunning = false - operationJob = null + if (operationJob === job) operationJob = null loadDirectory(currentDir, resetScroll = false) if (!ok) Toast.makeText(context, R.string.fm_create_folder_failed, Toast.LENGTH_SHORT).show() } @@ -560,6 +563,7 @@ fun FileManagerScreen( }, confirmButton = { TextButton(onClick = { + if (isOperationActive()) return@TextButton pendingBulkDelete = emptyList() selectionMode = false selectedPaths = emptySet() @@ -572,7 +576,7 @@ fun FileManagerScreen( if (!withContext(Dispatchers.IO) { FileOps.delete(f) { job?.isActive == false } }) failed++ } isOperationRunning = false - operationJob = null + if (operationJob === job) operationJob = null loadDirectory(currentDir, resetScroll = false) if (failed > 0) { Toast.makeText(context, context.resources.getQuantityString(R.plurals.fm_delete_some_failed, failed, failed), Toast.LENGTH_SHORT).show() 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 c14bb6eddd..05d467ef51 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt @@ -42,9 +42,10 @@ object FileOps { return ok } - fun totalSize(f: File?): Long { + fun totalSize(f: File?, isCancelled: () -> Boolean = { false }): Long { + if (isCancelled()) throw CancellationException("Size scan cancelled: $f") if (f == null || !f.exists() || isSymlink(f)) return 0 - if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it) } ?: 0 + if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it, isCancelled) } ?: 0 return f.length() } @@ -56,12 +57,12 @@ object FileOps { return true } if (!copyWithProgress(src, dst, progress, isCancelled)) return false - if (isCancelled()) return false - return delete(src, isCancelled) + // Once the destination is committed, finish deleting the source. + return delete(src) } fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean { - val total = maxOf(totalSize(src), 1L) + val total = maxOf(totalSize(src, isCancelled), 1L) return copyWithProgress(src, dst, longArrayOf(0), total, progress, isCancelled) } @@ -74,15 +75,23 @@ object FileOps { return false } if (src.isDirectory) { - 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, isCancelled)) { - Log.e(TAG, "Failed to copy: ${File(src, name)}") - allOk = false + val created = if (dst.exists()) false else { + if (!dst.mkdirs()) return false + true + } + try { + var allOk = true + src.list()?.forEach { name -> + if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) { + Log.e(TAG, "Failed to copy: ${File(src, name)}") + allOk = false + } } + return allOk + } catch (e: CancellationException) { + if (created) delete(dst) + throw e } - return allOk } val parent = dst.parentFile if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false @@ -134,8 +143,14 @@ object FileOps { } staging?.let { directory -> val copied = File(directory, "file").toPath() - if (permissions != null && Files.getPosixFilePermissions(copied) != permissions) { - Files.setPosixFilePermissions(copied, permissions) + if (permissions != null) { + try { + if (Files.getPosixFilePermissions(copied) != permissions) { + Files.setPosixFilePermissions(copied, permissions) + } + } catch (e: Exception) { + Log.w(TAG, "Failed to restore destination permissions: $target", e) + } } if (isCancelled()) throw java.util.concurrent.CancellationException("Copy cancelled: $src") Files.move(copied, target.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE) diff --git a/app/src/test/java/com/droiddeck/launcher/files/FileOpsCancellationTest.kt b/app/src/test/java/com/droiddeck/launcher/files/FileOpsCancellationTest.kt index 30c50558a5..8ba15591e4 100644 --- a/app/src/test/java/com/droiddeck/launcher/files/FileOpsCancellationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/files/FileOpsCancellationTest.kt @@ -19,9 +19,10 @@ class FileOpsCancellationTest { @Test fun cancellingCopyRemovesAnIncompleteNewFile() { val source = tmp.newFile("source").apply { writeBytes(ByteArray(5 * 1024 * 1024)) } val destination = File(tmp.root, "destination") + var cancelled = false assertThrows(CancellationException::class.java) { - FileOps.copyWithProgress(source, destination, { _, _ -> throw CancellationException("cancel") }) + FileOps.copyWithProgress(source, destination, { _, _ -> cancelled = true }) { cancelled } } assertTrue(source.exists()) @@ -31,15 +32,80 @@ class FileOpsCancellationTest { @Test fun cancellingMoveFallbackPreservesTheSourceAndExistingDestination() { val source = tmp.newFile("source").apply { writeText("replacement") } val destination = tmp.newFile("destination").apply { writeText("original") } + var cancelled = false assertThrows(CancellationException::class.java) { - FileOps.moveWithProgress(source, destination, { _, _ -> throw CancellationException("cancel") }) + FileOps.moveWithProgress(source, destination, { _, _ -> cancelled = true }) { cancelled } } assertEquals("replacement", source.readText()) assertEquals("original", destination.readText()) } + @Test fun aCommittedMoveFinishesRemovingTheSourceDespiteCancellation() { + val source = tmp.newFile("source").apply { writeText("replacement") } + val destination = tmp.newFile("destination").apply { writeText("original") } + val isCancelled = { destination.readText() == "replacement" } + + assertTrue(FileOps.moveWithProgress(source, destination, null, isCancelled)) + + assertTrue(isCancelled()) + assertEquals("replacement", destination.readText()) + assertFalse(source.exists()) + assertEquals(setOf("destination"), tmp.root.list()!!.toSet()) + } + + @Test fun cancellingTheSizeScanStopsBeforeCreatingTheDestination() { + val source = tmp.newFolder("source") + repeat(3) { File(source, "file-$it").writeText("content") } + val destination = File(tmp.root, "destination") + var checks = 0 + + assertThrows(CancellationException::class.java) { + FileOps.copyWithProgress(source, destination, null) { + assertFalse(destination.exists()) + ++checks > 2 + } + } + + assertEquals(3, checks) + assertFalse(destination.exists()) + assertEquals(3, source.listFiles()?.size) + } + + @Test fun cancellingCopyRemovesANewDestinationDirectory() { + val source = tmp.newFolder("source") + val payload = File(source, "nested/payload").apply { + parentFile!!.mkdirs() + writeText("content") + } + val destination = File(tmp.root, "destination") + + assertThrows(CancellationException::class.java) { + FileOps.copyWithProgress(source, destination, { _, _ -> throw CancellationException("cancel") }) + } + + assertEquals("content", payload.readText()) + assertFalse(destination.exists()) + } + + @Test fun cancellingCopyPreservesAnExistingDestinationDirectory() { + val source = tmp.newFolder("source") + File(source, "nested/payload").apply { + parentFile!!.mkdirs() + writeText("replacement") + } + val destination = tmp.newFolder("destination") + val existing = File(destination, "keep").apply { writeText("original") } + + assertThrows(CancellationException::class.java) { + FileOps.copyWithProgress(source, destination, { _, _ -> throw CancellationException("cancel") }) + } + + assertEquals("original", existing.readText()) + assertEquals(setOf("keep"), destination.list()!!.toSet()) + } + @Test fun cancellingRecursiveDeleteStopsBeforeTheNextFile() { val directory = tmp.newFolder("directory") repeat(3) { File(directory, "file-$it").writeText("content") } diff --git a/app/src/test/java/com/droiddeck/launcher/files/FileOpsCopyTest.kt b/app/src/test/java/com/droiddeck/launcher/files/FileOpsCopyTest.kt index ac13ac7814..e92ca2aec7 100644 --- a/app/src/test/java/com/droiddeck/launcher/files/FileOpsCopyTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/files/FileOpsCopyTest.kt @@ -53,27 +53,25 @@ class FileOpsCopyTest { assertEquals("replacement", src.readText()) } - @Test fun cancellingStopsATreeOfEmptyFiles() { + @Test fun cancellingRemovesANewTreeOfEmptyFiles() { val src = tmp.newFolder("source") for (name in listOf("a", "b", "c")) File(src, name).createNewFile() val dst = File(tmp.root, "dest") - var checks = 0 assertThrows(CancellationException::class.java) { - FileOps.copyWithProgress(src, dst, null) { checks++ > 1 } + FileOps.copyWithProgress(src, dst, null) { dst.list()?.isNotEmpty() == true } } - assertEquals(1, dst.list()!!.size) + assertFalse(dst.exists()) assertEquals(3, src.list()!!.size) } - @Test fun cancellingStopsATreeOfEmptyFolders() { + @Test fun cancellingRemovesANewTreeOfEmptyFolders() { val src = tmp.newFolder("source") for (name in listOf("a", "b", "c")) File(src, name).mkdir() val dst = File(tmp.root, "dest") - var checks = 0 assertThrows(CancellationException::class.java) { - FileOps.copyWithProgress(src, dst, null) { checks++ > 1 } + FileOps.copyWithProgress(src, dst, null) { dst.list()?.isNotEmpty() == true } } - assertEquals(1, dst.list()!!.size) + assertFalse(dst.exists()) } @Test fun aCompletedCopyReplacesTheDestination() {