mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
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.
This commit is contained in:
1 parent
1eb1e154ab
commit
0247831c7e
3 files changed
+130
-17
No files matched your search
@@ -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
|
||||
|
||||
@@ -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<java.nio.file.attribute.PosixFilePermission>? = 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user