From 3f2aea4d081ae87c422026ec6d6a15b1f6815b3a Mon Sep 17 00:00:00 2001 From: K11MCH1 <81425424+K11MCH1@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:56:39 +0900 Subject: [PATCH 1/5] Add File Manager Return and Exit navigation Description: - Add an Exit button at the right end of the File Manager toolbar. It finishes the File Manager activity from any directory. - Remember the directory supplied when Game files or Proton prefix opens the File Manager. Show a Return to start button in the toolbar for those launches, and use it to reopen that directory after the user switches storage locations or browses elsewhere. - When returning, restore the starting storage root and close search or favorites views. Show a message if the starting directory is no longer available. - Add accessible labels for both buttons while retaining the existing toolbar actions and File Manager styling. Why it was needed: - Exiting previously required repeatedly navigating back through directories to the original location. - Switching from the game's initial directory to Internal storage offered no direct route back, leaving users to find the path manually through Linux system storage. --- .../launcher/files/FileManagerActivity.kt | 2 +- .../launcher/files/FileManagerScreen.kt | 39 +++++++++++++++++-- app/src/main/res/values/strings.xml | 3 ++ 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt index 27cb9dbcea..1425a78e7e 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerActivity.kt @@ -29,7 +29,7 @@ class FileManagerActivity : ComponentActivity() { setContent { DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) { Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) { - FileManagerScreen(initialDir = initialDir) + FileManagerScreen(initialDir = initialDir, onExit = { finish() }) } } } 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 03b4aa2771..6f02927e9d 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -28,6 +28,8 @@ import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ExitToApp +import androidx.compose.material.icons.automirrored.filled.KeyboardReturn import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.ContentPaste import androidx.compose.material.icons.filled.CreateNewFolder @@ -104,6 +106,7 @@ fun FileManagerScreen( initialDir: File? = null, pickerTitle: String? = null, onPick: ((File) -> Unit)? = null, + onExit: (() -> Unit)? = null, ) { val context = LocalContext.current val scope = rememberCoroutineScope() @@ -117,12 +120,14 @@ fun FileManagerScreen( val pickPrefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) } val browsePrefs = pickPrefs - val rootDir = remember { + val rootDir = remember(initialDir) { initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0") } - + val launchDir = remember(initialDir, pickMode) { + initialDir?.takeIf { it.isDirectory && !pickMode } + } var currentDir by remember { mutableStateOf(rootDir) } - var currentRoot by remember { + val initialRoot = remember(rootDir) { val abs = rootDir.absolutePath val internal = "/storage/emulated/0" val vol = when { @@ -138,8 +143,9 @@ fun FileManagerScreen( ?: rootDir } } - mutableStateOf(vol) + vol } + var currentRoot by remember { mutableStateOf(initialRoot) } var entries by remember { mutableStateOf(listOf()) } var selectedEntry by remember { mutableStateOf(null) } var showMenuFor by remember { mutableStateOf(null) } @@ -208,6 +214,19 @@ fun FileManagerScreen( loadDirectory(dir) } + fun returnToStart() { + val dir = launchDir ?: return + if (!dir.isDirectory) { + Toast.makeText(context, R.string.fm_start_unavailable, Toast.LENGTH_SHORT).show() + return + } + showFavorites = false + showSearch = false + searchQuery = "" + currentRoot = initialRoot + loadDirectory(dir) + } + LaunchedEffect(Unit) { loadDirectory(rootDir) } BackHandler(enabled = showFavorites || currentDir != currentRoot) { @@ -669,6 +688,13 @@ fun FileManagerScreen( ) } + if (launchDir != null) { + IconButton(onClick = { returnToStart() }) { + Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary) + } + if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp)) + } + if (!showFavorites) { if (!pickMode) { OutlinedButton( @@ -744,6 +770,11 @@ fun FileManagerScreen( Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant) } } + if (!pickMode && onExit != null) { + IconButton(onClick = onExit) { + Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant) + } + } } if (showSearch && !showFavorites) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 830e66378c..e64eb7e7dd 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1543,6 +1543,9 @@ Skip Select this folder Back + Exit + Return to start + Starting folder is no longer available %1$s is mounted but not readable right now List view Grid view From 1eb1e154ab75477fddb66bfb79e0f10d81a48d5d Mon Sep 17 00:00:00 2001 From: K11MCH1 <81425424+K11MCH1@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:27:07 +0900 Subject: [PATCH 2/5] Confirm navigation during File Manager operations Description: - Ask for confirmation when Exit, Return to start, Android Back, or the parent-folder controls are used while a file operation is active. - Accept cancels the active job and waits for it to finish before navigating; Decline keeps the File Manager open and lets the operation continue. - Track single-file operations as jobs and handle Back from the file picker root through the same navigation guard. - Translate the existing Exit, Return, and unavailable-folder labels plus the new confirmation dialog in all 32 supported locale resource sets. Why it was needed: - Leaving the File Manager while a batch copy, move, or delete is running cancels its composition-bound coroutine, which can stop the batch after only some files are processed without a clear result. - The new File Manager controls previously appeared in English when the app was set to another supported language. --- .../launcher/files/FileManagerScreen.kt | 101 ++++++++++++++---- .../launcher/files/FilePickerActivity.kt | 1 + app/src/main/res/values-ar/strings.xml | 7 ++ app/src/main/res/values-b+es+419/strings.xml | 7 ++ app/src/main/res/values-bg/strings.xml | 7 ++ app/src/main/res/values-cs/strings.xml | 7 ++ app/src/main/res/values-da/strings.xml | 7 ++ app/src/main/res/values-de/strings.xml | 7 ++ app/src/main/res/values-el/strings.xml | 7 ++ app/src/main/res/values-es/strings.xml | 7 ++ app/src/main/res/values-fi/strings.xml | 7 ++ app/src/main/res/values-fr/strings.xml | 7 ++ app/src/main/res/values-hi/strings.xml | 7 ++ app/src/main/res/values-hu/strings.xml | 7 ++ app/src/main/res/values-in/strings.xml | 7 ++ app/src/main/res/values-it/strings.xml | 7 ++ app/src/main/res/values-ja/strings.xml | 7 ++ app/src/main/res/values-ko/strings.xml | 7 ++ app/src/main/res/values-ms/strings.xml | 7 ++ app/src/main/res/values-nb/strings.xml | 7 ++ app/src/main/res/values-nl/strings.xml | 7 ++ app/src/main/res/values-pl/strings.xml | 7 ++ app/src/main/res/values-pt-rPT/strings.xml | 7 ++ app/src/main/res/values-pt/strings.xml | 7 ++ app/src/main/res/values-ro/strings.xml | 7 ++ app/src/main/res/values-ru/strings.xml | 7 ++ app/src/main/res/values-sv/strings.xml | 7 ++ app/src/main/res/values-th/strings.xml | 7 ++ app/src/main/res/values-tr/strings.xml | 7 ++ app/src/main/res/values-uk/strings.xml | 7 ++ app/src/main/res/values-vi/strings.xml | 7 ++ app/src/main/res/values-zh-rCN/strings.xml | 7 ++ app/src/main/res/values-zh-rHK/strings.xml | 7 ++ app/src/main/res/values-zh-rTW/strings.xml | 7 ++ app/src/main/res/values/strings.xml | 4 + 35 files changed, 309 insertions(+), 21 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 6f02927e9d..2ce9a1c47b 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -92,11 +92,14 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.session.SessionPrefs import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import java.util.Date +private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK } + @OptIn(ExperimentalMaterial3Api::class) @Composable fun FileManagerScreen( @@ -156,8 +159,10 @@ fun FileManagerScreen( var pendingConflict by remember { mutableStateOf(null) } var conflictChoice by remember { mutableStateOf(null) } var conflictApplyToAll by remember { mutableStateOf(false) } - var operationJob by remember { mutableStateOf(null) } - var cancelledJob by remember { mutableStateOf(null) } + var operationJob by remember { mutableStateOf(null) } + var cancelledJob by remember { mutableStateOf(null) } + var pendingNavigation by remember { mutableStateOf(null) } + var cancellingNavigation by remember { mutableStateOf(false) } var pendingBulkDelete by remember { mutableStateOf>(emptyList()) } var searchQuery by remember { mutableStateOf("") } val visibleEntries = if (searchQuery.isBlank()) entries @@ -183,7 +188,7 @@ fun FileManagerScreen( var showFavorites by remember { mutableStateOf(false) } var favTick by remember { mutableIntStateOf(0) } - var listingJob by remember { mutableStateOf(null) } + var listingJob by remember { mutableStateOf(null) } fun loadDirectory(dir: File, resetScroll: Boolean = true) { currentDir = dir @@ -229,19 +234,67 @@ fun FileManagerScreen( LaunchedEffect(Unit) { loadDirectory(rootDir) } - BackHandler(enabled = showFavorites || currentDir != currentRoot) { - if (showFavorites) { - showFavorites = false - return@BackHandler + val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true + val operationActive = isOperationRunning || operationJob?.isCompleted == false || cancelledJob?.isCompleted == false + + fun navigate(action: FileManagerNavigation) { + when (action) { + FileManagerNavigation.EXIT -> onExit?.invoke() + FileManagerNavigation.RETURN_TO_START -> returnToStart() + FileManagerNavigation.BACK -> { + if (showFavorites) showFavorites = false + else if (canGoUp) currentDir.parentFile?.let { loadDirectory(it) } + else onExit?.invoke() + } } - val parent = currentDir.parentFile - if (parent != null && parent.exists()) loadDirectory(parent) } - val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true - fun goUp() { - val parent = currentDir.parentFile - if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent) + fun requestNavigation(action: FileManagerNavigation) { + if (cancellingNavigation) return + if (operationActive) pendingNavigation = action else navigate(action) + } + + BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot) { + requestNavigation(FileManagerNavigation.BACK) + } + + if (pendingNavigation != null) { + OutlinedAlertDialog( + onDismissRequest = { pendingNavigation = null }, + title = { Text(stringResource(R.string.fm_cancel_operation_title)) }, + text = { Text(stringResource(R.string.fm_cancel_operation_confirmation)) }, + confirmButton = { + TextButton(onClick = { + val action = pendingNavigation ?: return@TextButton + pendingNavigation = null + val job = operationJob?.takeUnless(Job::isCompleted) + ?: cancelledJob?.takeUnless(Job::isCompleted) + if (job == null) { + navigate(action) + } else { + cancellingNavigation = true + cancelledJob = job + job.cancel() + scope.launch { + job.join() + if (operationJob === job) operationJob = null + if (cancelledJob === job) cancelledJob = null + pendingConflict = null + isOperationRunning = false + operationDeterminate = false + if (action != FileManagerNavigation.EXIT) loadDirectory(currentDir, resetScroll = false) + cancellingNavigation = false + navigate(action) + } + } + }) { Text(stringResource(R.string.fm_accept)) } + }, + dismissButton = { + TextButton(onClick = { pendingNavigation = null }) { + Text(stringResource(R.string.fm_decline)) + } + }, + ) } fun uniqueDestination(dir: File, name: String): File { @@ -259,11 +312,13 @@ fun FileManagerScreen( } fun performDelete(file: File) { - scope.launch { + if (operationActive) return + operationJob = scope.launch { isOperationRunning = true operationLabel = context.getString(R.string.fm_op_deleting) val ok = withContext(Dispatchers.IO) { FileOps.delete(file) } isOperationRunning = false + operationJob = null loadDirectory(currentDir, resetScroll = false) if (!ok) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_SHORT).show() } @@ -356,32 +411,36 @@ fun FileManagerScreen( } fun performRename(file: File, newName: String) { + if (operationActive) 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 } - scope.launch { + operationJob = scope.launch { isOperationRunning = true operationLabel = context.getString(R.string.fm_op_renaming) val ok = withContext(Dispatchers.IO) { file.renameTo(target) } isOperationRunning = false + 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 val target = File(parent, name) if (target.exists()) { Toast.makeText(context, context.getString(R.string.fm_already_exists, name), Toast.LENGTH_SHORT).show() return } - scope.launch { + operationJob = scope.launch { isOperationRunning = true operationLabel = context.getString(R.string.fm_op_creating_folder) val ok = withContext(Dispatchers.IO) { target.mkdirs() } isOperationRunning = false + operationJob = null loadDirectory(currentDir, resetScroll = false) if (!ok) Toast.makeText(context, R.string.fm_create_folder_failed, Toast.LENGTH_SHORT).show() } @@ -598,7 +657,7 @@ fun FileManagerScreen( .background(MaterialTheme.colorScheme.surfaceContainer) .padding(horizontal = 8.dp, vertical = 6.dp), ) { - IconButton(onClick = { goUp() }, enabled = canGoUp) { + IconButton(onClick = { requestNavigation(FileManagerNavigation.BACK) }, enabled = canGoUp && !cancellingNavigation) { Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary) } @@ -689,7 +748,7 @@ fun FileManagerScreen( } if (launchDir != null) { - IconButton(onClick = { returnToStart() }) { + IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation) { Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary) } if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp)) @@ -771,7 +830,7 @@ fun FileManagerScreen( } } if (!pickMode && onExit != null) { - IconButton(onClick = onExit) { + IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation) { Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant) } } @@ -1014,7 +1073,7 @@ fun FileManagerScreen( contentPadding = PaddingValues(8.dp), ) { if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) { - ParentFolderRow(compact = compactRows, onTap = { goUp() }) + ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) }) } items(shownEntries, key = { it.absolutePath }) { file -> val isFav = remember(file.absolutePath, favTick) { @@ -1080,7 +1139,7 @@ fun FileManagerScreen( } else LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) { if (canGoUp) item(key = "..") { - ParentFolderRow(compact = compactRows, onTap = { goUp() }) + ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) }) } if (entries.isEmpty()) { item { diff --git a/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt b/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt index 6fd89fa99f..498ec504e8 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FilePickerActivity.kt @@ -50,6 +50,7 @@ class FilePickerActivity : ComponentActivity() { setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath)) finish() }, + onExit = { finish() }, ) } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 27109fd066..56a80316fd 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1579,6 +1579,13 @@ تخطّي اختيار هذا المجلد رجوع + خروج + العودة إلى المجلد الأول + لم يعد المجلد الأول متاحًا + إلغاء العملية؟ + سيتم إلغاء العملية. هل أنت متأكد؟ + موافق + رفض تم تركيب %1$s لكن تتعذّر قراءته حاليًا عرض القائمة عرض الشبكة diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 8988e18d1c..40b9c5239c 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1572,6 +1572,13 @@ Omitir Seleccionar esta carpeta Atrás + Salir + Volver a la carpeta inicial + La carpeta inicial ya no está disponible + ¿Cancelar la operación? + La operación se cancelará. ¿Estás seguro? + Aceptar + Rechazar %1$s está montado, pero ahora mismo no se puede leer Vista de lista Vista de cuadrícula diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index d48d3a0cab..cf4a7b5167 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -1503,6 +1503,13 @@ Пропускане Избор на тази папка Назад + Изход + Връщане в началната папка + Началната папка вече не е достъпна + Отмяна на операцията? + Операцията ще бъде отменена. Сигурни ли сте? + Приемам + Отказвам %1$s е монтирано, но в момента не може да се прочете Изглед като списък Изглед като мрежа diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index e3b3bc3c0f..da649de32a 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1541,6 +1541,13 @@ Přeskočit Vybrat tuto složku Zpět + Ukončit + Zpět do výchozí složky + Výchozí složka již není dostupná + Zrušit operaci? + Operace bude zrušena. Opravdu chcete pokračovat? + Přijmout + Odmítnout %1$s je připojeno, ale momentálně není čitelné Zobrazení seznamu Zobrazení mřížky diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 85062308d1..5f50002ece 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1503,6 +1503,13 @@ Spring over Vælg denne mappe Tilbage + Afslut + Tilbage til startmappen + Startmappen er ikke længere tilgængelig + Annuller handlingen? + Handlingen bliver annulleret. Er du sikker? + Accepter + Afvis %1$s er monteret, men kan ikke læses lige nu Listevisning Gittervisning diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 18199e20eb..284ff28d13 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1492,6 +1492,13 @@ Überspringen Diesen Ordner auswählen Zurück + Beenden + Zurück zum Startordner + Startordner ist nicht mehr verfügbar + Vorgang abbrechen? + Der Vorgang wird abgebrochen. Bist du sicher? + Akzeptieren + Ablehnen %1$s ist eingebunden, aber derzeit nicht lesbar Listenansicht Rasteransicht diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 0ff07c465a..6834955392 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1503,6 +1503,13 @@ Παράλειψη Επιλογή αυτού του φακέλου Πίσω + Έξοδος + Επιστροφή στον αρχικό φάκελο + Ο αρχικός φάκελος δεν είναι πλέον διαθέσιμος + Ακύρωση ενέργειας; + Η ενέργεια θα ακυρωθεί. Είστε σίγουροι; + Αποδοχή + Απόρριψη Το %1$s είναι προσαρτημένο αλλά δεν είναι αναγνώσιμο αυτή τη στιγμή Προβολή λίστας Προβολή πλέγματος diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 0373f7ab33..26e175bd9c 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1519,6 +1519,13 @@ Omitir Seleccionar esta carpeta Atrás + Salir + Volver a la carpeta inicial + La carpeta inicial ya no está disponible + ¿Cancelar la operación? + La operación se cancelará. ¿Estás seguro? + Aceptar + Rechazar %1$s está montado, pero ahora mismo no se puede leer Vista de lista Vista de cuadrícula diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 2a1f62a030..fa670786d5 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1503,6 +1503,13 @@ Ohita Valitse tämä kansio Takaisin + Poistu + Palaa aloituskansioon + Aloituskansio ei ole enää käytettävissä + Peruutetaanko toiminto? + Toiminto peruutetaan. Oletko varma? + Hyväksy + Hylkää %1$s on liitetty, mutta ei ole luettavissa juuri nyt Luettelonäkymä Ruudukkonäkymä diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index d151596fb3..dbc58cad60 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1519,6 +1519,13 @@ Ignorer Sélectionner ce dossier Retour + Quitter + Revenir au dossier de départ + Le dossier de départ est indisponible + Annuler l’opération ? + Cette opération sera annulée. Confirmez-vous ? + Accepter + Refuser %1$s est monté, mais illisible pour le moment Vue en liste Vue en grille diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index af68d4524f..7a93b2ce17 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1503,6 +1503,13 @@ छोड़ें यह फ़ोल्डर चुनें बैक + बाहर निकलें + शुरुआती फ़ोल्डर पर लौटें + शुरुआती फ़ोल्डर अब उपलब्ध नहीं है + कार्रवाई रद्द करें? + कार्रवाई रद्द कर दी जाएगी। क्या आप सुनिश्चित हैं? + स्वीकार करें + अस्वीकार करें %1$s माउंट है लेकिन अभी पढ़ा नहीं जा सकता लिस्ट व्यू ग्रिड व्यू diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 67f33c54d3..81d46e4506 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -1503,6 +1503,13 @@ Kihagyás Ennek a mappának a kiválasztása Vissza + Kilépés + Vissza a kezdőmappába + A kezdőmappa már nem érhető el + Művelet megszakítása? + A művelet megszakad. Biztos benne? + Elfogadom + Elutasítom A %1$s csatolva van, de jelenleg nem olvasható Listanézet Rácsnézet diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 6a0371282f..58964ebdc9 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -1484,6 +1484,13 @@ Lewati Pilih folder ini Kembali + Keluar + Kembali ke folder awal + Folder awal tidak lagi tersedia + Batalkan operasi? + Operasi akan dibatalkan. Anda yakin? + Terima + Tolak %1$s terpasang tetapi tidak dapat dibaca saat ini Tampilan daftar Tampilan kisi diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 6cf24b19d3..8e83dad4f1 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1511,6 +1511,13 @@ Salta Seleziona questa cartella Indietro + Esci + Torna alla cartella iniziale + La cartella iniziale non è più disponibile + Annullare operazione? + Questa operazione verrà annullata. Confermi? + Accetta + Rifiuta %1$s: montata ma al momento non leggibile Visualizzazione elenco Visualizzazione griglia diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index a1f640853b..e5d501ed22 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1484,6 +1484,13 @@ スキップ このフォルダを選択 戻る + 終了 + 開始フォルダーに戻る + 開始フォルダーは利用できなくなりました + 操作をキャンセルしますか? + 操作がキャンセルされます。よろしいですか? + 承諾 + 拒否 %1$sはマウントされていますが、現在読み取れません リスト表示 グリッド表示 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index ffd0d5a7a3..1fbf10b454 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1484,6 +1484,13 @@ 건너뛰기 이 폴더 선택 뒤로 + 종료 + 시작 폴더로 돌아가기 + 시작 폴더를 더 이상 사용할 수 없습니다 + 작업을 취소할까요? + 작업이 취소됩니다. 계속하시겠습니까? + 수락 + 거절 %1$s이(가) 마운트되었지만 지금은 읽을 수 없습니다 목록 보기 격자 보기 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 42d9888b70..7ba18fb321 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -1484,6 +1484,13 @@ Langkau Pilih folder ini Kembali + Keluar + Kembali ke folder asal + Folder asal tidak lagi tersedia + Batalkan operasi? + Operasi akan dibatalkan. Adakah anda pasti? + Terima + Tolak %1$s dilekapkan tetapi tidak dapat dibaca sekarang Paparan senarai Paparan grid diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 133d053781..40d10cdb78 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -1503,6 +1503,13 @@ Hopp over Velg denne mappen Tilbake + Avslutt + Tilbake til startmappen + Startmappen er ikke lenger tilgjengelig + Avbryt operasjonen? + Operasjonen blir avbrutt. Er du sikker? + Godta + Avslå %1$s er montert, men ikke lesbar akkurat nå Listevisning Rutenettvisning diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index f37c875827..7486a267f7 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1503,6 +1503,13 @@ Overslaan Deze map selecteren Terug + Afsluiten + Terug naar beginmap + De beginmap is niet meer beschikbaar + Bewerking annuleren? + De bewerking wordt geannuleerd. Weet je het zeker? + Accepteren + Weigeren %1$s is gekoppeld, maar nu niet leesbaar Lijstweergave Rasterweergave diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index de29734d21..41a611bf63 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1541,6 +1541,13 @@ Pomiń Wybierz ten folder Wstecz + Wyjdź + Wróć do folderu początkowego + Folder początkowy nie jest już dostępny + Anulować operację? + Operacja zostanie anulowana. Czy na pewno? + Akceptuj + Odrzuć %1$s: zamontowano, ale obecnie nie można odczytać Widok listy Widok siatki diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index edffdf14a9..24a190b2a4 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -1511,6 +1511,13 @@ Ignorar Selecionar esta pasta Voltar + Sair + Voltar à pasta inicial + A pasta inicial já não está disponível + Cancelar operação? + A operação será cancelada. Tem a certeza? + Aceitar + Recusar %1$s está montado, mas não é possível lê-lo de momento Vista de lista Vista de grelha diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index a4d96ea940..dc6c63b2f0 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1511,6 +1511,13 @@ Pular Selecionar esta pasta Voltar + Sair + Voltar à pasta inicial + A pasta inicial não está mais disponível + Cancelar operação? + A operação será cancelada. Tem certeza? + Aceitar + Recusar %1$s está montado, mas não pode ser lido agora Visualização em lista Visualização em grade diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index d97af4aed0..7ef6b8d113 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1522,6 +1522,13 @@ Omite Selectează acest folder Înapoi + Ieșire + Înapoi la dosarul inițial + Dosarul inițial nu mai este disponibil + Anulați operația? + Operația va fi anulată. Sunteți sigur? + Acceptă + Refuză %1$s este montat, dar nu poate fi citit acum Vizualizare listă Vizualizare grilă diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 1388738db6..37cf74d059 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1538,6 +1538,13 @@ Пропустить Выбрать эту папку Назад + Выход + Вернуться в начальную папку + Начальная папка больше недоступна + Отменить операцию? + Операция будет отменена. Вы уверены? + Принять + Отклонить %1$s: подключено, но сейчас недоступно для чтения Список Сетка diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index caf787c3a7..480d8c96ac 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1503,6 +1503,13 @@ Hoppa över Välj den här mappen Tillbaka + Avsluta + Tillbaka till startmappen + Startmappen är inte längre tillgänglig + Avbryt åtgärden? + Åtgärden avbryts. Är du säker? + Acceptera + Avböj %1$s är monterad men inte läsbar just nu Listvy Rutnätsvy diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 1107a67779..a7b8a4a648 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1484,6 +1484,13 @@ ข้าม เลือกโฟลเดอร์นี้ กลับ + ออก + กลับไปยังโฟลเดอร์เริ่มต้น + โฟลเดอร์เริ่มต้นไม่พร้อมใช้งานแล้ว + ยกเลิกการดำเนินการ? + การดำเนินการจะถูกยกเลิก คุณแน่ใจหรือไม่? + ยอมรับ + ปฏิเสธ %1$s ติดตั้งอยู่แต่อ่านไม่ได้ในขณะนี้ มุมมองรายการ มุมมองตาราง diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 05cd0192b9..30196e875b 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1492,6 +1492,13 @@ Atla Bu klasörü seç Geri + Çıkış + Başlangıç klasörüne dön + Başlangıç klasörü artık kullanılamıyor + İşlem iptal edilsin mi? + İşlem iptal edilecek. Emin misiniz? + Kabul et + Reddet %1$s bağlı ancak şu anda okunamıyor Liste görünümü Izgara görünümü diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index cf16a09384..2c40b53fa2 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1541,6 +1541,13 @@ Пропустити Вибрати цю папку Назад + Вийти + Повернутися до початкової папки + Початкова папка більше недоступна + Скасувати операцію? + Операцію буде скасовано. Ви впевнені? + Прийняти + Відхилити %1$s: підключено, але читання зараз недоступне Список Сітка diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 785e8d57f3..64139f47c6 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1484,6 +1484,13 @@ Bỏ qua Chọn thư mục này Quay lại + Thoát + Quay lại thư mục ban đầu + Thư mục ban đầu không còn khả dụng + Hủy thao tác? + Thao tác sẽ bị hủy. Bạn có chắc không? + Chấp nhận + Từ chối %1$s đã được gắn nhưng hiện không đọc được Xem dạng danh sách Xem dạng lưới diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 174e671587..cfbdec72b2 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1560,6 +1560,13 @@ 跳过 选择此文件夹 返回 + 退出 + 返回初始文件夹 + 初始文件夹已不可用 + 取消操作? + 操作将被取消。确定吗? + 接受 + 拒绝 %1$s 已挂载,但当前无法读取 列表视图 网格视图 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 97d53634ea..60adfbbab3 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1484,6 +1484,13 @@ 略過 選擇此資料夾 返回 + 離開 + 返回初始資料夾 + 初始資料夾已無法使用 + 取消操作? + 操作將會取消。確定嗎? + 接受 + 拒絕 %1$s 已掛載,但目前無法讀取 清單檢視 格狀檢視 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 2d09faba03..3f59e1d005 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1484,6 +1484,13 @@ 略過 選擇此資料夾 返回 + 離開 + 返回起始資料夾 + 起始資料夾已無法使用 + 取消操作? + 操作將會取消。確定嗎? + 接受 + 拒絕 %1$s 已掛載,但目前無法讀取 清單檢視 格狀檢視 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e64eb7e7dd..1c86ac6009 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1546,6 +1546,10 @@ Exit Return to start Starting folder is no longer available + Cancel operation? + The operation will be cancelled. Are you sure? + Accept + Decline %1$s is mounted but not readable right now List view Grid view 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 3/5] 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) + } +} 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 4/5] 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() { From 3b1dfadcf929303f6f5c3403c117edaaadae6d90 Mon Sep 17 00:00:00 2001 From: xXJsonDeruloXx Date: Thu, 22 Oct 2026 10:29:24 -0400 Subject: [PATCH 5/5] fix: keep deferred back inside selected drive root --- .../launcher/files/FileManagerScreen.kt | 11 ++++++++-- .../files/FileManagerNavigationTest.kt | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/files/FileManagerNavigationTest.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 be804fd0a5..627761c2da 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -101,6 +101,9 @@ import java.util.Date private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK } +internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean = + currentDir != currentRoot && currentDir.parentFile?.exists() == true + @OptIn(ExperimentalMaterial3Api::class) @Composable fun FileManagerScreen( @@ -192,6 +195,7 @@ fun FileManagerScreen( var listingJob by remember { mutableStateOf(null) } fun loadDirectory(dir: File, resetScroll: Boolean = true) { + if (cancellingNavigation) return currentDir = dir if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply() listingJob?.cancel() @@ -216,11 +220,13 @@ fun FileManagerScreen( } fun openDrive(dir: File) { + if (cancellingNavigation) return currentRoot = dir loadDirectory(dir) } fun returnToStart() { + if (cancellingNavigation) return val dir = launchDir ?: return if (!dir.isDirectory) { Toast.makeText(context, R.string.fm_start_unavailable, Toast.LENGTH_SHORT).show() @@ -240,12 +246,13 @@ fun FileManagerScreen( val operationActive = isOperationActive() fun navigate(action: FileManagerNavigation) { + if (cancellingNavigation) return when (action) { FileManagerNavigation.EXIT -> onExit?.invoke() FileManagerNavigation.RETURN_TO_START -> returnToStart() FileManagerNavigation.BACK -> { if (showFavorites) showFavorites = false - else if (canGoUp) currentDir.parentFile?.let { loadDirectory(it) } + else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it) } else onExit?.invoke() } } @@ -284,8 +291,8 @@ fun FileManagerScreen( pendingConflict = null isOperationRunning = false operationDeterminate = false - if (action != FileManagerNavigation.EXIT) loadDirectory(currentDir, resetScroll = false) cancellingNavigation = false + if (action != FileManagerNavigation.EXIT) loadDirectory(currentDir, resetScroll = false) navigate(action) } } diff --git a/app/src/test/java/com/droiddeck/launcher/files/FileManagerNavigationTest.kt b/app/src/test/java/com/droiddeck/launcher/files/FileManagerNavigationTest.kt new file mode 100644 index 0000000000..cbcf207553 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/FileManagerNavigationTest.kt @@ -0,0 +1,20 @@ +package com.droiddeck.launcher.files + +import java.io.File +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class FileManagerNavigationTest { + @get:Rule val tmp = TemporaryFolder() + + @Test fun backCannotNavigateAboveTheCurrentDriveRoot() { + val drive = tmp.newFolder("drive") + val child = File(drive, "folder").apply { mkdir() } + + assertTrue(canNavigateUp(child, drive)) + assertFalse(canNavigateUp(drive, drive)) + } +}