Add File Manager Return and Exit navigation (#1301)

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-23 11:04:35 -04:00
commit bf4aa58c68
40 files changed
+549 -55

No files matched your search

@@ -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() })
}
}
}
@@ -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
@@ -90,12 +92,18 @@ 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.ensureActive
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 }
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
currentDir != currentRoot && currentDir.parentFile?.exists() == true
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FileManagerScreen(
@@ -105,6 +113,7 @@ fun FileManagerScreen(
initialDir: File? = null,
pickerTitle: String? = null,
onPick: ((File) -> Unit)? = null,
onExit: (() -> Unit)? = null,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
@@ -118,12 +127,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 { !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 {
@@ -139,8 +150,9 @@ fun FileManagerScreen(
?: rootDir
}
}
mutableStateOf(vol)
vol
}
var currentRoot by remember { mutableStateOf(initialRoot) }
var entries by remember { mutableStateOf(listOf<File>()) }
var selectedEntry by remember { mutableStateOf<File?>(null) }
var showMenuFor by remember { mutableStateOf<File?>(null) }
@@ -151,8 +163,10 @@ fun FileManagerScreen(
var pendingConflict by remember { mutableStateOf<File?>(null) }
var conflictChoice by remember { mutableStateOf<ConflictChoice?>(null) }
var conflictApplyToAll by remember { mutableStateOf(false) }
var operationJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var cancelledJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var operationJob by remember { mutableStateOf<Job?>(null) }
var cancelledJob by remember { mutableStateOf<Job?>(null) }
var pendingNavigation by remember { mutableStateOf<FileManagerNavigation?>(null) }
var cancellingNavigation by remember { mutableStateOf(false) }
var pendingBulkDelete by remember { mutableStateOf<List<File>>(emptyList()) }
var searchQuery by remember { mutableStateOf("") }
val visibleEntries = if (searchQuery.isBlank()) entries
@@ -178,9 +192,10 @@ fun FileManagerScreen(
var showFavorites by remember { mutableStateOf(false) }
var favTick by remember { mutableIntStateOf(0) }
var listingJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
var listingJob by remember { mutableStateOf<Job?>(null) }
fun loadDirectory(dir: File, resetScroll: Boolean = true) {
if (cancellingNavigation) return
currentDir = dir
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
listingJob?.cancel()
@@ -205,25 +220,90 @@ 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()
return
}
showFavorites = false
showSearch = false
searchQuery = ""
currentRoot = initialRoot
loadDirectory(dir)
}
LaunchedEffect(Unit) { loadDirectory(rootDir) }
BackHandler(enabled = showFavorites || currentDir != currentRoot) {
if (showFavorites) {
showFavorites = false
return@BackHandler
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
fun isOperationActive() = isOperationRunning || operationJob?.isCompleted == false || cancelledJob?.isCompleted == false
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 (canNavigateUp(currentDir, currentRoot)) 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 (isOperationActive()) 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
cancellingNavigation = false
if (action != FileManagerNavigation.EXIT) loadDirectory(currentDir, resetScroll = 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 {
@@ -241,11 +321,14 @@ fun FileManagerScreen(
}
fun performDelete(file: File) {
scope.launch {
if (isOperationActive()) return
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
if (operationJob === job) operationJob = null
loadDirectory(currentDir, resetScroll = false)
if (!ok) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_SHORT).show()
}
@@ -260,7 +343,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
@@ -269,7 +352,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[kotlinx.coroutines.Job]
val job = coroutineContext[Job]
var applyToAll: ConflictChoice? = null
var failed = 0
@@ -322,7 +405,7 @@ fun FileManagerScreen(
isOperationRunning = false
operationDeterminate = false
operationJob = null
if (operationJob === job) operationJob = null
clipboardFiles = emptyList()
isCutOperation = false
selectionMode = false
@@ -340,32 +423,38 @@ fun FileManagerScreen(
}
fun performRename(file: File, newName: String) {
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
}
scope.launch {
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
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 (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
}
scope.launch {
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
if (operationJob === job) operationJob = null
loadDirectory(currentDir, resetScroll = false)
if (!ok) Toast.makeText(context, R.string.fm_create_folder_failed, Toast.LENGTH_SHORT).show()
}
@@ -481,18 +570,20 @@ fun FileManagerScreen(
},
confirmButton = {
TextButton(onClick = {
if (isOperationActive()) return@TextButton
pendingBulkDelete = emptyList()
selectionMode = false
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
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()
@@ -582,7 +673,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)
}
@@ -672,6 +763,13 @@ fun FileManagerScreen(
)
}
if (launchDir != null) {
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))
}
if (!showFavorites) {
if (!pickMode) {
OutlinedButton(
@@ -747,6 +845,11 @@ fun FileManagerScreen(
Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
if (!pickMode && onExit != null) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.EXIT) }, enabled = !cancellingNavigation) {
Icon(Icons.AutoMirrored.Filled.ExitToApp, stringResource(R.string.fm_exit), tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
if (showSearch && !showFavorites) {
@@ -986,7 +1089,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) {
@@ -1052,7 +1155,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 {
@@ -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,24 +25,27 @@ 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
}
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()
}
@@ -53,12 +57,12 @@ object FileOps {
return true
}
if (!copyWithProgress(src, dst, progress, isCancelled)) return false
if (isCancelled()) return false
// 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)
}
@@ -71,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
@@ -118,6 +130,7 @@ object FileOps {
val size = input.size()
var position = 0L
while (position < size) {
if (isCancelled()) throw CancellationException("Copy cancelled: $src")
val transferred = input.transferTo(position, minOf(chunk, size - position), channel)
if (transferred <= 0) break
position += transferred
@@ -125,12 +138,19 @@ object FileOps {
progress?.onProgress(done[0], total)
}
if (position < size) throw IOException("Incomplete copy: $position/$size bytes")
if (size > 0 && 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 (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)
@@ -50,6 +50,7 @@ class FilePickerActivity : ComponentActivity() {
setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath))
finish()
},
onExit = { finish() },
)
}
}