jarad2's picture
Add Android Bench sample: tasks and runs (part 14)
89995d3 verified
Raw History Blame Contribute Delete
465 kB
diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 5715433..be0afc1 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -5,6 +5,7 @@ import java.io.FileInputStream plugins { alias(libs.plugins.android) + alias(libs.plugins.kotlin.compose) alias(libs.plugins.detekt) } @@ -37,6 +38,7 @@ android { versionCode = project.property("VERSION_CODE").toString().toInt() multiDexEnabled = true vectorDrawables.useSupportLibrary = true + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } signingConfigs { @@ -62,6 +64,14 @@ android { buildFeatures { viewBinding = true buildConfig = true + compose = true + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + all { it.maxHeapSize = "3g" } + } } buildTypes { @@ -89,6 +99,8 @@ android { sourceSets { getByName("main").java.directories.add("src/main/kotlin") + getByName("test").java.directories.add("src/test/kotlin") + getByName("androidTest").java.directories.add("src/androidTest/kotlin") } compileOptions { @@ -145,5 +157,16 @@ dependencies { implementation(libs.gestureviews) implementation(libs.autofittextview) implementation(libs.zip4j) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.foundation) + implementation(libs.androidx.compose.material3) + implementation(libs.kotlinx.collections.immutable) + testImplementation(libs.junit) + testImplementation(libs.robolectric) + testImplementation(libs.androidx.compose.ui.test.junit4) + androidTestImplementation(libs.androidx.test.runner) + androidTestImplementation(libs.androidx.test.espresso.core) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) detektPlugins(libs.compose.detekt) } diff --git a/app/src/androidTest/kotlin/org/fossify/filemanager/ui/FilesTabCreateTest.kt b/app/src/androidTest/kotlin/org/fossify/filemanager/ui/FilesTabCreateTest.kt new file mode 100644 index 0000000..8ddc51b --- /dev/null +++ b/app/src/androidTest/kotlin/org/fossify/filemanager/ui/FilesTabCreateTest.kt @@ -0,0 +1,120 @@ +package org.fossify.filemanager.ui + +import android.content.Context +import android.os.Environment +import android.os.ParcelFileDescriptor +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createEmptyComposeRule +import androidx.compose.ui.test.onAllNodesWithTag +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.fossify.commons.helpers.TAB_FILES +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.MainActivity +import org.fossify.filemanager.compose.FilesTabTestTags +import org.fossify.filemanager.helpers.Config +import org.junit.After +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +/** + * The Compose "Create new" dialog of the Files tab. Robolectric can't idle while a text field is shown inside a + * Compose dialog, so these run on a device or emulator (`connectedFossDebugAndroidTest`). + */ +@RunWith(AndroidJUnit4::class) +class FilesTabCreateTest { + @get:Rule + val composeRule = createEmptyComposeRule() + + private val context: Context = ApplicationProvider.getApplicationContext() + private lateinit var folder: File + private var scenario: ActivityScenario<MainActivity>? = null + + @Before + fun setUp() { + InstrumentationRegistry.getInstrumentation().uiAutomation + .executeShellCommand("appops set --uid ${context.packageName} MANAGE_EXTERNAL_STORAGE allow") + // read the output to the end: the command runs asynchronously, and closing early races the grant + .let { ParcelFileDescriptor.AutoCloseInputStream(it).use { stream -> stream.readBytes() } } + folder = File(Environment.getExternalStorageDirectory(), "files_tab_create_test").apply { + deleteRecursively() + mkdirs() + } + File(folder, "existing.txt").writeText("x") + Config.newInstance(context).apply { + showTabs = TAB_FILES + wasStorageAnalysisTabAdded = true + homeFolder = folder.absolutePath + } + scenario = ActivityScenario.launch(MainActivity::class.java) + waitForItem("existing.txt") + } + + @After + fun tearDown() { + scenario?.close() + folder.deleteRecursively() + } + + private fun text(id: Int) = context.getString(id) + + private fun waitForItem(name: String) { + composeRule.waitUntil(10_000) { + composeRule.onAllNodesWithTag(FilesTabTestTags.item(File(folder, name).absolutePath)) + .fetchSemanticsNodes().isNotEmpty() + } + } + + private fun openDialog() { + composeRule.onNodeWithTag(FilesTabTestTags.FAB).performClick() + composeRule.onNodeWithText(text(R.string.create_new)).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.folder)).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.file)).assertIsDisplayed() + } + + @Test + fun createsAFolderByDefault() { + openDialog() + composeRule.onNodeWithTag(FilesTabTestTags.CREATE_NAME).performTextInput("new folder") + composeRule.onNodeWithText(text(R.string.ok)).performClick() + waitForItem("new folder") + assertTrue(File(folder, "new folder").isDirectory) + composeRule.onNodeWithTag(FilesTabTestTags.CREATE_NAME).assertDoesNotExist() + } + + @Test + fun createsAFile() { + openDialog() + composeRule.onNodeWithTag(FilesTabTestTags.CREATE_NAME).performTextInput("notes.txt") + composeRule.onNodeWithText(text(R.string.file)).performClick() + composeRule.onNodeWithText(text(R.string.ok)).performClick() + waitForItem("notes.txt") + assertTrue(File(folder, "notes.txt").isFile) + } + + @Test + fun refusesATakenNameAndCancelCreatesNothing() { + openDialog() + composeRule.onNodeWithTag(FilesTabTestTags.CREATE_NAME).performTextInput("existing.txt") + composeRule.onNodeWithText(text(R.string.ok)).performClick() + composeRule.waitForIdle() + // the dialog stays open with the name + composeRule.onNodeWithTag(FilesTabTestTags.CREATE_NAME).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.cancel)).performClick() + composeRule.waitForIdle() + composeRule.onNodeWithTag(FilesTabTestTags.CREATE_NAME).assertDoesNotExist() + assertFalse(File(folder, "existing.txt").isDirectory) + assertTrue(folder.list()!!.toList() == listOf("existing.txt")) + } +} diff --git a/app/src/androidTest/kotlin/org/fossify/filemanager/ui/ReadTextSaveAsTest.kt b/app/src/androidTest/kotlin/org/fossify/filemanager/ui/ReadTextSaveAsTest.kt new file mode 100644 index 0000000..7b0322a --- /dev/null +++ b/app/src/androidTest/kotlin/org/fossify/filemanager/ui/ReadTextSaveAsTest.kt @@ -0,0 +1,139 @@ +package org.fossify.filemanager.ui + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.ParcelFileDescriptor +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.junit4.createEmptyComposeRule +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextReplacement +import androidx.test.core.app.ActivityScenario +import androidx.test.core.app.ApplicationProvider +import androidx.test.espresso.Espresso.onView +import androidx.test.espresso.action.ViewActions.click +import androidx.test.espresso.assertion.ViewAssertions.matches +import androidx.test.espresso.matcher.RootMatchers.isDialog +import androidx.test.espresso.matcher.ViewMatchers.isDisplayed +import androidx.test.espresso.matcher.ViewMatchers.withText +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.ReadTextActivity +import org.fossify.filemanager.compose.ReadTextTestTags +import org.fossify.filemanager.compose.SaveAsDialogTestTags +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +/** + * The Compose "Save as" dialog of the text editor. Robolectric can't idle while a text field is shown + * inside a Compose dialog, so these run on a device or emulator (`connectedFossDebugAndroidTest`). + */ +@RunWith(AndroidJUnit4::class) +class ReadTextSaveAsTest { + @get:Rule + val composeRule = createEmptyComposeRule() + + private val context: Context = ApplicationProvider.getApplicationContext() + private lateinit var folder: File + private lateinit var file: File + private var scenario: ActivityScenario<ReadTextActivity>? = null + + @Before + fun setUp() { + InstrumentationRegistry.getInstrumentation().uiAutomation + .executeShellCommand("appops set --uid ${context.packageName} MANAGE_EXTERNAL_STORAGE allow") + // read the output to the end: the command runs asynchronously, and closing early races the grant + .let { ParcelFileDescriptor.AutoCloseInputStream(it).use { stream -> stream.readBytes() } } + folder = File(context.cacheDir, "save_as_test").apply { + deleteRecursively() + mkdirs() + } + file = File(folder, "notes.txt").apply { writeText("original text") } + val intent = Intent(context, ReadTextActivity::class.java).apply { + action = Intent.ACTION_VIEW + setDataAndType(Uri.fromFile(file), "text/plain") + } + scenario = ActivityScenario.launch(intent) + composeRule.waitUntil(10_000) { + composeRule.onAllNodesWithText("original text").fetchSemanticsNodes().isNotEmpty() + } + } + + @After + fun tearDown() { + scenario?.close() + folder.deleteRecursively() + } + + private fun text(id: Int) = context.getString(id) + + private fun openSaveAs() { + composeRule.onNodeWithContentDescription(text(R.string.more_options)).performClick() + composeRule.onNodeWithText(text(R.string.save_as)).performClick() + composeRule.onNodeWithTag(SaveAsDialogTestTags.FILENAME).assertIsDisplayed() + } + + @Test + fun prefillsNameAndWritesNewFile() { + composeRule.onNodeWithTag(ReadTextTestTags.EDITOR).performTextReplacement("copy me") + openSaveAs() + composeRule.onNodeWithTag(SaveAsDialogTestTags.FOLDER).assertIsDisplayed() + composeRule.onNodeWithTag(SaveAsDialogTestTags.FILENAME).assertTextEquals(text(R.string.filename), "notes") + composeRule.onNodeWithTag(SaveAsDialogTestTags.EXTENSION).assertTextEquals(text(R.string.extension), "txt") + + composeRule.onNodeWithTag(SaveAsDialogTestTags.FILENAME).performTextReplacement("copy") + composeRule.onNodeWithText(text(R.string.ok)).performClick() + + val copy = File(folder, "copy.txt") + composeRule.waitUntil(10_000) { copy.exists() && copy.readText() == "copy me" } + composeRule.onNodeWithTag(SaveAsDialogTestTags.FILENAME).assertDoesNotExist() + assertEquals("original text", file.readText()) + } + + @Test + fun emptyNameKeepsDialogOpen() { + openSaveAs() + composeRule.onNodeWithTag(SaveAsDialogTestTags.FILENAME).performTextReplacement("") + composeRule.onNodeWithText(text(R.string.ok)).performClick() + composeRule.onNodeWithTag(SaveAsDialogTestTags.FILENAME).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.cancel)).performClick() + composeRule.onNodeWithTag(SaveAsDialogTestTags.FILENAME).assertDoesNotExist() + } + + @Test + fun existingFileAsksBeforeOverwriting() { + File(folder, "other.txt").writeText("keep me") + composeRule.onNodeWithTag(ReadTextTestTags.EDITOR).performTextReplacement("new content") + openSaveAs() + composeRule.onNodeWithTag(SaveAsDialogTestTags.FILENAME).performTextReplacement("other") + composeRule.onNodeWithText(text(R.string.ok)).performClick() + + val question = String.format(text(R.string.file_already_exists_overwrite), "other.txt") + onView(withText(question)).inRoot(isDialog()).check(matches(isDisplayed())) + onView(withText(R.string.yes)).inRoot(isDialog()).perform(click()) + + composeRule.waitUntil(10_000) { File(folder, "other.txt").readText() == "new content" } + } + + @Test + fun pathFieldOpensFolderPicker() { + openSaveAs() + composeRule.onNodeWithTag(SaveAsDialogTestTags.FOLDER).performClick() + onView(withText(R.string.select_folder)).inRoot(isDialog()).check(matches(isDisplayed())) + onView(withText(R.string.cancel)).inRoot(isDialog()).perform(click()) + composeRule.onNodeWithTag(SaveAsDialogTestTags.FILENAME).assertIsDisplayed() + assertFalse(File(folder, "notes.txt").readText().isEmpty()) + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/activities/DecompressActivity.kt b/app/src/main/kotlin/org/fossify/filemanager/activities/DecompressActivity.kt index 350c9c5..fe46608 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/activities/DecompressActivity.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/activities/DecompressActivity.kt @@ -2,10 +2,15 @@ package org.fossify.filemanager.activities import android.net.Uri import android.os.Bundle +import androidx.activity.compose.setContent +import androidx.lifecycle.ViewModelProvider +import kotlinx.collections.immutable.toImmutableList import net.lingala.zip4j.exception.ZipException import net.lingala.zip4j.exception.ZipException.Type import net.lingala.zip4j.io.inputstream.ZipInputStream import net.lingala.zip4j.model.LocalFileHeader +import org.fossify.commons.compose.extensions.enableEdgeToEdgeSimple +import org.fossify.commons.compose.theme.AppThemeSurface import org.fossify.commons.dialogs.EnterPasswordDialog import org.fossify.commons.dialogs.FilePickerDialog import org.fossify.commons.extensions.createDirectorySync @@ -15,16 +20,16 @@ import org.fossify.commons.extensions.getFilenameFromPath import org.fossify.commons.extensions.getMimeType import org.fossify.commons.extensions.getParentPath import org.fossify.commons.extensions.getRealPathFromURI +import org.fossify.commons.extensions.hideKeyboard import org.fossify.commons.extensions.internalStoragePath -import org.fossify.commons.extensions.isGone import org.fossify.commons.extensions.showErrorToast import org.fossify.commons.extensions.toast -import org.fossify.commons.extensions.viewBinding -import org.fossify.commons.helpers.NavigationIcon import org.fossify.commons.helpers.ensureBackgroundThread import org.fossify.filemanager.R -import org.fossify.filemanager.adapters.DecompressItemsAdapter -import org.fossify.filemanager.databinding.ActivityDecompressBinding +import org.fossify.filemanager.compose.decompress.ArchiveEntry +import org.fossify.filemanager.compose.decompress.ArchiveLoadState +import org.fossify.filemanager.compose.decompress.DecompressScreen +import org.fossify.filemanager.compose.decompress.DecompressViewModel import org.fossify.filemanager.extensions.config import org.fossify.filemanager.extensions.setLastModified import org.fossify.filemanager.models.ListItem @@ -32,62 +37,59 @@ import java.io.BufferedInputStream import java.io.File class DecompressActivity : SimpleActivity() { - companion object { - private const val PASSWORD = "password" - } - - private val binding by viewBinding(ActivityDecompressBinding::inflate) - private val allFiles = ArrayList<ListItem>() - private var currentPath = "" + private lateinit var viewModel: DecompressViewModel private var uri: Uri? = null - private var password: String? = null private var passwordDialog: EnterPasswordDialog? = null private var filename = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - setContentView(binding.root) - setupOptionsMenu() - binding.apply { - setupEdgeToEdge(padBottomSystem = listOf(decompressList)) - setupMaterialScrollListener(binding.decompressList, binding.decompressAppbar) - } + enableEdgeToEdgeSimple() + viewModel = ViewModelProvider(this)[DecompressViewModel::class.java] uri = intent.data + if (uri != null) { + val realPath = getRealPathFromURI(uri!!) + filename = realPath?.getFilenameFromPath() ?: Uri.decode(uri.toString().getFilenameFromPath()) + } + + setContent { + AppThemeSurface { + DecompressScreen( + title = filename.ifEmpty { getString(R.string.decompress) }, + entries = viewModel.entries, + isLoading = viewModel.isLoading, + goBack = ::goBack, + onDecompress = ::decompressFiles, + onEntryClick = ::onEntryClicked + ) + } + } + if (uri == null) { toast(R.string.unknown_error_occurred) return } - password = savedInstanceState?.getString(PASSWORD, null) - - val realPath = getRealPathFromURI(uri!!) - filename = realPath?.getFilenameFromPath() ?: Uri.decode(uri.toString().getFilenameFromPath()) - binding.decompressToolbar.title = filename - setupFilesList() + when (viewModel.loadState) { + ArchiveLoadState.NOT_STARTED, ArchiveLoadState.NEEDS_PASSWORD -> setupFilesList() + ArchiveLoadState.LOADING, ArchiveLoadState.LOADED -> {} + } } - override fun onResume() { - super.onResume() - setupTopAppBar(binding.decompressAppbar, NavigationIcon.Arrow) + override fun onDestroy() { + super.onDestroy() + passwordDialog?.dismiss(notify = false) + passwordDialog = null } - override fun onSaveInstanceState(outState: Bundle) { - super.onSaveInstanceState(outState) - outState.putString(PASSWORD, password) - } - - private fun setupOptionsMenu() { - binding.decompressToolbar.setOnMenuItemClickListener { menuItem -> - when (menuItem.itemId) { - R.id.decompress -> decompressFiles() - else -> return@setOnMenuItemClickListener false - } - return@setOnMenuItemClickListener true - } + private fun goBack() { + hideKeyboard() + finish() } override fun onBackPressedCompat(): Boolean { + val currentPath = viewModel.currentPath return if (currentPath.isEmpty()) { false } else { @@ -97,37 +99,37 @@ class DecompressActivity : SimpleActivity() { } } + private fun onEntryClicked(entry: ArchiveEntry) { + if (entry.isDirectory) { + updateCurrentPath(entry.path) + } + } + private fun setupFilesList() { - allFiles.clear() + viewModel.loadState = ArchiveLoadState.LOADING + viewModel.allFiles.clear() fillAllListItems(uri!!) { - updateCurrentPath("") + viewModel.loadState = ArchiveLoadState.LOADED + updateCurrentPath(viewModel.currentPath) } } private fun updateCurrentPath(path: String) { - currentPath = path try { - val listItems = getFolderItems(currentPath) - updateAdapter(listItems = listItems) + val entries = getFolderItems(path).map { + ArchiveEntry(path = it.path, name = it.name, isDirectory = it.isDirectory) + }.toImmutableList() + runOnUiThread { + viewModel.currentPath = path + viewModel.entries = entries + } } catch (e: Exception) { showErrorToast(e) } } - private fun updateAdapter(listItems: MutableList<ListItem>) { - runOnUiThread { - DecompressItemsAdapter(this, listItems, binding.decompressList) { - if ((it as ListItem).isDirectory) { - updateCurrentPath(it.path) - } - }.apply { - binding.decompressList.adapter = this - } - } - } - private fun decompressFiles() { - val defaultFolder = getRealPathFromURI(uri!!) ?: internalStoragePath + val defaultFolder = getRealPathFromURI(uri ?: return) ?: internalStoragePath FilePickerDialog( activity = this, currPath = defaultFolder, @@ -151,8 +153,9 @@ class DecompressActivity : SimpleActivity() { try { val inputStream = contentResolver.openInputStream(uri!!) val zipInputStream = ZipInputStream(BufferedInputStream(inputStream!!)) + val password = viewModel.password if (password != null) { - zipInputStream.setPassword(password?.toCharArray()) + zipInputStream.setPassword(password.toCharArray()) } val buffer = ByteArray(1024) val foldersTimestamp = mutableListOf<Pair<File, LocalFileHeader>>() @@ -164,7 +167,6 @@ class DecompressActivity : SimpleActivity() { val parent = "$destination/$filename" val newPath = "$parent/${entry.fileName.trimEnd('/')}" - if (!getDoesFilePathExist(parent)) { if (!createDirectorySync(parent)) { continue @@ -211,7 +213,7 @@ class DecompressActivity : SimpleActivity() { } private fun getFolderItems(parent: String): ArrayList<ListItem> { - return allFiles.filter { + return viewModel.allFiles.toList().filter { val fileParent = if (it.path.contains("/")) { it.path.getParentPath() } else { @@ -227,12 +229,14 @@ class DecompressActivity : SimpleActivity() { contentResolver.openInputStream(uri) } catch (e: Exception) { showErrorToast(e) + viewModel.loadState = ArchiveLoadState.LOADED return@ensureBackgroundThread } + val password = viewModel.password val zipInputStream = ZipInputStream(BufferedInputStream(inputStream)) if (password != null) { - zipInputStream.setPassword(password?.toCharArray()) + zipInputStream.setPassword(password.toCharArray()) } var zipEntry: LocalFileHeader? while (true) { @@ -240,8 +244,12 @@ class DecompressActivity : SimpleActivity() { zipEntry = zipInputStream.nextEntry } catch (passwordException: ZipException) { if (passwordException.type == Type.WRONG_PASSWORD) { + viewModel.loadState = ArchiveLoadState.NEEDS_PASSWORD if (password != null) { toast(getString(R.string.invalid_password)) + } + + if (passwordDialog != null) { passwordDialog?.clearPassword() } else { runOnUiThread { @@ -261,11 +269,7 @@ class DecompressActivity : SimpleActivity() { } // Show progress bar only after password dialog is dismissed. - runOnUiThread { - if (binding.progressIndicator.isGone()) { - binding.progressIndicator.show() - } - } + viewModel.isLoading = true if (passwordDialog != null) { passwordDialog?.dismiss(notify = false) @@ -274,7 +278,7 @@ class DecompressActivity : SimpleActivity() { val lastModified = zipEntry.lastModifiedTime val filename = zipEntry.fileName.removeSuffix("/") - allFiles.add( + viewModel.allFiles.add( ListItem( mPath = filename, mName = filename.getFilenameFromPath(), @@ -288,18 +292,19 @@ class DecompressActivity : SimpleActivity() { ) } - runOnUiThread { - binding.progressIndicator.hide() - } - + viewModel.isLoading = false callback() } private fun askForPassword() { + if (isFinishing || isDestroyed) { + return + } + passwordDialog = EnterPasswordDialog( this, callback = { newPassword -> - password = newPassword + viewModel.password = newPassword setupFilesList() }, cancelCallback = { diff --git a/app/src/main/kotlin/org/fossify/filemanager/activities/FavoritesActivity.kt b/app/src/main/kotlin/org/fossify/filemanager/activities/FavoritesActivity.kt index a610b4a..e224a8d 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/activities/FavoritesActivity.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/activities/FavoritesActivity.kt @@ -1,71 +1,47 @@ package org.fossify.filemanager.activities -import android.graphics.Paint import android.os.Bundle +import androidx.activity.compose.setContent +import androidx.compose.runtime.mutableStateOf +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.toImmutableList +import org.fossify.commons.compose.extensions.enableEdgeToEdgeSimple +import org.fossify.commons.compose.theme.AppThemeSurface import org.fossify.commons.dialogs.FilePickerDialog -import org.fossify.commons.extensions.beVisibleIf -import org.fossify.commons.extensions.getProperPrimaryColor -import org.fossify.commons.extensions.getProperTextColor -import org.fossify.commons.extensions.viewBinding -import org.fossify.commons.helpers.NavigationIcon -import org.fossify.commons.interfaces.RefreshRecyclerViewListener -import org.fossify.filemanager.R -import org.fossify.filemanager.adapters.ManageFavoritesAdapter -import org.fossify.filemanager.databinding.ActivityFavoritesBinding +import org.fossify.commons.extensions.hideKeyboard +import org.fossify.filemanager.compose.favorites.ManageFavoritesScreen import org.fossify.filemanager.extensions.config -class FavoritesActivity : SimpleActivity(), RefreshRecyclerViewListener { - private val binding by viewBinding(ActivityFavoritesBinding::inflate) +class FavoritesActivity : SimpleActivity() { + private val favorites = mutableStateOf<ImmutableList<String>>(emptyList<String>().toImmutableList()) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - setContentView(binding.root) - setupOptionsMenu() + enableEdgeToEdgeSimple() updateFavorites() - binding.apply { - setupEdgeToEdge(padBottomSystem = listOf(manageFavoritesList)) - setupMaterialScrollListener(binding.manageFavoritesList, binding.manageFavoritesAppbar) + setContent { + AppThemeSurface { + ManageFavoritesScreen( + favorites = favorites.value, + goBack = ::goBack, + onAddFavorite = ::addFavorite, + onRemoveFavorites = ::removeFavorites + ) + } } } - override fun onResume() { - super.onResume() - setupTopAppBar(binding.manageFavoritesAppbar, NavigationIcon.Arrow) - } - - private fun setupOptionsMenu() { - binding.manageFavoritesToolbar.setOnMenuItemClickListener { menuItem -> - when (menuItem.itemId) { - R.id.add_favorite -> addFavorite() - else -> return@setOnMenuItemClickListener false - } - return@setOnMenuItemClickListener true - } + private fun goBack() { + hideKeyboard() + finish() } private fun updateFavorites() { - binding.apply { - val favorites = ArrayList<String>() - config.favorites.mapTo(favorites) { it } - manageFavoritesPlaceholder.beVisibleIf(favorites.isEmpty()) - manageFavoritesPlaceholder.setTextColor(getProperTextColor()) - - manageFavoritesPlaceholder2.apply { - paintFlags = paintFlags or Paint.UNDERLINE_TEXT_FLAG - beVisibleIf(favorites.isEmpty()) - setTextColor(getProperPrimaryColor()) - setOnClickListener { - addFavorite() - } - } - - ManageFavoritesAdapter(this@FavoritesActivity, favorites, this@FavoritesActivity, manageFavoritesList) { }.apply { - manageFavoritesList.adapter = this - } - } + favorites.value = config.favorites.toImmutableList() } - override fun refreshItems() { + private fun removeFavorites(paths: Set<String>) { + paths.forEach { config.removeFavorite(it) } updateFavorites() } diff --git a/app/src/main/kotlin/org/fossify/filemanager/activities/MainActivity.kt b/app/src/main/kotlin/org/fossify/filemanager/activities/MainActivity.kt index 4a6e4be..c441695 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/activities/MainActivity.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/activities/MainActivity.kt @@ -163,12 +163,14 @@ class MainActivity : SimpleActivity() { override fun onBackPressedCompat(): Boolean { val currentFragment = getCurrentFragment() - if (binding.mainMenu.isSearchOpen) { + if ((currentFragment as? ItemsFragment)?.onBackPressed() == true) { + return true + } else if (binding.mainMenu.isSearchOpen) { binding.mainMenu.closeSearch() return true } else if (currentFragment is RecentsFragment || currentFragment is StorageFragment) { return false - } else if ((currentFragment as ItemsFragment).getBreadcrumbs().getItemCount() <= 1) { + } else if ((currentFragment as ItemsFragment).getBreadcrumbCount() <= 1) { if (!wasBackJustPressed && config.pressBackTwice) { wasBackJustPressed = true toast(R.string.press_back_again) @@ -182,8 +184,7 @@ class MainActivity : SimpleActivity() { return true } } else { - currentFragment.getBreadcrumbs().removeBreadcrumb() - openPath(currentFragment.getBreadcrumbs().getLastItem().path) + openPath(currentFragment.removeLastBreadcrumb()) return true } } @@ -282,6 +283,11 @@ class MainActivity : SimpleActivity() { binding.mainMenu.updateColors() } + /** Restores the system bar appearance of the main toolbar, e.g. after the Files tab's selection bar was closed. */ + fun refreshSystemBarColors() { + updateMenuColors() + } + private fun storeStateVariables() { config.apply { mStoredFontSize = fontSize diff --git a/app/src/main/kotlin/org/fossify/filemanager/activities/ReadTextActivity.kt b/app/src/main/kotlin/org/fossify/filemanager/activities/ReadTextActivity.kt index 9696e06..f24e80a 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/activities/ReadTextActivity.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/activities/ReadTextActivity.kt @@ -8,24 +8,51 @@ import android.os.Bundle import android.print.PrintAttributes import android.print.PrintManager import android.util.Base64 -import android.view.inputmethod.EditorInfo import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient -import android.widget.ImageView -import android.widget.TextView +import androidx.activity.compose.setContent +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.input.TextFieldValue +import androidx.lifecycle.ViewModelProvider +import org.fossify.commons.compose.extensions.enableEdgeToEdgeSimple +import org.fossify.commons.compose.theme.AppThemeSurface import org.fossify.commons.dialogs.ConfirmationAdvancedDialog -import org.fossify.commons.extensions.* -import org.fossify.commons.helpers.NavigationIcon +import org.fossify.commons.dialogs.ConfirmationDialog +import org.fossify.commons.dialogs.FilePickerDialog +import org.fossify.commons.extensions.checkAppSideloading +import org.fossify.commons.extensions.getCurrentFormattedDateTime +import org.fossify.commons.extensions.getDoesFilePathExist +import org.fossify.commons.extensions.getFileOutputStream +import org.fossify.commons.extensions.getFilenameFromPath +import org.fossify.commons.extensions.getFilenameFromUri +import org.fossify.commons.extensions.getProperPrimaryColor +import org.fossify.commons.extensions.getProperTextColor +import org.fossify.commons.extensions.getRealPathFromURI +import org.fossify.commons.extensions.hideKeyboard +import org.fossify.commons.extensions.internalStoragePath +import org.fossify.commons.extensions.isAValidFilename +import org.fossify.commons.extensions.showErrorToast +import org.fossify.commons.extensions.toFileDirItem +import org.fossify.commons.extensions.toast import org.fossify.commons.helpers.REAL_FILE_PATH import org.fossify.commons.helpers.SAVE_DISCARD_PROMPT_INTERVAL import org.fossify.commons.helpers.ensureBackgroundThread -import org.fossify.commons.views.MyEditText import org.fossify.filemanager.R -import org.fossify.filemanager.databinding.ActivityReadTextBinding -import org.fossify.filemanager.dialogs.SaveAsDialog +import org.fossify.filemanager.compose.editor.EditorMenuAction +import org.fossify.filemanager.compose.editor.MAX_TEXT_ZOOM +import org.fossify.filemanager.compose.editor.MIN_TEXT_ZOOM +import org.fossify.filemanager.compose.editor.ReadTextScreen +import org.fossify.filemanager.compose.editor.ReadTextScreenActions +import org.fossify.filemanager.compose.editor.ReadTextScreenState +import org.fossify.filemanager.compose.editor.ReadTextViewModel +import org.fossify.filemanager.compose.editor.SaveAsAlertDialog +import org.fossify.filemanager.compose.editor.SaveAsRequest +import org.fossify.filemanager.extensions.config import org.fossify.filemanager.extensions.openPath -import org.fossify.filemanager.views.GestureEditText import java.io.File import java.io.OutputStream @@ -36,72 +63,116 @@ class ReadTextActivity : SimpleActivity() { private const val KEY_UNSAVED_TEXT = "KEY_UNSAVED_TEXT" } - private val binding by viewBinding(ActivityReadTextBinding::inflate) - - private var filePath = "" - private var originalText = "" - private var searchIndex = 0 + private lateinit var viewModel: ReadTextViewModel + private var title = "" private var lastSavePromptTS = 0L - private var searchMatches = emptyList<Int>() - private var isSearchActive = false + private var textZoom by mutableFloatStateOf(MIN_TEXT_ZOOM) - private lateinit var searchQueryET: MyEditText - private lateinit var searchPrevBtn: ImageView - private lateinit var searchNextBtn: ImageView - private lateinit var searchClearBtn: ImageView + private val screenActions = object : ReadTextScreenActions { + override fun onTextChange(value: TextFieldValue) = viewModel.onTextChange(value) - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(binding.root) - setupOptionsMenu() - binding.apply { - setupEdgeToEdge(padBottomImeAndSystem = listOf(readTextView)) - setupMaterialScrollListener(binding.readTextHolder, binding.readTextAppbar) + override fun onTextZoomChange(zoom: Float) { + textZoom = zoom + config.editorTextZoom = zoom } - searchQueryET = findViewById(R.id.search_query) - searchPrevBtn = findViewById(R.id.search_previous) - searchNextBtn = findViewById(R.id.search_next) - searchClearBtn = findViewById(R.id.search_clear) - - if (checkAppSideloading()) { - return + override fun onMenuAction(action: EditorMenuAction) { + when (action) { + EditorMenuAction.SEARCH -> viewModel.openSearch() + EditorMenuAction.SAVE -> saveText() + EditorMenuAction.SAVE_AS -> saveAsText() + EditorMenuAction.PRINT -> printText() + EditorMenuAction.OPEN_WITH -> openPath(intent.dataString!!, true) + } } + override fun onSearchQueryChange(query: String) = viewModel.onSearchQueryChange(query) + + override fun onPreviousSearchResult() = goToSearchResult(next = false) + + override fun onNextSearchResult() = goToSearchResult(next = true) + + override fun onCloseSearch() = closeSearch() + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdgeSimple() + viewModel = ViewModelProvider(this)[ReadTextViewModel::class.java] + title = getString(R.string.file_editor) + textZoom = config.editorTextZoom.coerceIn(MIN_TEXT_ZOOM, MAX_TEXT_ZOOM) + config.editorTextZoom = textZoom + val uri = if (intent.extras?.containsKey(REAL_FILE_PATH) == true) { Uri.fromFile(File(intent.extras?.get(REAL_FILE_PATH).toString())) } else { intent.data } - if (uri == null) { - finish() + if (uri != null) { + val filename = getFilenameFromUri(uri) + if (filename.isNotEmpty()) { + title = Uri.decode(filename) + } + } + + setupContent() + + if (checkAppSideloading()) { return } - val filename = getFilenameFromUri(uri) - if (filename.isNotEmpty()) { - binding.readTextToolbar.title = Uri.decode(filename) + if (uri == null) { + finish() + return } - binding.readTextView.onGlobalLayout { + if (!viewModel.isLoaded) { + val unsavedText = savedInstanceState?.getString(KEY_UNSAVED_TEXT) ensureBackgroundThread { - checkIntent(uri, savedInstanceState) + checkIntent(uri, unsavedText) } } - - setupSearchButtons() } - override fun onResume() { - super.onResume() - setupTopAppBar(binding.readTextAppbar, NavigationIcon.Arrow) + private fun setupContent() { + setContent { + AppThemeSurface { + val saveAsRequest = viewModel.saveAsRequest + if (saveAsRequest != null) { + SaveAsAlertDialog( + request = saveAsRequest, + onDismiss = { viewModel.saveAsRequest = null }, + onPickFolder = ::pickSaveAsFolder, + onConfirm = { folder, filename, extension -> + onSaveAsConfirmed(saveAsRequest, folder, filename, extension) + } + ) + } + + ReadTextScreen( + state = ReadTextScreenState( + title = title, + textFieldValue = viewModel.textFieldValue, + isSearchActive = viewModel.isSearchActive, + searchQuery = viewModel.searchQuery, + textZoom = textZoom, + editorFocusRequests = viewModel.editorFocusRequests, + searchFocusRequests = viewModel.searchFocusRequests + ), + actions = screenActions, + textColor = Color(getProperTextColor()), + primaryColor = Color(getProperPrimaryColor()), + goBack = ::goBack + ) + } + } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) - if (originalText != binding.readTextView.text.toString()) { - outState.putString(KEY_UNSAVED_TEXT, binding.readTextView.text.toString()) + if (viewModel.hasUnsavedChanges) { + outState.putString(KEY_UNSAVED_TEXT, viewModel.text) } } @@ -113,20 +184,22 @@ class ReadTextActivity : SimpleActivity() { val shouldExitAfterSaving = requestCode == SELECT_SAVE_FILE_AND_EXIT_INTENT val selectedFilePath = getRealPathFromURI(intent.data!!) - val shouldOverwriteOriginalText = selectedFilePath == filePath + val shouldOverwriteOriginalText = selectedFilePath == viewModel.filePath saveTextContent(outputStream, shouldExitAfterSaving, shouldOverwriteOriginalText) } } override fun onBackPressedCompat(): Boolean { - val hasUnsavedChanges = originalText != binding.readTextView.text.toString() + val shouldPromptToSave = viewModel.hasUnsavedChanges && + System.currentTimeMillis() - lastSavePromptTS > SAVE_DISCARD_PROMPT_INTERVAL return when { - isSearchActive -> { + viewModel.isSearchActive -> { closeSearch() true } - hasUnsavedChanges && System.currentTimeMillis() - lastSavePromptTS > SAVE_DISCARD_PROMPT_INTERVAL -> { + + shouldPromptToSave -> { lastSavePromptTS = System.currentTimeMillis() ConfirmationAdvancedDialog(this, "", R.string.save_before_closing, R.string.save, R.string.discard) { if (it) { @@ -142,75 +215,104 @@ class ReadTextActivity : SimpleActivity() { } } - private fun setupOptionsMenu() { - binding.readTextToolbar.setOnMenuItemClickListener { menuItem -> - when (menuItem.itemId) { - R.id.menu_search -> openSearch() - R.id.menu_save -> saveText() - R.id.menu_save_as -> saveAsText() - R.id.menu_open_with -> openPath(intent.dataString!!, true) - R.id.menu_print -> printText() - else -> return@setOnMenuItemClickListener false - } - return@setOnMenuItemClickListener true - } + private fun goBack() { + hideKeyboard() + finish() } - private fun openSearch() { - isSearchActive = true - binding.searchWrapper.beVisible() - showKeyboard(searchQueryET) - - binding.readTextView.requestFocus() - binding.readTextView.setSelection(0) + private fun goToSearchResult(next: Boolean) { + if (!viewModel.goToSearchResult(next)) { + hideKeyboard() + } + } - searchQueryET.postDelayed({ - searchQueryET.requestFocus() - }, 250) + private fun closeSearch() { + viewModel.closeSearch() + hideKeyboard() } private fun updateFilePath() { - if (filePath.isEmpty()) { - filePath = getRealPathFromURI(intent.data!!) ?: "" + if (viewModel.filePath.isEmpty()) { + viewModel.filePath = getRealPathFromURI(intent.data!!) ?: "" } } private fun saveAsText(shouldExitAfterSaving: Boolean = false) { updateFilePath() + val filePath = viewModel.filePath + val hidePath = filePath.isEmpty() + val path = filePath.ifEmpty { "$internalStoragePath/${getCurrentFormattedDateTime()}.txt" } + viewModel.saveAsRequest = SaveAsRequest( + path = path, + hidePath = hidePath, + exitAfterSaving = shouldExitAfterSaving + ) + } - if (filePath.isEmpty()) { - SaveAsDialog(this, filePath, true) { _, filename -> - Intent(Intent.ACTION_CREATE_DOCUMENT).apply { - type = "text/plain" - putExtra(Intent.EXTRA_TITLE, filename) - addCategory(Intent.CATEGORY_OPENABLE) - - val requestCode = if (shouldExitAfterSaving) { - SELECT_SAVE_FILE_AND_EXIT_INTENT - } else { - SELECT_SAVE_FILE_INTENT - } - @Suppress("DEPRECATION") - startActivityForResult(this, requestCode) - } + private fun pickSaveAsFolder(currentFolder: String, onPicked: (String) -> Unit) { + FilePickerDialog(this, currentFolder, false, false, true, true, showFavoritesButton = true) { + onPicked(it) + } + } + + private fun onSaveAsConfirmed(request: SaveAsRequest, folder: String, filename: String, extension: String) { + if (filename.isEmpty()) { + toast(R.string.filename_cannot_be_empty) + return + } + + var newFilename = filename + if (extension.isNotEmpty()) { + newFilename += ".$extension" + } + + val newPath = "$folder/$newFilename" + if (!newFilename.isAValidFilename()) { + toast(R.string.filename_invalid_characters) + return + } + + if (!request.hidePath && getDoesFilePathExist(newPath)) { + val title = String.format(getString(R.string.file_already_exists_overwrite), newFilename) + ConfirmationDialog(this, title) { + viewModel.saveAsRequest = null + onSaveAsPathChosen(request, newPath, newFilename) } } else { - SaveAsDialog(this, filePath, false) { path, _ -> - if (hasStoragePermission()) { - val file = File(path) - getFileOutputStream(file.toFileDirItem(this), true) { - val shouldOverwriteOriginalText = path == filePath - saveTextContent(it, shouldExitAfterSaving, shouldOverwriteOriginalText) - } + viewModel.saveAsRequest = null + onSaveAsPathChosen(request, newPath, newFilename) + } + } + + private fun onSaveAsPathChosen(request: SaveAsRequest, path: String, filename: String) { + if (request.hidePath) { + Intent(Intent.ACTION_CREATE_DOCUMENT).apply { + type = "text/plain" + putExtra(Intent.EXTRA_TITLE, filename) + addCategory(Intent.CATEGORY_OPENABLE) + + val requestCode = if (request.exitAfterSaving) { + SELECT_SAVE_FILE_AND_EXIT_INTENT } else { - toast(R.string.no_storage_permissions) + SELECT_SAVE_FILE_INTENT } + @Suppress("DEPRECATION") + startActivityForResult(this, requestCode) + } + } else if (hasStoragePermission()) { + val file = File(path) + getFileOutputStream(file.toFileDirItem(this), true) { + val shouldOverwriteOriginalText = path == viewModel.filePath + saveTextContent(it, request.exitAfterSaving, shouldOverwriteOriginalText) } + } else { + toast(R.string.no_storage_permissions) } } private fun saveText(shouldExitAfterSaving: Boolean = false) { updateFilePath() + val filePath = viewModel.filePath if (filePath.isEmpty()) { saveAsText(shouldExitAfterSaving) @@ -226,13 +328,13 @@ class ReadTextActivity : SimpleActivity() { private fun saveTextContent(outputStream: OutputStream?, shouldExitAfterSaving: Boolean, shouldOverwriteOriginalText: Boolean) { if (outputStream != null) { - val currentText = binding.readTextView.text.toString() + val currentText = viewModel.text outputStream.bufferedWriter().use { it.write(currentText) } toast(R.string.file_saved) hideKeyboard() if (shouldOverwriteOriginalText) { - originalText = currentText + viewModel.onTextSaved(currentText) } if (shouldExitAfterSaving) { @@ -254,7 +356,7 @@ class ReadTextActivity : SimpleActivity() { } } - val text = binding.readTextView.text.toString() + val text = viewModel.text ensureBackgroundThread { try { val base64 = Base64.encodeToString(text.toByteArray(), Base64.DEFAULT) @@ -271,6 +373,7 @@ class ReadTextActivity : SimpleActivity() { } private fun createWebPrintJob(webView: WebView) { + val filePath = viewModel.filePath val jobName = if (filePath.isNotEmpty()) { filePath.getFilenameFromPath() } else { @@ -284,10 +387,10 @@ class ReadTextActivity : SimpleActivity() { } } - private fun checkIntent(uri: Uri, savedInstanceState: Bundle?) { - originalText = if (uri.scheme == "file") { - filePath = uri.path!! - val file = File(filePath) + private fun checkIntent(uri: Uri, unsavedText: String?) { + val originalText = if (uri.scheme == "file") { + viewModel.filePath = uri.path!! + val file = File(viewModel.filePath) if (file.exists()) { try { file.readText() @@ -313,105 +416,12 @@ class ReadTextActivity : SimpleActivity() { } runOnUiThread { - var textToSet = originalText - - if (savedInstanceState != null) { - textToSet = savedInstanceState.getString(KEY_UNSAVED_TEXT, originalText) - } - - binding.readTextView.setText(textToSet) + viewModel.onTextLoaded(originalText, unsavedText ?: originalText) if (originalText.isNotEmpty()) { hideKeyboard() } else { - showKeyboard(binding.readTextView) - } - } - } - - private fun setupSearchButtons() { - searchQueryET.onTextChangeListener { - searchTextChanged(it) - } - - searchPrevBtn.setOnClickListener { - goToPrevSearchResult() - } - - searchNextBtn.setOnClickListener { - goToNextSearchResult() - } - - searchClearBtn.setOnClickListener { - closeSearch() - } - - searchQueryET.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ -> - if (actionId == EditorInfo.IME_ACTION_SEARCH) { - searchNextBtn.performClick() - return@OnEditorActionListener true + viewModel.requestEditorFocus() } - - false - }) - - binding.searchWrapper.setBackgroundColor(getProperPrimaryColor()) - val contrastColor = getProperPrimaryColor().getContrastColor() - arrayListOf(searchPrevBtn, searchNextBtn, searchClearBtn).forEach { - it.applyColorFilter(contrastColor) - } - } - - private fun searchTextChanged(text: String) { - binding.readTextView.text?.clearBackgroundSpans() - - if (text.isNotBlank() && text.length > 1) { - searchMatches = binding.readTextView.text.toString().searchMatches(text) - binding.readTextView.highlightText(text, getProperPrimaryColor()) - } - - if (searchMatches.isNotEmpty()) { - binding.readTextView.requestFocus() - binding.readTextView.setSelection(searchMatches.getOrNull(searchIndex) ?: 0) - } - - searchQueryET.postDelayed({ - searchQueryET.requestFocus() - }, 50) - } - - private fun goToPrevSearchResult() { - if (searchIndex > 0) { - searchIndex-- - } else { - searchIndex = searchMatches.lastIndex - } - - selectSearchMatch(binding.readTextView) - } - - private fun goToNextSearchResult() { - if (searchIndex < searchMatches.lastIndex) { - searchIndex++ - } else { - searchIndex = 0 - } - - selectSearchMatch(binding.readTextView) - } - - private fun closeSearch() { - searchQueryET.text?.clear() - isSearchActive = false - binding.searchWrapper.beGone() - hideKeyboard() - } - - private fun selectSearchMatch(editText: GestureEditText) { - if (searchMatches.isNotEmpty()) { - editText.requestFocus() - editText.setSelection(searchMatches.getOrNull(searchIndex) ?: 0) - } else { - hideKeyboard() } } } diff --git a/app/src/main/kotlin/org/fossify/filemanager/activities/SettingsActivity.kt b/app/src/main/kotlin/org/fossify/filemanager/activities/SettingsActivity.kt index 7f00eb6..8831cc0 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/activities/SettingsActivity.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/activities/SettingsActivity.kt @@ -2,274 +2,265 @@ package org.fossify.filemanager.activities import android.content.Intent import android.os.Bundle +import androidx.activity.compose.setContent +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import org.fossify.commons.compose.extensions.enableEdgeToEdgeSimple +import org.fossify.commons.compose.theme.AppThemeSurface import org.fossify.commons.dialogs.ChangeDateTimeFormatDialog import org.fossify.commons.dialogs.ConfirmationDialog import org.fossify.commons.dialogs.RadioGroupDialog import org.fossify.commons.dialogs.SecurityDialog -import org.fossify.commons.extensions.* -import org.fossify.commons.helpers.* +import org.fossify.commons.extensions.baseConfig +import org.fossify.commons.extensions.getFontSizeText +import org.fossify.commons.extensions.handleHiddenFolderPasswordProtection +import org.fossify.commons.extensions.hideKeyboard +import org.fossify.commons.extensions.isOrWasThankYouInstalled +import org.fossify.commons.extensions.launchPurchaseThankYouIntent +import org.fossify.commons.helpers.FONT_SIZE_EXTRA_LARGE +import org.fossify.commons.helpers.FONT_SIZE_LARGE +import org.fossify.commons.helpers.FONT_SIZE_MEDIUM +import org.fossify.commons.helpers.FONT_SIZE_SMALL +import org.fossify.commons.helpers.PROTECTION_FINGERPRINT +import org.fossify.commons.helpers.SHOW_ALL_TABS +import org.fossify.commons.helpers.isTiramisuPlus import org.fossify.commons.models.RadioItem import org.fossify.filemanager.R -import org.fossify.filemanager.databinding.ActivitySettingsBinding -import org.fossify.filemanager.dialogs.ManageVisibleTabsDialog +import org.fossify.filemanager.compose.settings.SettingsScreen +import org.fossify.filemanager.compose.settings.SettingsAction +import org.fossify.filemanager.compose.settings.SettingsUiState import org.fossify.filemanager.extensions.config import org.fossify.filemanager.helpers.RootHelpers import java.util.Locale import kotlin.system.exitProcess class SettingsActivity : SimpleActivity() { - private val binding by viewBinding(ActivitySettingsBinding::inflate) + private var uiState by mutableStateOf<SettingsUiState?>(null) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - setContentView(binding.root) - binding.apply { - setupEdgeToEdge(padBottomSystem = listOf(settingsNestedScrollview)) - setupMaterialScrollListener(binding.settingsNestedScrollview, binding.settingsAppbar) + enableEdgeToEdgeSimple() + uiState = buildUiState() + setContent { + AppThemeSurface { + uiState?.let { state -> + SettingsScreen( + state = state, + onAction = ::onSettingsAction, + onManageShownTabsConfirm = ::onManageShownTabsConfirmed, + goBack = ::goBack + ) + } + } } } override fun onResume() { super.onResume() - setupTopAppBar(binding.settingsAppbar, NavigationIcon.Arrow) + refreshUiState() + } - setupCustomizeColors() - setupUseEnglish() - setupLanguage() - setupManageFavorites() - setupManageShownTabs() - setupChangeDateTimeFormat() - setupFontSize() - setupShowHidden() - setupEnablePullToRefresh() - setupPressBackTwice() - setupHiddenItemPasswordProtection() - setupAppPasswordProtection() - setupFileDeletionPasswordProtection() - setupKeepLastModified() - setupDeleteConfirmation() - setupEnableRootAccess() - updateTextColors(binding.settingsNestedScrollview) + private fun refreshUiState() { + uiState = buildUiState() + } - binding.apply { - arrayOf( - settingsColorCustomizationSectionLabel, - settingsGeneralSettingsLabel, - settingsVisibilityLabel, - settingsScrollingLabel, - settingsFileOperationsLabel, - settingsSecurityLabel - ).forEach { - it.setTextColor(getProperPrimaryColor()) - } - } + private fun buildUiState(): SettingsUiState { + val hideGoogleRelations = resources.getBoolean(org.fossify.commons.R.bool.hide_google_relations) + val thankYouInstalled = isOrWasThankYouInstalled(allowPretend = false) + return SettingsUiState( + showPurchaseThankYou = !thankYouInstalled && !hideGoogleRelations, + canPurchaseThankYou = !thankYouInstalled, + showUseEnglish = (config.wasUseEnglishToggled || Locale.getDefault().language != "en") && !isTiramisuPlus(), + useEnglish = config.useEnglish, + showLanguage = isTiramisuPlus(), + language = Locale.getDefault().displayLanguage, + fontSize = getFontSizeText(), + pressBackTwice = config.pressBackTwice, + showHidden = config.showHidden, + enablePullToRefresh = config.enablePullToRefresh, + keepLastModified = config.keepLastModified, + skipDeleteConfirmation = config.skipDeleteConfirmation, + hiddenItemPasswordProtection = config.isHiddenPasswordProtectionOn, + appPasswordProtection = config.isAppPasswordProtectionOn, + fileDeletionPasswordProtection = config.isDeletePasswordProtectionOn, + showEnableRootAccess = config.isRootAvailable, + enableRootAccess = config.enableRootAccess, + showCheckmarksOnSwitches = baseConfig.showCheckmarksOnSwitches, + shownTabs = config.showTabs + ) } - private fun setupCustomizeColors() { - binding.settingsColorCustomizationHolder.setOnClickListener { - startCustomizationActivity() + private fun onSettingsAction(action: SettingsAction) { + when (action) { + SettingsAction.CUSTOMIZE_COLORS -> startCustomizationActivity() + SettingsAction.PURCHASE_THANK_YOU -> onPurchaseThankYouClick() + SettingsAction.USE_ENGLISH -> onUseEnglishClick() + SettingsAction.LANGUAGE -> launchChangeAppLanguageIntent() + SettingsAction.MANAGE_FAVORITES -> startActivity(Intent(this, FavoritesActivity::class.java)) + SettingsAction.CHANGE_DATE_TIME_FORMAT -> ChangeDateTimeFormatDialog(this) {} + SettingsAction.FONT_SIZE -> onFontSizeClick() + else -> onToggleAction(action) } } - private fun setupUseEnglish() { - binding.apply { - settingsUseEnglishHolder.beVisibleIf((config.wasUseEnglishToggled || Locale.getDefault().language != "en") && !isTiramisuPlus()) - settingsUseEnglish.isChecked = config.useEnglish - settingsUseEnglishHolder.setOnClickListener { - settingsUseEnglish.toggle() - config.useEnglish = settingsUseEnglish.isChecked - exitProcess(0) - } + private fun onToggleAction(action: SettingsAction) { + when (action) { + SettingsAction.PRESS_BACK_TWICE -> onPressBackTwiceClick() + SettingsAction.SHOW_HIDDEN -> onShowHiddenClick() + SettingsAction.ENABLE_PULL_TO_REFRESH -> onEnablePullToRefreshClick() + SettingsAction.KEEP_LAST_MODIFIED -> onKeepLastModifiedClick() + SettingsAction.SKIP_DELETE_CONFIRMATION -> onSkipDeleteConfirmationClick() + SettingsAction.HIDDEN_ITEM_PASSWORD_PROTECTION -> onHiddenItemPasswordProtectionClick() + SettingsAction.APP_PASSWORD_PROTECTION -> onAppPasswordProtectionClick() + SettingsAction.FILE_DELETION_PASSWORD_PROTECTION -> onFileDeletionPasswordProtectionClick() + SettingsAction.ENABLE_ROOT_ACCESS -> onEnableRootAccessClick() + else -> {} } } - private fun setupLanguage() { - binding.apply { - settingsLanguage.text = Locale.getDefault().displayLanguage - settingsLanguageHolder.beVisibleIf(isTiramisuPlus()) - settingsLanguageHolder.setOnClickListener { - launchChangeAppLanguageIntent() - } - } + private fun goBack() { + hideKeyboard() + finish() } - private fun setupManageFavorites() { - binding.settingsManageFavoritesHolder.setOnClickListener { - startActivity(Intent(this, FavoritesActivity::class.java)) + private fun onPurchaseThankYouClick() { + if (uiState?.canPurchaseThankYou == true) { + launchPurchaseThankYouIntent() } } - private fun setupManageShownTabs() { - binding.settingsManageTabsHolder.setOnClickListener { - ManageVisibleTabsDialog(this) - } + private fun onUseEnglishClick() { + config.useEnglish = !config.useEnglish + exitProcess(0) } - private fun setupChangeDateTimeFormat() { - binding.settingsChangeDateTimeFormatHolder.setOnClickListener { - ChangeDateTimeFormatDialog(this) {} - } + private fun onManageShownTabsConfirmed(tabsMask: Int) { + config.showTabs = tabsMask + refreshUiState() } - private fun setupFontSize() { - binding.settingsFontSize.text = getFontSizeText() - binding.settingsFontSizeHolder.setOnClickListener { - val items = arrayListOf( - RadioItem(FONT_SIZE_SMALL, getString(R.string.small)), - RadioItem(FONT_SIZE_MEDIUM, getString(R.string.medium)), - RadioItem(FONT_SIZE_LARGE, getString(R.string.large)), - RadioItem(FONT_SIZE_EXTRA_LARGE, getString(R.string.extra_large)) - ) + private fun onFontSizeClick() { + val items = arrayListOf( + RadioItem(FONT_SIZE_SMALL, getString(R.string.small)), + RadioItem(FONT_SIZE_MEDIUM, getString(R.string.medium)), + RadioItem(FONT_SIZE_LARGE, getString(R.string.large)), + RadioItem(FONT_SIZE_EXTRA_LARGE, getString(R.string.extra_large)) + ) - RadioGroupDialog(this@SettingsActivity, items, config.fontSize) { - config.fontSize = it as Int - binding.settingsFontSize.text = getFontSizeText() - } + RadioGroupDialog(this, items, config.fontSize) { + config.fontSize = it as Int + refreshUiState() } } - private fun setupShowHidden() { - binding.settingsShowHidden.isChecked = config.showHidden - binding.settingsShowHiddenHolder.setOnClickListener { - if (config.showHidden) { + private fun onPressBackTwiceClick() { + config.pressBackTwice = !config.pressBackTwice + refreshUiState() + } + + private fun onShowHiddenClick() { + if (config.showHidden) { + toggleShowHidden() + } else { + handleHiddenFolderPasswordProtection { toggleShowHidden() - } else { - handleHiddenFolderPasswordProtection { - toggleShowHidden() - } } } } private fun toggleShowHidden() { - binding.settingsShowHidden.toggle() - config.showHidden = binding.settingsShowHidden.isChecked + config.showHidden = !config.showHidden + refreshUiState() } - private fun setupEnablePullToRefresh() { - binding.apply { - settingsEnablePullToRefresh.isChecked = config.enablePullToRefresh - settingsEnablePullToRefreshHolder.setOnClickListener { - settingsEnablePullToRefresh.toggle() - config.enablePullToRefresh = settingsEnablePullToRefresh.isChecked - } - } + private fun onEnablePullToRefreshClick() { + config.enablePullToRefresh = !config.enablePullToRefresh + refreshUiState() } - private fun setupPressBackTwice() { - binding.apply { - settingsPressBackTwice.isChecked = config.pressBackTwice - settingsPressBackTwiceHolder.setOnClickListener { - settingsPressBackTwice.toggle() - config.pressBackTwice = settingsPressBackTwice.isChecked - } - } + private fun onKeepLastModifiedClick() { + config.keepLastModified = !config.keepLastModified + refreshUiState() } - private fun setupHiddenItemPasswordProtection() { - binding.settingsPasswordProtection.isChecked = config.isHiddenPasswordProtectionOn - binding.settingsPasswordProtectionHolder.setOnClickListener { - val tabToShow = if (config.isHiddenPasswordProtectionOn) config.hiddenProtectionType else SHOW_ALL_TABS - SecurityDialog(this, config.hiddenPasswordHash, tabToShow) { hash, type, success -> - if (success) { - val hasPasswordProtection = config.isHiddenPasswordProtectionOn - binding.settingsPasswordProtection.isChecked = !hasPasswordProtection - config.isHiddenPasswordProtectionOn = !hasPasswordProtection - config.hiddenPasswordHash = if (hasPasswordProtection) "" else hash - config.hiddenProtectionType = type - - if (config.isHiddenPasswordProtectionOn) { - val confirmationTextId = if (config.hiddenProtectionType == PROTECTION_FINGERPRINT) - R.string.fingerprint_setup_successfully else R.string.protection_setup_successfully - ConfirmationDialog(this, "", confirmationTextId, R.string.ok, 0) { } - } - } - } - } + private fun onSkipDeleteConfirmationClick() { + config.skipDeleteConfirmation = !config.skipDeleteConfirmation + refreshUiState() } - private fun setupAppPasswordProtection() { - binding.settingsAppPasswordProtection.isChecked = config.isAppPasswordProtectionOn - binding.settingsAppPasswordProtectionHolder.setOnClickListener { - val tabToShow = if (config.isAppPasswordProtectionOn) config.appProtectionType else SHOW_ALL_TABS - SecurityDialog(this, config.appPasswordHash, tabToShow) { hash, type, success -> - if (success) { - val hasPasswordProtection = config.isAppPasswordProtectionOn - binding.settingsAppPasswordProtection.isChecked = !hasPasswordProtection - config.isAppPasswordProtectionOn = !hasPasswordProtection - config.appPasswordHash = if (hasPasswordProtection) "" else hash - config.appProtectionType = type + private fun onHiddenItemPasswordProtectionClick() { + val tabToShow = if (config.isHiddenPasswordProtectionOn) config.hiddenProtectionType else SHOW_ALL_TABS + SecurityDialog(this, config.hiddenPasswordHash, tabToShow) { hash, type, success -> + if (success) { + val hasPasswordProtection = config.isHiddenPasswordProtectionOn + config.isHiddenPasswordProtectionOn = !hasPasswordProtection + config.hiddenPasswordHash = if (hasPasswordProtection) "" else hash + config.hiddenProtectionType = type + refreshUiState() - if (config.isAppPasswordProtectionOn) { - val confirmationTextId = if (config.appProtectionType == PROTECTION_FINGERPRINT) - R.string.fingerprint_setup_successfully else R.string.protection_setup_successfully - ConfirmationDialog(this, "", confirmationTextId, R.string.ok, 0) { } - } + if (config.isHiddenPasswordProtectionOn) { + showProtectionSetupConfirmation(config.hiddenProtectionType) } } } } - private fun setupFileDeletionPasswordProtection() { - binding.settingsFileDeletionPasswordProtection.isChecked = config.isDeletePasswordProtectionOn - binding.settingsFileDeletionPasswordProtectionHolder.setOnClickListener { - val tabToShow = if (config.isDeletePasswordProtectionOn) config.deleteProtectionType else SHOW_ALL_TABS - SecurityDialog(this, config.deletePasswordHash, tabToShow) { hash, type, success -> - if (success) { - val hasPasswordProtection = config.isDeletePasswordProtectionOn - binding.settingsFileDeletionPasswordProtection.isChecked = !hasPasswordProtection - config.isDeletePasswordProtectionOn = !hasPasswordProtection - config.deletePasswordHash = if (hasPasswordProtection) "" else hash - config.deleteProtectionType = type + private fun onAppPasswordProtectionClick() { + val tabToShow = if (config.isAppPasswordProtectionOn) config.appProtectionType else SHOW_ALL_TABS + SecurityDialog(this, config.appPasswordHash, tabToShow) { hash, type, success -> + if (success) { + val hasPasswordProtection = config.isAppPasswordProtectionOn + config.isAppPasswordProtectionOn = !hasPasswordProtection + config.appPasswordHash = if (hasPasswordProtection) "" else hash + config.appProtectionType = type + refreshUiState() - if (config.isDeletePasswordProtectionOn) { - val confirmationTextId = if (config.deleteProtectionType == PROTECTION_FINGERPRINT) - R.string.fingerprint_setup_successfully else R.string.protection_setup_successfully - ConfirmationDialog(this, "", confirmationTextId, R.string.ok, 0) { } - } + if (config.isAppPasswordProtectionOn) { + showProtectionSetupConfirmation(config.appProtectionType) } } } } - private fun setupKeepLastModified() { - binding.apply { - settingsKeepLastModified.isChecked = config.keepLastModified - settingsKeepLastModifiedHolder.setOnClickListener { - settingsKeepLastModified.toggle() - config.keepLastModified = settingsKeepLastModified.isChecked + private fun onFileDeletionPasswordProtectionClick() { + val tabToShow = if (config.isDeletePasswordProtectionOn) config.deleteProtectionType else SHOW_ALL_TABS + SecurityDialog(this, config.deletePasswordHash, tabToShow) { hash, type, success -> + if (success) { + val hasPasswordProtection = config.isDeletePasswordProtectionOn + config.isDeletePasswordProtectionOn = !hasPasswordProtection + config.deletePasswordHash = if (hasPasswordProtection) "" else hash + config.deleteProtectionType = type + refreshUiState() + + if (config.isDeletePasswordProtectionOn) { + showProtectionSetupConfirmation(config.deleteProtectionType) + } } } } - private fun setupDeleteConfirmation() { - binding.apply { - settingsSkipDeleteConfirmation.isChecked = config.skipDeleteConfirmation - settingsSkipDeleteConfirmationHolder.setOnClickListener { - settingsSkipDeleteConfirmation.toggle() - config.skipDeleteConfirmation = settingsSkipDeleteConfirmation.isChecked - } + private fun showProtectionSetupConfirmation(protectionType: Int) { + val confirmationTextId = if (protectionType == PROTECTION_FINGERPRINT) { + R.string.fingerprint_setup_successfully + } else { + R.string.protection_setup_successfully } + ConfirmationDialog(this, "", confirmationTextId, R.string.ok, 0) { } } - private fun setupEnableRootAccess() { - binding.apply { - settingsEnableRootAccessHolder.beVisibleIf(config.isRootAvailable) - settingsEnableRootAccess.isChecked = config.enableRootAccess - settingsEnableRootAccessHolder.setOnClickListener { - if (!config.enableRootAccess) { - RootHelpers(this@SettingsActivity).askRootIfNeeded { - toggleRootAccess(it) - } - } else { - toggleRootAccess(false) - } + private fun onEnableRootAccessClick() { + if (!config.enableRootAccess) { + RootHelpers(this).askRootIfNeeded { + toggleRootAccess(it) } + } else { + toggleRootAccess(false) } } private fun toggleRootAccess(enable: Boolean) { - binding.settingsEnableRootAccess.isChecked = enable config.enableRootAccess = enable + refreshUiState() } } diff --git a/app/src/main/kotlin/org/fossify/filemanager/adapters/DecompressItemsAdapter.kt b/app/src/main/kotlin/org/fossify/filemanager/adapters/DecompressItemsAdapter.kt deleted file mode 100644 index 4478a40..0000000 --- a/app/src/main/kotlin/org/fossify/filemanager/adapters/DecompressItemsAdapter.kt +++ /dev/null @@ -1,139 +0,0 @@ -package org.fossify.filemanager.adapters - -import android.content.pm.PackageManager -import android.graphics.drawable.Drawable -import android.util.TypedValue -import android.view.Menu -import android.view.View -import android.view.ViewGroup -import com.bumptech.glide.Glide -import com.bumptech.glide.load.engine.DiskCacheStrategy -import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions -import com.bumptech.glide.request.RequestOptions -import org.fossify.commons.adapters.MyRecyclerViewAdapter -import org.fossify.commons.extensions.getColoredDrawableWithColor -import org.fossify.commons.extensions.getTextSize -import org.fossify.commons.extensions.getTimeFormat -import org.fossify.commons.helpers.getFilePlaceholderDrawables -import org.fossify.commons.views.MyRecyclerView -import org.fossify.filemanager.R -import org.fossify.filemanager.activities.SimpleActivity -import org.fossify.filemanager.databinding.ItemDecompressionListFileDirBinding -import org.fossify.filemanager.extensions.config -import org.fossify.filemanager.models.ListItem -import java.util.Locale - -class DecompressItemsAdapter(activity: SimpleActivity, var listItems: MutableList<ListItem>, recyclerView: MyRecyclerView, itemClick: (Any) -> Unit) : - MyRecyclerViewAdapter(activity, recyclerView, itemClick) { - - private lateinit var fileDrawable: Drawable - private lateinit var folderDrawable: Drawable - private var fileDrawables = HashMap<String, Drawable>() - private var fontSize = 0f - private var smallerFontSize = 0f - private var dateFormat = "" - private var timeFormat = "" - - init { - initDrawables() - fontSize = activity.getTextSize() - smallerFontSize = fontSize * 0.8f - dateFormat = activity.config.dateFormat - timeFormat = activity.getTimeFormat() - } - - override fun getActionMenuId() = 0 - - override fun prepareActionMode(menu: Menu) {} - - override fun actionItemPressed(id: Int) {} - - override fun getSelectableItemCount() = 0 - - override fun getIsItemSelectable(position: Int) = false - - override fun getItemSelectionKey(position: Int) = 0 - - override fun getItemKeyPosition(key: Int) = 0 - - override fun onActionModeCreated() {} - - override fun onActionModeDestroyed() {} - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { - return createViewHolder(ItemDecompressionListFileDirBinding.inflate(layoutInflater, parent, false).root) - } - - override fun onBindViewHolder(holder: MyRecyclerViewAdapter.ViewHolder, position: Int) { - val fileDirItem = listItems[position] - holder.bindView(fileDirItem, true, false) { itemView, layoutPosition -> - setupView(itemView, fileDirItem) - } - bindViewHolder(holder) - } - - override fun getItemCount() = listItems.size - - override fun onViewRecycled(holder: ViewHolder) { - super.onViewRecycled(holder) - if (!activity.isDestroyed && !activity.isFinishing) { - ItemDecompressionListFileDirBinding.bind(holder.itemView).apply { - if (itemIcon != null) { - Glide.with(activity).clear(itemIcon) - } - } - } - } - - private fun setupView(view: View, listItem: ListItem) { - ItemDecompressionListFileDirBinding.bind(view).apply { - val fileName = listItem.name - itemName.text = fileName - itemName.setTextColor(textColor) - itemName.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize) - - if (listItem.isDirectory) { - itemIcon.setImageDrawable(folderDrawable) - } else { - val drawable = fileDrawables.getOrElse(fileName.substringAfterLast(".").lowercase(Locale.getDefault()), { fileDrawable }) - val options = RequestOptions() - .signature(listItem.getKey()) - .diskCacheStrategy(DiskCacheStrategy.RESOURCE) - .error(drawable) - .centerCrop() - - val itemToLoad = getImagePathToLoad(listItem.path) - if (!activity.isDestroyed) { - Glide.with(activity) - .load(itemToLoad) - .transition(DrawableTransitionOptions.withCrossFade()) - .apply(options) - .into(itemIcon) - } - } - } - } - - private fun getImagePathToLoad(path: String): Any { - return if (path.endsWith(".apk", true)) { - val packageInfo = activity.packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES) - val appInfo = packageInfo?.applicationInfo - if (appInfo != null) { - appInfo.sourceDir = path - appInfo.publicSourceDir = path - appInfo.loadIcon(activity.packageManager) - } else { - path - } - } else { - path - } - } - - private fun initDrawables() { - folderDrawable = resources.getColoredDrawableWithColor(R.drawable.ic_folder_vector, properPrimaryColor) - folderDrawable.alpha = 180 - fileDrawable = resources.getDrawable(R.drawable.ic_file_generic) - fileDrawables = getFilePlaceholderDrawables(activity) - } -} diff --git a/app/src/main/kotlin/org/fossify/filemanager/adapters/ItemsAdapter.kt b/app/src/main/kotlin/org/fossify/filemanager/adapters/ItemsAdapter.kt index 90b471f..206d2e0 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/adapters/ItemsAdapter.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/adapters/ItemsAdapter.kt @@ -1,14 +1,6 @@ package org.fossify.filemanager.adapters -import android.annotation.SuppressLint -import android.content.Intent -import android.content.pm.PackageManager -import android.content.pm.ShortcutInfo -import android.content.pm.ShortcutManager import android.graphics.drawable.Drawable -import android.graphics.drawable.Icon -import android.graphics.drawable.LayerDrawable -import android.net.Uri import android.util.TypedValue import android.view.LayoutInflater import android.view.Menu @@ -20,7 +12,6 @@ import android.widget.TextView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import androidx.viewbinding.ViewBinding import com.bumptech.glide.Glide -import com.bumptech.glide.load.DecodeFormat import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.resource.bitmap.CenterCrop import com.bumptech.glide.load.resource.bitmap.RoundedCorners @@ -28,95 +19,40 @@ import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.RequestOptions import com.qtalk.recyclerviewfastscroller.RecyclerViewFastScroller import com.stericson.RootTools.RootTools -import net.lingala.zip4j.exception.ZipException -import net.lingala.zip4j.io.inputstream.ZipInputStream -import net.lingala.zip4j.io.outputstream.ZipOutputStream -import net.lingala.zip4j.model.LocalFileHeader -import net.lingala.zip4j.model.ZipParameters -import net.lingala.zip4j.model.enums.EncryptionMethod import org.fossify.commons.adapters.MyRecyclerViewAdapter -import org.fossify.commons.dialogs.ConfirmationDialog -import org.fossify.commons.dialogs.FilePickerDialog -import org.fossify.commons.dialogs.PropertiesDialog -import org.fossify.commons.dialogs.RadioGroupDialog -import org.fossify.commons.dialogs.RenameDialog -import org.fossify.commons.dialogs.RenameItemDialog -import org.fossify.commons.dialogs.RenameItemsDialog import org.fossify.commons.extensions.applyColorFilter import org.fossify.commons.extensions.beGone import org.fossify.commons.extensions.beVisible import org.fossify.commons.extensions.beVisibleIf -import org.fossify.commons.extensions.convertToBitmap -import org.fossify.commons.extensions.copyToClipboard -import org.fossify.commons.extensions.createDirectorySync -import org.fossify.commons.extensions.deleteFile -import org.fossify.commons.extensions.deleteFileBg -import org.fossify.commons.extensions.deleteFolderBg import org.fossify.commons.extensions.formatDate import org.fossify.commons.extensions.formatSize -import org.fossify.commons.extensions.getAndroidSAFFileItems -import org.fossify.commons.extensions.getAndroidSAFUri import org.fossify.commons.extensions.getColoredDrawableWithColor -import org.fossify.commons.extensions.getDefaultCopyDestinationPath -import org.fossify.commons.extensions.getDocumentFile -import org.fossify.commons.extensions.getDoesFilePathExist -import org.fossify.commons.extensions.getFileCount -import org.fossify.commons.extensions.getFileInputStreamSync -import org.fossify.commons.extensions.getFileOutputStreamSync -import org.fossify.commons.extensions.getFilenameFromPath -import org.fossify.commons.extensions.getIsPathDirectory -import org.fossify.commons.extensions.getMimeType import org.fossify.commons.extensions.getParentPath -import org.fossify.commons.extensions.getProperSize import org.fossify.commons.extensions.getTextSize import org.fossify.commons.extensions.getTimeFormat -import org.fossify.commons.extensions.handleDeletePasswordProtection import org.fossify.commons.extensions.hasOTGConnected import org.fossify.commons.extensions.highlightTextPart -import org.fossify.commons.extensions.isPathOnOTG -import org.fossify.commons.extensions.isRestrictedSAFOnlyRoot -import org.fossify.commons.extensions.relativizeWith import org.fossify.commons.extensions.setupViewBackground -import org.fossify.commons.extensions.showErrorToast -import org.fossify.commons.extensions.toFileDirItem import org.fossify.commons.extensions.toast -import org.fossify.commons.helpers.CONFLICT_OVERWRITE -import org.fossify.commons.helpers.CONFLICT_SKIP import org.fossify.commons.helpers.VIEW_TYPE_LIST import org.fossify.commons.helpers.ensureBackgroundThread import org.fossify.commons.helpers.getFilePlaceholderDrawables import org.fossify.commons.models.FileDirItem -import org.fossify.commons.models.RadioItem import org.fossify.commons.views.MyRecyclerView import org.fossify.filemanager.R import org.fossify.filemanager.activities.SimpleActivity -import org.fossify.filemanager.activities.SplashActivity import org.fossify.filemanager.databinding.ItemDirGridBinding import org.fossify.filemanager.databinding.ItemEmptyBinding import org.fossify.filemanager.databinding.ItemFileDirListBinding import org.fossify.filemanager.databinding.ItemFileGridBinding import org.fossify.filemanager.databinding.ItemSectionBinding -import org.fossify.filemanager.dialogs.CompressAsDialog import org.fossify.filemanager.extensions.config import org.fossify.filemanager.extensions.isPathOnRoot import org.fossify.filemanager.extensions.isZipFile import org.fossify.filemanager.extensions.setAs -import org.fossify.filemanager.extensions.setLastModified -import org.fossify.filemanager.extensions.sharePaths -import org.fossify.filemanager.extensions.toggleItemVisibility -import org.fossify.filemanager.extensions.tryOpenPathIntent -import org.fossify.filemanager.helpers.OPEN_AS_AUDIO -import org.fossify.filemanager.helpers.OPEN_AS_IMAGE -import org.fossify.filemanager.helpers.OPEN_AS_OTHER -import org.fossify.filemanager.helpers.OPEN_AS_TEXT -import org.fossify.filemanager.helpers.OPEN_AS_VIDEO -import org.fossify.filemanager.helpers.RootHelpers +import org.fossify.filemanager.helpers.FileItemActions import org.fossify.filemanager.interfaces.ItemOperationsListener import org.fossify.filemanager.models.ListItem -import java.io.BufferedInputStream -import java.io.Closeable -import java.io.File -import java.util.LinkedList import java.util.Locale class ItemsAdapter( @@ -143,6 +79,11 @@ class ItemsAdapter( private var timeFormat = "" private val config = activity.config + private val fileActions = FileItemActions( + activity = activity, + refresh = { listener?.refreshFragment() }, + finishSelection = { finishActMode() } + ) private val viewType = if (canHaveIndividualViewType) { config.getFolderViewType( path = listItems.firstOrNull { !it.isSectionTitle }?.mPath?.getParentPath().orEmpty() @@ -207,7 +148,7 @@ class ItemsAdapter( R.id.cab_compress -> compressSelection() R.id.cab_decompress -> decompressSelection() R.id.cab_select_all -> selectAll() - R.id.cab_delete -> if (config.skipDeleteConfirmation) deleteFiles() else askConfirmDelete() + R.id.cab_delete -> askConfirmDelete() } } @@ -295,631 +236,71 @@ class ItemsAdapter( private fun confirmSelection() { if (selectedKeys.isNotEmpty()) { - val paths = getSelectedFileDirItems() - .asSequence() - .filter { !it.isDirectory }.map { it.path } - .toMutableList() as ArrayList<String> - if (paths.isEmpty()) { - finishActMode() - } else { + fileActions.confirmSelection(getSelectedFileDirItems()) { paths -> listener?.selectedPaths(paths) } } } private fun displayRenameDialog() { - val fileDirItems = getSelectedFileDirItems() - val paths = fileDirItems.asSequence().map { it.path }.toMutableList() as ArrayList<String> - when { - paths.size == 1 -> { - val oldPath = paths.first() - RenameItemDialog(activity, oldPath) { - config.moveFavorite(oldPath, it) - activity.runOnUiThread { - listener?.refreshFragment() - finishActMode() - } - } - } - - fileDirItems.any { it.isDirectory } -> RenameItemsDialog(activity, paths) { - activity.runOnUiThread { - listener?.refreshFragment() - finishActMode() - } - } - - else -> RenameDialog(activity, paths, false) { - activity.runOnUiThread { - listener?.refreshFragment() - finishActMode() - } - } - } + fileActions.rename(getSelectedFileDirItems()) } private fun showProperties() { - if (selectedKeys.size <= 1) { - PropertiesDialog(activity, getFirstSelectedItemPath(), config.shouldShowHidden()) - } else { - val paths = getSelectedFileDirItems().map { it.path } - PropertiesDialog(activity, paths, config.shouldShowHidden()) - } + fileActions.showProperties(getSelectedFileDirItems()) } private fun shareFiles() { - val selectedItems = getSelectedFileDirItems() - val paths = ArrayList<String>(selectedItems.size) - selectedItems.forEach { - addFileUris(it.path, paths) - } - activity.sharePaths(paths) + fileActions.share(getSelectedFileDirItems()) } private fun toggleFileVisibility(hide: Boolean) { - ensureBackgroundThread { - getSelectedFileDirItems().forEach { - activity.toggleItemVisibility(it.path, hide) - } - activity.runOnUiThread { - listener?.refreshFragment() - finishActMode() - } - } + fileActions.toggleVisibility(getSelectedFileDirItems(), hide) } - @SuppressLint("NewApi") private fun createShortcut() { - val manager = activity.getSystemService(ShortcutManager::class.java) - if (manager.isRequestPinShortcutSupported) { - val path = getFirstSelectedItemPath() - val drawable = resources.getDrawable(R.drawable.shortcut_folder).mutate() - getShortcutImage(path, drawable) { - val intent = Intent(activity, SplashActivity::class.java) - intent.action = Intent.ACTION_VIEW - intent.flags = - intent.flags or - Intent.FLAG_ACTIVITY_NEW_TASK or - Intent.FLAG_ACTIVITY_CLEAR_TASK or - Intent.FLAG_ACTIVITY_NO_HISTORY - intent.data = Uri.fromFile(File(path)) - - val shortcut = ShortcutInfo.Builder(activity, path) - .setShortLabel(path.getFilenameFromPath()) - .setIcon(Icon.createWithBitmap(drawable.convertToBitmap())) - .setIntent(intent) - .build() - - manager.requestPinShortcut(shortcut, null) - } - } - } - - private fun getShortcutImage(path: String, drawable: Drawable, callback: () -> Unit) { - val appIconColor = baseConfig.appIconColor - (drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_folder_background) - .applyColorFilter(appIconColor) - if (activity.getIsPathDirectory(path)) { - callback() - } else { - ensureBackgroundThread { - val options = RequestOptions() - .format(DecodeFormat.PREFER_ARGB_8888) - .skipMemoryCache(true) - .diskCacheStrategy(DiskCacheStrategy.NONE) - .fitCenter() - - val size = activity.resources.getDimension(R.dimen.shortcut_size).toInt() - val builder = Glide.with(activity) - .asDrawable() - .load(getImagePathToLoad(path)) - .apply(options) - .centerCrop() - .into(size, size) - - try { - val bitmap = builder.get() - drawable.findDrawableByLayerId(R.id.shortcut_folder_background) - .applyColorFilter(0) - drawable.setDrawableByLayerId(R.id.shortcut_folder_image, bitmap) - } catch (e: Exception) { - val fileIcon = fileDrawables - .getOrElse( - key = path.substringAfterLast(".").lowercase(Locale.getDefault()), - defaultValue = { fileDrawable } - ) - drawable.setDrawableByLayerId(R.id.shortcut_folder_image, fileIcon) - } - - activity.runOnUiThread { - callback() - } - } - } - } - - @SuppressLint("NewApi") - private fun addFileUris(path: String, paths: ArrayList<String>) { - if (activity.getIsPathDirectory(path)) { - val shouldShowHidden = config.shouldShowHidden() - when { - activity.isRestrictedSAFOnlyRoot(path) -> { - activity.getAndroidSAFFileItems(path, shouldShowHidden, false) { files -> - files.forEach { - addFileUris(activity.getAndroidSAFUri(it.path).toString(), paths) - } - } - } - - activity.isPathOnOTG(path) -> { - activity.getDocumentFile(path)?.listFiles() - ?.filter { if (shouldShowHidden) true else !it.name!!.startsWith(".") } - ?.forEach { - addFileUris(it.uri.toString(), paths) - } - } - - else -> { - File(path).listFiles() - ?.filter { if (shouldShowHidden) true else !it.name.startsWith('.') } - ?.forEach { - addFileUris(it.absolutePath, paths) - } - } - } - } else { - paths.add(path) - } + fileActions.firstItem.createShortcut(getFirstSelectedItemPath()) } private fun copyPath() { - activity.copyToClipboard(getFirstSelectedItemPath()) - finishActMode() + fileActions.firstItem.copyPath(getFirstSelectedItemPath()) } private fun setAs() { - activity.setAs(getFirstSelectedItemPath()) + fileActions.firstItem.setAs(getFirstSelectedItemPath()) } private fun openWith() { - activity.tryOpenPathIntent(getFirstSelectedItemPath(), true) + fileActions.firstItem.openWith(getFirstSelectedItemPath()) } private fun openAs() { - val res = activity.resources - val items = arrayListOf( - RadioItem(OPEN_AS_TEXT, res.getString(R.string.text_file)), - RadioItem(OPEN_AS_IMAGE, res.getString(R.string.image_file)), - RadioItem(OPEN_AS_AUDIO, res.getString(R.string.audio_file)), - RadioItem(OPEN_AS_VIDEO, res.getString(R.string.video_file)), - RadioItem(OPEN_AS_OTHER, res.getString(R.string.other_file)) - ) - - RadioGroupDialog(activity, items) { - activity.tryOpenPathIntent(getFirstSelectedItemPath(), false, it as Int) - } + fileActions.firstItem.openAs(getFirstSelectedItemPath()) } private fun tryMoveFiles() { - activity.handleDeletePasswordProtection { - copyMoveTo(false) - } + fileActions.tryMoveFiles(getSelectedFileDirItems()) } private fun copyMoveTo(isCopyOperation: Boolean) { - val files = getSelectedFileDirItems() - val firstFile = files[0] - val source = firstFile.getParentPath() - FilePickerDialog( - activity = activity, - currPath = activity.getDefaultCopyDestinationPath(config.shouldShowHidden(), source), - pickFile = false, - showHidden = config.shouldShowHidden(), - showFAB = true, - canAddShowHiddenButton = true, - showFavoritesButton = true - ) { - config.lastCopyPath = it - if (activity.isPathOnRoot(it) || activity.isPathOnRoot(firstFile.path)) { - copyMoveRootItems(files, it, isCopyOperation) - } else { - activity.copyMoveFilesTo( - fileDirItems = files, - source = source, - destination = it, - isCopyOperation = isCopyOperation, - copyPhotoVideoOnly = false, - copyHidden = config.shouldShowHidden() - ) { - if (!isCopyOperation) { - files.forEach { sourceFileDir -> - val sourcePath = sourceFileDir.path - if ( - activity.isRestrictedSAFOnlyRoot(sourcePath) - && activity.getDoesFilePathExist(sourcePath) - ) { - activity.deleteFile(sourceFileDir, true) { - listener?.refreshFragment() - activity.runOnUiThread { - finishActMode() - } - } - } else { - val sourceFile = File(sourcePath) - if ( - activity.getDoesFilePathExist(source) - && activity.getIsPathDirectory(source) - && sourceFile.list()?.isEmpty() == true - && sourceFile.getProperSize(true) == 0L - && sourceFile.getFileCount(true) == 0 - ) { - val sourceFolder = sourceFile.toFileDirItem(activity) - activity.deleteFile(sourceFolder, true) { - listener?.refreshFragment() - activity.runOnUiThread { - finishActMode() - } - } - } else { - listener?.refreshFragment() - finishActMode() - } - } - } - } else { - listener?.refreshFragment() - finishActMode() - } - } - } - } - } - - private fun copyMoveRootItems( - files: ArrayList<FileDirItem>, - destinationPath: String, - isCopyOperation: Boolean - ) { - activity.toast(R.string.copying) - ensureBackgroundThread { - val fileCnt = files.size - RootHelpers(activity).copyMoveFiles(files, destinationPath, isCopyOperation) { - when (it) { - fileCnt -> activity.toast(R.string.copying_success) - 0 -> activity.toast(R.string.copy_failed) - else -> activity.toast(R.string.copying_success_partial) - } - - activity.runOnUiThread { - listener?.refreshFragment() - finishActMode() - } - } - } + fileActions.copyMoveTo(getSelectedFileDirItems(), isCopyOperation) } private fun compressSelection() { - val firstPath = getFirstSelectedItemPath() - if (activity.isPathOnOTG(firstPath)) { - activity.toast(R.string.unknown_error_occurred) - return - } - - CompressAsDialog(activity, firstPath) { destination, password -> - activity.handleAndroidSAFDialog(firstPath) { granted -> - if (!granted) { - return@handleAndroidSAFDialog - } - activity.handleSAFDialog(firstPath) { - if (!it) { - return@handleSAFDialog - } - - activity.toast(R.string.compressing) - val paths = getSelectedFileDirItems().map { it.path } - ensureBackgroundThread { - if (compressPaths(paths, destination, password)) { - activity.runOnUiThread { - activity.toast(R.string.compression_successful) - listener?.refreshFragment() - finishActMode() - } - } else { - activity.toast(R.string.compressing_failed) - } - } - } - } + fileActions.archive.compress(getFirstSelectedItemPath()) { + getSelectedFileDirItems().map { it.path } } } private fun decompressSelection() { - val firstPath = getFirstSelectedItemPath() - if (activity.isPathOnOTG(firstPath)) { - activity.toast(R.string.unknown_error_occurred) - return - } - - activity.handleSAFDialog(firstPath) { - if (!it) { - return@handleSAFDialog - } - - val paths = getSelectedFileDirItems() - .asSequence() - .map { it.path } - .filter { it.isZipFile() } - .toList() - ensureBackgroundThread { - tryDecompressingPaths(paths) { success -> - activity.runOnUiThread { - if (success) { - activity.toast(R.string.decompression_successful) - listener?.refreshFragment() - finishActMode() - } else { - activity.toast(R.string.decompressing_failed) - } - } - } - } + fileActions.archive.decompress(getFirstSelectedItemPath()) { + getSelectedFileDirItems().map { it.path } } } - private fun tryDecompressingPaths( - sourcePaths: List<String>, - callback: (success: Boolean) -> Unit - ) { - sourcePaths.forEach { path -> - ZipInputStream(BufferedInputStream(activity.getFileInputStreamSync(path))).use { zipInputStream -> - try { - val fileDirItems = ArrayList<FileDirItem>() - var entry = zipInputStream.nextEntry - while (entry != null) { - val currPath = if (entry.isDirectory) { - path - } else { - "${path.getParentPath().trimEnd('/')}/${entry.fileName}" - } - val fileDirItem = FileDirItem( - path = currPath, - name = entry.fileName, - isDirectory = entry.isDirectory, - children = 0, - size = entry.uncompressedSize - ) - fileDirItems.add(fileDirItem) - entry = zipInputStream.nextEntry - } - val destinationPath = fileDirItems.first().getParentPath().trimEnd('/') - activity.runOnUiThread { - activity.checkConflicts(fileDirItems, destinationPath, 0, LinkedHashMap()) { - ensureBackgroundThread { - decompressPaths(sourcePaths, it, callback) - } - } - } - } catch (zipException: ZipException) { - if (zipException.type == ZipException.Type.WRONG_PASSWORD) { - activity.showErrorToast(activity.getString(R.string.invalid_password)) - } else { - activity.showErrorToast(zipException) - } - } catch (exception: Exception) { - activity.showErrorToast(exception) - } - } - } - } - - private fun decompressPaths( - paths: List<String>, - conflictResolutions: LinkedHashMap<String, Int>, - callback: (success: Boolean) -> Unit - ) { - paths.forEach { path -> - val zipInputStream = - ZipInputStream(BufferedInputStream(activity.getFileInputStreamSync(path))) - - val foldersTimestamp = mutableListOf<Pair<File, LocalFileHeader>>() - zipInputStream.use { - try { - var entry = zipInputStream.nextEntry - val zipFileName = path.getFilenameFromPath() - val newFolderName = zipFileName.subSequence(0, zipFileName.length - 4) - while (entry != null) { - val parentPath = path.getParentPath() - val newPath = "$parentPath/$newFolderName/${entry.fileName.trimEnd('/')}" - - val resolution = getConflictResolution(conflictResolutions, newPath) - val doesPathExist = activity.getDoesFilePathExist(newPath) - if (doesPathExist && resolution == CONFLICT_OVERWRITE) { - val fileDirItem = FileDirItem( - path = newPath, - name = newPath.getFilenameFromPath(), - isDirectory = entry.isDirectory - ) - if (activity.getIsPathDirectory(path)) { - activity.deleteFolderBg(fileDirItem, false) { - if (it) { - extractEntry(newPath, entry, zipInputStream, foldersTimestamp) - } else { - callback(false) - } - } - } else { - activity.deleteFileBg(fileDirItem, false, false) { - if (it) { - extractEntry(newPath, entry, zipInputStream, foldersTimestamp) - } else { - callback(false) - } - } - } - } else if (!doesPathExist) { - extractEntry(newPath, entry, zipInputStream, foldersTimestamp) - } - - entry = zipInputStream.nextEntry - } - for ((dir, header) in foldersTimestamp.asReversed()) { - dir.setLastModified(header) - } - callback(true) - } catch (e: Exception) { - activity.showErrorToast(e) - callback(false) - } - } - } - } - - private fun extractEntry( - newPath: String, - entry: LocalFileHeader, - zipInputStream: ZipInputStream, - foldersTimestamp: MutableList<Pair<File, LocalFileHeader>> - ) { - if (entry.isDirectory) { - if (!activity.createDirectorySync(newPath) && !activity.getDoesFilePathExist(newPath)) { - val error = - String.format(activity.getString(R.string.could_not_create_file), newPath) - activity.showErrorToast(error) - } else { - foldersTimestamp.add(Pair(File(newPath), entry)) - } - } else { - val fos = activity.getFileOutputStreamSync(newPath, newPath.getMimeType()) - if (fos != null) { - zipInputStream.copyTo(fos) - File(newPath).setLastModified(entry) - } - } - } - - private fun getConflictResolution( - conflictResolutions: LinkedHashMap<String, Int>, - path: String - ): Int { - return if (conflictResolutions.size == 1 && conflictResolutions.containsKey("")) { - conflictResolutions[""]!! - } else if (conflictResolutions.containsKey(path)) { - conflictResolutions[path]!! - } else { - CONFLICT_SKIP - } - } - - @SuppressLint("NewApi") - private fun compressPaths( - sourcePaths: List<String>, - targetPath: String, - password: String? = null - ): Boolean { - val queue = LinkedList<String>() - val fos = activity.getFileOutputStreamSync(targetPath, "application/zip") ?: return false - - val zout = - password?.let { ZipOutputStream(fos, password.toCharArray()) } ?: ZipOutputStream(fos) - var res: Closeable = fos - - fun zipEntry(name: String, lastModified: Long) = ZipParameters().also { - it.fileNameInZip = name - it.lastModifiedFileTime = lastModified - if (password != null) { - it.isEncryptFiles = true - it.encryptionMethod = EncryptionMethod.AES - } - } - - try { - sourcePaths.forEach { currentPath -> - var name: String - var mainFilePath = currentPath - val base = "${mainFilePath.getParentPath()}/" - res = zout - queue.push(mainFilePath) - if (activity.getIsPathDirectory(mainFilePath)) { - name = "${mainFilePath.getFilenameFromPath()}/" - val dirModified = File(mainFilePath).lastModified() - zout.putNextEntry( - ZipParameters().also { - it.fileNameInZip = name - it.lastModifiedFileTime = dirModified - } - ) - } - - while (!queue.isEmpty()) { - mainFilePath = queue.pop() - if (activity.getIsPathDirectory(mainFilePath)) { - if (activity.isRestrictedSAFOnlyRoot(mainFilePath)) { - activity.getAndroidSAFFileItems(mainFilePath, true) { files -> - for (file in files) { - name = file.path.relativizeWith(base) - if (activity.getIsPathDirectory(file.path)) { - queue.push(file.path) - name = "${name.trimEnd('/')}/" - zout.putNextEntry(zipEntry(name, file.modified)) - } else { - zout.putNextEntry(zipEntry(name, file.modified)) - activity.getFileInputStreamSync(file.path)!!.copyTo(zout) - zout.closeEntry() - } - } - } - } else { - val mainFile = File(mainFilePath) - for (file in mainFile.listFiles()) { - name = file.path.relativizeWith(base) - if (activity.getIsPathDirectory(file.absolutePath)) { - queue.push(file.absolutePath) - name = "${name.trimEnd('/')}/" - zout.putNextEntry(zipEntry(name, file.lastModified())) - } else { - zout.putNextEntry(zipEntry(name, file.lastModified())) - activity.getFileInputStreamSync(file.path)!!.copyTo(zout) - zout.closeEntry() - } - } - } - - } else { - name = - if (base == currentPath) { - currentPath.getFilenameFromPath() - } else { - mainFilePath.relativizeWith(base) - } - val fileModified = File(mainFilePath).lastModified() - zout.putNextEntry(zipEntry(name, fileModified)) - activity.getFileInputStreamSync(mainFilePath)!!.copyTo(zout) - zout.closeEntry() - } - } - } - } catch (exception: Exception) { - activity.showErrorToast(exception) - return false - } finally { - res.close() - } - return true - } - private fun askConfirmDelete() { - activity.handleDeletePasswordProtection { - val itemsCnt = selectedKeys.size - val items = if (itemsCnt == 1) { - "\"${getFirstSelectedItemPath().getFilenameFromPath()}\"" - } else { - resources.getQuantityString(R.plurals.delete_items, itemsCnt, itemsCnt) - } - - val question = String.format(resources.getString(R.string.deletion_confirmation), items) - ConfirmationDialog(activity, question) { - deleteFiles() - } + fileActions.askConfirmDelete(selectedKeys.size, getFirstSelectedItemPath()) { + deleteFiles() } } @@ -1096,7 +477,7 @@ class ItemsAdapter( .error(drawable) .transform(CenterCrop(), RoundedCorners(10)) - val itemToLoad = getImagePathToLoad(listItem.path) + val itemToLoad = FileItemActions.getImagePathToLoad(activity, listItem.path, hasOTGConnected) if (!activity.isDestroyed && itemIcon != null) { Glide.with(activity) .load(itemToLoad) @@ -1114,37 +495,6 @@ class ItemsAdapter( return activity.resources.getQuantityString(R.plurals.items, children, children) } - private fun getOTGPublicPath(itemToLoad: String): String { - return "${baseConfig.OTGTreeUri}/document/${baseConfig.OTGPartition}%3A${ - itemToLoad.substring(baseConfig.OTGPath.length).replace("/", "%2F") - }" - } - - private fun getImagePathToLoad(path: String): Any { - var itemToLoad = if (path.endsWith(".apk", true)) { - val packageInfo = - activity.packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES) - val appInfo = packageInfo?.applicationInfo - if (appInfo != null) { - appInfo.sourceDir = path - appInfo.publicSourceDir = path - appInfo.loadIcon(activity.packageManager) - } else { - path - } - } else { - path - } - - if (activity.isRestrictedSAFOnlyRoot(path)) { - itemToLoad = activity.getAndroidSAFUri(path) - } else if (hasOTGConnected && itemToLoad is String && activity.isPathOnOTG(itemToLoad) && baseConfig.OTGTreeUri.isNotEmpty() && baseConfig.OTGPartition.isNotEmpty()) { - itemToLoad = getOTGPublicPath(itemToLoad) - } - - return itemToLoad - } - fun initDrawables() { folderDrawable = resources.getColoredDrawableWithColor(R.drawable.ic_folder_vector, properPrimaryColor) diff --git a/app/src/main/kotlin/org/fossify/filemanager/adapters/ManageFavoritesAdapter.kt b/app/src/main/kotlin/org/fossify/filemanager/adapters/ManageFavoritesAdapter.kt deleted file mode 100644 index c8d3848..0000000 --- a/app/src/main/kotlin/org/fossify/filemanager/adapters/ManageFavoritesAdapter.kt +++ /dev/null @@ -1,138 +0,0 @@ -package org.fossify.filemanager.adapters - -import android.view.* -import androidx.appcompat.widget.PopupMenu -import org.fossify.commons.activities.BaseSimpleActivity -import org.fossify.commons.adapters.MyRecyclerViewAdapter -import org.fossify.commons.extensions.getPopupMenuTheme -import org.fossify.commons.extensions.getProperTextColor -import org.fossify.commons.extensions.setupViewBackground -import org.fossify.commons.interfaces.RefreshRecyclerViewListener -import org.fossify.commons.views.MyRecyclerView -import org.fossify.filemanager.R -import org.fossify.filemanager.databinding.ItemManageFavoriteBinding -import org.fossify.filemanager.extensions.config - -class ManageFavoritesAdapter( - activity: BaseSimpleActivity, var favorites: ArrayList<String>, val listener: RefreshRecyclerViewListener?, - recyclerView: MyRecyclerView, itemClick: (Any) -> Unit -) : MyRecyclerViewAdapter(activity, recyclerView, itemClick) { - - private val config = activity.config - - init { - setupDragListener(true) - } - - override fun getActionMenuId() = R.menu.cab_remove_only - - override fun actionItemPressed(id: Int) { - when (id) { - R.id.cab_remove -> removeSelection() - } - } - - override fun getSelectableItemCount() = favorites.size - - override fun getIsItemSelectable(position: Int) = true - - override fun getItemSelectionKey(position: Int) = favorites.getOrNull(position)?.hashCode() - - override fun getItemKeyPosition(key: Int) = favorites.indexOfFirst { it.hashCode() == key } - - override fun onActionModeCreated() {} - - override fun onActionModeDestroyed() {} - - override fun prepareActionMode(menu: Menu) {} - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { - return createViewHolder(ItemManageFavoriteBinding.inflate(layoutInflater, parent, false).root) - } - - override fun onBindViewHolder(holder: ViewHolder, position: Int) { - val favorite = favorites[position] - holder.bindView(favorite, true, true) { itemView, layoutPosition -> - setupView(itemView, favorite, selectedKeys.contains(favorite.hashCode())) - } - bindViewHolder(holder) - } - - override fun getItemCount() = favorites.size - - private fun setupView(view: View, favorite: String, isSelected: Boolean) { - ItemManageFavoriteBinding.bind(view).apply { - root.setupViewBackground(activity) - manageFavoriteTitle.apply { - text = favorite - setTextColor(activity.getProperTextColor()) - } - - manageFavoriteHolder.isSelected = isSelected - - overflowMenuIcon.drawable.apply { - mutate() - setTint(activity.getProperTextColor()) - } - - overflowMenuIcon.setOnClickListener { - showPopupMenu(overflowMenuAnchor, favorite) - } - } - } - - private fun showPopupMenu(view: View, favorite: String) { - finishActMode() - val theme = activity.getPopupMenuTheme() - val contextTheme = ContextThemeWrapper(activity, theme) - - PopupMenu(contextTheme, view, Gravity.END).apply { - inflate(getActionMenuId()) - setOnMenuItemClickListener { item -> - val eventTypeId = favorite.hashCode() - when (item.itemId) { - R.id.cab_remove -> { - executeItemMenuOperation(eventTypeId) { - removeSelection() - } - } - } - true - } - show() - } - } - - private fun executeItemMenuOperation(eventTypeId: Int, callback: () -> Unit) { - selectedKeys.clear() - selectedKeys.add(eventTypeId) - callback() - } - - private fun removeSelection() { - val removeFavorites = ArrayList<String>(selectedKeys.size) - val positions = ArrayList<Int>() - selectedKeys.forEach { key -> - val position = favorites.indexOfFirst { it.hashCode() == key } - if (position != -1) { - positions.add(position) - - val favorite = getItemWithKey(key) - if (favorite != null) { - removeFavorites.add(favorite) - config.removeFavorite(favorite) - } - } - } - - positions.sortDescending() - removeSelectedItems(positions) - - favorites.removeAll(removeFavorites.toSet()) - if (favorites.isEmpty()) { - listener?.refreshItems() - } - } - - private fun getItemWithKey(key: Int): String? = favorites.firstOrNull { it.hashCode() == key } -} diff --git a/app/src/main/kotlin/org/fossify/filemanager/adapters/ViewPagerAdapter.kt b/app/src/main/kotlin/org/fossify/filemanager/adapters/ViewPagerAdapter.kt index 9788121..2df6295 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/adapters/ViewPagerAdapter.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/adapters/ViewPagerAdapter.kt @@ -12,12 +12,18 @@ import org.fossify.commons.helpers.TAB_STORAGE_ANALYSIS import org.fossify.filemanager.R import org.fossify.filemanager.activities.SimpleActivity import org.fossify.filemanager.extensions.config +import org.fossify.filemanager.fragments.ItemsFragment import org.fossify.filemanager.fragments.MyViewPagerFragment class ViewPagerAdapter(val activity: SimpleActivity, val tabsToShow: ArrayList<Int>) : PagerAdapter() { override fun instantiateItem(container: ViewGroup, position: Int): Any { val layout = getFragment(position) - val view = activity.layoutInflater.inflate(layout, container, false) + val view = if (layout == FILES_TAB) { + // the Files tab is drawn by Compose and has no layout of its own + ItemsFragment(activity) + } else { + activity.layoutInflater.inflate(layout, container, false) + } container.addView(view) (view as MyViewPagerFragment<*>).apply { @@ -56,6 +62,10 @@ class ViewPagerAdapter(val activity: SimpleActivity, val tabsToShow: ArrayList<I container.removeView(item as View) } + companion object { + private const val FILES_TAB = 0 + } + override fun getCount() = tabsToShow.filter { it and activity.config.showTabs != 0 }.size override fun isViewFromObject(view: View, item: Any) = view == item @@ -64,7 +74,7 @@ class ViewPagerAdapter(val activity: SimpleActivity, val tabsToShow: ArrayList<I val showTabs = activity.config.showTabs val fragments = arrayListOf<Int>() if (showTabs and TAB_FILES != 0) { - fragments.add(R.layout.items_fragment) + fragments.add(FILES_TAB) } if (showTabs and TAB_RECENT_FILES != 0) { diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/TestTags.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/TestTags.kt new file mode 100644 index 0000000..54cabe9 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/TestTags.kt @@ -0,0 +1,51 @@ +package org.fossify.filemanager.compose + +/** Semantics test tags of the Compose screens, shared with the UI tests. */ + +object DecompressTestTags { + const val LIST = "decompress_list" + const val PROGRESS = "decompress_progress" + fun entry(path: String) = "decompress_entry_$path" +} + +object SaveAsDialogTestTags { + const val FOLDER = "save_as_folder" + const val FILENAME = "save_as_filename" + const val EXTENSION = "save_as_extension" +} + +object TopBarTestTags { + const val ACTION_MODE_TITLE = "action_mode_title" +} + +object ManageFavoritesTestTags { + const val LIST = "manage_favorites_list" + const val PLACEHOLDER = "manage_favorites_placeholder" + const val PLACEHOLDER_ADD = "manage_favorites_placeholder_add" + fun item(path: String) = "manage_favorites_item_$path" + fun itemMenu(path: String) = "manage_favorites_item_menu_$path" +} + +object ReadTextTestTags { + const val EDITOR = "read_text_editor" + const val SEARCH_FIELD = "read_text_search_field" +} + +object SettingsTestTags { + const val LIST = "settings_list" +} + +object FilesTabTestTags { + const val LIST = "files_list" + const val BREADCRUMBS = "files_breadcrumbs" + const val PROGRESS = "files_progress" + const val FAB = "files_fab" + const val FAST_SCROLLER = "files_fast_scroller" + const val CREATE_NAME = "files_create_name" + const val PLACEHOLDER = "files_placeholder" + const val PLACEHOLDER_TYPE_MORE = "files_placeholder_type_more" + fun breadcrumb(index: Int) = "files_breadcrumb_$index" + fun item(path: String) = "files_item_$path" + fun section(path: String) = "files_section_$path" + fun check(path: String) = "files_check_$path" +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/components/DrawablePainter.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/components/DrawablePainter.kt new file mode 100644 index 0000000..4d53437 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/components/DrawablePainter.kt @@ -0,0 +1,28 @@ +package org.fossify.filemanager.compose.components + +import android.graphics.drawable.Drawable +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.drawscope.DrawScope +import androidx.compose.ui.graphics.drawscope.drawIntoCanvas +import androidx.compose.ui.graphics.nativeCanvas +import androidx.compose.ui.graphics.painter.Painter +import kotlin.math.roundToInt + +/** + * Draws a platform [Drawable] (e.g. the file type placeholders shipped by Fossify Commons) in Compose. + */ +class DrawablePainter(private val drawable: Drawable) : Painter() { + override val intrinsicSize: Size + get() = if (drawable.intrinsicWidth > 0 && drawable.intrinsicHeight > 0) { + Size(drawable.intrinsicWidth.toFloat(), drawable.intrinsicHeight.toFloat()) + } else { + Size.Unspecified + } + + override fun DrawScope.onDraw() { + drawIntoCanvas { canvas -> + drawable.setBounds(0, 0, size.width.roundToInt(), size.height.roundToInt()) + drawable.draw(canvas.nativeCanvas) + } + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/components/TopBars.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/components/TopBars.kt new file mode 100644 index 0000000..325c696 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/components/TopBars.kt @@ -0,0 +1,133 @@ +package org.fossify.filemanager.compose.components + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.ReadOnlyComposable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.colorResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.res.vectorResource +import androidx.compose.ui.text.style.TextOverflow +import org.fossify.commons.compose.lists.topAppBarInsets +import org.fossify.commons.compose.lists.topAppBarPaddings +import org.fossify.commons.compose.system_ui_controller.rememberSystemUiController +import org.fossify.commons.compose.theme.LocalTheme +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.commons.compose.theme.isLitWell +import org.fossify.commons.compose.theme.model.Theme +import org.fossify.commons.extensions.getContrastColor +import org.fossify.filemanager.compose.TopBarTestTags + +private const val SELECTED_ITEM_ALPHA = 0.3f + +/** + * Contextual top bar shown while items are selected, mirroring the view based action mode: + * "selected / total" title that selects everything (or finishes when all are selected) and a close icon. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ActionModeTopBar( + selectedCount: Int, + totalCount: Int, + onClose: () -> Unit, + onSelectAll: () -> Unit, + modifier: Modifier = Modifier, + drawBehindStatusBar: Boolean = true, + actions: @Composable RowScope.(iconColor: Color) -> Unit = {}, +) { + val systemUiController = rememberSystemUiController() + val bgColor = actionModeBackgroundColor() + val textColor = Color(bgColor.toArgb().getContrastColor()) + DisposableEffect(systemUiController, bgColor, drawBehindStatusBar) { + if (drawBehindStatusBar) { + systemUiController.setStatusBarColor(color = Color.Transparent, darkIcons = bgColor.isLitWell()) + } + onDispose {} + } + // when the bar does not draw behind the status bar, it starts below it and leaves the status bar untouched, + // like the platform action mode shown over a view based toolbar + val insets = topAppBarInsets() + val barModifier = if (drawBehindStatusBar) modifier else modifier.windowInsetsPadding(insets) + TopAppBar( + title = { + Box( + modifier = Modifier + .clickable { + if (selectedCount == totalCount) onClose() else onSelectAll() + } + .testTag(TopBarTestTags.ACTION_MODE_TITLE), + contentAlignment = Alignment.Center + ) { + Text( + text = "${minOf(selectedCount, totalCount)} / $totalCount", + color = textColor, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + }, + navigationIcon = { + IconButton(onClick = onClose) { + Icon( + imageVector = ImageVector.vectorResource(id = org.fossify.commons.R.drawable.ic_arrow_left_vector), + contentDescription = stringResource(id = androidx.appcompat.R.string.abc_action_mode_done), + tint = textColor + ) + } + }, + actions = { actions(textColor) }, + colors = TopAppBarDefaults.topAppBarColors(containerColor = bgColor), + modifier = barModifier.topAppBarPaddings(), + windowInsets = if (drawBehindStatusBar) insets else WindowInsets(0) + ) +} + +@Composable +@ReadOnlyComposable +private fun actionModeBackgroundColor(): Color = + if (LocalTheme.current is Theme.SystemDefaultMaterialYou) { + colorResource(id = org.fossify.commons.R.color.you_contextual_status_bar_color) + } else { + colorResource(id = org.fossify.commons.R.color.dark_grey) + } + +@Composable +@ReadOnlyComposable +fun selectedItemBackground(isSelected: Boolean): Color = + if (isSelected) SimpleTheme.colorScheme.primary.copy(alpha = SELECTED_ITEM_ALPHA) else Color.Transparent + +/** + * Number of action slots (including the overflow button) the platform toolbar gives to menu items, + * following AppCompat's ActionBarPolicy, so "if room" actions land in the same place as before. + */ +@Composable +@ReadOnlyComposable +fun maxToolbarActionIcons(): Int { + val configuration = LocalConfiguration.current + val widthDp = configuration.screenWidthDp + val heightDp = configuration.screenHeightDp + val smallest = configuration.smallestScreenWidthDp + return when { + smallest > 600 || widthDp > 600 || (widthDp > 960 && heightDp > 720) || (widthDp > 720 && heightDp > 960) -> 5 + widthDp >= 500 || (widthDp >= 640 && heightDp >= 480) || (widthDp >= 480 && heightDp >= 640) -> 4 + widthDp >= 360 -> 3 + else -> 2 + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/decompress/DecompressScreen.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/decompress/DecompressScreen.kt new file mode 100644 index 0000000..091b358 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/decompress/DecompressScreen.kt @@ -0,0 +1,190 @@ +package org.fossify.filemanager.compose.decompress + +import android.graphics.drawable.Drawable +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.graphics.painter.Painter +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.dimensionResource +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.vectorResource +import androidx.compose.ui.text.style.TextOverflow +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.persistentListOf +import org.fossify.commons.compose.lists.SimpleScaffold +import org.fossify.commons.compose.lists.SimpleScaffoldTopBar +import org.fossify.commons.compose.menus.ActionItem +import org.fossify.commons.compose.menus.ActionMenu +import org.fossify.commons.compose.menus.OverflowMode +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.commons.extensions.getProperPrimaryColor +import org.fossify.commons.extensions.getProperTextColor +import org.fossify.commons.extensions.getTextSize +import org.fossify.commons.helpers.getFilePlaceholderDrawables +import org.fossify.filemanager.R +import org.fossify.filemanager.compose.DecompressTestTags +import org.fossify.filemanager.compose.components.DrawablePainter +import java.util.Locale + +private const val FOLDER_ICON_ALPHA = 180f / 255f + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DecompressScreen( + title: String, + entries: ImmutableList<ArchiveEntry>, + isLoading: Boolean, + goBack: () -> Unit, + onDecompress: () -> Unit, + onEntryClick: (ArchiveEntry) -> Unit, + modifier: Modifier = Modifier, +) { + SimpleScaffold( + modifier = modifier, + customTopBar = { scrolledColor, navigationInteractionSource, scrollBehavior, statusBarColor, + colorTransitionFraction, contrastColor -> + SimpleScaffoldTopBar( + title = { color -> + Text(text = title, color = color, maxLines = 1, overflow = TextOverflow.Ellipsis) + }, + actions = { DecompressActionMenu(iconColor = scrolledColor, onDecompress = onDecompress) }, + scrolledColor = scrolledColor, + navigationIconInteractionSource = navigationInteractionSource, + scrollBehavior = scrollBehavior, + statusBarColor = statusBarColor, + colorTransitionFraction = colorTransitionFraction, + contrastColor = contrastColor, + goBack = goBack + ) + } + ) { paddingValues -> + val context = LocalContext.current + val placeholders = remember(context) { getFilePlaceholderDrawables(context) } + val textSize = with(LocalDensity.current) { remember(context) { context.getTextSize() }.toSp() } + val textColor = Color(remember(context) { context.getProperTextColor() }) + LazyColumn( + modifier = Modifier + .fillMaxSize() + .testTag(DecompressTestTags.LIST), + contentPadding = PaddingValues( + top = SimpleTheme.dimens.padding.small, + bottom = paddingValues.calculateBottomPadding() + ) + ) { + items(entries, key = { it.path }) { entry -> + ArchiveEntryItem( + entry = entry, + icon = entryIcon(entry, placeholders), + isFolder = entry.isDirectory, + textStyleSize = textSize, + textColor = textColor, + onClick = { onEntryClick(entry) } + ) + } + } + + if (isLoading) { + CircularProgressIndicator( + modifier = Modifier + .align(Alignment.Center) + .testTag(DecompressTestTags.PROGRESS) + ) + } + } +} + +@Composable +private fun entryIcon(entry: ArchiveEntry, placeholders: Map<String, Drawable>): Painter { + return if (entry.isDirectory) { + painterResource(id = R.drawable.ic_folder_vector) + } else { + val extension = entry.name.substringAfterLast(".").lowercase(Locale.getDefault()) + val placeholder = placeholders[extension] + if (placeholder != null) { + remember(placeholder) { DrawablePainter(placeholder) } + } else { + painterResource(id = R.drawable.ic_file_generic) + } + } +} + +@Composable +private fun ArchiveEntryItem( + entry: ArchiveEntry, + icon: Painter, + isFolder: Boolean, + textStyleSize: androidx.compose.ui.unit.TextUnit, + textColor: Color, + onClick: () -> Unit, +) { + val context = LocalContext.current + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(end = SimpleTheme.dimens.padding.extraLarge) + .testTag(DecompressTestTags.entry(entry.path)), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .size(dimensionResource(org.fossify.commons.R.dimen.file_picker_icon_size)) + .padding(SimpleTheme.dimens.padding.medium) + ) { + Image( + painter = icon, + contentDescription = null, + modifier = Modifier.fillMaxSize(), + alpha = if (isFolder) FOLDER_ICON_ALPHA else 1f, + colorFilter = if (isFolder) ColorFilter.tint(Color(context.getProperPrimaryColor())) else null + ) + } + Text( + text = entry.name, + modifier = Modifier + .weight(1f) + .padding(start = SimpleTheme.dimens.padding.extraSmall), + color = textColor, + fontSize = textStyleSize, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } +} + +@Composable +private fun DecompressActionMenu(iconColor: Color, onDecompress: () -> Unit) { + val icon = ImageVector.vectorResource(id = R.drawable.ic_decompress_vector) + val items = remember(icon, onDecompress) { + persistentListOf( + ActionItem( + nameRes = R.string.decompress, + icon = icon, + overflowMode = OverflowMode.NEVER_OVERFLOW, + doAction = onDecompress + ) + ) + } + ActionMenu(items = items, numIcons = 1, isMenuVisible = false, iconsColor = iconColor, onMenuToggle = {}) +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/decompress/DecompressViewModel.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/decompress/DecompressViewModel.kt new file mode 100644 index 0000000..69988cd --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/decompress/DecompressViewModel.kt @@ -0,0 +1,55 @@ +package org.fossify.filemanager.compose.decompress + +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModel +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.persistentListOf +import org.fossify.filemanager.models.ListItem +import java.util.Collections + +@Immutable +data class ArchiveEntry( + val path: String, + val name: String, + val isDirectory: Boolean, +) + +enum class ArchiveLoadState { + NOT_STARTED, LOADING, NEEDS_PASSWORD, LOADED +} + +/** + * Holds the parsed archive listing and the folder being browsed, so neither is lost on rotation. + * The browsed folder and the password are also kept in the saved state, like the password always was. + */ +class DecompressViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() { + companion object { + private const val KEY_CURRENT_PATH = "current_path" + private const val KEY_PASSWORD = "password" + } + + val allFiles: MutableList<ListItem> = Collections.synchronizedList(ArrayList()) + + @Volatile + var loadState = ArchiveLoadState.NOT_STARTED + + var isLoading by mutableStateOf(false) + + var entries by mutableStateOf<ImmutableList<ArchiveEntry>>(persistentListOf()) + + var currentPath: String + get() = savedStateHandle[KEY_CURRENT_PATH] ?: "" + set(value) { + savedStateHandle[KEY_CURRENT_PATH] = value + } + + var password: String? + get() = savedStateHandle[KEY_PASSWORD] + set(value) { + savedStateHandle[KEY_PASSWORD] = value + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/editor/EditorSearchBar.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/editor/EditorSearchBar.kt new file mode 100644 index 0000000..a52bd41 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/editor/EditorSearchBar.kt @@ -0,0 +1,99 @@ +package org.fossify.filemanager.compose.editor + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.res.vectorResource +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.sp +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.filemanager.R +import org.fossify.filemanager.compose.ReadTextTestTags + +private const val MAX_SEARCH_LENGTH = 50 +private const val HINT_ALPHA = 0.6f + +/** + * In-screen "find in text" bar shown under the top app bar: query field plus previous / next / close. + */ +@Composable +fun EditorSearchBar( + query: String, + backgroundColor: Color, + contentColor: Color, + focusRequester: FocusRequester, + onQueryChange: (String) -> Unit, + onPrevious: () -> Unit, + onNext: () -> Unit, + onClose: () -> Unit, + modifier: Modifier = Modifier, +) { + Row( + modifier = modifier + .fillMaxWidth() + .background(backgroundColor) + .padding(vertical = SimpleTheme.dimens.padding.small), + verticalAlignment = Alignment.CenterVertically + ) { + Box( + modifier = Modifier + .weight(1f) + .padding(start = SimpleTheme.dimens.padding.extraLarge, end = SimpleTheme.dimens.padding.large), + contentAlignment = Alignment.CenterStart + ) { + BasicTextField( + value = query, + onValueChange = { onQueryChange(it.take(MAX_SEARCH_LENGTH)) }, + singleLine = true, + textStyle = TextStyle(color = contentColor, fontSize = 16.sp), + cursorBrush = SolidColor(contentColor), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { onNext() }), + modifier = Modifier + .fillMaxWidth() + .focusRequester(focusRequester) + .testTag(ReadTextTestTags.SEARCH_FIELD) + ) + if (query.isEmpty()) { + Text( + text = stringResource(id = R.string.search), + color = contentColor.copy(alpha = HINT_ALPHA), + fontSize = 16.sp + ) + } + } + SearchBarButton(R.drawable.ic_chevron_left_vector, R.string.previous, contentColor, onPrevious) + SearchBarButton(R.drawable.ic_chevron_right_vector, R.string.next, contentColor, onNext) + SearchBarButton(R.drawable.ic_cross_vector, R.string.close, contentColor, onClose) + } +} + +@Composable +private fun SearchBarButton(iconId: Int, descriptionId: Int, tint: Color, onClick: () -> Unit) { + IconButton(onClick = onClick) { + Icon( + imageVector = ImageVector.vectorResource(id = iconId), + contentDescription = stringResource(id = descriptionId), + tint = tint + ) + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/editor/ReadTextScreen.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/editor/ReadTextScreen.kt new file mode 100644 index 0000000..58fac8e --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/editor/ReadTextScreen.kt @@ -0,0 +1,282 @@ +package org.fossify.filemanager.compose.editor + +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.calculateZoom +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.vectorResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.OffsetMapping +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.input.TransformedText +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.sp +import kotlinx.collections.immutable.persistentListOf +import org.fossify.commons.compose.lists.SimpleScaffold +import org.fossify.commons.compose.lists.SimpleScaffoldTopBar +import org.fossify.commons.compose.menus.ActionItem +import org.fossify.commons.compose.menus.ActionMenu +import org.fossify.commons.compose.menus.OverflowMode +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.commons.extensions.getContrastColor +import org.fossify.filemanager.R +import org.fossify.filemanager.compose.ReadTextTestTags +import org.fossify.filemanager.compose.components.maxToolbarActionIcons + +/** Text zoom limits of the previous pinch-to-zoom editor (GestureViews: fit = 1x, max = 2x). */ +const val MIN_TEXT_ZOOM = 1f +const val MAX_TEXT_ZOOM = 2f +private const val BASE_TEXT_SIZE = 12f +private const val HIGHLIGHT_ALPHA = 128f / 255f + +@Immutable +data class ReadTextScreenState( + val title: String, + val textFieldValue: TextFieldValue, + val isSearchActive: Boolean, + val searchQuery: String, + val textZoom: Float, + val editorFocusRequests: Int, + val searchFocusRequests: Int, +) + +/** Top app bar actions of the editor, in their menu order. */ +enum class EditorMenuAction { + SEARCH, SAVE, SAVE_AS, PRINT, OPEN_WITH +} + +interface ReadTextScreenActions { + fun onTextChange(value: TextFieldValue) + fun onTextZoomChange(zoom: Float) + fun onMenuAction(action: EditorMenuAction) + fun onSearchQueryChange(query: String) + fun onPreviousSearchResult() + fun onNextSearchResult() + fun onCloseSearch() +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ReadTextScreen( + state: ReadTextScreenState, + actions: ReadTextScreenActions, + textColor: Color, + primaryColor: Color, + goBack: () -> Unit, + modifier: Modifier = Modifier, +) { + SimpleScaffold( + modifier = modifier, + customTopBar = { scrolledColor, navigationInteractionSource, scrollBehavior, statusBarColor, + colorTransitionFraction, contrastColor -> + SimpleScaffoldTopBar( + title = { color -> + Text(text = state.title, color = color, maxLines = 1, overflow = TextOverflow.Ellipsis) + }, + actions = { EditorActionMenu(iconColor = scrolledColor, actions = actions) }, + scrolledColor = scrolledColor, + navigationIconInteractionSource = navigationInteractionSource, + scrollBehavior = scrollBehavior, + statusBarColor = statusBarColor, + colorTransitionFraction = colorTransitionFraction, + contrastColor = contrastColor, + goBack = goBack + ) + } + ) { + val keyboardController = LocalSoftwareKeyboardController.current + val editorFocusRequester = remember { FocusRequester() } + val searchFocusRequester = remember { FocusRequester() } + + LaunchedEffect(state.editorFocusRequests) { + if (state.editorFocusRequests > 0) { + editorFocusRequester.requestFocus() + keyboardController?.show() + } + } + + LaunchedEffect(state.searchFocusRequests, state.isSearchActive) { + if (state.searchFocusRequests > 0 && state.isSearchActive) { + searchFocusRequester.requestFocus() + keyboardController?.show() + } + } + + Column( + modifier = Modifier + .fillMaxSize() + .windowInsetsPadding(WindowInsets.navigationBars.union(WindowInsets.ime).only(WindowInsetsSides.Bottom)) + ) { + if (state.isSearchActive) { + EditorSearchBar( + query = state.searchQuery, + backgroundColor = primaryColor, + contentColor = Color(primaryColor.toArgb().getContrastColor()), + focusRequester = searchFocusRequester, + onQueryChange = actions::onSearchQueryChange, + onPrevious = actions::onPreviousSearchResult, + onNext = actions::onNextSearchResult, + onClose = actions::onCloseSearch + ) + } + + TextEditor( + value = state.textFieldValue, + onValueChange = actions::onTextChange, + searchQuery = state.searchQuery, + textZoom = state.textZoom, + onTextZoomChange = actions::onTextZoomChange, + textColor = textColor, + highlightColor = primaryColor.copy(alpha = HIGHLIGHT_ALPHA), + focusRequester = editorFocusRequester + ) + } + } +} + +@Composable +private fun TextEditor( + value: TextFieldValue, + onValueChange: (TextFieldValue) -> Unit, + searchQuery: String, + textZoom: Float, + onTextZoomChange: (Float) -> Unit, + textColor: Color, + highlightColor: Color, + focusRequester: FocusRequester, +) { + val currentZoom by rememberUpdatedState(textZoom) + val currentOnZoomChange by rememberUpdatedState(onTextZoomChange) + val highlight = remember(searchQuery, highlightColor) { SearchHighlightTransformation(searchQuery, highlightColor) } + + Box( + modifier = Modifier + .fillMaxSize() + .pointerInput(Unit) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + do { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.changes.count { it.pressed } >= 2) { + val zoomChange = event.calculateZoom() + if (zoomChange != 1f) { + currentOnZoomChange((currentZoom * zoomChange).coerceIn(MIN_TEXT_ZOOM, MAX_TEXT_ZOOM)) + } + event.changes.forEach { it.consume() } + } + } while (event.changes.any { it.pressed }) + } + } + ) { + BasicTextField( + value = value, + onValueChange = onValueChange, + textStyle = TextStyle(color = textColor, fontSize = (BASE_TEXT_SIZE * textZoom).sp), + cursorBrush = SolidColor(textColor), + visualTransformation = highlight, + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, keyboardType = KeyboardType.Text), + modifier = Modifier + .fillMaxSize() + .padding(SimpleTheme.dimens.padding.medium) + .focusRequester(focusRequester) + .testTag(ReadTextTestTags.EDITOR) + ) + } +} + +@Composable +private fun EditorActionMenu(iconColor: Color, actions: ReadTextScreenActions) { + val searchIcon = ImageVector.vectorResource(id = R.drawable.ic_search_vector) + val saveIcon = ImageVector.vectorResource(id = R.drawable.ic_save_vector) + val printIcon = ImageVector.vectorResource(id = R.drawable.ic_print_vector) + val items = remember(searchIcon, saveIcon, printIcon, actions) { + persistentListOf( + ActionItem(R.string.search, searchIcon, OverflowMode.NEVER_OVERFLOW, { + actions.onMenuAction(EditorMenuAction.SEARCH) + }), + ActionItem(R.string.save, saveIcon, OverflowMode.NEVER_OVERFLOW, { + actions.onMenuAction(EditorMenuAction.SAVE) + }), + ActionItem(R.string.save_as, null, OverflowMode.ALWAYS_OVERFLOW, { + actions.onMenuAction(EditorMenuAction.SAVE_AS) + }), + ActionItem(R.string.print, printIcon, OverflowMode.IF_NECESSARY, { + actions.onMenuAction(EditorMenuAction.PRINT) + }), + ActionItem(R.string.open_with, null, OverflowMode.ALWAYS_OVERFLOW, { + actions.onMenuAction(EditorMenuAction.OPEN_WITH) + }), + ) + } + var isMenuVisible by rememberSaveable { mutableStateOf(false) } + ActionMenu( + items = items, + numIcons = maxToolbarActionIcons(), + isMenuVisible = isMenuVisible, + iconsColor = iconColor, + onMenuToggle = { isMenuVisible = it } + ) +} + +/** + * Highlights every (case insensitive) occurrence of the search query, without changing the text itself. + */ +@Immutable +private data class SearchHighlightTransformation( + val query: String, + val color: Color, +) : VisualTransformation { + override fun filter(text: AnnotatedString): TransformedText { + if (query.isBlank() || query.length < 2) { + return TransformedText(text, OffsetMapping.Identity) + } + + val builder = AnnotatedString.Builder(text) + val content = text.text + var index = content.indexOf(query, 0, ignoreCase = true) + while (index != -1) { + builder.addStyle(SpanStyle(background = color), index, index + query.length) + index = content.indexOf(query, index + 1, ignoreCase = true) + } + return TransformedText(builder.toAnnotatedString(), OffsetMapping.Identity) + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/editor/ReadTextViewModel.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/editor/ReadTextViewModel.kt new file mode 100644 index 0000000..7df0d89 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/editor/ReadTextViewModel.kt @@ -0,0 +1,138 @@ +package org.fossify.filemanager.compose.editor + +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.TextFieldValue +import androidx.lifecycle.ViewModel +import org.fossify.commons.extensions.searchMatches + +/** + * A pending "Save as" dialog. [hidePath] is set for documents we can't write back to directly + * (the dialog then only asks for a file name and the system file creator picks the folder). + */ +@Immutable +data class SaveAsRequest( + val path: String, + val hidePath: Boolean, + val exitAfterSaving: Boolean, +) + +/** + * Editor state that has to survive configuration changes: the (possibly unsaved) text with its cursor, + * and the in-screen search. Kept in a ViewModel instead of the saved state bundle so large files don't + * hit the binder transaction limit on rotation. + */ +class ReadTextViewModel : ViewModel() { + companion object { + private const val MIN_SEARCH_LENGTH = 2 + } + + var isLoaded by mutableStateOf(false) + private set + + var originalText = "" + private set + + var filePath = "" + + var textFieldValue by mutableStateOf(TextFieldValue("")) + private set + + var isSearchActive by mutableStateOf(false) + private set + + var searchQuery by mutableStateOf("") + private set + + var searchIndex by mutableIntStateOf(0) + private set + + var saveAsRequest by mutableStateOf<SaveAsRequest?>(null) + + /** Incremented whenever the editor should grab focus and show the keyboard. */ + var editorFocusRequests by mutableIntStateOf(0) + private set + + /** Incremented whenever the search field should grab focus (and the keyboard). */ + var searchFocusRequests by mutableIntStateOf(0) + private set + + val text: String + get() = textFieldValue.text + + val hasUnsavedChanges: Boolean + get() = isLoaded && originalText != text + + val searchMatches: List<Int> + get() = if (searchQuery.isNotBlank() && searchQuery.length >= MIN_SEARCH_LENGTH) { + text.searchMatches(searchQuery) + } else { + emptyList() + } + + fun onTextLoaded(original: String, textToShow: String) { + originalText = original + textFieldValue = TextFieldValue(textToShow, TextRange(0)) + isLoaded = true + } + + fun onTextSaved(savedText: String) { + originalText = savedText + } + + fun onTextChange(value: TextFieldValue) { + textFieldValue = value + } + + fun requestEditorFocus() { + editorFocusRequests++ + } + + fun openSearch() { + isSearchActive = true + textFieldValue = textFieldValue.copy(selection = TextRange(0)) + searchFocusRequests++ + } + + fun closeSearch() { + searchQuery = "" + isSearchActive = false + } + + fun onSearchQueryChange(query: String) { + searchQuery = query + val matches = searchMatches + if (matches.isNotEmpty()) { + moveCursorTo(matches.getOrNull(searchIndex) ?: 0) + } + } + + /** + * Moves the cursor to the next (or previous) match, wrapping around at the ends. + * Returns false when there is nothing to jump to. + */ + fun goToSearchResult(next: Boolean): Boolean { + val matches = searchMatches + searchIndex = when { + next && searchIndex < matches.lastIndex -> searchIndex + 1 + next -> 0 + searchIndex > 0 -> searchIndex - 1 + else -> matches.lastIndex + } + + if (matches.isEmpty()) { + return false + } + + moveCursorTo(matches.getOrNull(searchIndex) ?: 0) + return true + } + + private fun moveCursorTo(offset: Int) { + textFieldValue = textFieldValue.copy(selection = TextRange(offset.coerceIn(0, text.length))) + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/editor/SaveAsAlertDialog.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/editor/SaveAsAlertDialog.kt new file mode 100644 index 0000000..c1d85f5 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/editor/SaveAsAlertDialog.kt @@ -0,0 +1,146 @@ +package org.fossify.filemanager.compose.editor + +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.PressInteraction +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.sp +import org.fossify.commons.compose.alert_dialog.dialogBorder +import org.fossify.commons.compose.alert_dialog.dialogContainerColor +import org.fossify.commons.compose.alert_dialog.dialogElevation +import org.fossify.commons.compose.alert_dialog.dialogShape +import org.fossify.commons.compose.alert_dialog.dialogTextColor +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.commons.extensions.getFilenameFromPath +import org.fossify.commons.extensions.getParentPath +import org.fossify.commons.extensions.humanizePath +import org.fossify.filemanager.R +import org.fossify.filemanager.compose.SaveAsDialogTestTags + +/** + * Compose version of the editor's "Save as" dialog. Validation and writing stay with the caller: + * [onConfirm] receives the chosen folder, file name and extension, and the caller hides the dialog + * once the input was accepted. + */ +@Composable +fun SaveAsAlertDialog( + request: SaveAsRequest, + onDismiss: () -> Unit, + onPickFolder: (currentFolder: String, onPicked: (String) -> Unit) -> Unit, + onConfirm: (folder: String, filename: String, extension: String) -> Unit, + modifier: Modifier = Modifier, +) { + val context = LocalContext.current + val fullName = remember(request) { request.path.getFilenameFromPath() } + val dotAt = fullName.lastIndexOf(".") + var folder by rememberSaveable(request) { mutableStateOf(request.path.getParentPath()) } + var filename by rememberSaveable(request, stateSaver = TextFieldValue.Saver) { + val name = if (dotAt > 0) fullName.substring(0, dotAt) else fullName + mutableStateOf(TextFieldValue(name, TextRange(name.length))) + } + var extension by rememberSaveable(request) { + mutableStateOf(if (dotAt > 0) fullName.substring(dotAt + 1) else "") + } + val focusRequester = remember { FocusRequester() } + val currentFolder by rememberUpdatedState(folder) + val currentOnPickFolder by rememberUpdatedState(onPickFolder) + val folderInteractionSource = remember { MutableInteractionSource() } + LaunchedEffect(folderInteractionSource) { + // the read-only path field opens the folder picker when tapped, like the old dialog + folderInteractionSource.interactions.collect { interaction -> + if (interaction is PressInteraction.Release) { + currentOnPickFolder(currentFolder) { folder = it } + } + } + } + + AlertDialog( + modifier = modifier.dialogBorder(), + shape = dialogShape, + containerColor = dialogContainerColor, + tonalElevation = dialogElevation, + onDismissRequest = onDismiss, + confirmButton = { + TextButton(onClick = { onConfirm(folder, filename.text, extension) }) { + Text(text = stringResource(id = R.string.ok)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(text = stringResource(id = R.string.cancel)) + } + }, + title = { + Text( + text = stringResource(id = R.string.save_as), + color = dialogTextColor, + fontSize = 21.sp, + ) + }, + text = { + LaunchedEffect(Unit) { + focusRequester.requestFocus() + } + Column { + if (!request.hidePath) { + OutlinedTextField( + value = context.humanizePath(folder), + onValueChange = {}, + readOnly = true, + singleLine = true, + interactionSource = folderInteractionSource, + label = { Text(text = stringResource(id = R.string.path)) }, + modifier = Modifier + .fillMaxWidth() + .padding(bottom = SimpleTheme.dimens.padding.extraLarge) + .testTag(SaveAsDialogTestTags.FOLDER) + ) + } + OutlinedTextField( + value = filename, + onValueChange = { filename = it }, + singleLine = true, + label = { Text(text = stringResource(id = R.string.filename)) }, + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), + modifier = Modifier + .fillMaxWidth() + .padding(bottom = SimpleTheme.dimens.padding.extraLarge) + .focusRequester(focusRequester) + .testTag(SaveAsDialogTestTags.FILENAME) + ) + OutlinedTextField( + value = extension, + onValueChange = { extension = it }, + singleLine = true, + label = { Text(text = stringResource(id = R.string.extension)) }, + modifier = Modifier + .fillMaxWidth() + .testTag(SaveAsDialogTestTags.EXTENSION) + ) + } + } + ) +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/favorites/ManageFavoritesScreen.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/favorites/ManageFavoritesScreen.kt new file mode 100644 index 0000000..1c367e5 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/favorites/ManageFavoritesScreen.kt @@ -0,0 +1,317 @@ +package org.fossify.filemanager.compose.favorites + +import androidx.activity.compose.BackHandler +import androidx.compose.animation.Crossfade +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.res.vectorResource +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.unit.sp +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.persistentListOf +import org.fossify.commons.compose.alert_dialog.dialogBorder +import org.fossify.commons.compose.alert_dialog.dialogContainerColor +import org.fossify.commons.compose.components.SimpleDropDownMenuItem +import org.fossify.commons.compose.lists.SimpleScaffold +import org.fossify.commons.compose.lists.SimpleScaffoldTopBar +import org.fossify.commons.compose.menus.ActionItem +import org.fossify.commons.compose.menus.ActionMenu +import org.fossify.commons.compose.menus.OverflowMode +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.filemanager.R +import org.fossify.filemanager.compose.ManageFavoritesTestTags +import org.fossify.filemanager.compose.components.ActionModeTopBar +import org.fossify.filemanager.compose.components.selectedItemBackground + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ManageFavoritesScreen( + favorites: ImmutableList<String>, + goBack: () -> Unit, + onAddFavorite: () -> Unit, + onRemoveFavorites: (Set<String>) -> Unit, + modifier: Modifier = Modifier, +) { + var selectedPaths by rememberSaveable { mutableStateOf(emptyList<String>()) } + val validSelection = selectedPaths.filter { it in favorites } + val isInActionMode = validSelection.isNotEmpty() + var lastLongPressedIndex by rememberSaveable { mutableIntStateOf(-1) } + val clearSelection = { + selectedPaths = emptyList() + lastLongPressedIndex = -1 + } + + BackHandler(enabled = isInActionMode, onBack = clearSelection) + + SimpleScaffold( + modifier = modifier, + darkStatusBarIcons = !isInActionMode, + customTopBar = { scrolledColor, navigationInteractionSource, scrollBehavior, statusBarColor, + colorTransitionFraction, contrastColor -> + Crossfade(targetState = isInActionMode, label = "favorites-toolbar") { actionMode -> + if (actionMode) { + ActionModeTopBar( + selectedCount = validSelection.size, + totalCount = favorites.size, + onClose = clearSelection, + onSelectAll = { selectedPaths = favorites.toList() }, + actions = { iconColor -> + RemoveActionMenu( + iconColor = iconColor, + onRemove = { + onRemoveFavorites(validSelection.toSet()) + clearSelection() + } + ) + } + ) + } else { + SimpleScaffoldTopBar( + title = { color -> + Text(text = stringResource(id = R.string.manage_favorites), color = color, maxLines = 1) + }, + actions = { AddFavoriteActionMenu(iconColor = scrolledColor, onAddFavorite = onAddFavorite) }, + scrolledColor = scrolledColor, + navigationIconInteractionSource = navigationInteractionSource, + scrollBehavior = scrollBehavior, + statusBarColor = statusBarColor, + colorTransitionFraction = colorTransitionFraction, + contrastColor = contrastColor, + goBack = goBack + ) + } + } + } + ) { paddingValues -> + LazyColumn( + modifier = Modifier + .fillMaxSize() + .testTag(ManageFavoritesTestTags.LIST), + contentPadding = PaddingValues(bottom = paddingValues.calculateBottomPadding()) + ) { + if (favorites.isEmpty()) { + emptyFavorites(onAddFavorite) + } else { + favoriteItems( + favorites = favorites, + selectedPaths = validSelection, + isInActionMode = isInActionMode, + onToggle = { path -> + val newSelection = if (path in validSelection) validSelection - path else validSelection + path + if (newSelection.isEmpty()) { + clearSelection() + } else { + selectedPaths = newSelection + } + }, + onLongPress = { index -> + val range = if (lastLongPressedIndex == -1) { + listOf(favorites[index]) + } else { + val from = minOf(lastLongPressedIndex, index).coerceIn(favorites.indices) + val to = maxOf(lastLongPressedIndex, index).coerceIn(favorites.indices) + favorites.subList(from, to + 1) + } + selectedPaths = (validSelection + range).distinct() + lastLongPressedIndex = index + }, + onRemove = { path -> + clearSelection() + onRemoveFavorites(setOf(path)) + } + ) + } + } + } +} + +private fun LazyListScope.favoriteItems( + favorites: ImmutableList<String>, + selectedPaths: List<String>, + isInActionMode: Boolean, + onToggle: (String) -> Unit, + onLongPress: (Int) -> Unit, + onRemove: (String) -> Unit, +) { + itemsIndexed(favorites, key = { _, path -> path }) { index, path -> + FavoriteItem( + path = path, + isSelected = path in selectedPaths, + onClick = { + if (isInActionMode) { + onToggle(path) + } + }, + onLongClick = { onLongPress(index) }, + onRemove = { onRemove(path) } + ) + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun FavoriteItem( + path: String, + isSelected: Boolean, + onClick: () -> Unit, + onLongClick: () -> Unit, + onRemove: () -> Unit, +) { + val haptics = LocalHapticFeedback.current + Row( + modifier = Modifier + .fillMaxWidth() + .background(selectedItemBackground(isSelected)) + .combinedClickable( + onClick = onClick, + onLongClick = { + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + onLongClick() + } + ) + .padding(start = SimpleTheme.dimens.padding.extraLarge) + .testTag(ManageFavoritesTestTags.item(path)), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = path, + modifier = Modifier.weight(1f), + color = SimpleTheme.colorScheme.onSurface, + fontSize = 16.sp + ) + FavoriteItemMenu(path = path, onRemove = onRemove) + } +} + +@Composable +private fun FavoriteItemMenu(path: String, onRemove: () -> Unit) { + var isMenuVisible by remember { mutableStateOf(false) } + Box { + IconButton( + onClick = { isMenuVisible = true }, + modifier = Modifier.testTag(ManageFavoritesTestTags.itemMenu(path)) + ) { + Icon( + imageVector = ImageVector.vectorResource(id = R.drawable.ic_three_dots_vector), + contentDescription = stringResource(id = R.string.more_options), + tint = SimpleTheme.colorScheme.onSurface + ) + } + DropdownMenu( + modifier = Modifier + .background(dialogContainerColor) + .dialogBorder(), + expanded = isMenuVisible, + onDismissRequest = { isMenuVisible = false } + ) { + SimpleDropDownMenuItem(text = R.string.remove, onClick = { + isMenuVisible = false + onRemove() + }) + } + } +} + +private fun LazyListScope.emptyFavorites(onAddFavorite: () -> Unit) { + item(key = ManageFavoritesTestTags.PLACEHOLDER) { + Text( + text = stringResource(id = R.string.favorites_activity_placeholder), + style = TextStyle( + fontStyle = FontStyle.Italic, + textAlign = TextAlign.Center, + fontSize = 16.sp, + color = SimpleTheme.colorScheme.onSurface.copy(alpha = 0.8f) + ), + modifier = Modifier + .fillMaxWidth() + .padding( + start = SimpleTheme.dimens.padding.extraLarge, + end = SimpleTheme.dimens.padding.extraLarge, + top = SimpleTheme.dimens.padding.extraLarge, + bottom = SimpleTheme.dimens.padding.small + ) + .testTag(ManageFavoritesTestTags.PLACEHOLDER) + ) + } + item(key = ManageFavoritesTestTags.PLACEHOLDER_ADD) { + Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + Text( + text = stringResource(id = R.string.add_favorites), + style = TextStyle( + textDecoration = TextDecoration.Underline, + fontSize = 16.sp, + color = SimpleTheme.colorScheme.primary + ), + modifier = Modifier + .combinedClickable(onClick = onAddFavorite) + .padding(SimpleTheme.dimens.padding.large) + .testTag(ManageFavoritesTestTags.PLACEHOLDER_ADD) + ) + } + } +} + +@Composable +private fun AddFavoriteActionMenu(iconColor: Color, onAddFavorite: () -> Unit) { + val addIcon = ImageVector.vectorResource(id = R.drawable.ic_plus_vector) + val items = remember(addIcon, onAddFavorite) { + persistentListOf( + ActionItem( + nameRes = R.string.add_favorites, + icon = addIcon, + overflowMode = OverflowMode.NEVER_OVERFLOW, + doAction = onAddFavorite + ) + ) + } + ActionMenu(items = items, numIcons = 1, isMenuVisible = false, iconsColor = iconColor, onMenuToggle = {}) +} + +@Composable +private fun RemoveActionMenu(iconColor: Color, onRemove: () -> Unit) { + val removeIcon = ImageVector.vectorResource(id = R.drawable.ic_minus_circle_vector) + val items = remember(removeIcon, onRemove) { + persistentListOf( + ActionItem( + nameRes = R.string.remove, + icon = removeIcon, + overflowMode = OverflowMode.NEVER_OVERFLOW, + doAction = onRemove + ) + ) + } + ActionMenu(items = items, numIcons = 1, isMenuVisible = false, iconsColor = iconColor, onMenuToggle = {}) +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/files/CreateNewItemAlertDialog.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/files/CreateNewItemAlertDialog.kt new file mode 100644 index 0000000..f4b4691 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/files/CreateNewItemAlertDialog.kt @@ -0,0 +1,100 @@ +package org.fossify.filemanager.compose.files + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.unit.sp +import org.fossify.commons.compose.alert_dialog.dialogBorder +import org.fossify.commons.compose.alert_dialog.dialogContainerColor +import org.fossify.commons.compose.alert_dialog.dialogElevation +import org.fossify.commons.compose.alert_dialog.dialogShape +import org.fossify.commons.compose.alert_dialog.dialogTextColor +import org.fossify.commons.compose.components.RadioGroupDialogComponent +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.filemanager.R +import org.fossify.filemanager.compose.FilesTabTestTags + +/** + * The "Create new" dialog of the Files tab: a name and whether to create a folder (the default) or a file. + * [onConfirm] validates and creates the item; the owner hides the dialog once that worked. + */ +@Composable +fun CreateNewItemAlertDialog( + onDismiss: () -> Unit, + onConfirm: (name: String, isDirectory: Boolean) -> Unit, + modifier: Modifier = Modifier, +) { + val folder = stringResource(id = R.string.folder) + val file = stringResource(id = R.string.file) + var name by rememberSaveable { mutableStateOf("") } + var isDirectory by rememberSaveable { mutableStateOf(true) } + val focusRequester = remember { FocusRequester() } + + AlertDialog( + modifier = modifier.dialogBorder(), + shape = dialogShape, + containerColor = dialogContainerColor, + tonalElevation = dialogElevation, + onDismissRequest = onDismiss, + confirmButton = { + TextButton(onClick = { onConfirm(name, isDirectory) }) { + Text(text = stringResource(id = R.string.ok)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(text = stringResource(id = R.string.cancel)) + } + }, + title = { + Text( + text = stringResource(id = R.string.create_new), + color = dialogTextColor, + fontSize = 21.sp, + ) + }, + text = { + LaunchedEffect(Unit) { + focusRequester.requestFocus() + } + Column { + OutlinedTextField( + value = name, + onValueChange = { name = it }, + singleLine = true, + label = { Text(text = stringResource(id = R.string.title)) }, + keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences), + modifier = Modifier + .fillMaxWidth() + .padding(bottom = SimpleTheme.dimens.padding.extraLarge) + .focusRequester(focusRequester) + .testTag(FilesTabTestTags.CREATE_NAME) + ) + RadioGroupDialogComponent( + items = listOf(folder, file), + selected = if (isDirectory) folder else file, + horizontalPadding = SimpleTheme.dimens.padding.small, + setSelected = { isDirectory = it == folder } + ) + } + } + ) +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/files/FastScroller.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FastScroller.kt new file mode 100644 index 0000000..93d0901 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FastScroller.kt @@ -0,0 +1,175 @@ +package org.fossify.filemanager.compose.files + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectVerticalDragGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.grid.LazyGridState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import kotlinx.collections.immutable.ImmutableList +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import org.fossify.commons.extensions.getContrastColor +import org.fossify.filemanager.compose.FilesTabTestTags +import org.fossify.filemanager.models.ListItem +import kotlin.math.roundToInt + +private const val HIDE_DELAY_MS = 1000L + +// The fast scroller's own metrics: the view based list drew it with the RecyclerViewFastScroller library, whose sizes +// are not Fossify dimension resources. +private val handleWidth = 6.dp +private val handleHeight = 48.dp +private val handleEndMargin = 4.dp +private val touchWidth = 32.dp +private val bubbleCorner = 16.dp +private val bubblePaddingHorizontal = 16.dp +private val bubblePaddingVertical = 8.dp + +/** + * A draggable scroll handle on the right edge, shown while the list scrolls. Dragging it jumps through the list and + * shows a bubble with the name, size, date or extension of the item at that position, following the sorting. + */ +@Composable +fun FastScroller( + gridState: LazyGridState, + items: ImmutableList<ListItem>, + dateFormat: String, + timeFormat: String, + color: Color, + modifier: Modifier = Modifier, +) { + val canScroll by remember(gridState) { + derivedStateOf { gridState.canScrollForward || gridState.canScrollBackward } + } + if (items.isEmpty() || !canScroll) { + return + } + + val context = LocalContext.current + val density = LocalDensity.current + val scope = rememberCoroutineScope() + var isDragging by remember { mutableStateOf(false) } + var isVisible by remember { mutableStateOf(false) } + var dragFraction by remember { mutableFloatStateOf(0f) } + val scrollFraction by remember(gridState, items) { + derivedStateOf { + val info = gridState.layoutInfo + val total = info.totalItemsCount + val visible = info.visibleItemsInfo.size + if (total <= visible || total == 0) { + 0f + } else { + (gridState.firstVisibleItemIndex.toFloat() / (total - visible)).coerceIn(0f, 1f) + } + } + } + + LaunchedEffect(gridState.isScrollInProgress, isDragging) { + if (gridState.isScrollInProgress || isDragging) { + isVisible = true + } else { + delay(HIDE_DELAY_MS) + isVisible = false + } + } + + BoxWithConstraints(modifier = modifier.fillMaxSize()) { + val trackHeight = with(density) { (maxHeight - handleHeight).toPx() }.coerceAtLeast(1f) + val fraction = if (isDragging) dragFraction else scrollFraction + val handleOffset = (trackHeight * fraction).roundToInt() + + fun scrollTo(y: Float) { + dragFraction = (y / trackHeight).coerceIn(0f, 1f) + val index = (dragFraction * items.lastIndex).roundToInt() + scope.launch { gridState.scrollToItem(index) } + } + + AnimatedVisibility( + visible = isVisible, + enter = fadeIn(), + exit = fadeOut(), + modifier = Modifier.align(Alignment.TopEnd) + ) { + Box( + modifier = Modifier + .fillMaxHeight() + .width(touchWidth) + .pointerInput(items, trackHeight) { + detectVerticalDragGestures( + onDragStart = { offset -> + isDragging = true + scrollTo(offset.y - handleHeight.toPx() / 2) + }, + onDragEnd = { isDragging = false }, + onDragCancel = { isDragging = false }, + onVerticalDrag = { change, _ -> + change.consume() + scrollTo(change.position.y - handleHeight.toPx() / 2) + } + ) + } + .testTag(FilesTabTestTags.FAST_SCROLLER) + ) { + Box( + modifier = Modifier + .align(Alignment.TopEnd) + .offset { IntOffset(0, handleOffset) } + .padding(end = handleEndMargin) + .size(width = handleWidth, height = handleHeight) + .background(color, RoundedCornerShape(handleWidth / 2)) + ) + } + } + + if (isDragging) { + val item = items.getOrNull((dragFraction * items.lastIndex).roundToInt()) + val bubbleText = remember(item, dateFormat, timeFormat) { + item?.getBubbleText(context, dateFormat, timeFormat).orEmpty() + } + if (bubbleText.isNotEmpty()) { + Row( + modifier = Modifier + .align(Alignment.TopEnd) + .padding(end = touchWidth) + .offset { IntOffset(0, handleOffset) } + .background(color, RoundedCornerShape(bubbleCorner)) + .padding(horizontal = bubblePaddingHorizontal, vertical = bubblePaddingVertical) + ) { + Text(text = bubbleText, color = Color(color.toArgb().getContrastColor()), fontSize = 18.sp) + } + } + } + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/files/FileItemDecorations.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FileItemDecorations.kt new file mode 100644 index 0000000..0ccde38 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FileItemDecorations.kt @@ -0,0 +1,119 @@ +package org.fossify.filemanager.compose.files + +import android.text.Spanned +import android.text.style.ForegroundColorSpan +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.runtime.ReadOnlyComposable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.colorResource +import androidx.compose.ui.res.dimensionResource +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.vectorResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import org.fossify.commons.compose.theme.LocalTheme +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.commons.compose.theme.model.Theme +import org.fossify.commons.extensions.getContrastColor +import org.fossify.commons.extensions.highlightTextPart +import org.fossify.filemanager.R + +private const val FOLDER_ICON_ALPHA = 180f / 255f + +@Composable +internal fun FolderIcon(color: Color, modifier: Modifier = Modifier) { + Image( + painter = painterResource(id = R.drawable.ic_folder_vector), + contentDescription = null, + colorFilter = ColorFilter.tint(color), + alpha = FOLDER_ICON_ALPHA, + modifier = modifier + ) +} + +@Composable +internal fun SelectionCheck(color: Color, modifier: Modifier = Modifier) { + Box( + modifier = modifier + .size(dimensionResource(org.fossify.commons.R.dimen.selection_check_size)) + .background(color = color, shape = CircleShape) + .padding(SimpleTheme.dimens.padding.extraSmall), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = ImageVector.vectorResource(id = R.drawable.ic_check_vector), + contentDescription = null, + tint = Color(color.toArgb().getContrastColor()) + ) + } +} + +@OptIn(ExperimentalFoundationApi::class) +@Composable +internal fun Modifier.itemClicks(onClick: () -> Unit, onLongClick: () -> Unit): Modifier { + val haptics = LocalHapticFeedback.current + return combinedClickable( + onClick = onClick, + onLongClick = { + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + onLongClick() + } + ) +} + +/** Selected rows of the list use the highlight of the clickable selector (Material You aware). */ +@Composable +@ReadOnlyComposable +internal fun listSelectionColor(isSelected: Boolean): Color = when { + !isSelected -> Color.Transparent + LocalTheme.current is Theme.SystemDefaultMaterialYou -> + colorResource(id = org.fossify.commons.R.color.you_selected_item_background_color) + + else -> colorResource(id = org.fossify.commons.R.color.activated_item_foreground) +} + +/** Selected grid cells get the translucent foreground of the grid selector. */ +@Composable +@ReadOnlyComposable +internal fun gridSelectionColor(isSelected: Boolean): Color = + if (isSelected) colorResource(id = org.fossify.commons.R.color.activated_item_foreground) else Color.Transparent + +/** [text] with the searched part in the accent color, like the view based list highlights it. */ +@Composable +internal fun highlighted(text: String, highlight: String, color: Color): AnnotatedString = + remember(text, highlight, color) { + if (highlight.isEmpty()) { + AnnotatedString(text) + } else { + text.highlightTextPart(highlight, color.toArgb()).toAnnotatedString() + } + } + +private fun Spanned.toAnnotatedString(): AnnotatedString = buildAnnotatedString { + append(this@toAnnotatedString.toString()) + getSpans(0, length, ForegroundColorSpan::class.java).forEach { span -> + addStyle( + style = SpanStyle(color = Color(span.foregroundColor)), + start = getSpanStart(span), + end = getSpanEnd(span) + ) + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/files/FileItems.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FileItems.kt new file mode 100644 index 0000000..adf38ea --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FileItems.kt @@ -0,0 +1,242 @@ +package org.fossify.filemanager.compose.files + +import android.graphics.drawable.Drawable +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.dimensionResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.TextUnit +import androidx.compose.ui.unit.dp +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.commons.extensions.formatDate +import org.fossify.commons.extensions.formatSize +import org.fossify.filemanager.R +import org.fossify.filemanager.compose.FilesTabTestTags +import org.fossify.filemanager.models.ListItem +import java.util.Locale + +internal const val SMALLER_FONT_RATIO = 0.8f +private const val SECONDARY_TEXT_ALPHA = 0.6f + +/** Colors, text sizes and formats shared by all rows of the list. */ +@Immutable +data class FileItemStyle( + val textColor: Color, + val primaryColor: Color, + val fontSize: TextUnit, + val smallerFontSize: TextUnit, + val dateFormat: String, + val timeFormat: String, + val highlightText: String, + val displayFilenames: Boolean, + val hasOTGConnected: Boolean, +) + +/** The file type placeholder of [item], shown until (or instead of) its thumbnail. */ +fun fileTypeDrawable(item: ListItem, placeholders: Map<String, Drawable>, genericFile: Drawable): Drawable = + placeholders[item.name.substringAfterLast(".").lowercase(Locale.getDefault())] ?: genericFile + +/** Ends the folders of the grid so that the files start on a new row. */ +@Composable +fun GridTypeDivider(modifier: Modifier = Modifier) { + Spacer(modifier = modifier.fillMaxWidth().height(0.dp)) +} + +/** The folder title above the search results of one folder. */ +@Composable +fun SectionTitleItem( + item: ListItem, + style: FileItemStyle, + onClick: () -> Unit, + onLongClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val padding = SimpleTheme.dimens.padding + Row( + modifier = modifier + .fillMaxWidth() + .itemClicks(onClick = onClick, onLongClick = onLongClick) + .padding(top = padding.large, bottom = padding.extraSmall, end = padding.extraLarge) + .testTag(FilesTabTestTags.section(item.path)), + verticalAlignment = Alignment.CenterVertically + ) { + FolderIcon( + color = style.primaryColor, + modifier = Modifier + .size(dimensionResource(org.fossify.commons.R.dimen.file_picker_icon_size)) + .padding(padding.medium) + ) + Text( + text = highlighted(item.mName, style.highlightText, style.primaryColor), + color = style.textColor, + fontSize = style.fontSize, + modifier = Modifier + .weight(1f) + .padding(top = padding.extraLarge, end = padding.large, bottom = padding.extraLarge) + ) + } +} + +/** A row of the list view: icon, name, then size or item count and the modification date. */ +@Composable +fun FileListItem( + item: ListItem, + isSelected: Boolean, + icon: Drawable, + style: FileItemStyle, + onClick: () -> Unit, + onLongClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val padding = SimpleTheme.dimens.padding + val context = LocalContext.current + Row( + modifier = modifier + .fillMaxWidth() + .padding(bottom = padding.extraSmall) + .background(listSelectionColor(isSelected)) + .itemClicks(onClick = onClick, onLongClick = onLongClick) + .padding( + top = padding.extraSmall, + bottom = padding.extraSmall, + start = padding.small, + end = dimensionResource(org.fossify.commons.R.dimen.bigger_margin) + ) + .testTag(FilesTabTestTags.item(item.path)), + verticalAlignment = Alignment.CenterVertically + ) { + ItemIcon( + item = item, + icon = icon, + style = style, + modifier = Modifier + .size(dimensionResource(org.fossify.commons.R.dimen.file_picker_icon_size)) + .padding(padding.medium) + ) + Column(modifier = Modifier.weight(1f)) { + Text( + text = highlighted(item.name, style.highlightText, style.primaryColor), + color = style.textColor, + fontSize = style.fontSize, + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + modifier = Modifier.padding(start = padding.extraSmall) + ) + Row(verticalAlignment = Alignment.CenterVertically) { + val details = if (item.isDirectory) { + pluralStringResource(R.plurals.items, item.children, item.children) + } else { + item.size.formatSize() + } + Text( + text = details, + color = style.textColor.copy(alpha = SECONDARY_TEXT_ALPHA), + fontSize = style.fontSize, + maxLines = 1, + modifier = Modifier + .weight(1f) + .padding(start = padding.extraSmall) + ) + if (!item.isDirectory) { + Text( + text = item.modified.formatDate(context, style.dateFormat, style.timeFormat), + color = style.textColor.copy(alpha = SECONDARY_TEXT_ALPHA), + fontSize = style.smallerFontSize, + textAlign = TextAlign.End, + maxLines = 1 + ) + } + } + } + } +} + +/** A cell of the grid view: a big icon or thumbnail with the name below it. */ +@Composable +fun FileGridItem( + item: ListItem, + isSelected: Boolean, + icon: Drawable, + style: FileItemStyle, + onClick: () -> Unit, + onLongClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val padding = SimpleTheme.dimens.padding + Box( + modifier = modifier + .fillMaxWidth() + .itemClicks(onClick = onClick, onLongClick = onLongClick) + .background(gridSelectionColor(isSelected)) + .padding(horizontal = padding.small, vertical = padding.extraSmall) + .testTag(FilesTabTestTags.item(item.path)) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(bottom = if (item.isDirectory) padding.medium else padding.large), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Box(modifier = Modifier.fillMaxWidth()) { + ItemIcon( + item = item, + icon = icon, + style = style, + modifier = Modifier + .fillMaxWidth() + .aspectRatio(1f) + .padding(padding.small) + ) + // like the view based grid, only folders show the check mark, files are only highlighted + if (isSelected && item.isDirectory) { + SelectionCheck( + color = style.primaryColor, + modifier = Modifier + .align(Alignment.TopEnd) + .testTag(FilesTabTestTags.check(item.path)) + ) + } + } + if (item.isDirectory || style.displayFilenames) { + Text( + text = highlighted(item.name, style.highlightText, style.primaryColor), + color = style.textColor, + fontSize = style.smallerFontSize, + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = padding.small) + ) + } + } + } +} + +@Composable +private fun ItemIcon(item: ListItem, icon: Drawable, style: FileItemStyle, modifier: Modifier = Modifier) { + if (item.isDirectory) { + FolderIcon(color = style.primaryColor, modifier = modifier) + } else { + FileThumbnail(item = item, placeholder = icon, hasOTGConnected = style.hasOTGConnected, modifier = modifier) + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/files/FileThumbnail.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FileThumbnail.kt new file mode 100644 index 0000000..3f759fd --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FileThumbnail.kt @@ -0,0 +1,93 @@ +package org.fossify.filemanager.compose.files + +import android.app.Activity +import android.graphics.drawable.Drawable +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.IntSize +import com.bumptech.glide.Glide +import com.bumptech.glide.load.engine.DiskCacheStrategy +import com.bumptech.glide.load.resource.bitmap.CenterCrop +import com.bumptech.glide.load.resource.bitmap.RoundedCorners +import com.bumptech.glide.request.RequestOptions +import com.bumptech.glide.request.target.CustomTarget +import com.bumptech.glide.request.transition.Transition +import org.fossify.filemanager.activities.SimpleActivity +import org.fossify.filemanager.compose.components.DrawablePainter +import org.fossify.filemanager.helpers.FileItemActions +import org.fossify.filemanager.models.ListItem + +private const val THUMBNAIL_CORNER_RADIUS = 10 + +/** + * The icon of a file: its thumbnail loaded by Glide with the same options the list adapter uses, or the + * file type [placeholder] until then and when the file has no preview. + */ +@Composable +fun FileThumbnail( + item: ListItem, + placeholder: Drawable, + hasOTGConnected: Boolean, + modifier: Modifier = Modifier, +) { + val context = LocalContext.current + var size by remember { mutableStateOf(IntSize.Zero) } + var loaded by remember(item.path, item.modified, item.size) { mutableStateOf<Drawable?>(null) } + val drawable = loaded ?: placeholder + val painter = remember(drawable) { DrawablePainter(drawable) } + + Box(modifier = modifier.onSizeChanged { size = it }) { + Image(painter = painter, contentDescription = null, modifier = Modifier.fillMaxSize()) + } + + DisposableEffect(item.path, item.modified, item.size, size, placeholder) { + val activity = (context as? SimpleActivity)?.takeUnless { it.isDestroyedOrFinishing() } + if (activity == null || size.width <= 0 || size.height <= 0) { + return@DisposableEffect onDispose { } + } + + val target = object : CustomTarget<Drawable>(size.width, size.height) { + override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) { + loaded = resource + } + + override fun onLoadFailed(errorDrawable: Drawable?) { + loaded = errorDrawable + } + + override fun onLoadCleared(placeholderDrawable: Drawable?) { + loaded = null + } + } + + val options = RequestOptions() + .signature(item.getKey()) + .diskCacheStrategy(DiskCacheStrategy.RESOURCE) + .error(placeholder) + .transform(CenterCrop(), RoundedCorners(THUMBNAIL_CORNER_RADIUS)) + + Glide.with(activity) + .load(FileItemActions.getImagePathToLoad(activity, item.path, hasOTGConnected)) + .apply(options) + .into(target) + + onDispose { + loaded = null + if (!activity.isDestroyedOrFinishing()) { + Glide.with(activity).clear(target) + } + } + } +} + +private fun Activity.isDestroyedOrFinishing() = isDestroyed || isFinishing diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesActionModeBar.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesActionModeBar.kt new file mode 100644 index 0000000..af6fd6f --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesActionModeBar.kt @@ -0,0 +1,152 @@ +package org.fossify.filemanager.compose.files + +import androidx.activity.compose.BackHandler +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.vectorResource +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.toImmutableList +import org.fossify.commons.compose.menus.ActionItem +import org.fossify.commons.compose.menus.ActionMenu +import org.fossify.commons.compose.menus.OverflowMode +import org.fossify.commons.compose.theme.AppTheme +import org.fossify.commons.models.FileDirItem +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.MainActivity +import org.fossify.filemanager.compose.components.ActionModeTopBar +import org.fossify.filemanager.compose.components.maxToolbarActionIcons +import org.fossify.filemanager.extensions.isZipFile + +/** The Fossify theme for Compose content hosted by the view based main screen. */ +@Composable +fun MainScreenTheme(content: @Composable () -> Unit) { + val context = LocalContext.current + AppTheme { + content() + LaunchedEffect(Unit) { + // the theme makes the system bars transparent with default icon colors, give the main toolbar its own back + (context as? MainActivity)?.refreshSystemBarColors() + } + } +} + +/** + * The contextual top bar of the Files tab while items are selected, drawn over the main toolbar: "selected / total" + * (tap to select all or, with everything selected, to finish), the close arrow and the actions on the selection with + * the same entries, visibility rules and overflow placement as the old action mode menu. + */ +@Composable +fun FilesActionModeBar( + state: FilesTabState, + onAction: (actionId: Int) -> Unit, + onFinish: () -> Unit, + modifier: Modifier = Modifier, +) { + if (!state.isInSelectionMode) { + return + } + + val currentOnFinish by rememberUpdatedState(onFinish) + DisposableEffect(Unit) { + onDispose { currentOnFinish() } + } + BackHandler(onBack = state::clearSelection) + + var isMenuVisible by remember { mutableStateOf(false) } + val selectedItems = state.selectedItems + val selectableCount = state.selectableItems.size + val actionItems = rememberSelectionActions( + selectedItems = selectedItems, + isPickMultipleIntent = state.isPickMultipleIntent, + onAction = onAction + ) + + ActionModeTopBar( + selectedCount = selectedItems.size, + totalCount = selectableCount, + onClose = state::clearSelection, + onSelectAll = state::selectAll, + drawBehindStatusBar = false, + modifier = modifier, + actions = { iconColor -> + ActionMenu( + items = actionItems, + numIcons = maxToolbarActionIcons(), + isMenuVisible = isMenuVisible, + iconsColor = iconColor, + onMenuToggle = { isMenuVisible = it } + ) + } + ) +} + +@Composable +private fun rememberSelectionActions( + selectedItems: List<FileDirItem>, + isPickMultipleIntent: Boolean, + onAction: (Int) -> Unit, +): ImmutableList<ActionItem> { + val deleteIcon = ImageVector.vectorResource(id = R.drawable.ic_delete_vector) + val checkIcon = ImageVector.vectorResource(id = R.drawable.ic_check_vector) + val infoIcon = ImageVector.vectorResource(id = R.drawable.ic_info_vector) + val renameIcon = ImageVector.vectorResource(id = R.drawable.ic_rename_vector) + val shareIcon = ImageVector.vectorResource(id = R.drawable.ic_share_vector) + val hideIcon = ImageVector.vectorResource(id = R.drawable.ic_hide_vector) + val unhideIcon = ImageVector.vectorResource(id = R.drawable.ic_unhide_vector) + val selectAllIcon = ImageVector.vectorResource(id = R.drawable.ic_select_all_vector) + val currentOnAction by rememberUpdatedState(onAction) + + val isOneItemSelected = selectedItems.size == 1 + val isOneFileSelected = isOneItemSelected && !selectedItems.first().isDirectory + val hasZip = selectedItems.any { it.path.isZipFile() } + val hasHidden = selectedItems.any { it.name.startsWith(".") } + val hasUnhidden = selectedItems.any { !it.name.startsWith(".") } + + return remember(isPickMultipleIntent, isOneItemSelected, isOneFileSelected, hasZip, hasHidden, hasUnhidden) { + fun item(nameRes: Int, id: Int, mode: OverflowMode, icon: ImageVector? = null) = + ActionItem(nameRes = nameRes, icon = icon, overflowMode = mode, doAction = { currentOnAction(id) }) + + buildList { + add(item(R.string.delete, R.id.cab_delete, OverflowMode.NEVER_OVERFLOW, deleteIcon)) + if (isPickMultipleIntent) { + add( + item(R.string.confirm_selection, R.id.cab_confirm_selection, OverflowMode.NEVER_OVERFLOW, checkIcon) + ) + } + add(item(R.string.properties, R.id.cab_properties, OverflowMode.NEVER_OVERFLOW, infoIcon)) + add(item(R.string.rename, R.id.cab_rename, OverflowMode.NEVER_OVERFLOW, renameIcon)) + add(item(R.string.share, R.id.cab_share, OverflowMode.IF_NECESSARY, shareIcon)) + if (hasUnhidden) { + add(item(R.string.hide, R.id.cab_hide, OverflowMode.IF_NECESSARY, hideIcon)) + } + if (hasHidden) { + add(item(R.string.unhide, R.id.cab_unhide, OverflowMode.IF_NECESSARY, unhideIcon)) + } + if (isOneItemSelected) { + add(item(R.string.create_shortcut, R.id.cab_create_shortcut, OverflowMode.ALWAYS_OVERFLOW)) + add(item(R.string.copy_path, R.id.cab_copy_path, OverflowMode.ALWAYS_OVERFLOW)) + } + if (isOneFileSelected) { + add(item(R.string.set_as, R.id.cab_set_as, OverflowMode.ALWAYS_OVERFLOW)) + add(item(R.string.open_with, R.id.cab_open_with, OverflowMode.ALWAYS_OVERFLOW)) + add(item(R.string.open_as, R.id.cab_open_as, OverflowMode.ALWAYS_OVERFLOW)) + } + add(item(R.string.copy_to, R.id.cab_copy_to, OverflowMode.ALWAYS_OVERFLOW)) + add(item(R.string.move_to, R.id.cab_move_to, OverflowMode.ALWAYS_OVERFLOW)) + add(item(R.string.compress, R.id.cab_compress, OverflowMode.ALWAYS_OVERFLOW)) + if (hasZip) { + add(item(R.string.decompress, R.id.cab_decompress, OverflowMode.ALWAYS_OVERFLOW)) + } + add(item(R.string.select_all, R.id.cab_select_all, OverflowMode.IF_NECESSARY, selectAllIcon)) + }.toImmutableList() + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesBreadcrumbs.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesBreadcrumbs.kt new file mode 100644 index 0000000..f24f9fc --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesBreadcrumbs.kt @@ -0,0 +1,151 @@ +package org.fossify.filemanager.compose.files + +import android.content.Context +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.defaultMinSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ColorFilter +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.dimensionResource +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.unit.TextUnit +import kotlinx.collections.immutable.ImmutableList +import kotlinx.coroutines.launch +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.commons.extensions.getBasePath +import org.fossify.commons.extensions.getDialogBackgroundColor +import org.fossify.commons.extensions.humanizePath +import org.fossify.commons.helpers.MEDIUM_ALPHA +import org.fossify.commons.models.FileDirItem +import org.fossify.filemanager.compose.FilesTabTestTags + +/** + * The folders from the storage root to [fullPath], as the breadcrumbs of the Files tab show them: + * the first one is the humanized storage root ("Internal", "SD card", …), each path ends with a slash. + */ +fun buildBreadcrumbs(context: Context, fullPath: String): List<FileDirItem> { + val breadcrumbs = ArrayList<FileDirItem>() + var currPath = fullPath.getBasePath(context) + context.humanizePath(fullPath).split("/") + .dropLastWhile(String::isEmpty) + .forEachIndexed { i, dir -> + if (i > 0) { + currPath += "$dir/" + } + if (dir.isEmpty()) { + return@forEachIndexed + } + currPath = "${currPath.trimEnd('/')}/" + breadcrumbs.add(FileDirItem(currPath, dir, true, 0, 0, 0)) + } + return breadcrumbs +} + +/** + * The breadcrumbs above the file list. The storage root stays pinned at the start, the folders after it scroll + * horizontally and the current folder (the last one) is highlighted and scrolled into view. + */ +@Composable +fun FilesBreadcrumbs( + breadcrumbs: ImmutableList<FileDirItem>, + textColor: Color, + accentColor: Color, + fontSize: TextUnit, + onBreadcrumbClick: (index: Int) -> Unit, + modifier: Modifier = Modifier, +) { + if (breadcrumbs.isEmpty()) { + return + } + + val context = LocalContext.current + val padding = SimpleTheme.dimens.padding + val minHeight = dimensionResource(org.fossify.commons.R.dimen.breadcrumbs_layout_height) + val corner = RoundedCornerShape(dimensionResource(org.fossify.commons.R.dimen.material_button_corner_radius)) + val oneDp = dimensionResource(org.fossify.commons.R.dimen.one_dp) + val scrollState = rememberScrollState() + val scope = rememberCoroutineScope() + LaunchedEffect(breadcrumbs, scrollState.maxValue) { + scrollState.scrollTo(scrollState.maxValue) + } + + Row( + modifier = modifier + .fillMaxWidth() + .padding(top = padding.medium) + .padding(start = padding.extraLarge, top = padding.small, end = padding.small, bottom = padding.small) + .testTag(FilesTabTestTags.BREADCRUMBS), + verticalAlignment = Alignment.CenterVertically + ) { + val rootBackground = remember(context, textColor, accentColor) { Color(context.getDialogBackgroundColor()) } + Surface( + shape = corner, + color = rootBackground, + border = BorderStroke(oneDp, accentColor.copy(alpha = MEDIUM_ALPHA)), + shadowElevation = oneDp, + modifier = Modifier.testTag(FilesTabTestTags.breadcrumb(0)) + ) { + Text( + text = breadcrumbs.first().name, + color = textColor, + fontSize = fontSize, + maxLines = 1, + modifier = Modifier + .clip(corner) + .clickable { onBreadcrumbClick(0) } + .defaultMinSize(minHeight = minHeight) + .padding(horizontal = padding.large, vertical = padding.medium) + ) + } + + Row( + modifier = Modifier.horizontalScroll(scrollState), + verticalAlignment = Alignment.CenterVertically + ) { + for (index in 1 until breadcrumbs.size) { + val isLast = index == breadcrumbs.lastIndex + val color = if (isLast) accentColor else textColor + Row( + modifier = Modifier + .clip(corner) + .clickable { + if (isLast) { + scope.launch { scrollState.animateScrollTo(scrollState.maxValue) } + } else { + onBreadcrumbClick(index) + } + } + .defaultMinSize(minHeight = minHeight) + .padding(end = padding.extraSmall, top = padding.medium, bottom = padding.medium) + .testTag(FilesTabTestTags.breadcrumb(index)), + verticalAlignment = Alignment.CenterVertically + ) { + Image( + painter = painterResource(id = org.fossify.commons.R.drawable.ic_chevron_right_vector), + contentDescription = null, + colorFilter = ColorFilter.tint(color) + ) + Text(text = breadcrumbs[index].name, color = color, fontSize = fontSize, maxLines = 1) + } + } + } + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesTabScreen.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesTabScreen.kt new file mode 100644 index 0000000..166d19a --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesTabScreen.kt @@ -0,0 +1,426 @@ +package org.fossify.filemanager.compose.files + +import android.graphics.drawable.Drawable +import androidx.appcompat.content.res.AppCompatResources +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.calculateZoom +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.GridItemSpan +import androidx.compose.foundation.lazy.grid.LazyGridState +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.itemsIndexed +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FloatingActionButton +import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults +import androidx.compose.material3.pulltorefresh.pullToRefresh +import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.res.vectorResource +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.sp +import kotlinx.coroutines.delay +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.commons.extensions.getContrastColor +import org.fossify.commons.extensions.hasOTGConnected +import org.fossify.commons.helpers.LOWER_ALPHA +import org.fossify.commons.helpers.getFilePlaceholderDrawables +import org.fossify.filemanager.R +import org.fossify.filemanager.compose.FilesTabTestTags +import org.fossify.filemanager.models.ListItem + +private const val PROGRESS_SHOW_DELAY_MS = 250L +private const val ZOOM_IN_SCALE = 1.4f +private const val ZOOM_OUT_SCALE = 0.85f +private const val PLACEHOLDER_ALPHA = 0.8f + +/** What the Files tab reports back to its owner. */ +interface FilesTabActions { + fun onItemClick(index: Int) + fun onItemLongClick(index: Int) + fun onBreadcrumbClick(index: Int) + fun onRefresh() + fun onFabClick() + + /** Pinch out in the grid view: one column less. */ + fun onZoomIn() + + /** Pinch in in the grid view: one column more. */ + fun onZoomOut() + fun onCreateItem(name: String, isDirectory: Boolean) + fun onDismissCreateDialog() +} + +/** + * The Files tab: breadcrumbs, the folder content as a list or a grid with pull-to-refresh, pinch to zoom and a fast + * scroller, the search placeholders, the loading indicator and the create button. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun FilesTabScreen( + state: FilesTabState, + actions: FilesTabActions, + modifier: Modifier = Modifier, +) { + val density = LocalDensity.current + val textColor = Color(state.textColor) + val primaryColor = Color(state.primaryColor) + val fontSize = with(density) { state.fontSizePx.toSp() } + + Box(modifier = modifier.fillMaxSize()) { + Column(modifier = Modifier.fillMaxSize()) { + FilesBreadcrumbs( + breadcrumbs = state.breadcrumbs, + textColor = textColor, + accentColor = primaryColor, + fontSize = fontSize, + onBreadcrumbClick = actions::onBreadcrumbClick + ) + + Box(modifier = Modifier.weight(1f)) { + FilesPlaceholders(placeholder = state.placeholder, textColor = textColor) + if (state.isListVisible) { + RefreshableFileList( + state = state, + actions = actions, + textColor = textColor, + primaryColor = primaryColor + ) + } + } + } + + LoadingIndicator(isLoading = state.isLoading, color = primaryColor) + + FloatingActionButton( + onClick = actions::onFabClick, + containerColor = primaryColor, + contentColor = Color(state.primaryColor.getContrastColor()), + modifier = Modifier + .align(Alignment.BottomEnd) + .padding(SimpleTheme.dimens.padding.extraLarge) + .testTag(FilesTabTestTags.FAB) + ) { + val icon = if (state.isCreateDocumentIntent) R.drawable.ic_check_vector else R.drawable.ic_plus_vector + val description = if (state.isCreateDocumentIntent) R.string.ok else R.string.create_new + Icon( + imageVector = ImageVector.vectorResource(id = icon), + contentDescription = stringResource(id = description) + ) + } + + if (state.isCreateDialogVisible) { + CreateNewItemAlertDialog( + onDismiss = actions::onDismissCreateDialog, + onConfirm = actions::onCreateItem + ) + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun RefreshableFileList( + state: FilesTabState, + actions: FilesTabActions, + textColor: Color, + primaryColor: Color, +) { + val pullToRefreshState = rememberPullToRefreshState() + Box( + modifier = Modifier + .fillMaxSize() + .pullToRefresh( + isRefreshing = state.isRefreshing, + state = pullToRefreshState, + enabled = state.canPullToRefresh, + onRefresh = { + state.isRefreshing = true + actions.onRefresh() + } + ) + ) { + FileList(state = state, actions = actions, textColor = textColor, primaryColor = primaryColor) + PullToRefreshDefaults.Indicator( + state = pullToRefreshState, + isRefreshing = state.isRefreshing, + color = primaryColor, + modifier = Modifier.align(Alignment.TopCenter) + ) + } +} + +@Composable +private fun FileList( + state: FilesTabState, + actions: FilesTabActions, + textColor: Color, + primaryColor: Color, +) { + val context = LocalContext.current + val density = LocalDensity.current + val placeholders = remember(context, state.drawablesVersion) { getFilePlaceholderDrawables(context) } + val genericFile = remember(context, state.drawablesVersion) { + requireNotNull(AppCompatResources.getDrawable(context, R.drawable.ic_file_generic)) + } + val hasOTGConnected = remember(context, state.drawablesVersion) { context.hasOTGConnected() } + val style = FileItemStyle( + textColor = textColor, + primaryColor = primaryColor, + fontSize = with(density) { state.fontSizePx.toSp() }, + smallerFontSize = with(density) { (state.fontSizePx * SMALLER_FONT_RATIO).toSp() }, + dateFormat = state.dateFormat, + timeFormat = state.timeFormat, + highlightText = state.highlightText, + displayFilenames = state.displayFilenames, + hasOTGConnected = hasOTGConnected + ) + val iconFor: (ListItem) -> Drawable = { item -> fileTypeDrawable(item, placeholders, genericFile) } + + val gridState = state.gridState + LaunchedEffect(state.pendingScroll, state.items) { + val target = state.pendingScroll ?: return@LaunchedEffect + if (state.items.isNotEmpty()) { + gridState.scrollToItem(target.index.coerceAtMost(state.items.lastIndex), target.offset) + } + state.pendingScroll = null + } + + val currentActions by rememberUpdatedState(actions) + var dragAnchor by remember { mutableStateOf<DragAnchor?>(null) } + val columns = if (state.isGrid) state.columnCount.coerceAtLeast(1) else 1 + + Box(modifier = Modifier.fillMaxSize()) { + LazyVerticalGrid( + columns = GridCells.Fixed(columns), + state = gridState, + modifier = Modifier + .fillMaxSize() + .pinchToZoom( + enabled = state.isGrid, + onZoomIn = { currentActions.onZoomIn() }, + onZoomOut = { currentActions.onZoomOut() } + ) + .dragToSelect( + gridState = gridState, + anchor = { dragAnchor }, + onDrag = { anchor, index -> state.dragSelect(anchor.index, index, anchor.previousSelection) }, + onDragEnd = { dragAnchor = null } + ) + .testTag(FilesTabTestTags.LIST) + ) { + itemsIndexed( + items = state.items, + key = { index, item -> item.listKey(index) }, + span = { _, item -> + if (item.isSectionTitle || item.isGridTypeDivider) GridItemSpan(maxLineSpan) else GridItemSpan(1) + }, + contentType = { _, item -> item.contentType(state.isGrid) } + ) { index, item -> + val isSelected = item.path in state.selectedPaths + val onClick = { currentActions.onItemClick(index) } + val onLongClick = { + if (!item.isSectionTitle) { + dragAnchor = DragAnchor(index, state.selectedPaths.toSet() + item.path) + } + currentActions.onItemLongClick(index) + } + when { + item.isGridTypeDivider -> GridTypeDivider() + item.isSectionTitle -> SectionTitleItem( + item = item, + style = style, + onClick = onClick, + onLongClick = onLongClick + ) + + state.isGrid -> FileGridItem( + item = item, + isSelected = isSelected, + icon = iconFor(item), + style = style, + onClick = onClick, + onLongClick = onLongClick + ) + + else -> FileListItem( + item = item, + isSelected = isSelected, + icon = iconFor(item), + style = style, + onClick = onClick, + onLongClick = onLongClick + ) + } + } + } + + FastScroller( + gridState = gridState, + items = state.items, + dateFormat = state.dateFormat, + timeFormat = state.timeFormat, + color = primaryColor, + modifier = Modifier.matchParentSize() + ) + } +} + +private fun ListItem.listKey(index: Int) = when { + isGridTypeDivider -> "grid_type_divider" + isSectionTitle -> "section_${index}_$path" + else -> path +} + +private fun ListItem.contentType(isGrid: Boolean) = when { + isGridTypeDivider -> "divider" + isSectionTitle -> "section" + isGrid && isDirectory -> "grid_folder" + isGrid -> "grid_file" + else -> "list_item" +} + +/** The item a drag selection started at and what was selected before it. */ +private class DragAnchor(val index: Int, val previousSelection: Set<String>) + +/** + * Pinching in the grid changes the column count once per gesture, with the thresholds of the old recycler view. + * The events are only observed, so scrolling keeps working. + */ +private fun Modifier.pinchToZoom(enabled: Boolean, onZoomIn: () -> Unit, onZoomOut: () -> Unit) = + if (!enabled) { + this + } else { + pointerInput(Unit) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + var zoom = 1f + var handled = false + do { + val event = awaitPointerEvent(PointerEventPass.Initial) + if (event.changes.count { it.pressed } >= 2 && !handled) { + zoom *= event.calculateZoom() + if (zoom >= ZOOM_IN_SCALE) { + handled = true + onZoomIn() + } else if (zoom <= ZOOM_OUT_SCALE) { + handled = true + onZoomOut() + } + } + } while (event.changes.any { it.pressed }) + } + } + } + +/** + * After a long press on an item, dragging the finger selects every item between it and the one under the finger, + * like the drag selection of the old recycler view. The list does not scroll during the drag. + */ +private fun Modifier.dragToSelect( + gridState: LazyGridState, + anchor: () -> DragAnchor?, + onDrag: (DragAnchor, Int) -> Unit, + onDragEnd: () -> Unit, +) = pointerInput(Unit) { + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) + do { + val event = awaitPointerEvent(PointerEventPass.Initial) + val change = event.changes.firstOrNull { it.id == down.id } ?: break + val currentAnchor = anchor() + if (currentAnchor != null && change.pressed) { + change.consume() + gridState.itemIndexAt(change.position)?.let { index -> onDrag(currentAnchor, index) } + } + } while (change.pressed) + onDragEnd() + } +} + +private fun LazyGridState.itemIndexAt(position: Offset): Int? = + layoutInfo.visibleItemsInfo.firstOrNull { info -> + position.x.toInt() in info.offset.x..(info.offset.x + info.size.width) && + position.y.toInt() in info.offset.y..(info.offset.y + info.size.height) + }?.index + +@Composable +private fun FilesPlaceholders(placeholder: FilesPlaceholder, textColor: Color) { + if (placeholder == FilesPlaceholder.NONE) { + return + } + + Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { + Text( + text = stringResource(id = R.string.no_items_found), + color = textColor.copy(alpha = PLACEHOLDER_ALPHA), + fontSize = 16.sp, + fontStyle = FontStyle.Italic, + textAlign = TextAlign.Center, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = SimpleTheme.dimens.padding.extraLarge) + .testTag(FilesTabTestTags.PLACEHOLDER) + ) + if (placeholder == FilesPlaceholder.TYPE_MORE) { + Text( + text = stringResource(id = R.string.type_2_characters), + color = textColor.copy(alpha = PLACEHOLDER_ALPHA), + fontSize = 16.sp, + fontStyle = FontStyle.Italic, + textAlign = TextAlign.Center, + modifier = Modifier + .padding(SimpleTheme.dimens.padding.extraLarge) + .testTag(FilesTabTestTags.PLACEHOLDER_TYPE_MORE) + ) + } + } +} + +/** The indeterminate bar at the top of the tab, shown only when loading takes longer than a moment. */ +@Composable +private fun LoadingIndicator(isLoading: Boolean, color: Color) { + var isVisible by remember { mutableStateOf(false) } + LaunchedEffect(isLoading) { + if (isLoading) { + delay(PROGRESS_SHOW_DELAY_MS) + } + isVisible = isLoading + } + + if (isVisible) { + LinearProgressIndicator( + color = color, + trackColor = color.copy(alpha = LOWER_ALPHA), + modifier = Modifier + .fillMaxWidth() + .testTag(FilesTabTestTags.PROGRESS) + ) + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesTabState.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesTabState.kt new file mode 100644 index 0000000..42168c7 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/files/FilesTabState.kt @@ -0,0 +1,170 @@ +package org.fossify.filemanager.compose.files + +import androidx.compose.foundation.lazy.grid.LazyGridState +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.ImmutableSet +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.persistentSetOf +import kotlinx.collections.immutable.toImmutableSet +import org.fossify.commons.models.FileDirItem +import org.fossify.filemanager.models.ListItem + +/** Which of the search placeholders of the Files tab is shown instead of the list. */ +enum class FilesPlaceholder { + NONE, + + /** "No items found." */ + NO_ITEMS, + + /** "No items found." plus "Type at least 2 characters to start the search." */ + TYPE_MORE, +} + +/** First visible item and its offset, remembered per folder like the RecyclerView layout manager state was. */ +data class ScrollPosition(val index: Int, val offset: Int) + +/** + * Everything the Compose Files tab draws. It is owned by [org.fossify.filemanager.fragments.ItemsFragment], + * which loads the folders and runs the actions, and only mutated on the main thread. + */ +@Stable +class FilesTabState { + var currentPath by mutableStateOf("") + var breadcrumbs by mutableStateOf<ImmutableList<FileDirItem>>(persistentListOf()) + + /** The rows shown right now: the folder content, or the search results with their folder titles. */ + var items by mutableStateOf<ImmutableList<ListItem>>(persistentListOf()) + var highlightText by mutableStateOf("") + var placeholder by mutableStateOf(FilesPlaceholder.NONE) + var isListVisible by mutableStateOf(true) + + var isGrid by mutableStateOf(false) + var columnCount by mutableIntStateOf(DEFAULT_COLUMN_COUNT) + var displayFilenames by mutableStateOf(true) + + var isLoading by mutableStateOf(false) + var isRefreshing by mutableStateOf(false) + var isPullToRefreshEnabled by mutableStateOf(true) + var isSearchActive by mutableStateOf(false) + + var isCreateDocumentIntent by mutableStateOf(false) + var isPickMultipleIntent by mutableStateOf(false) + var isCreateDialogVisible by mutableStateOf(false) + + var textColor by mutableIntStateOf(0) + var primaryColor by mutableIntStateOf(0) + var fontSizePx by mutableFloatStateOf(0f) + var dateFormat by mutableStateOf("") + var timeFormat by mutableStateOf("") + + /** Bumped whenever the thumbnails should be reloaded, e.g. after returning to the app. */ + var drawablesVersion by mutableIntStateOf(0) + + var selectedPaths by mutableStateOf<ImmutableSet<String>>(persistentSetOf()) + private set + private var lastLongPressedIndex = -1 + + val gridState = LazyGridState() + + /** Where the list should scroll once the new folder content was laid out. */ + var pendingScroll by mutableStateOf<ScrollPosition?>(null) + + val isInSelectionMode: Boolean + get() = selectedPaths.isNotEmpty() + + val selectableItems: List<ListItem> + get() = items.filter { it.isSelectable() } + + val selectedItems: ArrayList<FileDirItem> + get() = ArrayList<FileDirItem>(items.filter { it.isSelectable() && it.path in selectedPaths }) + + val canPullToRefresh: Boolean + get() = isPullToRefreshEnabled && !isSearchActive && !isInSelectionMode + + fun clearSelection() { + selectedPaths = persistentSetOf() + lastLongPressedIndex = -1 + } + + fun selectAll() { + selectedPaths = selectableItems.map { it.path }.toImmutableSet() + lastLongPressedIndex = -1 + } + + /** A tap while items are selected (un)selects the item, like the view based action mode did. */ + fun toggleSelection(index: Int) { + val item = items.getOrNull(index) + if (item != null && item.isSelectable()) { + setSelected(item, item.path !in selectedPaths) + } + lastLongPressedIndex = -1 + } + + /** + * A long press selects the item; a second long press selects everything between the two items. + */ + fun longPress(index: Int) { + val item = items.getOrNull(index) ?: return + setSelected(item, true) + lastLongPressedIndex = if (lastLongPressedIndex == -1) { + index + } else { + val from = minOf(lastLongPressedIndex, index) + val to = maxOf(lastLongPressedIndex, index) + val range = (from..to).mapNotNull { items.getOrNull(it) }.filter { it.isSelectable() }.map { it.path } + selectedPaths = (selectedPaths + range).toImmutableSet() + index + } + } + + /** Selects the items between [anchor] and [current] while dragging after a long press. */ + fun dragSelect(anchor: Int, current: Int, previouslySelected: Set<String>) { + val from = minOf(anchor, current) + val to = maxOf(anchor, current) + val range = (from..to).mapNotNull { items.getOrNull(it) }.filter { it.isSelectable() }.map { it.path } + val newSelection = (previouslySelected + range).toImmutableSet() + if (newSelection != selectedPaths) { + selectedPaths = newSelection + } + } + + /** Drops selected paths that are not in the list anymore, finishing the selection mode if none is left. */ + fun keepValidSelection() { + val paths = selectableItems.map { it.path }.toSet() + val valid = selectedPaths.filter { it in paths } + if (valid.size != selectedPaths.size) { + selectedPaths = valid.toImmutableSet() + } + if (selectedPaths.isEmpty()) { + lastLongPressedIndex = -1 + } + } + + private fun setSelected(item: ListItem, select: Boolean) { + if (select && !item.isSelectable()) { + return + } + + selectedPaths = if (select) { + (selectedPaths + item.path).toImmutableSet() + } else { + (selectedPaths - item.path).toImmutableSet() + } + + if (selectedPaths.isEmpty()) { + lastLongPressedIndex = -1 + } + } + + companion object { + const val DEFAULT_COLUMN_COUNT = 3 + } +} + +fun ListItem.isSelectable() = !isSectionTitle && !isGridTypeDivider diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/settings/ManageVisibleTabsAlertDialog.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/settings/ManageVisibleTabsAlertDialog.kt new file mode 100644 index 0000000..5d91086 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/settings/ManageVisibleTabsAlertDialog.kt @@ -0,0 +1,120 @@ +package org.fossify.filemanager.compose.settings + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CheckboxDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.sp +import org.fossify.commons.compose.alert_dialog.AlertDialogState +import org.fossify.commons.compose.alert_dialog.dialogBorder +import org.fossify.commons.compose.alert_dialog.dialogContainerColor +import org.fossify.commons.compose.alert_dialog.dialogElevation +import org.fossify.commons.compose.alert_dialog.dialogShape +import org.fossify.commons.compose.alert_dialog.dialogTextColor +import org.fossify.commons.compose.theme.SimpleTheme +import org.fossify.commons.helpers.TAB_FILES +import org.fossify.commons.helpers.TAB_RECENT_FILES +import org.fossify.commons.helpers.TAB_STORAGE_ANALYSIS +import org.fossify.filemanager.R +import org.fossify.filemanager.helpers.ALL_TABS_MASK + +private val manageableTabs = listOf( + TAB_FILES to R.string.files_tab, + TAB_RECENT_FILES to R.string.recent_files_tab, + TAB_STORAGE_ANALYSIS to R.string.storage_analysis, +) + +/** + * Lets the user pick which main screen tabs are visible. Hiding every tab shows all of them, + * exactly like the previous view based dialog did. + */ +@Composable +fun ManageVisibleTabsAlertDialog( + alertDialogState: AlertDialogState, + shownTabs: Int, + onConfirm: (tabsMask: Int) -> Unit, + modifier: Modifier = Modifier, +) { + var selectedTabs by rememberSaveable { mutableIntStateOf(shownTabs) } + AlertDialog( + modifier = modifier.dialogBorder(), + shape = dialogShape, + containerColor = dialogContainerColor, + tonalElevation = dialogElevation, + onDismissRequest = alertDialogState::hide, + confirmButton = { + TextButton( + onClick = { + alertDialogState.hide() + val checkedTabs = selectedTabs and ALL_TABS_MASK + onConfirm(if (checkedTabs == 0) ALL_TABS_MASK else checkedTabs) + } + ) { + Text(text = stringResource(id = R.string.ok)) + } + }, + dismissButton = { + TextButton(onClick = alertDialogState::hide) { + Text(text = stringResource(id = R.string.cancel)) + } + }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState())) { + manageableTabs.forEach { (tab, labelId) -> + val isChecked = selectedTabs and tab != 0 + TabCheckboxRow( + label = stringResource(id = labelId), + checked = isChecked, + onCheckedChange = { checked -> + selectedTabs = if (checked) selectedTabs or tab else selectedTabs and tab.inv() + } + ) + } + } + } + ) +} + +@Composable +private fun TabCheckboxRow( + label: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, +) { + Row( + modifier = Modifier + .fillMaxWidth() + .toggleable(value = checked, role = Role.Checkbox, onValueChange = onCheckedChange) + .padding(vertical = SimpleTheme.dimens.padding.small), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SimpleTheme.dimens.padding.medium) + ) { + Checkbox( + checked = checked, + onCheckedChange = null, + colors = CheckboxDefaults.colors( + checkedColor = SimpleTheme.colorScheme.primary, + checkmarkColor = SimpleTheme.colorScheme.surface, + ) + ) + Text(text = label, color = dialogTextColor, fontSize = 16.sp) + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/compose/settings/SettingsScreen.kt b/app/src/main/kotlin/org/fossify/filemanager/compose/settings/SettingsScreen.kt new file mode 100644 index 0000000..27fc644 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/compose/settings/SettingsScreen.kt @@ -0,0 +1,255 @@ +package org.fossify.filemanager.compose.settings + +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import org.fossify.commons.compose.alert_dialog.rememberAlertDialogStateSaveable +import org.fossify.commons.compose.lists.SimpleColumnScaffold +import org.fossify.commons.compose.settings.SettingsGroup +import org.fossify.commons.compose.settings.SettingsHorizontalDivider +import org.fossify.commons.compose.settings.SettingsPreferenceComponent +import org.fossify.commons.compose.settings.SettingsSwitchComponent +import org.fossify.commons.compose.settings.SettingsTitleTextComponent +import org.fossify.filemanager.R +import org.fossify.filemanager.compose.SettingsTestTags + +@Immutable +data class SettingsUiState( + val showPurchaseThankYou: Boolean, + val canPurchaseThankYou: Boolean, + val showUseEnglish: Boolean, + val useEnglish: Boolean, + val showLanguage: Boolean, + val language: String, + val fontSize: String, + val pressBackTwice: Boolean, + val showHidden: Boolean, + val enablePullToRefresh: Boolean, + val keepLastModified: Boolean, + val skipDeleteConfirmation: Boolean, + val hiddenItemPasswordProtection: Boolean, + val appPasswordProtection: Boolean, + val fileDeletionPasswordProtection: Boolean, + val showEnableRootAccess: Boolean, + val enableRootAccess: Boolean, + val showCheckmarksOnSwitches: Boolean, + val shownTabs: Int, +) + +/** Rows of the settings screen that trigger an action in the hosting activity. */ +enum class SettingsAction { + CUSTOMIZE_COLORS, + PURCHASE_THANK_YOU, + USE_ENGLISH, + LANGUAGE, + MANAGE_FAVORITES, + CHANGE_DATE_TIME_FORMAT, + FONT_SIZE, + PRESS_BACK_TWICE, + SHOW_HIDDEN, + ENABLE_PULL_TO_REFRESH, + KEEP_LAST_MODIFIED, + SKIP_DELETE_CONFIRMATION, + HIDDEN_ITEM_PASSWORD_PROTECTION, + APP_PASSWORD_PROTECTION, + FILE_DELETION_PASSWORD_PROTECTION, + ENABLE_ROOT_ACCESS, +} + +@Composable +fun SettingsScreen( + state: SettingsUiState, + onAction: (SettingsAction) -> Unit, + onManageShownTabsConfirm: (tabsMask: Int) -> Unit, + goBack: () -> Unit, + modifier: Modifier = Modifier, +) { + val manageTabsDialogState = rememberAlertDialogStateSaveable() + manageTabsDialogState.DialogMember { + ManageVisibleTabsAlertDialog( + alertDialogState = manageTabsDialogState, + shownTabs = state.shownTabs, + onConfirm = onManageShownTabsConfirm + ) + } + + SimpleColumnScaffold( + title = stringResource(id = R.string.settings), + goBack = goBack, + modifier = modifier.testTag(SettingsTestTags.LIST) + ) { + ColorCustomizationSection(onAction) + SettingsHorizontalDivider() + GeneralSection(state = state, onAction = onAction, onManageShownTabsClick = manageTabsDialogState::show) + SettingsHorizontalDivider() + SettingsSection(title = stringResource(id = R.string.visibility)) { + SettingsSwitch( + label = stringResource(id = R.string.show_hidden_items), + checked = state.showHidden, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.SHOW_HIDDEN) } + ) + } + SettingsHorizontalDivider() + SettingsSection(title = stringResource(id = R.string.scrolling)) { + SettingsSwitch( + label = stringResource(id = R.string.enable_pull_to_refresh), + checked = state.enablePullToRefresh, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.ENABLE_PULL_TO_REFRESH) } + ) + } + SettingsHorizontalDivider() + FileOperationsSection(state = state, onAction = onAction) + SettingsHorizontalDivider() + SecuritySection(state = state, onAction = onAction) + } +} + +@Composable +private fun ColorCustomizationSection(onAction: (SettingsAction) -> Unit) { + SettingsSection(title = stringResource(id = R.string.color_customization)) { + SettingsPreferenceComponent( + label = stringResource(id = R.string.customize_colors), + doOnPreferenceClick = { onAction(SettingsAction.CUSTOMIZE_COLORS) } + ) + } +} + +@Composable +private fun GeneralSection( + state: SettingsUiState, + onAction: (SettingsAction) -> Unit, + onManageShownTabsClick: () -> Unit, +) { + SettingsSection(title = stringResource(id = R.string.general_settings)) { + if (state.showPurchaseThankYou) { + SettingsPreferenceComponent( + label = stringResource(id = R.string.purchase_simple_thank_you), + value = stringResource(id = R.string.enables_more_customization), + doOnPreferenceClick = { onAction(SettingsAction.PURCHASE_THANK_YOU) } + ) + } + if (state.showUseEnglish) { + SettingsSwitch( + label = stringResource(id = R.string.use_english_language), + checked = state.useEnglish, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.USE_ENGLISH) } + ) + } + if (state.showLanguage) { + SettingsPreferenceComponent( + label = stringResource(id = R.string.language), + value = state.language, + doOnPreferenceClick = { onAction(SettingsAction.LANGUAGE) } + ) + } + SettingsPreferenceComponent( + label = stringResource(id = R.string.manage_favorites), + doOnPreferenceClick = { onAction(SettingsAction.MANAGE_FAVORITES) } + ) + SettingsPreferenceComponent( + label = stringResource(id = R.string.manage_shown_tabs), + doOnPreferenceClick = onManageShownTabsClick + ) + SettingsPreferenceComponent( + label = stringResource(id = R.string.change_date_and_time_format), + doOnPreferenceClick = { onAction(SettingsAction.CHANGE_DATE_TIME_FORMAT) } + ) + SettingsPreferenceComponent( + label = stringResource(id = R.string.font_size), + value = state.fontSize, + doOnPreferenceClick = { onAction(SettingsAction.FONT_SIZE) } + ) + SettingsSwitch( + label = stringResource(id = R.string.press_back_twice), + checked = state.pressBackTwice, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.PRESS_BACK_TWICE) } + ) + } +} + +@Composable +private fun FileOperationsSection(state: SettingsUiState, onAction: (SettingsAction) -> Unit) { + SettingsSection(title = stringResource(id = R.string.file_operations)) { + SettingsSwitch( + label = stringResource(id = R.string.keep_last_modified), + checked = state.keepLastModified, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.KEEP_LAST_MODIFIED) } + ) + SettingsSwitch( + label = stringResource(id = R.string.skip_delete_confirmation), + checked = state.skipDeleteConfirmation, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.SKIP_DELETE_CONFIRMATION) } + ) + } +} + +@Composable +private fun SecuritySection(state: SettingsUiState, onAction: (SettingsAction) -> Unit) { + SettingsSection(title = stringResource(id = R.string.security)) { + SettingsSwitch( + label = stringResource(id = R.string.password_protect_hidden_items), + checked = state.hiddenItemPasswordProtection, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.HIDDEN_ITEM_PASSWORD_PROTECTION) } + ) + SettingsSwitch( + label = stringResource(id = R.string.password_protect_whole_app), + checked = state.appPasswordProtection, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.APP_PASSWORD_PROTECTION) } + ) + SettingsSwitch( + label = stringResource(id = R.string.password_protect_file_deletion), + checked = state.fileDeletionPasswordProtection, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.FILE_DELETION_PASSWORD_PROTECTION) } + ) + if (state.showEnableRootAccess) { + SettingsSwitch( + label = stringResource(id = R.string.enable_root_access), + checked = state.enableRootAccess, + showCheckmark = state.showCheckmarksOnSwitches, + onClick = { onAction(SettingsAction.ENABLE_ROOT_ACCESS) } + ) + } + } +} + +@Composable +private fun SettingsSection( + title: String, + content: @Composable ColumnScope.() -> Unit, +) { + SettingsGroup( + title = { SettingsTitleTextComponent(text = title) }, + content = content + ) +} + +/** + * The switch only reflects the stored value, a click asks the activity to change it, + * because some toggles need confirmation first (password protection, root access, hidden items). + */ +@Composable +private fun SettingsSwitch( + label: String, + checked: Boolean, + showCheckmark: Boolean, + onClick: () -> Unit, +) { + SettingsSwitchComponent( + label = label, + initialValue = checked, + showCheckmark = showCheckmark, + onChange = { onClick() } + ) +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/dialogs/ManageVisibleTabsDialog.kt b/app/src/main/kotlin/org/fossify/filemanager/dialogs/ManageVisibleTabsDialog.kt deleted file mode 100644 index 29760be..0000000 --- a/app/src/main/kotlin/org/fossify/filemanager/dialogs/ManageVisibleTabsDialog.kt +++ /dev/null @@ -1,53 +0,0 @@ -package org.fossify.filemanager.dialogs - -import org.fossify.commons.activities.BaseSimpleActivity -import org.fossify.commons.extensions.getAlertDialogBuilder -import org.fossify.commons.extensions.setupDialogStuff -import org.fossify.commons.helpers.TAB_FILES -import org.fossify.commons.helpers.TAB_RECENT_FILES -import org.fossify.commons.helpers.TAB_STORAGE_ANALYSIS -import org.fossify.commons.views.MyAppCompatCheckbox -import org.fossify.filemanager.R -import org.fossify.filemanager.databinding.DialogManageVisibleTabsBinding -import org.fossify.filemanager.extensions.config -import org.fossify.filemanager.helpers.ALL_TABS_MASK - -class ManageVisibleTabsDialog(val activity: BaseSimpleActivity) { - private val binding = DialogManageVisibleTabsBinding.inflate(activity.layoutInflater) - private val tabs = LinkedHashMap<Int, Int>() - - init { - tabs.apply { - put(TAB_FILES, R.id.manage_visible_tabs_files) - put(TAB_RECENT_FILES, R.id.manage_visible_tabs_recent_files) - put(TAB_STORAGE_ANALYSIS, R.id.manage_visible_tabs_storage_analysis) - } - - val showTabs = activity.config.showTabs - for ((key, value) in tabs) { - binding.root.findViewById<MyAppCompatCheckbox>(value).isChecked = showTabs and key != 0 - } - - activity.getAlertDialogBuilder() - .setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() } - .setNegativeButton(R.string.cancel, null) - .apply { - activity.setupDialogStuff(binding.root, this) - } - } - - private fun dialogConfirmed() { - var result = 0 - for ((key, value) in tabs) { - if (binding.root.findViewById<MyAppCompatCheckbox>(value).isChecked) { - result += key - } - } - - if (result == 0) { - result = ALL_TABS_MASK - } - - activity.config.showTabs = result - } -} diff --git a/app/src/main/kotlin/org/fossify/filemanager/dialogs/SaveAsDialog.kt b/app/src/main/kotlin/org/fossify/filemanager/dialogs/SaveAsDialog.kt deleted file mode 100644 index 3ddd935..0000000 --- a/app/src/main/kotlin/org/fossify/filemanager/dialogs/SaveAsDialog.kt +++ /dev/null @@ -1,89 +0,0 @@ -package org.fossify.filemanager.dialogs - -import androidx.appcompat.app.AlertDialog -import org.fossify.commons.activities.BaseSimpleActivity -import org.fossify.commons.dialogs.ConfirmationDialog -import org.fossify.commons.dialogs.FilePickerDialog -import org.fossify.commons.extensions.* -import org.fossify.filemanager.R -import org.fossify.filemanager.databinding.DialogSaveAsBinding - -class SaveAsDialog( - val activity: BaseSimpleActivity, var path: String, val hidePath: Boolean, - val callback: (path: String, filename: String) -> Unit -) { - - init { - if (path.isEmpty()) { - path = "${activity.internalStoragePath}/${activity.getCurrentFormattedDateTime()}.txt" - } - - var realPath = path.getParentPath() - val binding = DialogSaveAsBinding.inflate(activity.layoutInflater).apply { - folderValue.setText(activity.humanizePath(realPath)) - - val fullName = path.getFilenameFromPath() - val dotAt = fullName.lastIndexOf(".") - var name = fullName - - if (dotAt > 0) { - name = fullName.substring(0, dotAt) - val extension = fullName.substring(dotAt + 1) - extensionValue.setText(extension) - } - - filenameValue.setText(name) - - if (hidePath) { - folderHint.beGone() - } else { - folderValue.setOnClickListener { - FilePickerDialog(activity, realPath, false, false, true, true, showFavoritesButton = true) { - folderValue.setText(activity.humanizePath(it)) - realPath = it - } - } - } - } - - activity.getAlertDialogBuilder() - .setPositiveButton(R.string.ok, null) - .setNegativeButton(R.string.cancel, null) - .apply { - activity.setupDialogStuff(binding.root, this, R.string.save_as) { alertDialog -> - alertDialog.showKeyboard(binding.filenameValue) - alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { - val filename = binding.filenameValue.value - val extension = binding.extensionValue.value - - if (filename.isEmpty()) { - activity.toast(R.string.filename_cannot_be_empty) - return@setOnClickListener - } - - var newFilename = filename - if (extension.isNotEmpty()) { - newFilename += ".$extension" - } - - val newPath = "$realPath/$newFilename" - if (!newFilename.isAValidFilename()) { - activity.toast(R.string.filename_invalid_characters) - return@setOnClickListener - } - - if (!hidePath && activity.getDoesFilePathExist(newPath)) { - val title = String.format(activity.getString(R.string.file_already_exists_overwrite), newFilename) - ConfirmationDialog(activity, title) { - callback(newPath, newFilename) - alertDialog.dismiss() - } - } else { - callback(newPath, newFilename) - alertDialog.dismiss() - } - } - } - } - } -} diff --git a/app/src/main/kotlin/org/fossify/filemanager/fragments/ItemsFragment.kt b/app/src/main/kotlin/org/fossify/filemanager/fragments/ItemsFragment.kt index d758964..47981b4 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/fragments/ItemsFragment.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/fragments/ItemsFragment.kt @@ -2,101 +2,188 @@ package org.fossify.filemanager.fragments import android.annotation.SuppressLint import android.content.Context -import android.os.Parcelable import android.util.AttributeSet -import androidx.recyclerview.widget.GridLayoutManager +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.ComposeView +import com.stericson.RootTools.RootTools +import kotlinx.collections.immutable.toImmutableList import org.fossify.commons.activities.BaseSimpleActivity import org.fossify.commons.dialogs.StoragePickerDialog -import org.fossify.commons.extensions.* -import org.fossify.commons.helpers.* +import org.fossify.commons.extensions.getAndroidSAFFileItems +import org.fossify.commons.extensions.getDirectChildrenCount +import org.fossify.commons.extensions.getFolderLastModifieds +import org.fossify.commons.extensions.getOTGItems +import org.fossify.commons.extensions.getParentPath +import org.fossify.commons.extensions.getProperPrimaryColor +import org.fossify.commons.extensions.getProperSize +import org.fossify.commons.extensions.getTextSize +import org.fossify.commons.extensions.getTimeFormat +import org.fossify.commons.extensions.humanizePath +import org.fossify.commons.extensions.isPathOnOTG +import org.fossify.commons.extensions.isRestrictedSAFOnlyRoot +import org.fossify.commons.extensions.normalizeString +import org.fossify.commons.extensions.toast +import org.fossify.commons.helpers.SORT_BY_SIZE +import org.fossify.commons.helpers.VIEW_TYPE_GRID +import org.fossify.commons.helpers.VIEW_TYPE_LIST +import org.fossify.commons.helpers.ensureBackgroundThread import org.fossify.commons.models.FileDirItem -import org.fossify.commons.views.Breadcrumbs -import org.fossify.commons.views.MyGridLayoutManager -import org.fossify.commons.views.MyRecyclerView import org.fossify.filemanager.R import org.fossify.filemanager.activities.MainActivity import org.fossify.filemanager.activities.SimpleActivity -import org.fossify.filemanager.adapters.ItemsAdapter -import org.fossify.filemanager.databinding.ItemsFragmentBinding -import org.fossify.filemanager.dialogs.CreateNewItemDialog +import org.fossify.filemanager.compose.files.FilesActionModeBar +import org.fossify.filemanager.compose.files.FilesPlaceholder +import org.fossify.filemanager.compose.files.FilesTabActions +import org.fossify.filemanager.compose.files.FilesTabScreen +import org.fossify.filemanager.compose.files.FilesTabState +import org.fossify.filemanager.compose.files.MainScreenTheme +import org.fossify.filemanager.compose.files.ScrollPosition +import org.fossify.filemanager.compose.files.buildBreadcrumbs import org.fossify.filemanager.extensions.config import org.fossify.filemanager.extensions.isPathOnRoot +import org.fossify.filemanager.helpers.FileItemActions import org.fossify.filemanager.helpers.MAX_COLUMN_COUNT +import org.fossify.filemanager.helpers.NewItemCreator import org.fossify.filemanager.helpers.RootHelpers import org.fossify.filemanager.interfaces.ItemOperationsListener import org.fossify.filemanager.models.ListItem import java.io.File -class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerFragment<MyViewPagerFragment.ItemsInnerBinding>(context, attributeSet), - ItemOperationsListener, - Breadcrumbs.BreadcrumbsListener { +/** + * The Files tab of the main screen. The view only hosts Compose: the tab content ([FilesTabScreen]) and, while + * items are selected, the contextual top bar ([FilesActionModeBar]) drawn over the main toolbar like the old + * action mode. Loading folders, searching and running the actions stays here. + */ +// Not new: detekt's baseline lists this class's TooManyFunctions finding under its old signature, which also named +// the breadcrumbs view's listener, and the baselines stay as they are. The functions MyViewPagerFragment and +// ItemOperationsListener require are 11 on their own, already the rule's threshold. +@Suppress("TooManyFunctions") +class ItemsFragment(context: Context, attributeSet: AttributeSet? = null) : + MyViewPagerFragment<MyViewPagerFragment.ItemsInnerBinding>(context, attributeSet), + ItemOperationsListener { + val state = FilesTabState() + private var showHidden = false private var lastSearchedText = "" - private var scrollStates = HashMap<String, Parcelable>() - private var zoomListener: MyRecyclerView.MyZoomListener? = null - + private val scrollStates = HashMap<String, ScrollPosition>() private var storedItems = ArrayList<ListItem>() private var itemsIgnoringSearch = ArrayList<ListItem>() - private lateinit var binding: ItemsFragmentBinding - - override fun onFinishInflate() { - super.onFinishInflate() - binding = ItemsFragmentBinding.bind(this) - innerBinding = ItemsInnerBinding(binding) + private var fileActions: FileItemActions? = null + + private val tabActions = object : FilesTabActions { + override fun onItemClick(index: Int) = itemClicked(index) + override fun onItemLongClick(index: Int) = itemLongClicked(index) + override fun onBreadcrumbClick(index: Int) = breadcrumbClicked(index) + override fun onRefresh() = refreshFragment() + override fun onFabClick() = fabClicked() + override fun onZoomIn() = zoomIn() + override fun onZoomOut() = zoomOut() + override fun onCreateItem(name: String, isDirectory: Boolean) = createNewItem(name, isDirectory) + override fun onDismissCreateDialog() { + state.isCreateDialogVisible = false + } } - override fun setupFragment(activity: SimpleActivity) { - if (this.activity == null) { - this.activity = activity - binding.apply { - breadcrumbs.listener = this@ItemsFragment - itemsSwipeRefresh.setOnRefreshListener { refreshFragment() } - itemsFab.setOnClickListener { - if (isCreateDocumentIntent) { - (activity as MainActivity).createDocumentConfirmed(currentPath) - } else { - createNewItem() - } - } - } + init { + id = R.id.items_fragment + innerBinding = ItemsInnerBinding() + val composeView = ComposeView(context).apply { + id = R.id.items_compose_view + setContent { TabContent() } } + addView(composeView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) } - override fun onResume(textColor: Int) { - context!!.updateTextColors(this) - getRecyclerAdapter()?.apply { - updatePrimaryColor() - updateTextColor(textColor) - initDrawables() + @Composable + private fun TabContent() { + MainScreenTheme { + FilesTabScreen(state = state, actions = tabActions) } + } - binding.apply { - val properPrimaryColor = context!!.getProperPrimaryColor() - itemsFastscroller.updateColors(properPrimaryColor) - progressBar.setIndicatorColor(properPrimaryColor) - progressBar.trackColor = properPrimaryColor.adjustAlpha(LOWER_ALPHA) + @Composable + private fun ActionModeContent() { + MainScreenTheme { + FilesActionModeBar( + state = state, + onAction = ::actionItemPressed, + onFinish = { (activity as? MainActivity)?.refreshSystemBarColors() } + ) + } + } - if (currentPath != "") { - breadcrumbs.updateColor(textColor) - } + /** + * The contextual bar lives above the activity content so that it covers the main toolbar like the action mode + * did. It is added once per activity (a previous one, e.g. of a recreated tab, is replaced) and goes away with it. + */ + private fun attachActionModeBar(activity: SimpleActivity) { + val content = activity.findViewById<ViewGroup>(android.R.id.content) ?: return + content.findViewById<View>(R.id.items_action_mode_view)?.let { content.removeView(it) } + val actionModeView = ComposeView(activity).apply { + id = R.id.items_action_mode_view + setContent { ActionModeContent() } + } + content.addView( + actionModeView, + FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.TOP) + ) + } - itemsSwipeRefresh.isEnabled = lastSearchedText.isEmpty() && activity?.config?.enablePullToRefresh != false + override fun setupFragment(activity: SimpleActivity) { + if (this.activity == null) { + this.activity = activity + fileActions = FileItemActions( + activity = activity, + refresh = { activity.runOnUiThread { refreshFragment() } }, + finishSelection = { activity.runOnUiThread { finishActMode() } } + ) + state.isPickMultipleIntent = isPickMultipleIntent + state.columnCount = activity.config.fileColumnCnt + state.displayFilenames = activity.config.displayFilenames + setupFontSize() + setupDateTimeFormat() + // not while the view hierarchy is dispatching the attachment of the tab + post { attachActionModeBar(activity) } } } + override fun updateIsCreateDocumentIntent(isCreateDocumentIntent: Boolean) { + super.updateIsCreateDocumentIntent(isCreateDocumentIntent) + state.isCreateDocumentIntent = isCreateDocumentIntent + } + + override fun onResume(textColor: Int) { + state.textColor = textColor + state.primaryColor = context.getProperPrimaryColor() + state.drawablesVersion++ + state.isPullToRefreshEnabled = activity?.config?.enablePullToRefresh != false + } + override fun setupFontSize() { - getRecyclerAdapter()?.updateFontSizes() - if (currentPath != "") { - binding.breadcrumbs.updateFontSize(context!!.getTextSize(), false) - } + state.fontSizePx = context.getTextSize() } override fun setupDateTimeFormat() { - getRecyclerAdapter()?.updateDateTimeFormat() + state.dateFormat = context.config.dateFormat + state.timeFormat = context.getTimeFormat() } override fun finishActMode() { - getRecyclerAdapter()?.finishActMode() + state.clearSelection() + } + + /** Leaves the selection mode on back, like the action mode did. Returns whether back was consumed. */ + fun onBackPressed(): Boolean { + return if (state.isInSelectionMode) { + finishActMode() + true + } else { + false + } } fun openPath(path: String, forceRefresh: Boolean = false) { @@ -109,19 +196,24 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF realPath = "/" } - scrollStates[currentPath] = getScrollState()!! + if (currentPath.isNotEmpty()) { + scrollStates[currentPath] = ScrollPosition( + state.gridState.firstVisibleItemIndex, + state.gridState.firstVisibleItemScrollOffset + ) + } currentPath = realPath - showHidden = context!!.config.shouldShowHidden() + showHidden = context.config.shouldShowHidden() showProgressBar() getItems(currentPath) { originalPath, listItems -> if (currentPath != originalPath) { return@getItems } - FileDirItem.sorting = context!!.config.getFolderSorting(currentPath) + FileDirItem.sorting = context.config.getFolderSorting(currentPath) listItems.sort() - if (context!!.config.getFolderViewType(currentPath) == VIEW_TYPE_GRID && listItems.none { it.isSectionTitle }) { + if (context.config.getFolderViewType(currentPath) == VIEW_TYPE_GRID && listItems.none { it.isSectionTitle }) { if (listItems.any { it.mIsDirectory } && listItems.any { !it.mIsDirectory }) { val firstFileIndex = listItems.indexOfFirst { !it.mIsDirectory } if (firstFileIndex != -1) { @@ -135,9 +227,6 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF activity?.runOnUiThread { (activity as? MainActivity)?.refreshMenuItems() addItems(listItems, forceRefresh) - if (context != null && currentViewType != context!!.config.getFolderViewType(currentPath)) { - setupLayoutManager() - } hideProgressBar() } } @@ -145,46 +234,35 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF private fun addItems(items: ArrayList<ListItem>, forceRefresh: Boolean = false) { activity?.runOnUiThread { - binding.itemsSwipeRefresh.isRefreshing = false - binding.breadcrumbs.setBreadcrumb(currentPath) + state.isRefreshing = false + state.currentPath = currentPath + state.breadcrumbs = buildBreadcrumbs(context, currentPath).toImmutableList() + state.isGrid = context.config.getFolderViewType(currentPath) == VIEW_TYPE_GRID if (!forceRefresh && items.hashCode() == storedItems.hashCode()) { return@runOnUiThread } storedItems = items - if (binding.itemsList.adapter == null) { - binding.breadcrumbs.updateFontSize(context!!.getTextSize(), true) - } - - ItemsAdapter(activity as SimpleActivity, storedItems, this, binding.itemsList, isPickMultipleIntent, binding.itemsSwipeRefresh) { - if ((it as? ListItem)?.isSectionTitle == true) { - openDirectory(it.mPath) - searchClosed() - } else { - itemClicked(it as FileDirItem) - } - }.apply { - setupZoomListener(zoomListener) - binding.itemsList.adapter = this - } - - if (context.areSystemAnimationsEnabled) { - binding.itemsList.scheduleLayoutAnimation() - } - - getRecyclerLayoutManager().onRestoreInstanceState(scrollStates[currentPath]) + showItems(storedItems, highlightText = "") + state.pendingScroll = scrollStates[currentPath] ?: ScrollPosition(0, 0) } } - private fun getScrollState() = getRecyclerLayoutManager().onSaveInstanceState() - - private fun getRecyclerLayoutManager() = (binding.itemsList.layoutManager as MyGridLayoutManager) + /** Shows [items], leaving the selection mode when the list really changed, like the adapter did. */ + private fun showItems(items: List<ListItem>, highlightText: String) { + val newItems = items.toImmutableList() + if (newItems != state.items) { + state.items = newItems + state.clearSelection() + } + state.highlightText = highlightText + } @SuppressLint("NewApi") private fun getItems(path: String, callback: (originalPath: String, items: ArrayList<ListItem>) -> Unit) { ensureBackgroundThread { if (activity?.isDestroyed == false && activity?.isFinishing == false) { - val config = context!!.config + val config = context.config if (context.isRestrictedSAFOnlyRoot(path)) { activity?.runOnUiThread { hideProgressBar() } activity?.handleAndroidSAFDialog(path, openInSystemAppAllowed = true) { @@ -192,17 +270,17 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF activity?.toast(R.string.no_storage_permissions) return@handleAndroidSAFDialog } - val getProperChildCount = context!!.config.getFolderViewType(currentPath) == VIEW_TYPE_LIST + val getProperChildCount = context.config.getFolderViewType(currentPath) == VIEW_TYPE_LIST context.getAndroidSAFFileItems(path, context.config.shouldShowHidden(), getProperChildCount) { fileItems -> callback(path, getListItemsFromFileDirItems(fileItems)) } } - } else if (context!!.isPathOnOTG(path) && config.OTGTreeUri.isNotEmpty()) { - val getProperFileSize = context!!.config.getFolderSorting(currentPath) and SORT_BY_SIZE != 0 - context!!.getOTGItems(path, config.shouldShowHidden(), getProperFileSize) { + } else if (context.isPathOnOTG(path) && config.OTGTreeUri.isNotEmpty()) { + val getProperFileSize = context.config.getFolderSorting(currentPath) and SORT_BY_SIZE != 0 + context.getOTGItems(path, config.shouldShowHidden(), getProperFileSize) { callback(path, getListItemsFromFileDirItems(it)) } - } else if (!config.enableRootAccess || !context!!.isPathOnRoot(path)) { + } else if (!config.enableRootAccess || !context.isPathOnRoot(path)) { getRegularItemsOf(path, callback) } else { RootHelpers(activity!!).getFiles(path, callback) @@ -214,14 +292,14 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF private fun getRegularItemsOf(path: String, callback: (originalPath: String, items: ArrayList<ListItem>) -> Unit) { val items = ArrayList<ListItem>() val files = File(path).listFiles()?.filterNotNull() - if (context == null || files == null) { + if (files == null) { callback(path, items) return } - val isSortingBySize = context!!.config.getFolderSorting(currentPath) and SORT_BY_SIZE != 0 - val getProperChildCount = context!!.config.getFolderViewType(currentPath) == VIEW_TYPE_LIST - val lastModifieds = context!!.getFolderLastModifieds(path) + val isSortingBySize = context.config.getFolderSorting(currentPath) and SORT_BY_SIZE != 0 + val getProperChildCount = context.config.getFolderViewType(currentPath) == VIEW_TYPE_LIST + val lastModifieds = context.getFolderLastModifieds(path) for (file in files) { val listItem = getListItemFromFile(file, isSortingBySize, lastModifieds, false) @@ -237,19 +315,31 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF if (getProperChildCount) { items.filter { it.mIsDirectory }.forEach { - if (context != null) { - val childrenCount = it.getDirectChildrenCount(activity as BaseSimpleActivity, showHidden) - if (childrenCount != 0) { - activity?.runOnUiThread { - getRecyclerAdapter()?.updateChildCount(it.mPath, childrenCount) - } + val childrenCount = it.getDirectChildrenCount(activity as BaseSimpleActivity, showHidden) + if (childrenCount != 0) { + activity?.runOnUiThread { + updateChildCount(it.mPath, childrenCount) } } } } } - private fun getListItemFromFile(file: File, isSortingBySize: Boolean, lastModifieds: HashMap<String, Long>, getProperChildCount: Boolean): ListItem? { + private fun updateChildCount(path: String, count: Int) { + val index = state.items.indexOfFirst { it.path == path } + val item = state.items.getOrNull(index) ?: return + item.children = count + state.items = state.items.toMutableList().apply { + set(index, item.copy(mChildren = count).also { it.children = count }) + }.toImmutableList() + } + + private fun getListItemFromFile( + file: File, + isSortingBySize: Boolean, + lastModifieds: HashMap<String, Long>, + getProperChildCount: Boolean + ): ListItem? { val curPath = file.absolutePath val curName = file.name if (!showHidden && curName.startsWith(".")) { @@ -287,14 +377,33 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF return listItems } - private fun itemClicked(item: FileDirItem) { - if (item.isDirectory) { + private fun itemClicked(index: Int) { + val item = state.items.getOrNull(index) ?: return + if (state.isInSelectionMode) { + state.toggleSelection(index) + } else if (item.isSectionTitle) { + openDirectory(item.mPath) + searchClosed() + } else if (item.isDirectory) { openDirectory(item.path) } else { clickedPath(item.path) } } + private fun itemLongClicked(index: Int) { + val item = state.items.getOrNull(index) ?: return + if (item.isSectionTitle) { + // section titles are not selectable, a long press acts like a tap + itemClicked(index) + } else { + if (!state.isInSelectionMode) { + state.isRefreshing = false + } + state.longPress(index) + } + } + private fun openDirectory(path: String) { (activity as? MainActivity)?.apply { openedDirectory() @@ -304,67 +413,64 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF override fun searchQueryChanged(text: String) { lastSearchedText = text - if (context == null) { - return - } + state.isSearchActive = text.isNotEmpty() + when { + text.isEmpty() -> { + state.isListVisible = true + showItems(itemsIgnoringSearch, highlightText = "") + state.placeholder = FilesPlaceholder.NONE + hideProgressBar() + } - binding.apply { - itemsSwipeRefresh.isEnabled = text.isEmpty() && activity?.config?.enablePullToRefresh != false - when { - text.isEmpty() -> { - itemsFastscroller.beVisible() - getRecyclerAdapter()?.updateItems(itemsIgnoringSearch) - itemsPlaceholder.beGone() - itemsPlaceholder2.beGone() - hideProgressBar() - } + text.length == 1 -> { + state.isListVisible = false + state.placeholder = FilesPlaceholder.TYPE_MORE + hideProgressBar() + } - text.length == 1 -> { - itemsFastscroller.beGone() - itemsPlaceholder.beVisible() - itemsPlaceholder2.beVisible() - hideProgressBar() - } + else -> { + showProgressBar() + ensureBackgroundThread { + val files = searchFiles(text, currentPath) + files.sortBy { it.getParentPath() } - else -> { - showProgressBar() - ensureBackgroundThread { - val files = searchFiles(text, currentPath) - files.sortBy { it.getParentPath() } + if (lastSearchedText != text) { + return@ensureBackgroundThread + } - if (lastSearchedText != text) { - return@ensureBackgroundThread + val listItems = ArrayList<ListItem>() + + var previousParent = "" + files.forEach { + val parent = it.mPath.getParentPath() + if (!it.isDirectory && parent != previousParent) { + val sectionTitle = + ListItem(parent, context.humanizePath(parent), false, 0, 0, 0, true, false) + listItems.add(sectionTitle) + previousParent = parent + } + + if (it.isDirectory) { + val sectionTitle = + ListItem(it.path, context.humanizePath(it.path), true, 0, 0, 0, true, false) + listItems.add(sectionTitle) + previousParent = parent } - val listItems = ArrayList<ListItem>() - - var previousParent = "" - files.forEach { - val parent = it.mPath.getParentPath() - if (!it.isDirectory && parent != previousParent && context != null) { - val sectionTitle = ListItem(parent, context!!.humanizePath(parent), false, 0, 0, 0, true, false) - listItems.add(sectionTitle) - previousParent = parent - } - - if (it.isDirectory) { - val sectionTitle = ListItem(it.path, context!!.humanizePath(it.path), true, 0, 0, 0, true, false) - listItems.add(sectionTitle) - previousParent = parent - } - - if (!it.isDirectory) { - listItems.add(it) - } + if (!it.isDirectory) { + listItems.add(it) } + } - activity?.runOnUiThread { - getRecyclerAdapter()?.updateItems(listItems, text) - itemsFastscroller.beVisibleIf(listItems.isNotEmpty()) - itemsPlaceholder.beVisibleIf(listItems.isEmpty()) - itemsPlaceholder2.beGone() - hideProgressBar() + activity?.runOnUiThread { + if (lastSearchedText != text) { + return@runOnUiThread } + showItems(listItems, highlightText = text) + state.isListVisible = listItems.isNotEmpty() + state.placeholder = + if (listItems.isEmpty()) FilesPlaceholder.NO_ITEMS else FilesPlaceholder.NONE + hideProgressBar() } } } @@ -373,13 +479,9 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF private fun searchFiles(text: String, path: String): ArrayList<ListItem> { val files = ArrayList<ListItem>() - if (context == null) { - return files - } - val normalizedText = text.normalizeString() - val sorting = context!!.config.getFolderSorting(path) - FileDirItem.sorting = context!!.config.getFolderSorting(currentPath) + val sorting = context.config.getFolderSorting(path) + FileDirItem.sorting = context.config.getFolderSorting(currentPath) val isSortingBySize = sorting and SORT_BY_SIZE != 0 File(path).listFiles()?.sortedBy { it.isDirectory }?.forEach { if (!showHidden && it.isHidden) { @@ -408,130 +510,86 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF } private fun searchClosed() { - binding.apply { - lastSearchedText = "" - itemsSwipeRefresh.isEnabled = activity?.config?.enablePullToRefresh != false - itemsFastscroller.beVisible() - itemsPlaceholder.beGone() - itemsPlaceholder2.beGone() - hideProgressBar() - } - } - - private fun createNewItem() { - CreateNewItemDialog(activity as SimpleActivity, currentPath) { - if (it) { - refreshFragment() - } else { - activity?.toast(R.string.unknown_error_occurred) - } - } + lastSearchedText = "" + state.isSearchActive = false + state.isListVisible = true + state.placeholder = FilesPlaceholder.NONE + hideProgressBar() } - private fun getRecyclerAdapter() = binding.itemsList.adapter as? ItemsAdapter - - private fun setupLayoutManager() { - if (context!!.config.getFolderViewType(currentPath) == VIEW_TYPE_GRID) { - currentViewType = VIEW_TYPE_GRID - setupGridLayoutManager() + private fun fabClicked() { + if (isCreateDocumentIntent) { + (activity as MainActivity).createDocumentConfirmed(currentPath) } else { - currentViewType = VIEW_TYPE_LIST - setupListLayoutManager() + state.isCreateDialogVisible = true } - - binding.itemsList.adapter = null - initZoomListener() - addItems(storedItems, true) } - private fun setupGridLayoutManager() { - val layoutManager = binding.itemsList.layoutManager as MyGridLayoutManager - layoutManager.spanCount = context?.config?.fileColumnCnt ?: 3 - - layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { - override fun getSpanSize(position: Int): Int { - return if (getRecyclerAdapter()?.isASectionTitle(position) == true || getRecyclerAdapter()?.isGridTypeDivider(position) == true) { - layoutManager.spanCount + private fun createNewItem(name: String, isDirectory: Boolean) { + val activity = activity ?: return + NewItemCreator( + activity = activity, + onCreated = { activity.runOnUiThread { state.isCreateDialogVisible = false } }, + callback = { + if (it) { + refreshFragment() } else { - 1 + activity.toast(R.string.unknown_error_occurred) } } - } + ).create(currentPath, name, isDirectory) } - private fun setupListLayoutManager() { - val layoutManager = binding.itemsList.layoutManager as MyGridLayoutManager - layoutManager.spanCount = 1 - zoomListener = null - } - - private fun initZoomListener() { - if (context?.config?.getFolderViewType(currentPath) == VIEW_TYPE_GRID) { - val layoutManager = binding.itemsList.layoutManager as MyGridLayoutManager - zoomListener = object : MyRecyclerView.MyZoomListener { - override fun zoomIn() { - if (layoutManager.spanCount > 1) { - reduceColumnCount() - getRecyclerAdapter()?.finishActMode() - } - } - - override fun zoomOut() { - if (layoutManager.spanCount < MAX_COLUMN_COUNT) { - increaseColumnCount() - getRecyclerAdapter()?.finishActMode() - } - } - } - } else { - zoomListener = null - } - } - - private fun increaseColumnCount() { - if (currentViewType == VIEW_TYPE_GRID) { - context!!.config.fileColumnCnt += 1 + private fun zoomIn() { + if (state.isGrid && state.columnCount > 1) { + context.config.fileColumnCnt -= 1 (activity as? MainActivity)?.updateFragmentColumnCounts() + finishActMode() } } - private fun reduceColumnCount() { - if (currentViewType == VIEW_TYPE_GRID) { - context!!.config.fileColumnCnt -= 1 + private fun zoomOut() { + if (state.isGrid && state.columnCount < MAX_COLUMN_COUNT) { + context.config.fileColumnCnt += 1 (activity as? MainActivity)?.updateFragmentColumnCounts() + finishActMode() } } override fun columnCountChanged() { - (binding.itemsList.layoutManager as MyGridLayoutManager).spanCount = context!!.config.fileColumnCnt + state.columnCount = context.config.fileColumnCnt (activity as? MainActivity)?.refreshMenuItems() - getRecyclerAdapter()?.apply { - notifyItemRangeChanged(0, listItems.size) - } } fun showProgressBar() { - binding.progressBar.show() + state.isLoading = true } private fun hideProgressBar() { - binding.progressBar.hide() + state.isLoading = false } - fun getBreadcrumbs() = binding.breadcrumbs + /** How many breadcrumbs are shown; back leaves the app once only the storage root is left. */ + fun getBreadcrumbCount() = state.breadcrumbs.size + + /** Drops the last breadcrumb and returns the path of the one before it, where back navigates to. */ + fun removeLastBreadcrumb(): String { + state.breadcrumbs = state.breadcrumbs.dropLast(1).toImmutableList() + return state.breadcrumbs.last().path + } override fun toggleFilenameVisibility() { - getRecyclerAdapter()?.updateDisplayFilenamesInGrid() + state.displayFilenames = context.config.displayFilenames } - override fun breadcrumbClicked(id: Int) { - if (id == 0) { - StoragePickerDialog(activity as SimpleActivity, currentPath, context!!.config.enableRootAccess, true) { - getRecyclerAdapter()?.finishActMode() + private fun breadcrumbClicked(index: Int) { + if (index == 0) { + StoragePickerDialog(activity as SimpleActivity, currentPath, context.config.enableRootAccess, true) { + finishActMode() openPath(it) } } else { - val item = binding.breadcrumbs.getItem(id) + val item = state.breadcrumbs.getOrNull(index) ?: return openPath(item.path) } } @@ -548,4 +606,79 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF override fun selectedPaths(paths: ArrayList<String>) { (activity as MainActivity).pickedPaths(paths) } + + private fun actionItemPressed(id: Int) { + val actions = fileActions ?: return + val selected = state.selectedItems + if (selected.isEmpty()) { + return + } + + if (!runFirstItemAction(id, actions, selected.first().path)) { + runSelectionAction(id, actions, selected) + } + } + + /** The actions that work on the first selected item. Returns whether [id] was one of them. */ + private fun runFirstItemAction(id: Int, actions: FileItemActions, firstPath: String): Boolean { + when (id) { + R.id.cab_create_shortcut -> actions.firstItem.createShortcut(firstPath) + R.id.cab_copy_path -> actions.firstItem.copyPath(firstPath) + R.id.cab_set_as -> actions.firstItem.setAs(firstPath) + R.id.cab_open_with -> actions.firstItem.openWith(firstPath) + R.id.cab_open_as -> actions.firstItem.openAs(firstPath) + R.id.cab_compress -> actions.archive.compress(firstPath) { state.selectedItems.map { it.path } } + R.id.cab_decompress -> actions.archive.decompress(firstPath) { state.selectedItems.map { it.path } } + else -> return false + } + return true + } + + private fun runSelectionAction(id: Int, actions: FileItemActions, selected: ArrayList<FileDirItem>) { + when (id) { + R.id.cab_confirm_selection -> actions.confirmSelection(selected) { selectedPaths(it) } + R.id.cab_rename -> actions.rename(selected) + R.id.cab_properties -> actions.showProperties(selected) + R.id.cab_share -> actions.share(selected) + R.id.cab_hide -> actions.toggleVisibility(selected, true) + R.id.cab_unhide -> actions.toggleVisibility(selected, false) + R.id.cab_copy_to -> actions.copyMoveTo(selected, true) + R.id.cab_move_to -> actions.tryMoveFiles(selected) + R.id.cab_select_all -> state.selectAll() + R.id.cab_delete -> actions.askConfirmDelete(selected.size, selected.first().path) { deleteSelectedFiles() } + } + } + + private fun deleteSelectedFiles() { + val activity = activity ?: return + val selected = state.selectedItems + if (selected.isEmpty()) { + return + } + + val safPath = selected.first().path + if (activity.isPathOnRoot(safPath) && !RootTools.isRootAvailable()) { + activity.toast(R.string.rooted_device_only) + return + } + + activity.handleSAFDialog(safPath) { granted -> + if (!granted) { + return@handleSAFDialog + } + + ensureBackgroundThread { + selected.forEach { + activity.config.removeFavorite(it.path) + } + + activity.runOnUiThread { + val deletedPaths = selected.map { it.path }.toSet() + state.items = state.items.filter { it.path !in deletedPaths }.toImmutableList() + finishActMode() + deleteFiles(selected) + } + } + } + } } diff --git a/app/src/main/kotlin/org/fossify/filemanager/fragments/MyViewPagerFragment.kt b/app/src/main/kotlin/org/fossify/filemanager/fragments/MyViewPagerFragment.kt index 993c8e4..e1f8579 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/fragments/MyViewPagerFragment.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/fragments/MyViewPagerFragment.kt @@ -10,14 +10,13 @@ import org.fossify.commons.views.MyFloatingActionButton import org.fossify.filemanager.R import org.fossify.filemanager.activities.MainActivity import org.fossify.filemanager.activities.SimpleActivity -import org.fossify.filemanager.databinding.ItemsFragmentBinding import org.fossify.filemanager.databinding.RecentsFragmentBinding import org.fossify.filemanager.databinding.StorageFragmentBinding import org.fossify.filemanager.extensions.isPathOnRoot import org.fossify.filemanager.extensions.tryOpenPathIntent import org.fossify.filemanager.helpers.RootHelpers -abstract class MyViewPagerFragment<BINDING : MyViewPagerFragment.InnerBinding>(context: Context, attributeSet: AttributeSet) : +abstract class MyViewPagerFragment<BINDING : MyViewPagerFragment.InnerBinding>(context: Context, attributeSet: AttributeSet?) : RelativeLayout(context, attributeSet) { protected var activity: SimpleActivity? = null protected var currentViewType = VIEW_TYPE_LIST @@ -44,7 +43,7 @@ abstract class MyViewPagerFragment<BINDING : MyViewPagerFragment.InnerBinding>(c } } - fun updateIsCreateDocumentIntent(isCreateDocumentIntent: Boolean) { + open fun updateIsCreateDocumentIntent(isCreateDocumentIntent: Boolean) { val iconId = if (isCreateDocumentIntent) { R.drawable.ic_check_vector } else { @@ -100,8 +99,9 @@ abstract class MyViewPagerFragment<BINDING : MyViewPagerFragment.InnerBinding>(c val itemsFab: MyFloatingActionButton? } - class ItemsInnerBinding(val binding: ItemsFragmentBinding) : InnerBinding { - override val itemsFab: MyFloatingActionButton = binding.itemsFab + /** The Files tab is drawn by Compose, its create button included. */ + class ItemsInnerBinding : InnerBinding { + override val itemsFab: MyFloatingActionButton? = null } class RecentsInnerBinding(val binding: RecentsFragmentBinding) : InnerBinding { diff --git a/app/src/main/kotlin/org/fossify/filemanager/helpers/ArchiveItemActions.kt b/app/src/main/kotlin/org/fossify/filemanager/helpers/ArchiveItemActions.kt new file mode 100644 index 0000000..603e63b --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/helpers/ArchiveItemActions.kt @@ -0,0 +1,363 @@ +package org.fossify.filemanager.helpers + +import android.annotation.SuppressLint +import net.lingala.zip4j.exception.ZipException +import net.lingala.zip4j.io.inputstream.ZipInputStream +import net.lingala.zip4j.io.outputstream.ZipOutputStream +import net.lingala.zip4j.model.LocalFileHeader +import net.lingala.zip4j.model.ZipParameters +import net.lingala.zip4j.model.enums.EncryptionMethod +import org.fossify.commons.extensions.createDirectorySync +import org.fossify.commons.extensions.deleteFileBg +import org.fossify.commons.extensions.deleteFolderBg +import org.fossify.commons.extensions.getAndroidSAFFileItems +import org.fossify.commons.extensions.getDoesFilePathExist +import org.fossify.commons.extensions.getFileInputStreamSync +import org.fossify.commons.extensions.getFileOutputStreamSync +import org.fossify.commons.extensions.getFilenameFromPath +import org.fossify.commons.extensions.getIsPathDirectory +import org.fossify.commons.extensions.getMimeType +import org.fossify.commons.extensions.getParentPath +import org.fossify.commons.extensions.isPathOnOTG +import org.fossify.commons.extensions.isRestrictedSAFOnlyRoot +import org.fossify.commons.extensions.relativizeWith +import org.fossify.commons.extensions.showErrorToast +import org.fossify.commons.extensions.toast +import org.fossify.commons.helpers.CONFLICT_OVERWRITE +import org.fossify.commons.helpers.CONFLICT_SKIP +import org.fossify.commons.helpers.ensureBackgroundThread +import org.fossify.commons.models.FileDirItem +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.SimpleActivity +import org.fossify.filemanager.dialogs.CompressAsDialog +import org.fossify.filemanager.extensions.isZipFile +import org.fossify.filemanager.extensions.setLastModified +import java.io.BufferedInputStream +import java.io.Closeable +import java.io.File +import java.util.LinkedList + +private const val ZIP_EXTENSION_LENGTH = 4 + +/** + * Compressing the selection into a zip and extracting selected zips next to them, as the contextual action bar offers + * it. [refresh] reloads the list the selection comes from and [finishSelection] leaves the selection mode. + */ +class ArchiveItemActions( + private val activity: SimpleActivity, + private val refresh: () -> Unit, + private val finishSelection: () -> Unit, +) { + /** [selectedPaths] is read once the destination was confirmed, like the adapter did with its selection. */ + fun compress(firstPath: String, selectedPaths: () -> List<String>) { + if (activity.isPathOnOTG(firstPath)) { + activity.toast(R.string.unknown_error_occurred) + return + } + + CompressAsDialog(activity, firstPath) { destination, password -> + activity.handleAndroidSAFDialog(firstPath) { granted -> + if (!granted) { + return@handleAndroidSAFDialog + } + activity.handleSAFDialog(firstPath) { + if (!it) { + return@handleSAFDialog + } + + activity.toast(R.string.compressing) + val paths = selectedPaths() + ensureBackgroundThread { + if (compressPaths(paths, destination, password)) { + activity.runOnUiThread { + activity.toast(R.string.compression_successful) + refresh() + finishSelection() + } + } else { + activity.toast(R.string.compressing_failed) + } + } + } + } + } + } + + fun decompress(firstPath: String, selectedPaths: () -> List<String>) { + if (activity.isPathOnOTG(firstPath)) { + activity.toast(R.string.unknown_error_occurred) + return + } + + activity.handleSAFDialog(firstPath) { + if (!it) { + return@handleSAFDialog + } + + val paths = selectedPaths() + .asSequence() + .filter { it.isZipFile() } + .toList() + ensureBackgroundThread { + tryDecompressingPaths(paths) { success -> + activity.runOnUiThread { + if (success) { + activity.toast(R.string.decompression_successful) + refresh() + finishSelection() + } else { + activity.toast(R.string.decompressing_failed) + } + } + } + } + } + } + + // moved unchanged from ItemsAdapter, where detekt's baseline covered these findings + @Suppress("NestedBlockDepth", "TooGenericExceptionCaught") + private fun tryDecompressingPaths( + sourcePaths: List<String>, + callback: (success: Boolean) -> Unit + ) { + sourcePaths.forEach { path -> + ZipInputStream(BufferedInputStream(activity.getFileInputStreamSync(path))).use { zipInputStream -> + try { + val fileDirItems = ArrayList<FileDirItem>() + var entry = zipInputStream.nextEntry + while (entry != null) { + val currPath = if (entry.isDirectory) { + path + } else { + "${path.getParentPath().trimEnd('/')}/${entry.fileName}" + } + val fileDirItem = FileDirItem( + path = currPath, + name = entry.fileName, + isDirectory = entry.isDirectory, + children = 0, + size = entry.uncompressedSize + ) + fileDirItems.add(fileDirItem) + entry = zipInputStream.nextEntry + } + val destinationPath = fileDirItems.first().getParentPath().trimEnd('/') + activity.runOnUiThread { + activity.checkConflicts(fileDirItems, destinationPath, 0, LinkedHashMap()) { + ensureBackgroundThread { + decompressPaths(sourcePaths, it, callback) + } + } + } + } catch (zipException: ZipException) { + if (zipException.type == ZipException.Type.WRONG_PASSWORD) { + activity.showErrorToast(activity.getString(R.string.invalid_password)) + } else { + activity.showErrorToast(zipException) + } + } catch (exception: Exception) { + activity.showErrorToast(exception) + } + } + } + } + + // moved unchanged from ItemsAdapter, where detekt's baseline covered these findings + @Suppress("NestedBlockDepth", "TooGenericExceptionCaught") + private fun decompressPaths( + paths: List<String>, + conflictResolutions: LinkedHashMap<String, Int>, + callback: (success: Boolean) -> Unit + ) { + paths.forEach { path -> + val zipInputStream = + ZipInputStream(BufferedInputStream(activity.getFileInputStreamSync(path))) + + val foldersTimestamp = mutableListOf<Pair<File, LocalFileHeader>>() + zipInputStream.use { + try { + var entry = zipInputStream.nextEntry + val zipFileName = path.getFilenameFromPath() + val newFolderName = zipFileName.subSequence(0, zipFileName.length - ZIP_EXTENSION_LENGTH) + while (entry != null) { + val parentPath = path.getParentPath() + val newPath = "$parentPath/$newFolderName/${entry.fileName.trimEnd('/')}" + + val resolution = getConflictResolution(conflictResolutions, newPath) + val doesPathExist = activity.getDoesFilePathExist(newPath) + if (doesPathExist && resolution == CONFLICT_OVERWRITE) { + val fileDirItem = FileDirItem( + path = newPath, + name = newPath.getFilenameFromPath(), + isDirectory = entry.isDirectory + ) + if (activity.getIsPathDirectory(path)) { + activity.deleteFolderBg(fileDirItem, false) { + if (it) { + extractEntry(newPath, entry, zipInputStream, foldersTimestamp) + } else { + callback(false) + } + } + } else { + activity.deleteFileBg(fileDirItem, false, false) { + if (it) { + extractEntry(newPath, entry, zipInputStream, foldersTimestamp) + } else { + callback(false) + } + } + } + } else if (!doesPathExist) { + extractEntry(newPath, entry, zipInputStream, foldersTimestamp) + } + + entry = zipInputStream.nextEntry + } + for ((dir, header) in foldersTimestamp.asReversed()) { + dir.setLastModified(header) + } + callback(true) + } catch (e: Exception) { + activity.showErrorToast(e) + callback(false) + } + } + } + } + + private fun extractEntry( + newPath: String, + entry: LocalFileHeader, + zipInputStream: ZipInputStream, + foldersTimestamp: MutableList<Pair<File, LocalFileHeader>> + ) { + if (entry.isDirectory) { + if (!activity.createDirectorySync(newPath) && !activity.getDoesFilePathExist(newPath)) { + val error = + String.format(activity.getString(R.string.could_not_create_file), newPath) + activity.showErrorToast(error) + } else { + foldersTimestamp.add(Pair(File(newPath), entry)) + } + } else { + val fos = activity.getFileOutputStreamSync(newPath, newPath.getMimeType()) + if (fos != null) { + zipInputStream.copyTo(fos) + File(newPath).setLastModified(entry) + } + } + } + + private fun getConflictResolution( + conflictResolutions: LinkedHashMap<String, Int>, + path: String + ): Int { + return if (conflictResolutions.size == 1 && conflictResolutions.containsKey("")) { + conflictResolutions[""]!! + } else if (conflictResolutions.containsKey(path)) { + conflictResolutions[path]!! + } else { + CONFLICT_SKIP + } + } + + // moved unchanged from ItemsAdapter, where detekt's baseline covered these findings + @Suppress("CyclomaticComplexMethod", "NestedBlockDepth", "TooGenericExceptionCaught") + @SuppressLint("NewApi") + private fun compressPaths( + sourcePaths: List<String>, + targetPath: String, + password: String? = null + ): Boolean { + val queue = LinkedList<String>() + val fos = activity.getFileOutputStreamSync(targetPath, "application/zip") ?: return false + + val zout = + password?.let { ZipOutputStream(fos, password.toCharArray()) } ?: ZipOutputStream(fos) + var res: Closeable = fos + + fun zipEntry(name: String, lastModified: Long) = ZipParameters().also { + it.fileNameInZip = name + it.lastModifiedFileTime = lastModified + if (password != null) { + it.isEncryptFiles = true + it.encryptionMethod = EncryptionMethod.AES + } + } + + try { + sourcePaths.forEach { currentPath -> + var name: String + var mainFilePath = currentPath + val base = "${mainFilePath.getParentPath()}/" + res = zout + queue.push(mainFilePath) + if (activity.getIsPathDirectory(mainFilePath)) { + name = "${mainFilePath.getFilenameFromPath()}/" + val dirModified = File(mainFilePath).lastModified() + zout.putNextEntry( + ZipParameters().also { + it.fileNameInZip = name + it.lastModifiedFileTime = dirModified + } + ) + } + + while (!queue.isEmpty()) { + mainFilePath = queue.pop() + if (activity.getIsPathDirectory(mainFilePath)) { + if (activity.isRestrictedSAFOnlyRoot(mainFilePath)) { + activity.getAndroidSAFFileItems(mainFilePath, true) { files -> + for (file in files) { + name = file.path.relativizeWith(base) + if (activity.getIsPathDirectory(file.path)) { + queue.push(file.path) + name = "${name.trimEnd('/')}/" + zout.putNextEntry(zipEntry(name, file.modified)) + } else { + zout.putNextEntry(zipEntry(name, file.modified)) + activity.getFileInputStreamSync(file.path)!!.copyTo(zout) + zout.closeEntry() + } + } + } + } else { + val mainFile = File(mainFilePath) + for (file in mainFile.listFiles()) { + name = file.path.relativizeWith(base) + if (activity.getIsPathDirectory(file.absolutePath)) { + queue.push(file.absolutePath) + name = "${name.trimEnd('/')}/" + zout.putNextEntry(zipEntry(name, file.lastModified())) + } else { + zout.putNextEntry(zipEntry(name, file.lastModified())) + activity.getFileInputStreamSync(file.path)!!.copyTo(zout) + zout.closeEntry() + } + } + } + + } else { + name = + if (base == currentPath) { + currentPath.getFilenameFromPath() + } else { + mainFilePath.relativizeWith(base) + } + val fileModified = File(mainFilePath).lastModified() + zout.putNextEntry(zipEntry(name, fileModified)) + activity.getFileInputStreamSync(mainFilePath)!!.copyTo(zout) + zout.closeEntry() + } + } + } + } catch (exception: Exception) { + activity.showErrorToast(exception) + return false + } finally { + res.close() + } + return true + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/helpers/FileItemActions.kt b/app/src/main/kotlin/org/fossify/filemanager/helpers/FileItemActions.kt new file mode 100644 index 0000000..6f29cb3 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/helpers/FileItemActions.kt @@ -0,0 +1,314 @@ +package org.fossify.filemanager.helpers + +import android.annotation.SuppressLint +import android.content.Context +import android.content.pm.PackageManager +import org.fossify.commons.dialogs.ConfirmationDialog +import org.fossify.commons.dialogs.FilePickerDialog +import org.fossify.commons.dialogs.PropertiesDialog +import org.fossify.commons.dialogs.RenameDialog +import org.fossify.commons.dialogs.RenameItemDialog +import org.fossify.commons.dialogs.RenameItemsDialog +import org.fossify.commons.extensions.baseConfig +import org.fossify.commons.extensions.deleteFile +import org.fossify.commons.extensions.getAndroidSAFFileItems +import org.fossify.commons.extensions.getAndroidSAFUri +import org.fossify.commons.extensions.getDefaultCopyDestinationPath +import org.fossify.commons.extensions.getDocumentFile +import org.fossify.commons.extensions.getDoesFilePathExist +import org.fossify.commons.extensions.getFileCount +import org.fossify.commons.extensions.getFilenameFromPath +import org.fossify.commons.extensions.getIsPathDirectory +import org.fossify.commons.extensions.getParentPath +import org.fossify.commons.extensions.getProperSize +import org.fossify.commons.extensions.handleDeletePasswordProtection +import org.fossify.commons.extensions.isPathOnOTG +import org.fossify.commons.extensions.isRestrictedSAFOnlyRoot +import org.fossify.commons.extensions.toFileDirItem +import org.fossify.commons.extensions.toast +import org.fossify.commons.helpers.ensureBackgroundThread +import org.fossify.commons.models.FileDirItem +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.SimpleActivity +import org.fossify.filemanager.extensions.config +import org.fossify.filemanager.extensions.isPathOnRoot +import org.fossify.filemanager.extensions.sharePaths +import org.fossify.filemanager.extensions.toggleItemVisibility +import java.io.File + +/** + * The actions that can be run on a selection of files and folders (the contextual action bar of the file lists). + * Shared by the view based [org.fossify.filemanager.adapters.ItemsAdapter] (Recents, Storage, mime types) and the + * Compose Files tab, so that both run exactly the same code. The actions on the first selected item only are in + * [firstItem], compressing and extracting archives in [archive]. + * + * [refresh] reloads the list the selection comes from and [finishSelection] leaves the selection mode. + */ +class FileItemActions( + private val activity: SimpleActivity, + private val refresh: () -> Unit, + private val finishSelection: () -> Unit, +) { + private val config = activity.config + private val resources = activity.resources + val firstItem = FirstItemActions(activity, finishSelection) + val archive = ArchiveItemActions(activity, refresh, finishSelection) + + fun confirmSelection(items: List<FileDirItem>, onPicked: (ArrayList<String>) -> Unit) { + if (items.isNotEmpty()) { + val paths = items + .asSequence() + .filter { !it.isDirectory }.map { it.path } + .toMutableList() as ArrayList<String> + if (paths.isEmpty()) { + finishSelection() + } else { + onPicked(paths) + } + } + } + + fun rename(items: List<FileDirItem>) { + val paths = items.asSequence().map { it.path }.toMutableList() as ArrayList<String> + when { + paths.size == 1 -> { + val oldPath = paths.first() + RenameItemDialog(activity, oldPath) { + config.moveFavorite(oldPath, it) + activity.runOnUiThread { + refresh() + finishSelection() + } + } + } + + items.any { it.isDirectory } -> RenameItemsDialog(activity, paths) { + activity.runOnUiThread { + refresh() + finishSelection() + } + } + + else -> RenameDialog(activity, paths, false) { + activity.runOnUiThread { + refresh() + finishSelection() + } + } + } + } + + fun showProperties(items: List<FileDirItem>) { + if (items.size <= 1) { + PropertiesDialog(activity, items.first().path, config.shouldShowHidden()) + } else { + val paths = items.map { it.path } + PropertiesDialog(activity, paths, config.shouldShowHidden()) + } + } + + fun share(items: List<FileDirItem>) { + val paths = ArrayList<String>(items.size) + items.forEach { + addFileUris(it.path, paths) + } + activity.sharePaths(paths) + } + + fun toggleVisibility(items: List<FileDirItem>, hide: Boolean) { + ensureBackgroundThread { + items.forEach { + activity.toggleItemVisibility(it.path, hide) + } + activity.runOnUiThread { + refresh() + finishSelection() + } + } + } + + @SuppressLint("NewApi") + private fun addFileUris(path: String, paths: ArrayList<String>) { + if (activity.getIsPathDirectory(path)) { + val shouldShowHidden = config.shouldShowHidden() + when { + activity.isRestrictedSAFOnlyRoot(path) -> { + activity.getAndroidSAFFileItems(path, shouldShowHidden, false) { files -> + files.forEach { + addFileUris(activity.getAndroidSAFUri(it.path).toString(), paths) + } + } + } + + activity.isPathOnOTG(path) -> { + activity.getDocumentFile(path)?.listFiles() + ?.filter { if (shouldShowHidden) true else !it.name!!.startsWith(".") } + ?.forEach { + addFileUris(it.uri.toString(), paths) + } + } + + else -> { + File(path).listFiles() + ?.filter { if (shouldShowHidden) true else !it.name.startsWith('.') } + ?.forEach { + addFileUris(it.absolutePath, paths) + } + } + } + } else { + paths.add(path) + } + } + + fun tryMoveFiles(items: ArrayList<FileDirItem>) { + activity.handleDeletePasswordProtection { + copyMoveTo(items, false) + } + } + + fun copyMoveTo(files: ArrayList<FileDirItem>, isCopyOperation: Boolean) { + val firstFile = files[0] + val source = firstFile.getParentPath() + FilePickerDialog( + activity = activity, + currPath = activity.getDefaultCopyDestinationPath(config.shouldShowHidden(), source), + pickFile = false, + showHidden = config.shouldShowHidden(), + showFAB = true, + canAddShowHiddenButton = true, + showFavoritesButton = true + ) { + config.lastCopyPath = it + if (activity.isPathOnRoot(it) || activity.isPathOnRoot(firstFile.path)) { + copyMoveRootItems(files, it, isCopyOperation) + } else { + activity.copyMoveFilesTo( + fileDirItems = files, + source = source, + destination = it, + isCopyOperation = isCopyOperation, + copyPhotoVideoOnly = false, + copyHidden = config.shouldShowHidden() + ) { + if (!isCopyOperation) { + files.forEach { sourceFileDir -> + val sourcePath = sourceFileDir.path + if ( + activity.isRestrictedSAFOnlyRoot(sourcePath) + && activity.getDoesFilePathExist(sourcePath) + ) { + activity.deleteFile(sourceFileDir, true) { + refresh() + activity.runOnUiThread { + finishSelection() + } + } + } else { + val sourceFile = File(sourcePath) + val sourceIsFolder = + activity.getDoesFilePathExist(source) && activity.getIsPathDirectory(source) + if (sourceIsFolder && sourceFile.isEmptyFolder()) { + val sourceFolder = sourceFile.toFileDirItem(activity) + activity.deleteFile(sourceFolder, true) { + refresh() + activity.runOnUiThread { + finishSelection() + } + } + } else { + refresh() + finishSelection() + } + } + } + } else { + refresh() + finishSelection() + } + } + } + } + } + + private fun copyMoveRootItems( + files: ArrayList<FileDirItem>, + destinationPath: String, + isCopyOperation: Boolean + ) { + activity.toast(R.string.copying) + ensureBackgroundThread { + val fileCnt = files.size + RootHelpers(activity).copyMoveFiles(files, destinationPath, isCopyOperation) { + when (it) { + fileCnt -> activity.toast(R.string.copying_success) + 0 -> activity.toast(R.string.copy_failed) + else -> activity.toast(R.string.copying_success_partial) + } + + activity.runOnUiThread { + refresh() + finishSelection() + } + } + } + } + + /** Asks for confirmation (unless the user turned that off) and runs [delete] on "Yes". */ + fun askConfirmDelete(itemsCnt: Int, firstPath: String, delete: () -> Unit) { + if (config.skipDeleteConfirmation) { + delete() + return + } + + activity.handleDeletePasswordProtection { + val items = if (itemsCnt == 1) { + "\"${firstPath.getFilenameFromPath()}\"" + } else { + resources.getQuantityString(R.plurals.delete_items, itemsCnt, itemsCnt) + } + + val question = String.format(resources.getString(R.string.deletion_confirmation), items) + ConfirmationDialog(activity, question) { + delete() + } + } + } + + companion object { + /** What Glide loads for [path]: the icon of an apk, a SAF/OTG uri or the path itself. */ + fun getImagePathToLoad(context: Context, path: String, hasOTGConnected: Boolean): Any { + var itemToLoad = if (path.endsWith(".apk", true)) { + val packageInfo = + context.packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES) + val appInfo = packageInfo?.applicationInfo + if (appInfo != null) { + appInfo.sourceDir = path + appInfo.publicSourceDir = path + appInfo.loadIcon(context.packageManager) + } else { + path + } + } else { + path + } + + val baseConfig = context.baseConfig + if (context.isRestrictedSAFOnlyRoot(path)) { + itemToLoad = context.getAndroidSAFUri(path) + } else { + val otgPath = (itemToLoad as? String)?.takeIf { hasOTGConnected && context.isPathOnOTG(it) } + if (otgPath != null && baseConfig.OTGTreeUri.isNotEmpty() && baseConfig.OTGPartition.isNotEmpty()) { + itemToLoad = "${baseConfig.OTGTreeUri}/document/${baseConfig.OTGPartition}%3A${ + otgPath.substring(baseConfig.OTGPath.length).replace("/", "%2F") + }" + } + } + + return itemToLoad + } + } +} + +/** A folder left with nothing in it (no entries, no size, no files below it) after its content was moved away. */ +private fun File.isEmptyFolder() = list()?.isEmpty() == true && getProperSize(true) == 0L && getFileCount(true) == 0 diff --git a/app/src/main/kotlin/org/fossify/filemanager/helpers/FirstItemActions.kt b/app/src/main/kotlin/org/fossify/filemanager/helpers/FirstItemActions.kt new file mode 100644 index 0000000..8069080 --- /dev/null +++ b/app/src/main/kotlin/org/fossify/filemanager/helpers/FirstItemActions.kt @@ -0,0 +1,141 @@ +package org.fossify.filemanager.helpers + +import android.annotation.SuppressLint +import android.content.Intent +import android.content.pm.ShortcutInfo +import android.content.pm.ShortcutManager +import android.graphics.drawable.Drawable +import android.graphics.drawable.Icon +import android.graphics.drawable.LayerDrawable +import android.net.Uri +import com.bumptech.glide.Glide +import com.bumptech.glide.load.DecodeFormat +import com.bumptech.glide.load.engine.DiskCacheStrategy +import com.bumptech.glide.request.RequestOptions +import org.fossify.commons.dialogs.RadioGroupDialog +import org.fossify.commons.extensions.applyColorFilter +import org.fossify.commons.extensions.baseConfig +import org.fossify.commons.extensions.convertToBitmap +import org.fossify.commons.extensions.copyToClipboard +import org.fossify.commons.extensions.getFilenameFromPath +import org.fossify.commons.extensions.getIsPathDirectory +import org.fossify.commons.extensions.hasOTGConnected +import org.fossify.commons.helpers.ensureBackgroundThread +import org.fossify.commons.helpers.getFilePlaceholderDrawables +import org.fossify.commons.models.RadioItem +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.SimpleActivity +import org.fossify.filemanager.activities.SplashActivity +import org.fossify.filemanager.extensions.setAs +import org.fossify.filemanager.extensions.tryOpenPathIntent +import java.io.File +import java.util.Locale + +/** + * The actions of the contextual action bar that work on the first selected item: a home screen shortcut, copying its + * path, "Set as", "Open with" and "Open as". [finishSelection] leaves the selection mode. + */ +class FirstItemActions( + private val activity: SimpleActivity, + private val finishSelection: () -> Unit, +) { + private val resources = activity.resources + + @SuppressLint("NewApi") + fun createShortcut(path: String) { + val manager = activity.getSystemService(ShortcutManager::class.java) + if (manager.isRequestPinShortcutSupported) { + val drawable = resources.getDrawable(R.drawable.shortcut_folder).mutate() + getShortcutImage(path, drawable) { + val intent = Intent(activity, SplashActivity::class.java) + intent.action = Intent.ACTION_VIEW + intent.flags = + intent.flags or + Intent.FLAG_ACTIVITY_NEW_TASK or + Intent.FLAG_ACTIVITY_CLEAR_TASK or + Intent.FLAG_ACTIVITY_NO_HISTORY + intent.data = Uri.fromFile(File(path)) + + val shortcut = ShortcutInfo.Builder(activity, path) + .setShortLabel(path.getFilenameFromPath()) + .setIcon(Icon.createWithBitmap(drawable.convertToBitmap())) + .setIntent(intent) + .build() + + manager.requestPinShortcut(shortcut, null) + } + } + } + + // moved unchanged from ItemsAdapter, where detekt's baseline covered these findings + @Suppress("TooGenericExceptionCaught", "SwallowedException") + private fun getShortcutImage(path: String, drawable: Drawable, callback: () -> Unit) { + val appIconColor = activity.baseConfig.appIconColor + (drawable as LayerDrawable).findDrawableByLayerId(R.id.shortcut_folder_background) + .applyColorFilter(appIconColor) + if (activity.getIsPathDirectory(path)) { + callback() + } else { + ensureBackgroundThread { + val options = RequestOptions() + .format(DecodeFormat.PREFER_ARGB_8888) + .skipMemoryCache(true) + .diskCacheStrategy(DiskCacheStrategy.NONE) + .fitCenter() + + val size = activity.resources.getDimension(R.dimen.shortcut_size).toInt() + val builder = Glide.with(activity) + .asDrawable() + .load(FileItemActions.getImagePathToLoad(activity, path, activity.hasOTGConnected())) + .apply(options) + .centerCrop() + .into(size, size) + + try { + val bitmap = builder.get() + drawable.findDrawableByLayerId(R.id.shortcut_folder_background) + .applyColorFilter(0) + drawable.setDrawableByLayerId(R.id.shortcut_folder_image, bitmap) + } catch (e: Exception) { + val fileIcon = getFilePlaceholderDrawables(activity) + .getOrElse( + key = path.substringAfterLast(".").lowercase(Locale.getDefault()), + defaultValue = { resources.getDrawable(R.drawable.ic_file_generic) } + ) + drawable.setDrawableByLayerId(R.id.shortcut_folder_image, fileIcon) + } + + activity.runOnUiThread { + callback() + } + } + } + } + + fun copyPath(path: String) { + activity.copyToClipboard(path) + finishSelection() + } + + fun setAs(path: String) { + activity.setAs(path) + } + + fun openWith(path: String) { + activity.tryOpenPathIntent(path, true) + } + + fun openAs(path: String) { + val items = arrayListOf( + RadioItem(OPEN_AS_TEXT, resources.getString(R.string.text_file)), + RadioItem(OPEN_AS_IMAGE, resources.getString(R.string.image_file)), + RadioItem(OPEN_AS_AUDIO, resources.getString(R.string.audio_file)), + RadioItem(OPEN_AS_VIDEO, resources.getString(R.string.video_file)), + RadioItem(OPEN_AS_OTHER, resources.getString(R.string.other_file)) + ) + + RadioGroupDialog(activity, items) { + activity.tryOpenPathIntent(path, false, it as Int) + } + } +} diff --git a/app/src/main/kotlin/org/fossify/filemanager/dialogs/CreateNewItemDialog.kt b/app/src/main/kotlin/org/fossify/filemanager/helpers/NewItemCreator.kt similarity index 60% rename from app/src/main/kotlin/org/fossify/filemanager/dialogs/CreateNewItemDialog.kt rename to app/src/main/kotlin/org/fossify/filemanager/helpers/NewItemCreator.kt index e2aa6f5..9bc17d0 100644 --- a/app/src/main/kotlin/org/fossify/filemanager/dialogs/CreateNewItemDialog.kt +++ b/app/src/main/kotlin/org/fossify/filemanager/helpers/NewItemCreator.kt @@ -1,55 +1,57 @@ -package org.fossify.filemanager.dialogs +package org.fossify.filemanager.helpers -import android.view.View -import androidx.appcompat.app.AlertDialog -import org.fossify.commons.extensions.* +import org.fossify.commons.extensions.createAndroidSAFDirectory +import org.fossify.commons.extensions.createAndroidSAFFile +import org.fossify.commons.extensions.getDocumentFile +import org.fossify.commons.extensions.getDoesFilePathExist +import org.fossify.commons.extensions.getFilenameFromPath +import org.fossify.commons.extensions.getMimeType +import org.fossify.commons.extensions.getParentPath +import org.fossify.commons.extensions.internalStoragePath +import org.fossify.commons.extensions.isAValidFilename +import org.fossify.commons.extensions.isRestrictedSAFOnlyRoot +import org.fossify.commons.extensions.needsStupidWritePermissions +import org.fossify.commons.extensions.showErrorToast +import org.fossify.commons.extensions.toast import org.fossify.commons.helpers.isRPlus import org.fossify.filemanager.R import org.fossify.filemanager.activities.SimpleActivity -import org.fossify.filemanager.databinding.DialogCreateNewBinding -import org.fossify.filemanager.helpers.RootHelpers import java.io.File import java.io.IOException -class CreateNewItemDialog(val activity: SimpleActivity, val path: String, val callback: (success: Boolean) -> Unit) { - private val binding = DialogCreateNewBinding.inflate(activity.layoutInflater) - - init { - activity.getAlertDialogBuilder() - .setPositiveButton(R.string.ok, null) - .setNegativeButton(R.string.cancel, null) - .apply { - activity.setupDialogStuff(binding.root, this, R.string.create_new) { alertDialog -> - alertDialog.showKeyboard(binding.itemTitle) - alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(View.OnClickListener { - val name = binding.itemTitle.value - if (name.isEmpty()) { - activity.toast(R.string.empty_name) - } else if (name.isAValidFilename()) { - val newPath = "$path/$name" - if (activity.getDoesFilePathExist(newPath)) { - activity.toast(R.string.name_taken) - return@OnClickListener - } +/** + * Creates the file or folder asked for in the "Create new" dialog of the Files tab. + * + * [onCreated] is called once the item exists (the dialog then closes), [callback] reports failures with `false` + * and successes with `true`, exactly like the view based dialog did. + */ +class NewItemCreator( + private val activity: SimpleActivity, + private val onCreated: () -> Unit, + private val callback: (success: Boolean) -> Unit, +) { + /** Validates [name] like the old dialog did and creates the item inside [parentPath]. */ + fun create(parentPath: String, name: String, isDirectory: Boolean) { + if (name.isEmpty()) { + activity.toast(R.string.empty_name) + } else if (name.isAValidFilename()) { + val newPath = "$parentPath/$name" + if (activity.getDoesFilePathExist(newPath)) { + activity.toast(R.string.name_taken) + return + } - if (binding.dialogRadioGroup.checkedRadioButtonId == R.id.dialog_radio_directory) { - createDirectory(newPath, alertDialog) { - callback(it) - } - } else { - createFile(newPath, alertDialog) { - callback(it) - } - } - } else { - activity.toast(R.string.invalid_name) - } - }) - } + if (isDirectory) { + createDirectory(newPath) + } else { + createFile(newPath) } + } else { + activity.toast(R.string.invalid_name) + } } - private fun createDirectory(path: String, alertDialog: AlertDialog, callback: (Boolean) -> Unit) { + private fun createDirectory(path: String) { when { activity.needsStupidWritePermissions(path) -> activity.handleSAFDialog(path) { if (!it) { @@ -64,7 +66,7 @@ class CreateNewItemDialog(val activity: SimpleActivity, val path: String, val ca return@handleSAFDialog } documentFile.createDirectory(path.getFilenameFromPath()) - success(alertDialog) + success() } isRPlus() || path.startsWith(activity.internalStoragePath, true) -> { @@ -75,7 +77,7 @@ class CreateNewItemDialog(val activity: SimpleActivity, val path: String, val ca return@handleAndroidSAFDialog } if (activity.createAndroidSAFDirectory(path)) { - success(alertDialog) + success() } else { val error = String.format(activity.getString(R.string.could_not_create_folder), path) activity.showErrorToast(error) @@ -84,7 +86,7 @@ class CreateNewItemDialog(val activity: SimpleActivity, val path: String, val ca } } else { if (File(path).mkdirs()) { - success(alertDialog) + success() } } } @@ -92,7 +94,7 @@ class CreateNewItemDialog(val activity: SimpleActivity, val path: String, val ca else -> { RootHelpers(activity).createFileFolder(path, false) { if (it) { - success(alertDialog) + success() } else { callback(false) } @@ -101,7 +103,7 @@ class CreateNewItemDialog(val activity: SimpleActivity, val path: String, val ca } } - private fun createFile(path: String, alertDialog: AlertDialog, callback: (Boolean) -> Unit) { + private fun createFile(path: String) { try { when { activity.isRestrictedSAFOnlyRoot(path) -> { @@ -111,7 +113,7 @@ class CreateNewItemDialog(val activity: SimpleActivity, val path: String, val ca return@handleAndroidSAFDialog } if (activity.createAndroidSAFFile(path)) { - success(alertDialog) + success() } else { val error = String.format(activity.getString(R.string.could_not_create_file), path) activity.showErrorToast(error) @@ -134,20 +136,20 @@ class CreateNewItemDialog(val activity: SimpleActivity, val path: String, val ca return@handleSAFDialog } documentFile.createFile(path.getMimeType(), path.getFilenameFromPath()) - success(alertDialog) + success() } } isRPlus() || path.startsWith(activity.internalStoragePath, true) -> { if (File(path).createNewFile()) { - success(alertDialog) + success() } } else -> { RootHelpers(activity).createFileFolder(path, true) { if (it) { - success(alertDialog) + success() } else { callback(false) } @@ -160,8 +162,8 @@ class CreateNewItemDialog(val activity: SimpleActivity, val path: String, val ca } } - private fun success(alertDialog: AlertDialog) { - alertDialog.dismiss() + private fun success() { + onCreated() callback(true) } } diff --git a/app/src/main/kotlin/org/fossify/filemanager/views/GestureEditText.kt b/app/src/main/kotlin/org/fossify/filemanager/views/GestureEditText.kt deleted file mode 100644 index cfd0178..0000000 --- a/app/src/main/kotlin/org/fossify/filemanager/views/GestureEditText.kt +++ /dev/null @@ -1,91 +0,0 @@ -package org.fossify.filemanager.views - -import android.content.Context -import android.util.AttributeSet -import android.util.TypedValue -import android.view.MotionEvent -import androidx.appcompat.widget.AppCompatEditText -import com.alexvasilkov.gestures.GestureController -import com.alexvasilkov.gestures.State -import com.alexvasilkov.gestures.views.interfaces.GestureView -import org.fossify.commons.extensions.getProperPrimaryColor -import org.fossify.commons.extensions.getProperTextColor -import org.fossify.commons.extensions.onGlobalLayout -import org.fossify.filemanager.extensions.config - -// inspired by -// https://github.com/alexvasilkov/GestureViews/blob/f0a4c266e31dcad23bd0d9013531bc1c501b9c9f/sample/src/main/java/com/alexvasilkov/gestures/sample/ex/custom/text/GestureTextView.java -class GestureEditText : AppCompatEditText, GestureView { - constructor(context: Context) : super(context) - - constructor(context: Context, attrs: AttributeSet) : super(context, attrs) - - constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) - - private val controller: GestureController = GestureController(this) - private var origSize = 0f - private var size = 0f - - init { - controller.settings.setOverzoomFactor(1f).isPanEnabled = false - controller.addOnStateChangeListener(object : GestureController.OnStateChangeListener { - override fun onStateChanged(state: State) { - applyState(state) - } - - override fun onStateReset(oldState: State, newState: State) { - applyState(newState) - } - }) - - origSize = textSize - setTextColor(context.getProperTextColor()) - setLinkTextColor(context.getProperPrimaryColor()) - - val storedTextZoom = context.config.editorTextZoom - if (storedTextZoom != 0f) { - onGlobalLayout { - controller.state.zoomTo(storedTextZoom, width / 2f, height / 2f) - controller.updateState() - } - } - } - - override fun getController() = controller - - override fun onTouchEvent(event: MotionEvent): Boolean { - controller.onTouch(this, event) - return super.onTouchEvent(event) - } - - override fun setTextSize(size: Float) { - super.setTextSize(size) - origSize = textSize - applyState(controller.state) - } - - override fun setTextSize(unit: Int, size: Float) { - super.setTextSize(unit, size) - origSize = textSize - applyState(controller.state) - } - - override fun onSizeChanged(width: Int, height: Int, oldWidth: Int, oldHeight: Int) { - super.onSizeChanged(width, height, oldWidth, oldHeight) - controller.settings.setViewport(width, height).setImage(width, height) - controller.updateState() - } - - private fun applyState(state: State) { - var size = origSize * state.zoom - val maxSize = origSize * controller.stateController.getMaxZoom(state) - size = Math.max(origSize, Math.min(size, maxSize)) - - size = Math.round(size).toFloat() - if (!State.equals(this.size, size)) { - this.size = size - super.setTextSize(TypedValue.COMPLEX_UNIT_PX, size) - context.config.editorTextZoom = state.zoom - } - } -} diff --git a/app/src/main/res/layout/activity_decompress.xml b/app/src/main/res/layout/activity_decompress.xml deleted file mode 100644 index f8e1318..0000000 --- a/app/src/main/res/layout/activity_decompress.xml +++ /dev/null @@ -1,50 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - android:id="@+id/decompress_coordinator" - android:layout_width="match_parent" - android:layout_height="match_parent"> - - <org.fossify.commons.views.MyAppBarLayout - android:id="@+id/decompress_appbar" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <com.google.android.material.appbar.MaterialToolbar - android:id="@+id/decompress_toolbar" - android:layout_width="match_parent" - android:layout_height="?attr/actionBarSize" - android:background="@color/color_primary" - app:menu="@menu/menu_decompress" - app:title="@string/decompress" - app:titleTextAppearance="@style/AppTheme.ActionBar.TitleTextStyle" /> - - </org.fossify.commons.views.MyAppBarLayout> - - <RelativeLayout - android:id="@+id/decompress_wrapper" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:fillViewport="true" - android:scrollbars="none" - app:layout_behavior="@string/appbar_scrolling_view_behavior"> - - <org.fossify.commons.views.MyRecyclerView - android:id="@+id/decompress_list" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:clipToPadding="false" - android:paddingTop="@dimen/small_margin" - android:scrollbars="none" - app:layoutManager="org.fossify.commons.views.MyLinearLayoutManager" /> - - </RelativeLayout> - - <com.google.android.material.progressindicator.CircularProgressIndicator - android:id="@+id/progress_indicator" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_gravity="center" - android:indeterminate="true" - android:visibility="gone" /> -</androidx.coordinatorlayout.widget.CoordinatorLayout> diff --git a/app/src/main/res/layout/activity_favorites.xml b/app/src/main/res/layout/activity_favorites.xml deleted file mode 100644 index 5fc2dcd..0000000 --- a/app/src/main/res/layout/activity_favorites.xml +++ /dev/null @@ -1,73 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - xmlns:tools="http://schemas.android.com/tools" - android:id="@+id/manage_favorites_coordinator" - android:layout_width="match_parent" - android:layout_height="match_parent"> - - <org.fossify.commons.views.MyAppBarLayout - android:id="@+id/manage_favorites_appbar" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <com.google.android.material.appbar.MaterialToolbar - android:id="@+id/manage_favorites_toolbar" - android:layout_width="match_parent" - android:layout_height="?attr/actionBarSize" - android:background="@color/color_primary" - app:menu="@menu/menu_favorites" - app:title="@string/manage_favorites" - app:titleTextAppearance="@style/AppTheme.ActionBar.TitleTextStyle" /> - - </org.fossify.commons.views.MyAppBarLayout> - - <RelativeLayout - android:id="@+id/manage_favorites_holder" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:fillViewport="true" - android:scrollbars="none" - app:layout_behavior="@string/appbar_scrolling_view_behavior"> - - <org.fossify.commons.views.MyRecyclerView - android:id="@+id/manage_favorites_list" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:clipToPadding="false" - app:layoutManager="org.fossify.commons.views.MyLinearLayoutManager" - tools:itemCount="4" - tools:listitem="@layout/item_manage_favorite" /> - - <org.fossify.commons.views.MyTextView - android:id="@+id/manage_favorites_placeholder" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_centerHorizontal="true" - android:layout_marginBottom="@dimen/small_margin" - android:alpha="0.8" - android:gravity="center" - android:lineSpacingExtra="@dimen/tiny_margin" - android:paddingStart="@dimen/activity_margin" - android:paddingTop="@dimen/activity_margin" - android:paddingEnd="@dimen/activity_margin" - android:text="@string/favorites_activity_placeholder" - android:textSize="@dimen/bigger_text_size" - android:textStyle="italic" - android:visibility="gone" /> - - <org.fossify.commons.views.MyTextView - android:id="@+id/manage_favorites_placeholder_2" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_below="@+id/manage_favorites_placeholder" - android:layout_centerHorizontal="true" - android:background="@drawable/ripple_all_corners" - android:gravity="center" - android:padding="@dimen/normal_margin" - android:text="@string/add_favorites" - android:textSize="@dimen/bigger_text_size" - android:visibility="gone" /> - - </RelativeLayout> -</androidx.coordinatorlayout.widget.CoordinatorLayout> diff --git a/app/src/main/res/layout/activity_read_text.xml b/app/src/main/res/layout/activity_read_text.xml deleted file mode 100644 index f42e46d..0000000 --- a/app/src/main/res/layout/activity_read_text.xml +++ /dev/null @@ -1,56 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - android:id="@+id/read_text_coordinator" - android:layout_width="match_parent" - android:layout_height="match_parent"> - - <org.fossify.commons.views.MyAppBarLayout - android:id="@+id/read_text_appbar" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <com.google.android.material.appbar.MaterialToolbar - android:id="@+id/read_text_toolbar" - android:layout_width="match_parent" - android:layout_height="?attr/actionBarSize" - android:background="@color/color_primary" - app:menu="@menu/menu_editor" - app:title="@string/file_editor" - app:titleTextAppearance="@style/AppTheme.ActionBar.TitleTextStyle" /> - - </org.fossify.commons.views.MyAppBarLayout> - - <LinearLayout - android:id="@+id/read_text_wrapper" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:fillViewport="true" - android:orientation="vertical" - android:scrollbars="none" - app:layout_behavior="@string/appbar_scrolling_view_behavior"> - - <include - android:id="@+id/search_wrapper" - layout="@layout/search_bar" /> - - <androidx.core.widget.NestedScrollView - android:id="@+id/read_text_holder" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:fillViewport="true"> - - <org.fossify.filemanager.views.GestureEditText - android:id="@+id/read_text_view" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:background="@null" - android:gravity="top" - android:inputType="textMultiLine|textNoSuggestions" - android:padding="@dimen/medium_margin" - android:textCursorDrawable="@null" - android:textSize="@dimen/smaller_text_size" /> - - </androidx.core.widget.NestedScrollView> - </LinearLayout> -</androidx.coordinatorlayout.widget.CoordinatorLayout> diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml deleted file mode 100644 index a2c5541..0000000 --- a/app/src/main/res/layout/activity_settings.xml +++ /dev/null @@ -1,364 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - xmlns:tools="http://schemas.android.com/tools" - android:id="@+id/settings_coordinator" - android:layout_width="match_parent" - android:layout_height="match_parent"> - - <org.fossify.commons.views.MyAppBarLayout - android:id="@+id/settings_appbar" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <com.google.android.material.appbar.MaterialToolbar - android:id="@+id/settings_toolbar" - android:layout_width="match_parent" - android:layout_height="?attr/actionBarSize" - android:background="@color/color_primary" - app:title="@string/settings" - app:titleTextAppearance="@style/AppTheme.ActionBar.TitleTextStyle" /> - - </org.fossify.commons.views.MyAppBarLayout> - - <androidx.core.widget.NestedScrollView - android:id="@+id/settings_nested_scrollview" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:fillViewport="true" - android:scrollbars="none" - app:layout_behavior="@string/appbar_scrolling_view_behavior"> - - <LinearLayout - android:id="@+id/settings_holder" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:orientation="vertical"> - - <TextView - android:id="@+id/settings_color_customization_section_label" - style="@style/SettingsSectionLabelStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/color_customization" /> - - <androidx.constraintlayout.widget.ConstraintLayout - android:id="@+id/settings_color_customization_holder" - style="@style/SettingsHolderTextViewOneLinerStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyTextView - android:id="@+id/settings_color_customization_label" - style="@style/SettingsTextLabelStyle" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/customize_colors" - app:layout_constraintStart_toStartOf="parent" - app:layout_constraintTop_toTopOf="parent" /> - - </androidx.constraintlayout.widget.ConstraintLayout> - - <include - android:id="@+id/settings_color_customization_divider" - layout="@layout/divider" /> - - <TextView - android:id="@+id/settings_general_settings_label" - style="@style/SettingsSectionLabelStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/general_settings" /> - - <org.fossify.commons.views.PurchaseThankYouItem - android:id="@+id/settings_purchase_thank_you_holder" - android:layout_width="match_parent" - android:layout_height="wrap_content"/> - - <RelativeLayout - android:id="@+id/settings_use_english_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_use_english" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/use_english_language" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_language_holder" - style="@style/SettingsHolderTextViewStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyTextView - android:id="@+id/settings_language_label" - style="@style/SettingsTextLabelStyle" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/language" /> - - <org.fossify.commons.views.MyTextView - android:id="@+id/settings_language" - style="@style/SettingsTextValueStyle" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_below="@+id/settings_language_label" - tools:text="English" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_manage_favorites_holder" - style="@style/SettingsHolderTextViewOneLinerStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyTextView - android:id="@+id/settings_manage_favorites" - style="@style/SettingsTextLabelStyle" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/manage_favorites" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_manage_tabs_holder" - style="@style/SettingsHolderTextViewOneLinerStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyTextView - android:id="@+id/settings_manage_tabs" - style="@style/SettingsTextLabelStyle" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/manage_shown_tabs" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_change_date_time_format_holder" - style="@style/SettingsHolderTextViewOneLinerStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyTextView - android:id="@+id/settings_change_date_time_format" - style="@style/SettingsTextLabelStyle" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/change_date_and_time_format" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_font_size_holder" - style="@style/SettingsHolderTextViewStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyTextView - android:id="@+id/settings_font_size_label" - style="@style/SettingsTextLabelStyle" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:text="@string/font_size" /> - - <org.fossify.commons.views.MyTextView - android:id="@+id/settings_font_size" - style="@style/SettingsTextValueStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_below="@+id/settings_font_size_label" - tools:text="@string/medium" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_press_back_twice_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_press_back_twice" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/press_back_twice" /> - - </RelativeLayout> - - <include - android:id="@+id/settings_general_settings_divider" - layout="@layout/divider" /> - - <TextView - android:id="@+id/settings_visibility_label" - style="@style/SettingsSectionLabelStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/visibility" /> - - <RelativeLayout - android:id="@+id/settings_show_hidden_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_show_hidden" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/show_hidden_items" /> - - </RelativeLayout> - - <include - android:id="@+id/settings_visibility_divider" - layout="@layout/divider" /> - - <TextView - android:id="@+id/settings_scrolling_label" - style="@style/SettingsSectionLabelStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/scrolling" /> - - <RelativeLayout - android:id="@+id/settings_enable_pull_to_refresh_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_enable_pull_to_refresh" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/enable_pull_to_refresh" /> - - </RelativeLayout> - - <include - android:id="@+id/settings_scrolling_divider" - layout="@layout/divider" /> - - <TextView - android:id="@+id/settings_file_operations_label" - style="@style/SettingsSectionLabelStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/file_operations" /> - - <RelativeLayout - android:id="@+id/settings_keep_last_modified_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_keep_last_modified" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/keep_last_modified" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_skip_delete_confirmation_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_skip_delete_confirmation" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/skip_delete_confirmation" /> - - </RelativeLayout> - - <include - android:id="@+id/settings_file_operations_divider" - layout="@layout/divider" /> - - <TextView - android:id="@+id/settings_security_label" - style="@style/SettingsSectionLabelStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/security" /> - - <RelativeLayout - android:id="@+id/settings_password_protection_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_password_protection" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/password_protect_hidden_items" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_app_password_protection_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_app_password_protection" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/password_protect_whole_app" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_file_deletion_password_protection_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_file_deletion_password_protection" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/password_protect_file_deletion" /> - - </RelativeLayout> - - <RelativeLayout - android:id="@+id/settings_enable_root_access_holder" - style="@style/SettingsHolderSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyMaterialSwitch - android:id="@+id/settings_enable_root_access" - style="@style/SettingsSwitchStyle" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/enable_root_access" /> - - </RelativeLayout> - </LinearLayout> - </androidx.core.widget.NestedScrollView> -</androidx.coordinatorlayout.widget.CoordinatorLayout> diff --git a/app/src/main/res/layout/dialog_create_new.xml b/app/src/main/res/layout/dialog_create_new.xml deleted file mode 100644 index 621d3ba..0000000 --- a/app/src/main/res/layout/dialog_create_new.xml +++ /dev/null @@ -1,47 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/dialog_holder" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:orientation="vertical" - android:paddingStart="@dimen/activity_margin" - android:paddingTop="@dimen/activity_margin" - android:paddingEnd="@dimen/activity_margin"> - - <org.fossify.commons.views.MyTextInputLayout - android:id="@+id/item_title_hint" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginBottom="@dimen/activity_margin" - android:hint="@string/title"> - - <com.google.android.material.textfield.TextInputEditText - android:id="@+id/item_title" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:inputType="textCapSentences" - android:singleLine="true" - android:textCursorDrawable="@null" - android:textSize="@dimen/bigger_text_size" /> - - </org.fossify.commons.views.MyTextInputLayout> - - <RadioGroup - android:id="@+id/dialog_radio_group" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.MyCompatRadioButton - android:id="@+id/dialog_radio_directory" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:checked="true" - android:text="@string/folder" /> - - <org.fossify.commons.views.MyCompatRadioButton - android:id="@+id/dialog_radio_file" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:text="@string/file" /> - </RadioGroup> -</LinearLayout> diff --git a/app/src/main/res/layout/dialog_manage_visible_tabs.xml b/app/src/main/res/layout/dialog_manage_visible_tabs.xml deleted file mode 100644 index 469636e..0000000 --- a/app/src/main/res/layout/dialog_manage_visible_tabs.xml +++ /dev/null @@ -1,41 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/manage_visible_tabs_scroll_view" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <LinearLayout - android:id="@+id/manage_visible_tabs_holder" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:orientation="vertical" - android:paddingStart="@dimen/activity_margin" - android:paddingTop="@dimen/activity_margin" - android:paddingEnd="@dimen/activity_margin"> - - <org.fossify.commons.views.MyAppCompatCheckbox - android:id="@+id/manage_visible_tabs_files" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:paddingTop="@dimen/activity_margin" - android:paddingBottom="@dimen/activity_margin" - android:text="@string/files_tab" /> - - <org.fossify.commons.views.MyAppCompatCheckbox - android:id="@+id/manage_visible_tabs_recent_files" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:paddingTop="@dimen/activity_margin" - android:paddingBottom="@dimen/activity_margin" - android:text="@string/recent_files_tab" /> - - <org.fossify.commons.views.MyAppCompatCheckbox - android:id="@+id/manage_visible_tabs_storage_analysis" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:paddingTop="@dimen/activity_margin" - android:paddingBottom="@dimen/activity_margin" - android:text="@string/storage_analysis" /> - - </LinearLayout> -</ScrollView> diff --git a/app/src/main/res/layout/dialog_save_as.xml b/app/src/main/res/layout/dialog_save_as.xml deleted file mode 100644 index ff0bc8d..0000000 --- a/app/src/main/res/layout/dialog_save_as.xml +++ /dev/null @@ -1,57 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" - android:id="@+id/save_as_holder" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:orientation="vertical" - android:padding="@dimen/activity_margin"> - - <org.fossify.commons.views.MyTextInputLayout - android:id="@+id/folder_hint" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginBottom="@dimen/activity_margin" - android:hint="@string/path"> - - <com.google.android.material.textfield.TextInputEditText - android:id="@+id/folder_value" - style="@style/UnclickableEditText" - android:layout_width="match_parent" - android:layout_height="wrap_content" /> - - </org.fossify.commons.views.MyTextInputLayout> - - <org.fossify.commons.views.MyTextInputLayout - android:id="@+id/filename_hint" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginBottom="@dimen/activity_margin" - android:hint="@string/filename"> - - <com.google.android.material.textfield.TextInputEditText - android:id="@+id/filename_value" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:inputType="textCapSentences" - android:singleLine="true" - android:textCursorDrawable="@null" - android:textSize="@dimen/bigger_text_size" /> - - </org.fossify.commons.views.MyTextInputLayout> - - <org.fossify.commons.views.MyTextInputLayout - android:id="@+id/extension_hint" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:hint="@string/extension"> - - <com.google.android.material.textfield.TextInputEditText - android:id="@+id/extension_value" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:singleLine="true" - android:textCursorDrawable="@null" - android:textSize="@dimen/bigger_text_size" /> - - </org.fossify.commons.views.MyTextInputLayout> -</LinearLayout> diff --git a/app/src/main/res/layout/item_decompression_list_file_dir.xml b/app/src/main/res/layout/item_decompression_list_file_dir.xml deleted file mode 100644 index 933c810..0000000 --- a/app/src/main/res/layout/item_decompression_list_file_dir.xml +++ /dev/null @@ -1,33 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:tools="http://schemas.android.com/tools" - android:id="@+id/item_holder" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:background="?attr/selectableItemBackground" - android:paddingEnd="@dimen/activity_margin"> - - <ImageView - android:id="@+id/item_icon" - android:layout_width="@dimen/file_picker_icon_size" - android:layout_height="@dimen/file_picker_icon_size" - android:layout_centerVertical="true" - android:padding="@dimen/medium_margin" - android:src="@drawable/ic_folder_vector" /> - - <TextView - android:id="@+id/item_name" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_alignTop="@+id/item_icon" - android:layout_alignBottom="@+id/item_icon" - android:layout_toEndOf="@+id/item_icon" - android:ellipsize="end" - android:gravity="center_vertical" - android:maxLines="1" - android:paddingStart="@dimen/tiny_margin" - android:paddingTop="@dimen/small_margin" - android:textSize="@dimen/bigger_text_size" - tools:text="Directory" /> - -</RelativeLayout> diff --git a/app/src/main/res/layout/item_manage_favorite.xml b/app/src/main/res/layout/item_manage_favorite.xml deleted file mode 100644 index ee89f44..0000000 --- a/app/src/main/res/layout/item_manage_favorite.xml +++ /dev/null @@ -1,37 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:tools="http://schemas.android.com/tools" - android:id="@+id/manage_favorite_holder" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginBottom="@dimen/tiny_margin" - android:paddingStart="@dimen/activity_margin" - android:paddingEnd="0dp"> - - <org.fossify.commons.views.MyTextView - android:id="@+id/manage_favorite_title" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_centerVertical="true" - android:layout_marginTop="@dimen/medium_margin" - android:layout_toStartOf="@+id/overflow_menu_icon" - tools:text="/Internal/DCIM" /> - - <ImageView - android:id="@+id/overflow_menu_icon" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_alignParentTop="true" - android:layout_alignParentEnd="true" - android:layout_centerVertical="true" - android:background="?attr/selectableItemBackgroundBorderless" - android:padding="@dimen/activity_margin" - android:src="@drawable/ic_three_dots_vector" /> - - <View - android:id="@+id/overflow_menu_anchor" - style="@style/OverflowMenuAnchorStyle" - android:layout_alignParentEnd="true" - android:layout_centerVertical="true" /> - -</RelativeLayout> diff --git a/app/src/main/res/layout/items_fragment.xml b/app/src/main/res/layout/items_fragment.xml deleted file mode 100644 index 312d24c..0000000 --- a/app/src/main/res/layout/items_fragment.xml +++ /dev/null @@ -1,105 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<org.fossify.filemanager.fragments.ItemsFragment xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - xmlns:tools="http://schemas.android.com/tools" - android:id="@+id/items_fragment" - android:layout_width="match_parent" - android:layout_height="match_parent"> - - <androidx.coordinatorlayout.widget.CoordinatorLayout - android:id="@+id/items_coordinator" - android:layout_width="match_parent" - android:layout_height="match_parent"> - - <RelativeLayout - android:id="@+id/items_wrapper" - android:layout_width="match_parent" - android:layout_height="wrap_content"> - - <org.fossify.commons.views.Breadcrumbs - android:id="@+id/breadcrumbs" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginTop="@dimen/medium_margin" - android:paddingStart="@dimen/activity_margin" - android:paddingTop="@dimen/small_margin" - android:paddingEnd="@dimen/small_margin" - android:paddingBottom="@dimen/small_margin" /> - - <com.google.android.material.progressindicator.LinearProgressIndicator - android:id="@+id/progress_bar" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_alignParentTop="true" - android:indeterminate="true" - android:visibility="gone" - app:hideAnimationBehavior="outward" - app:showAnimationBehavior="inward" - app:showDelay="250" - tools:visibility="visible" /> - - <org.fossify.commons.views.MyTextView - android:id="@+id/items_placeholder" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_below="@+id/breadcrumbs" - android:layout_centerHorizontal="true" - android:alpha="0.8" - android:gravity="center" - android:paddingStart="@dimen/activity_margin" - android:paddingEnd="@dimen/activity_margin" - android:text="@string/no_items_found" - android:textSize="@dimen/bigger_text_size" - android:textStyle="italic" - android:visibility="gone" /> - - <org.fossify.commons.views.MyTextView - android:id="@+id/items_placeholder_2" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_below="@+id/items_placeholder" - android:layout_centerHorizontal="true" - android:alpha="0.8" - android:background="?attr/selectableItemBackground" - android:gravity="center" - android:padding="@dimen/activity_margin" - android:text="@string/type_2_characters" - android:textSize="@dimen/bigger_text_size" - android:textStyle="italic" - android:visibility="gone" /> - - <org.fossify.filemanager.views.MySwipeRefreshLayout - android:id="@+id/items_swipe_refresh" - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_below="@+id/breadcrumbs"> - - <com.qtalk.recyclerviewfastscroller.RecyclerViewFastScroller - android:id="@+id/items_fastscroller" - android:layout_width="match_parent" - android:layout_height="wrap_content" - app:supportSwipeToRefresh="true"> - - <org.fossify.commons.views.MyRecyclerView - android:id="@+id/items_list" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:clipToPadding="false" - android:layoutAnimation="@anim/layout_animation" - android:scrollbars="none" - app:layoutManager="org.fossify.commons.views.MyGridLayoutManager" /> - - </com.qtalk.recyclerviewfastscroller.RecyclerViewFastScroller> - </org.fossify.filemanager.views.MySwipeRefreshLayout> - </RelativeLayout> - - <org.fossify.commons.views.MyFloatingActionButton - android:id="@+id/items_fab" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_gravity="bottom|end" - android:layout_margin="@dimen/activity_margin" - android:src="@drawable/ic_plus_vector" /> - - </androidx.coordinatorlayout.widget.CoordinatorLayout> -</org.fossify.filemanager.fragments.ItemsFragment> diff --git a/app/src/main/res/menu/menu_decompress.xml b/app/src/main/res/menu/menu_decompress.xml deleted file mode 100644 index 44f0361..0000000 --- a/app/src/main/res/menu/menu_decompress.xml +++ /dev/null @@ -1,9 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<menu xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto"> - <item - android:id="@+id/decompress" - android:icon="@drawable/ic_decompress_vector" - android:title="@string/decompress" - app:showAsAction="always" /> -</menu> diff --git a/app/src/main/res/menu/menu_editor.xml b/app/src/main/res/menu/menu_editor.xml deleted file mode 100644 index 7cc37d7..0000000 --- a/app/src/main/res/menu/menu_editor.xml +++ /dev/null @@ -1,31 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<menu xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto" - xmlns:tools="http://schemas.android.com/tools" - tools:ignore="AppCompatResource"> - <item - android:id="@+id/menu_search" - android:icon="@drawable/ic_search_vector" - android:title="@string/search" - app:showAsAction="always" /> - <item - android:id="@+id/menu_save" - android:icon="@drawable/ic_save_vector" - android:title="@string/save" - app:showAsAction="always" /> - <item - android:id="@+id/menu_save_as" - android:showAsAction="never" - android:title="@string/save_as" - app:showAsAction="never" /> - <item - android:id="@+id/menu_print" - android:icon="@drawable/ic_print_vector" - android:title="@string/print" - app:showAsAction="ifRoom" /> - <item - android:id="@+id/menu_open_with" - android:showAsAction="never" - android:title="@string/open_with" - app:showAsAction="never" /> -</menu> diff --git a/app/src/main/res/menu/menu_favorites.xml b/app/src/main/res/menu/menu_favorites.xml deleted file mode 100644 index e5d346f..0000000 --- a/app/src/main/res/menu/menu_favorites.xml +++ /dev/null @@ -1,9 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<menu xmlns:android="http://schemas.android.com/apk/res/android" - xmlns:app="http://schemas.android.com/apk/res-auto"> - <item - android:id="@+id/add_favorite" - android:icon="@drawable/ic_plus_vector" - android:title="@string/add_favorites" - app:showAsAction="always" /> -</menu> diff --git a/app/src/main/res/values/ids.xml b/app/src/main/res/values/ids.xml new file mode 100644 index 0000000..df99b60 --- /dev/null +++ b/app/src/main/res/values/ids.xml @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <!-- the Files tab of the main screen, created in code and drawn by Compose --> + <item name="items_fragment" type="id" /> + <item name="items_compose_view" type="id" /> + <item name="items_action_mode_view" type="id" /> +</resources> diff --git a/app/src/test/kotlin/org/fossify/filemanager/ui/DecompressScreenTest.kt b/app/src/test/kotlin/org/fossify/filemanager/ui/DecompressScreenTest.kt new file mode 100644 index 0000000..1fb8760 --- /dev/null +++ b/app/src/test/kotlin/org/fossify/filemanager/ui/DecompressScreenTest.kt @@ -0,0 +1,194 @@ +package org.fossify.filemanager.ui + +import android.content.DialogInterface +import android.content.Intent +import android.net.Uri +import android.widget.EditText +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createEmptyComposeRule +import androidx.compose.ui.test.onAllNodesWithTag +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +import net.lingala.zip4j.io.outputstream.ZipOutputStream +import net.lingala.zip4j.model.ZipParameters +import net.lingala.zip4j.model.enums.EncryptionMethod +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.DecompressActivity +import org.fossify.filemanager.compose.DecompressTestTags +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import java.io.File +import java.io.FileOutputStream + +@RunWith(AndroidJUnit4::class) +@Config(sdk = [34], qualifiers = "w411dp-h914dp-xxhdpi") +class DecompressScreenTest { + @get:Rule + val composeRule = createEmptyComposeRule() + + private var scenario: ActivityScenario<DecompressActivity>? = null + private lateinit var activity: DecompressActivity + private lateinit var archive: File + + @Before + fun setUp() { + grantAllFilesAccess() + archive = File(appContext.cacheDir, "sample.zip") + writeZip( + archive, + password = null, + entries = listOf("dir1/", "dir1/a.txt", "dir1/sub/", "dir1/sub/b.txt", "c.txt", "img.png") + ) + } + + @After + fun tearDown() { + scenario?.close() + } + + private fun text(id: Int) = appContext.getString(id) + + private fun writeZip(target: File, password: String?, entries: List<String>) { + ZipOutputStream(FileOutputStream(target), password?.toCharArray()).use { zip -> + entries.forEach { name -> writeEntry(zip, name, encrypt = password != null) } + } + } + + private fun writeEntry(zip: ZipOutputStream, name: String, encrypt: Boolean) { + val isDirectory = name.endsWith("/") + val parameters = ZipParameters().apply { + fileNameInZip = name + if (encrypt && !isDirectory) { + isEncryptFiles = true + encryptionMethod = EncryptionMethod.ZIP_STANDARD + } + } + zip.putNextEntry(parameters) + if (!isDirectory) { + zip.write("content of $name".toByteArray()) + } + zip.closeEntry() + } + + private fun launch(file: File = archive): ActivityScenario<DecompressActivity> { + val intent = Intent(appContext, DecompressActivity::class.java).apply { + action = Intent.ACTION_VIEW + setDataAndType(Uri.fromFile(file), "application/zip") + } + return ActivityScenario.launch<DecompressActivity>(intent).also { + scenario = it + it.onActivity { launched -> activity = launched } + } + } + + private fun waitForEntries(vararg names: String) { + composeRule.waitUntilTrue { + composeRule.onAllNodesWithTag(DecompressTestTags.LIST).fetchSemanticsNodes().isNotEmpty() && + names.all { name -> runCatching { composeRule.onNodeWithText(name).assertExists() }.isSuccess } + } + } + + private fun assertListing(vararg names: String) { + waitForEntries(*names) + val shown = composeRule.onNodeWithTag(DecompressTestTags.LIST).fetchSemanticsNode().children.size + assertEquals(names.size, shown) + } + + @Test + fun listsFoldersFirstAndWalksInAndOut() { + launch() + composeRule.onNodeWithText("sample.zip").assertIsDisplayed() + composeRule.onNodeWithContentDescription(text(R.string.decompress)).assertIsDisplayed() + assertListing("dir1", "c.txt", "img.png") + + // files do nothing on tap + composeRule.onNodeWithText("c.txt").performClick() + assertListing("dir1", "c.txt", "img.png") + + composeRule.onNodeWithText("dir1").performClick() + assertListing("sub", "a.txt") + composeRule.onNodeWithText("sub").performClick() + assertListing("b.txt") + + activity.onBackPressedDispatcher.onBackPressed() + assertListing("sub", "a.txt") + activity.onBackPressedDispatcher.onBackPressed() + assertListing("dir1", "c.txt", "img.png") + assertTrue(!activity.isFinishing) + + activity.onBackPressedDispatcher.onBackPressed() + idleMainLooper() + assertTrue(activity.isFinishing) + } + + @Test + fun currentFolderSurvivesRotation() { + val scenario = launch() + waitForEntries("dir1") + composeRule.onNodeWithText("dir1").performClick() + assertListing("sub", "a.txt") + + scenario.recreate() + scenario.onActivity { activity = it } + composeRule.waitForIdle() + assertListing("sub", "a.txt") + + activity.onBackPressedDispatcher.onBackPressed() + assertListing("dir1", "c.txt", "img.png") + } + + @Test + fun asksForPasswordOfEncryptedArchive() { + val secret = File(appContext.cacheDir, "secret.zip") + writeZip(secret, password = "pw123", entries = listOf("s.txt")) + launch(secret) + + composeRule.waitUntilTrue { latestShownDialog() != null } + val dialog = latestAlertDialog() + dialog.findViewById<EditText>(org.fossify.commons.R.id.password)!!.setText("pw123") + dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() + + assertListing("s.txt") + assertTrue(!dialog.isShowing) + } + + @Test + fun cancellingThePasswordClosesTheViewer() { + val secret = File(appContext.cacheDir, "secret.zip") + writeZip(secret, password = "pw123", entries = listOf("s.txt")) + launch(secret) + + composeRule.waitUntilTrue { latestShownDialog() != null } + latestAlertDialog().getButton(DialogInterface.BUTTON_NEGATIVE).performClick() + idleMainLooper() + assertTrue(activity.isFinishing) + } + + @Test + fun extractsToPickedFolder() { + launch() + waitForEntries("dir1") + composeRule.onNodeWithContentDescription(text(R.string.decompress)).performClick() + composeRule.waitForIdle() + + // the folder picker starts next to the archive, confirming extracts there + val picker = latestAlertDialog() + picker.getButton(DialogInterface.BUTTON_POSITIVE).performClick() + + val extracted = File(archive.parentFile, "sample") + composeRule.waitUntilTrue { activity.isFinishing } + assertEquals("content of dir1/sub/b.txt", File(extracted, "dir1/sub/b.txt").readText()) + assertEquals("content of c.txt", File(extracted, "c.txt").readText()) + assertTrue(File(extracted, "img.png").exists()) + } +} diff --git a/app/src/test/kotlin/org/fossify/filemanager/ui/FilesTabTest.kt b/app/src/test/kotlin/org/fossify/filemanager/ui/FilesTabTest.kt new file mode 100644 index 0000000..b04f63a --- /dev/null +++ b/app/src/test/kotlin/org/fossify/filemanager/ui/FilesTabTest.kt @@ -0,0 +1,342 @@ +package org.fossify.filemanager.ui + +import android.app.Activity +import android.content.DialogInterface +import android.content.Intent +import android.os.Environment +import android.widget.EditText +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createEmptyComposeRule +import androidx.compose.ui.test.longClick +import androidx.compose.ui.test.onAllNodesWithTag +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.pinch +import androidx.compose.ui.test.swipeDown +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.android.material.appbar.MaterialToolbar +import org.fossify.commons.helpers.SORT_BY_NAME +import org.fossify.commons.helpers.SORT_DESCENDING +import org.fossify.commons.helpers.TAB_FILES +import org.fossify.commons.helpers.VIEW_TYPE_GRID +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.MainActivity +import org.fossify.filemanager.compose.FilesTabTestTags +import org.fossify.filemanager.compose.TopBarTestTags +import org.fossify.filemanager.fragments.ItemsFragment +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config +import java.io.File + +/** The Files tab of the main screen, drawn by Compose, driven through the real [MainActivity]. */ +@RunWith(AndroidJUnit4::class) +@Config(sdk = [34], qualifiers = "w411dp-h914dp-xxhdpi") +class FilesTabTest { + @get:Rule + val composeRule = createEmptyComposeRule() + + private var scenario: ActivityScenario<MainActivity>? = null + private lateinit var root: File + + @Before + fun setUp() { + grantAllFilesAccess() + denyManageMedia() + root = File(Environment.getExternalStorageDirectory(), "fmtest") + root.deleteRecursively() + File(root, "dirA/sub").mkdirs() + File(root, "dirA/inner.txt").writeText("inner") + File(root, "dirB").mkdirs() + File(root, "a.txt").writeText("hello") + File(root, "b.txt").writeText("world!") + File(root, ".hidden.txt").writeText("h") + + testConfig.apply { + showTabs = TAB_FILES + wasStorageAnalysisTabAdded = true + homeFolder = root.absolutePath + skipDeleteConfirmation = false + sorting = SORT_BY_NAME + } + } + + @After + fun tearDown() { + scenario?.close() + root.deleteRecursively() + } + + private fun text(id: Int) = appContext.getString(id) + + private fun path(name: String) = File(root, name).absolutePath + + private fun launch(): ActivityScenario<MainActivity> { + return ActivityScenario.launch(MainActivity::class.java).also { + scenario = it + waitForFolder(root.absolutePath) + } + } + + private fun activity(): MainActivity { + var activity: MainActivity? = null + scenario!!.onActivity { activity = it } + return activity!! + } + + private fun fragment(): ItemsFragment = activity().findViewById(R.id.items_fragment) + + private fun shownNames() = fragment().state.items.map { it.name } + + private fun waitForFolder(folder: String) { + composeRule.waitUntilTrue(timeoutMillis = 10_000) { + val state = fragment().state + state.currentPath == folder && !state.isLoading && state.breadcrumbs.isNotEmpty() + } + composeRule.waitForIdle() + } + + private fun longPress(name: String) { + composeRule.onNodeWithTag(FilesTabTestTags.item(path(name))).performTouchInput { longClick() } + composeRule.waitForIdle() + } + + private fun pressBack() { + activity().onBackPressedDispatcher.onBackPressed() + composeRule.waitForIdle() + } + + @Test + fun listsFolderWithBreadcrumbsAndDetails() { + launch() + assertEquals(listOf("dirA", "dirB", "a.txt", "b.txt"), shownNames()) + composeRule.onNodeWithTag(FilesTabTestTags.item(path("a.txt"))).assertIsDisplayed() + composeRule.onNodeWithText("2 items").assertIsDisplayed() + composeRule.onNodeWithText("6 B").assertIsDisplayed() + composeRule.onNodeWithText("Internal").assertIsDisplayed() + composeRule.onNodeWithText("fmtest").assertIsDisplayed() + composeRule.onNodeWithContentDescription(text(R.string.create_new)).assertIsDisplayed() + } + + @Test + fun opensFoldersAndGoesBackViaBackAndBreadcrumbs() { + launch() + composeRule.onNodeWithTag(FilesTabTestTags.item(path("dirA"))).performClick() + waitForFolder(path("dirA")) + assertEquals(listOf("sub", "inner.txt"), shownNames()) + composeRule.onNodeWithText("dirA").assertIsDisplayed() + + composeRule.onNodeWithTag(FilesTabTestTags.item(path("dirA/sub"))).performClick() + waitForFolder(path("dirA/sub")) + + // the breadcrumb of an upper folder opens it + composeRule.onNodeWithTag(FilesTabTestTags.breadcrumb(2)).performClick() + waitForFolder(path("dirA")) + + // back goes to the parent folder + pressBack() + waitForFolder(root.absolutePath) + assertEquals(listOf("dirA", "dirB", "a.txt", "b.txt"), shownNames()) + } + + @Test + fun selectionModeShowsCounterActionsAndOverflow() { + launch() + longPress("a.txt") + composeRule.onNodeWithTag(TopBarTestTags.ACTION_MODE_TITLE).assertIsDisplayed() + composeRule.onNodeWithText("1 / 4").assertIsDisplayed() + composeRule.onNodeWithContentDescription(text(R.string.delete)).assertIsDisplayed() + composeRule.onNodeWithContentDescription(text(R.string.properties)).assertIsDisplayed() + composeRule.onNodeWithContentDescription(text(R.string.rename)).assertIsDisplayed() + + // a tap adds to the selection + composeRule.onNodeWithTag(FilesTabTestTags.item(path("dirA"))).performClick() + composeRule.onNodeWithText("2 / 4").assertIsDisplayed() + + composeRule.onNodeWithContentDescription(text(R.string.more_options)).performClick() + composeRule.waitForIdle() + listOf( + R.string.share, R.string.hide, R.string.copy_to, R.string.move_to, R.string.compress, R.string.select_all + ).forEach { composeRule.onNodeWithText(text(it)).assertIsDisplayed() } + // single item entries are gone with two items selected + composeRule.onNodeWithText(text(R.string.copy_path)).assertDoesNotExist() + composeRule.onNodeWithText(text(R.string.open_with)).assertDoesNotExist() + composeRule.onNodeWithText(text(R.string.decompress)).assertDoesNotExist() + composeRule.onNodeWithText(text(R.string.select_all)).performClick() + composeRule.onNodeWithText("4 / 4").assertIsDisplayed() + + // tapping the counter with everything selected finishes the selection + composeRule.onNodeWithTag(TopBarTestTags.ACTION_MODE_TITLE).performClick() + composeRule.waitForIdle() + composeRule.onNodeWithTag(TopBarTestTags.ACTION_MODE_TITLE).assertDoesNotExist() + + // back leaves the selection mode before navigating + longPress("b.txt") + composeRule.onNodeWithText("1 / 4").assertIsDisplayed() + pressBack() + composeRule.onNodeWithTag(TopBarTestTags.ACTION_MODE_TITLE).assertDoesNotExist() + assertEquals(root.absolutePath, fragment().state.currentPath) + } + + @Test + fun singleFileSelectionOffersFileEntries() { + File(root, "archive.zip").writeText("not really a zip") + launch() + longPress("archive.zip") + composeRule.onNodeWithContentDescription(text(R.string.more_options)).performClick() + composeRule.waitForIdle() + listOf( + R.string.create_shortcut, R.string.copy_path, R.string.set_as, R.string.open_with, R.string.open_as, + R.string.decompress + ).forEach { composeRule.onNodeWithText(text(it)).assertIsDisplayed() } + } + + @Test + fun deleteAsksAndRemovesTheFile() { + launch() + longPress("b.txt") + composeRule.onNodeWithContentDescription(text(R.string.delete)).performClick() + composeRule.waitForIdle() + latestAlertDialog().getButton(DialogInterface.BUTTON_POSITIVE).performClick() + composeRule.waitUntilTrue { !File(root, "b.txt").exists() } + composeRule.waitUntilTrue { "b.txt" !in shownNames() } + composeRule.onNodeWithTag(TopBarTestTags.ACTION_MODE_TITLE).assertDoesNotExist() + } + + @Test + fun renameRenamesOnDisk() { + launch() + longPress("a.txt") + composeRule.onNodeWithContentDescription(text(R.string.rename)).performClick() + composeRule.waitForIdle() + // the rename dialog of Fossify Commons opens for the selected file + val dialog = latestAlertDialog() + val name = dialog.findViewById<EditText>(org.fossify.commons.R.id.rename_item_name)!! + assertEquals("a", name.text.toString()) + val extension = dialog.findViewById<EditText>(org.fossify.commons.R.id.rename_item_extension)!! + assertEquals("txt", extension.text.toString()) + name.setText("renamed") + dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() + composeRule.waitUntilTrue { File(root, "renamed.txt").exists() && !File(root, "a.txt").exists() } + } + + @Test + fun createButtonConfirmsTheFolderWhenCreatingADocumentForAnotherApp() { + val intent = Intent(appContext, MainActivity::class.java).apply { + action = Intent.ACTION_CREATE_DOCUMENT + putExtra(Intent.EXTRA_TITLE, "export.txt") + } + scenario = ActivityScenario.launchActivityForResult(intent) + waitForFolder(root.absolutePath) + // the create button turns into a check mark that picks the current folder + composeRule.onNodeWithContentDescription(text(R.string.ok)).performClick() + composeRule.waitForIdle() + val result = scenario!!.result + assertEquals(Activity.RESULT_OK, result.resultCode) + assertTrue(result.resultData.data.toString().endsWith("export.txt")) + } + + @Test + fun pullToRefreshShowsNewFiles() { + launch() + File(root, "external.txt").writeText("x") + composeRule.onNodeWithTag(FilesTabTestTags.LIST).performTouchInput { swipeDown() } + composeRule.waitUntilTrue { "external.txt" in shownNames() } + composeRule.waitUntilTrue { !fragment().state.isRefreshing } + } + + @Test + fun showsHiddenItemsOnRequest() { + launch() + assertFalse(".hidden.txt" in shownNames()) + val toolbar = activity().findViewById<MaterialToolbar>(org.fossify.commons.R.id.top_toolbar) + toolbar.menu.performIdentifierAction(R.id.temporarily_show_hidden, 0) + composeRule.waitUntilTrue { ".hidden.txt" in shownNames() } + toolbar.menu.performIdentifierAction(R.id.stop_showing_hidden, 0) + composeRule.waitUntilTrue { ".hidden.txt" !in shownNames() } + } + + @Test + fun sortingIsFollowed() { + launch() + testConfig.sorting = SORT_BY_NAME or SORT_DESCENDING + fragment().refreshFragment() + composeRule.waitUntilTrue { shownNames() == listOf("dirB", "dirA", "b.txt", "a.txt") } + } + + @Test + fun searchShowsResultsWithFolderTitles() { + launch() + val search = activity().findViewById<EditText>(org.fossify.commons.R.id.top_toolbar_search) + search.setText("i") + composeRule.waitForIdle() + composeRule.onNodeWithText(text(R.string.type_2_characters)).assertIsDisplayed() + + search.setText("inner") + composeRule.waitUntilTrue { shownNames().contains("inner.txt") } + composeRule.onNodeWithTag(FilesTabTestTags.section(path("dirA"))).assertIsDisplayed() + + search.setText("nothing-matches") + composeRule.waitUntilTrue { fragment().state.placeholder.name == "NO_ITEMS" } + composeRule.onNodeWithText(text(R.string.no_items_found)).assertIsDisplayed() + + search.setText("") + composeRule.waitUntilTrue { shownNames() == listOf("dirA", "dirB", "a.txt", "b.txt") } + } + + @Test + fun gridViewAndPinchChangeColumns() { + testConfig.viewType = VIEW_TYPE_GRID + testConfig.fileColumnCnt = 3 + launch() + assertTrue(fragment().state.isGrid) + // folders come first, a divider starts the files on a new row + assertTrue(fragment().state.items.any { it.isGridTypeDivider }) + + composeRule.onNodeWithTag(FilesTabTestTags.LIST).performTouchInput { + pinch( + start0 = center - Offset(20f, 0f), + end0 = center - Offset(300f, 0f), + start1 = center + Offset(20f, 0f), + end1 = center + Offset(300f, 0f) + ) + } + composeRule.waitUntilTrue { testConfig.fileColumnCnt == 2 && fragment().state.columnCount == 2 } + + composeRule.onNodeWithTag(FilesTabTestTags.LIST).performTouchInput { + pinch( + start0 = center - Offset(300f, 0f), + end0 = center - Offset(20f, 0f), + start1 = center + Offset(300f, 0f), + end1 = center + Offset(20f, 0f) + ) + } + composeRule.waitUntilTrue { testConfig.fileColumnCnt == 3 && fragment().state.columnCount == 3 } + + // a selected folder shows the check mark in the grid + longPress("dirA") + composeRule.onAllNodesWithTag(FilesTabTestTags.check(path("dirA")), useUnmergedTree = true) + .fetchSemanticsNodes().let { assertEquals(1, it.size) } + } + + @Test + fun keepsTheFolderWhenRecreated() { + launch() + composeRule.onNodeWithTag(FilesTabTestTags.item(path("dirA"))).performClick() + waitForFolder(path("dirA")) + scenario!!.recreate() + waitForFolder(path("dirA")) + assertEquals(listOf("sub", "inner.txt"), shownNames()) + } +} diff --git a/app/src/test/kotlin/org/fossify/filemanager/ui/ManageFavoritesScreenTest.kt b/app/src/test/kotlin/org/fossify/filemanager/ui/ManageFavoritesScreenTest.kt new file mode 100644 index 0000000..30b49b5 --- /dev/null +++ b/app/src/test/kotlin/org/fossify/filemanager/ui/ManageFavoritesScreenTest.kt @@ -0,0 +1,146 @@ +package org.fossify.filemanager.ui + +import android.content.DialogInterface +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createEmptyComposeRule +import androidx.compose.ui.test.longClick +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTouchInput +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.FavoritesActivity +import org.fossify.filemanager.compose.ManageFavoritesTestTags +import org.fossify.filemanager.compose.TopBarTestTags +import org.junit.After +import org.junit.Before +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.annotation.Config + +@RunWith(AndroidJUnit4::class) +@Config(sdk = [34], qualifiers = "w411dp-h914dp-xxhdpi") +class ManageFavoritesScreenTest { + @get:Rule + val composeRule = createEmptyComposeRule() + + private var scenario: ActivityScenario<FavoritesActivity>? = null + + private val first = "/storage/emulated/0/Download" + private val second = "/storage/emulated/0/Music" + + @Before + fun setUp() { + grantAllFilesAccess() + } + + @After + fun tearDown() { + scenario?.close() + } + + private fun launch(): ActivityScenario<FavoritesActivity> { + return ActivityScenario.launch(FavoritesActivity::class.java).also { + scenario = it + composeRule.waitForIdle() + } + } + + private fun text(id: Int) = appContext.getString(id) + + @Test + fun emptyStateShowsPlaceholderAndAddAction() { + launch() + composeRule.onNodeWithText(text(R.string.manage_favorites)).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.favorites_activity_placeholder)).assertIsDisplayed() + composeRule.onNodeWithTag(ManageFavoritesTestTags.PLACEHOLDER_ADD).assertIsDisplayed().performClick() + composeRule.waitForIdle() + + // the folder picker from Fossify Commons opens, picking a folder adds it + latestAlertDialog().getButton(DialogInterface.BUTTON_POSITIVE).performClick() + composeRule.waitUntilTrue { testConfig.favorites.isNotEmpty() } + val added = testConfig.favorites.single() + composeRule.onNodeWithText(added).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.favorites_activity_placeholder)).assertDoesNotExist() + } + + @Test + fun topBarAddActionOpensFolderPicker() { + launch() + composeRule.onNodeWithContentDescription(text(R.string.add_favorites)).performClick() + composeRule.waitForIdle() + val dialog = latestAlertDialog() + dialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick() + composeRule.waitForIdle() + assertTrue(testConfig.favorites.isEmpty()) + } + + @Test + fun listsAndRemovesFavoritesFromRowMenu() { + testConfig.addFavorite(first) + testConfig.addFavorite(second) + launch() + composeRule.onNodeWithText(first).assertIsDisplayed() + composeRule.onNodeWithText(second).assertIsDisplayed() + + composeRule.onNodeWithTag(ManageFavoritesTestTags.itemMenu(first)).performClick() + composeRule.onNodeWithText(text(R.string.remove)).performClick() + composeRule.waitForIdle() + assertEquals(setOf(second), testConfig.favorites) + composeRule.onNodeWithText(first).assertDoesNotExist() + + composeRule.onNodeWithTag(ManageFavoritesTestTags.itemMenu(second)).performClick() + composeRule.onNodeWithText(text(R.string.remove)).performClick() + composeRule.waitForIdle() + assertTrue(testConfig.favorites.isEmpty()) + composeRule.onNodeWithText(text(R.string.favorites_activity_placeholder)).assertIsDisplayed() + } + + @Test + fun longPressSelectsAndContextualBarRemoves() { + testConfig.addFavorite(first) + testConfig.addFavorite(second) + val scenario = launch() + + composeRule.onNodeWithTag(ManageFavoritesTestTags.item(first)).performTouchInput { longClick() } + composeRule.onNodeWithText("1 / 2").assertIsDisplayed() + + // selection survives rotation + scenario.recreate() + composeRule.waitForIdle() + composeRule.onNodeWithText("1 / 2").assertIsDisplayed() + + // tapping the title selects everything + composeRule.onNodeWithTag(TopBarTestTags.ACTION_MODE_TITLE).performClick() + composeRule.onNodeWithText("2 / 2").assertIsDisplayed() + + // tapping a selected row deselects it + composeRule.onNodeWithTag(ManageFavoritesTestTags.item(second)).performClick() + composeRule.onNodeWithText("1 / 2").assertIsDisplayed() + + composeRule.onNodeWithContentDescription(text(R.string.remove)).performClick() + composeRule.waitForIdle() + assertEquals(setOf(second), testConfig.favorites) + composeRule.onNodeWithText(first).assertDoesNotExist() + composeRule.onNodeWithText(text(R.string.manage_favorites)).assertIsDisplayed() + } + + @Test + fun backLeavesSelectionModeFirst() { + testConfig.addFavorite(first) + val scenario = launch() + composeRule.onNodeWithTag(ManageFavoritesTestTags.item(first)).performTouchInput { longClick() } + composeRule.onNodeWithText("1 / 1").assertIsDisplayed() + scenario.onActivity { it.onBackPressedDispatcher.onBackPressed() } + composeRule.waitForIdle() + composeRule.onNodeWithText("1 / 1").assertDoesNotExist() + composeRule.onNodeWithText(text(R.string.manage_favorites)).assertIsDisplayed() + assertEquals(setOf(first), testConfig.favorites) + } +} diff --git a/app/src/test/kotlin/org/fossify/filemanager/ui/ReadTextScreenTest.kt b/app/src/test/kotlin/org/fossify/filemanager/ui/ReadTextScreenTest.kt new file mode 100644 index 0000000..5dfa621 --- /dev/null +++ b/app/src/test/kotlin/org/fossify/filemanager/ui/ReadTextScreenTest.kt @@ -0,0 +1,212 @@ +package org.fossify.filemanager.ui + +import android.content.DialogInterface +import android.content.Intent +import android.net.Uri +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.SemanticsNodeInteraction +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.junit4.createEmptyComposeRule +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextInputSelection +import androidx.compose.ui.test.performTextReplacement +import androidx.compose.ui.text.TextRange +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.ReadTextActivity +import org.fossify.filemanager.compose.ReadTextTestTags +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowToast +import java.io.ByteArrayInputStream +import java.io.File + +@RunWith(AndroidJUnit4::class) +@Config(sdk = [34], qualifiers = "w411dp-h914dp-xxhdpi") +class ReadTextScreenTest { + @get:Rule + val composeRule = createEmptyComposeRule() + + private var scenario: ActivityScenario<ReadTextActivity>? = null + private lateinit var activity: ReadTextActivity + private lateinit var file: File + + private val content = listOf( + "First line has an apple", + "second line plain", + "third: green apple pie", + "fourth line", + "last apple here", + ).joinToString(separator = "\n", postfix = "\n") + + @Before + fun setUp() { + grantAllFilesAccess() + file = File(appContext.cacheDir, "notes.txt").apply { writeText(content) } + } + + @After + fun tearDown() { + scenario?.close() + } + + private fun text(id: Int) = appContext.getString(id) + + private fun launch(intent: Intent = viewIntent(Uri.fromFile(file))): ActivityScenario<ReadTextActivity> { + return ActivityScenario.launch<ReadTextActivity>(intent).also { + scenario = it + it.onActivity { launched -> activity = launched } + composeRule.waitUntilTrue { editorText() != null && editorText()!!.isNotEmpty() } + } + } + + private fun viewIntent(uri: Uri) = Intent(appContext, ReadTextActivity::class.java).apply { + action = Intent.ACTION_VIEW + setDataAndType(uri, "text/plain") + } + + private fun editor(): SemanticsNodeInteraction = composeRule.onNodeWithTag(ReadTextTestTags.EDITOR) + + private fun editorText(): String? { + return runCatching { + editor().fetchSemanticsNode().config[SemanticsProperties.EditableText].text + }.getOrNull() + } + + private fun editorSelection(): TextRange { + return editor().fetchSemanticsNode().config[SemanticsProperties.TextSelectionRange] + } + + @Test + fun opensFileFromFilesTabWithTitleAndMenu() { + launch() + composeRule.onNodeWithText("notes.txt").assertIsDisplayed() + assertEquals(content, editorText()) + composeRule.onNodeWithContentDescription(text(R.string.search)).assertIsDisplayed() + composeRule.onNodeWithContentDescription(text(R.string.save)).assertIsDisplayed() + + composeRule.onNodeWithContentDescription(text(R.string.more_options)).performClick() + composeRule.onNodeWithText(text(R.string.save_as)).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.print)).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.open_with)).assertIsDisplayed() + } + + @Test + fun opensContentFromOtherApps() { + val uri = Uri.parse("content://org.example.provider/shared%20note.txt") + shadowOf(appContext.contentResolver).registerInputStream(uri, ByteArrayInputStream("shared text".toByteArray())) + launch(viewIntent(uri)) + assertEquals("shared text", editorText()) + } + + @Test + fun savesInPlace() { + launch() + editor().performTextReplacement("changed text") + composeRule.onNodeWithContentDescription(text(R.string.save)).performClick() + composeRule.waitUntilTrue { file.readText() == "changed text" } + assertEquals(text(R.string.file_saved), ShadowToast.getTextOfLatestToast()) + + // nothing unsaved anymore, back leaves without asking + activity.onBackPressedDispatcher.onBackPressed() + idleMainLooper() + assertTrue(activity.isFinishing) + } + + @Test + fun asksToSaveWhenLeavingWithUnsavedChanges() { + launch() + editor().performTextReplacement("unsaved") + activity.onBackPressedDispatcher.onBackPressed() + val dialog = latestAlertDialog() + assertEquals(text(R.string.save), dialog.getButton(DialogInterface.BUTTON_POSITIVE).text.toString()) + assertEquals(text(R.string.discard), dialog.getButton(DialogInterface.BUTTON_NEGATIVE).text.toString()) + + dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick() + composeRule.waitUntilTrue { file.readText() == "unsaved" } + assertTrue(activity.isFinishing) + } + + @Test + fun discardLeavesFileUntouched() { + launch() + editor().performTextReplacement("unsaved") + activity.onBackPressedDispatcher.onBackPressed() + latestAlertDialog().getButton(DialogInterface.BUTTON_NEGATIVE).performClick() + idleMainLooper() + assertTrue(activity.isFinishing) + assertEquals(content, file.readText()) + } + + @Test + fun findsTextWithPreviousAndNext() { + launch() + val matches = listOf(content.indexOf("apple"), content.indexOf("apple", 20), content.lastIndexOf("apple")) + composeRule.onNodeWithContentDescription(text(R.string.search)).performClick() + composeRule.onNodeWithTag(ReadTextTestTags.SEARCH_FIELD).assertIsDisplayed().performTextInput("apple") + composeRule.waitForIdle() + assertEquals(TextRange(matches[0]), editorSelection()) + + composeRule.onNodeWithContentDescription(text(R.string.next)).performClick() + assertEquals(TextRange(matches[1]), editorSelection()) + composeRule.onNodeWithContentDescription(text(R.string.next)).performClick() + assertEquals(TextRange(matches[2]), editorSelection()) + composeRule.onNodeWithContentDescription(text(R.string.next)).performClick() + assertEquals(TextRange(matches[0]), editorSelection()) + composeRule.onNodeWithContentDescription(text(R.string.previous)).performClick() + assertEquals(TextRange(matches[2]), editorSelection()) + + // back closes the search first, the editor stays open + activity.onBackPressedDispatcher.onBackPressed() + composeRule.waitForIdle() + composeRule.onNodeWithTag(ReadTextTestTags.SEARCH_FIELD).assertDoesNotExist() + assertTrue(!activity.isFinishing) + + composeRule.onNodeWithContentDescription(text(R.string.search)).performClick() + composeRule.onNodeWithContentDescription(text(R.string.close)).performClick() + composeRule.onNodeWithTag(ReadTextTestTags.SEARCH_FIELD).assertDoesNotExist() + } + + @Test + fun unsavedEditsCursorAndSearchSurviveRotation() { + val scenario = launch() + editor().performTextReplacement("edited apple text") + editor().performTextInputSelection(TextRange(4)) + composeRule.onNodeWithContentDescription(text(R.string.search)).performClick() + composeRule.onNodeWithTag(ReadTextTestTags.SEARCH_FIELD).performTextInput("te") + composeRule.waitForIdle() + val selectionBefore = editorSelection() + + scenario.recreate() + composeRule.waitForIdle() + + assertEquals("edited apple text", editorText()) + assertEquals(selectionBefore, editorSelection()) + composeRule.onNodeWithTag(ReadTextTestTags.SEARCH_FIELD).assertTextEquals("te") + assertEquals(content, file.readText()) + } + + @Test + fun cursorSurvivesRotationWithoutSearch() { + val scenario = launch() + editor().performTextReplacement("0123456789") + editor().performTextInputSelection(TextRange(7)) + scenario.recreate() + composeRule.waitForIdle() + assertEquals("0123456789", editorText()) + assertEquals(TextRange(7), editorSelection()) + } +} diff --git a/app/src/test/kotlin/org/fossify/filemanager/ui/SettingsScreenTest.kt b/app/src/test/kotlin/org/fossify/filemanager/ui/SettingsScreenTest.kt new file mode 100644 index 0000000..be9719c --- /dev/null +++ b/app/src/test/kotlin/org/fossify/filemanager/ui/SettingsScreenTest.kt @@ -0,0 +1,224 @@ +package org.fossify.filemanager.ui + +import android.content.DialogInterface +import android.widget.RadioButton +import android.widget.RadioGroup +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsOff +import androidx.compose.ui.test.assertIsOn +import androidx.compose.ui.test.hasParent +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isToggleable +import androidx.compose.ui.test.junit4.createEmptyComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.fossify.commons.activities.CustomizationActivity +import org.fossify.commons.helpers.FONT_SIZE_LARGE +import org.fossify.commons.helpers.TAB_FILES +import org.fossify.commons.helpers.TAB_RECENT_FILES +import org.fossify.commons.helpers.TAB_STORAGE_ANALYSIS +import org.fossify.filemanager.R +import org.fossify.filemanager.activities.FavoritesActivity +import org.fossify.filemanager.activities.SettingsActivity +import org.fossify.filemanager.helpers.ALL_TABS_MASK +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@RunWith(AndroidJUnit4::class) +@Config(sdk = [34], qualifiers = "w411dp-h914dp-xxhdpi") +class SettingsScreenTest { + @get:Rule + val composeRule = createEmptyComposeRule() + + private var scenario: ActivityScenario<SettingsActivity>? = null + + @After + fun tearDown() { + scenario?.close() + } + + private fun launch(): ActivityScenario<SettingsActivity> { + return ActivityScenario.launch(SettingsActivity::class.java).also { + scenario = it + composeRule.waitForIdle() + } + } + + private fun text(id: Int) = appContext.getString(id) + + private fun switchOf(labelId: Int) = composeRule.onNode(isToggleable() and hasParent(hasText(text(labelId)))) + + private fun clickRow(labelId: Int) { + composeRule.onNodeWithText(text(labelId)).performScrollTo().performClick() + composeRule.waitForIdle() + } + + @Test + fun showsEverySectionAndRow() { + launch() + composeRule.onNodeWithText(text(R.string.settings)).assertIsDisplayed() + val labels = listOf( + R.string.color_customization, + R.string.customize_colors, + R.string.general_settings, + R.string.language, + R.string.manage_favorites, + R.string.manage_shown_tabs, + R.string.change_date_and_time_format, + R.string.font_size, + R.string.press_back_twice, + R.string.visibility, + R.string.show_hidden_items, + R.string.scrolling, + R.string.enable_pull_to_refresh, + R.string.file_operations, + R.string.keep_last_modified, + R.string.skip_delete_confirmation, + R.string.security, + R.string.password_protect_hidden_items, + R.string.password_protect_whole_app, + R.string.password_protect_file_deletion, + ) + labels.forEach { composeRule.onNodeWithText(text(it)).performScrollTo().assertIsDisplayed() } + composeRule.onNodeWithText(text(R.string.medium)).assertExists() + + // rows that are only shown in some situations + composeRule.onNodeWithText(text(R.string.enable_root_access)).assertDoesNotExist() + composeRule.onNodeWithText(text(R.string.use_english_language)).assertDoesNotExist() + } + + @Test + fun rootAccessRowIsShownWhenRootIsAvailable() { + testConfig.isRootAvailable = true + launch() + composeRule.onNodeWithText(text(R.string.enable_root_access)).performScrollTo().assertIsDisplayed() + switchOf(R.string.enable_root_access).assertIsOff() + } + + @Test + fun switchesWriteTheSamePreferencesAsBefore() { + launch() + val config = testConfig + assertTrue(config.pressBackTwice) + switchOf(R.string.press_back_twice).performScrollTo().assertIsOn() + clickRow(R.string.press_back_twice) + assertFalse(config.pressBackTwice) + switchOf(R.string.press_back_twice).assertIsOff() + + assertFalse(config.showHidden) + clickRow(R.string.show_hidden_items) + assertTrue(config.showHidden) + switchOf(R.string.show_hidden_items).assertIsOn() + + clickRow(R.string.enable_pull_to_refresh) + assertFalse(config.enablePullToRefresh) + + clickRow(R.string.keep_last_modified) + assertFalse(config.keepLastModified) + + clickRow(R.string.skip_delete_confirmation) + assertTrue(config.skipDeleteConfirmation) + switchOf(R.string.skip_delete_confirmation).assertIsOn() + + val prefs = appContext.getSharedPreferences("Prefs", 0) + assertEquals(false, prefs.getBoolean("press_back_twice", true)) + assertEquals(true, prefs.getBoolean("show_hidden", false)) + assertEquals(false, prefs.getBoolean("enable_pull_to_refresh", true)) + assertEquals(false, prefs.getBoolean("keep_last_modified", true)) + assertEquals(true, prefs.getBoolean("skip_delete_confirmation", false)) + } + + @Test + fun storedValuesAreShownAndSurviveRecreation() { + testConfig.showHidden = true + testConfig.pressBackTwice = false + val scenario = launch() + switchOf(R.string.show_hidden_items).performScrollTo().assertIsOn() + switchOf(R.string.press_back_twice).performScrollTo().assertIsOff() + + clickRow(R.string.skip_delete_confirmation) + scenario.recreate() + composeRule.waitForIdle() + switchOf(R.string.skip_delete_confirmation).performScrollTo().assertIsOn() + switchOf(R.string.show_hidden_items).performScrollTo().assertIsOn() + } + + @Test + fun fontSizeDialogUpdatesValue() { + launch() + clickRow(R.string.font_size) + val dialog = latestAlertDialog() + val radioGroup = dialog.findViewById<RadioGroup>(org.fossify.commons.R.id.dialog_radio_group)!! + val large = (0 until radioGroup.childCount) + .map { radioGroup.getChildAt(it) as RadioButton } + .first { it.text == text(R.string.large) } + large.performClick() + idleMainLooper() + composeRule.waitForIdle() + assertEquals(FONT_SIZE_LARGE, testConfig.fontSize) + composeRule.onNodeWithText(text(R.string.large)).performScrollTo().assertIsDisplayed() + } + + @Test + fun manageShownTabsDialogStoresMask() { + launch() + clickRow(R.string.manage_shown_tabs) + composeRule.onNodeWithText(text(R.string.files_tab)).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.storage_analysis)).assertIsDisplayed() + composeRule.onNodeWithText(text(R.string.recent_files_tab)).performClick() + composeRule.onNodeWithText(text(R.string.ok)).performClick() + composeRule.waitForIdle() + assertEquals(TAB_FILES or TAB_STORAGE_ANALYSIS, testConfig.showTabs) + + // unchecking everything falls back to showing all tabs + clickRow(R.string.manage_shown_tabs) + composeRule.onNodeWithText(text(R.string.files_tab)).performClick() + composeRule.onNodeWithText(text(R.string.storage_analysis)).performClick() + composeRule.onNodeWithText(text(R.string.ok)).performClick() + composeRule.waitForIdle() + assertEquals(ALL_TABS_MASK, testConfig.showTabs) + + // cancel keeps the stored value + testConfig.showTabs = TAB_RECENT_FILES + clickRow(R.string.manage_shown_tabs) + composeRule.onNodeWithText(text(R.string.files_tab)).performClick() + composeRule.onNodeWithText(text(R.string.cancel)).performClick() + composeRule.waitForIdle() + assertEquals(TAB_RECENT_FILES, testConfig.showTabs) + } + + @Test + fun rowsOpenTheirScreensAndDialogs() { + val scenario = launch() + clickRow(R.string.customize_colors) + scenario.onActivity { + val started = shadowOf(it).nextStartedActivity + assertEquals(CustomizationActivity::class.java.name, started.component?.className) + } + + clickRow(R.string.manage_favorites) + scenario.onActivity { + val started = shadowOf(it).nextStartedActivity + assertEquals(FavoritesActivity::class.java.name, started.component?.className) + } + + clickRow(R.string.change_date_and_time_format) + latestAlertDialog().getButton(DialogInterface.BUTTON_NEGATIVE).performClick() + + clickRow(R.string.password_protect_whole_app) + assertNotNull(latestShownDialog()) + latestAlertDialog().dismiss() + assertFalse(testConfig.isAppPasswordProtectionOn) + } +} diff --git a/app/src/test/kotlin/org/fossify/filemanager/ui/TestHelpers.kt b/app/src/test/kotlin/org/fossify/filemanager/ui/TestHelpers.kt new file mode 100644 index 0000000..f3ac425 --- /dev/null +++ b/app/src/test/kotlin/org/fossify/filemanager/ui/TestHelpers.kt @@ -0,0 +1,67 @@ +package org.fossify.filemanager.ui + +import android.Manifest +import android.app.AppOpsManager +import android.app.Dialog +import android.content.Context +import android.os.Looper +import android.os.Process +import androidx.appcompat.app.AlertDialog +import androidx.compose.ui.test.junit4.ComposeTestRule +import androidx.test.core.app.ApplicationProvider +import org.fossify.filemanager.helpers.Config +import org.robolectric.Shadows.shadowOf +import org.robolectric.shadows.ShadowDialog +import org.robolectric.shadows.ShadowEnvironment + +internal val appContext: Context + get() = ApplicationProvider.getApplicationContext() + +internal val testConfig: Config + get() = Config.newInstance(appContext) + +/** Lets [SimpleActivity.hasStoragePermission] succeed, like granting "All files access" on a device. */ +internal fun grantAllFilesAccess() { + val application = ApplicationProvider.getApplicationContext<android.app.Application>() + ShadowEnvironment.addExternalDir("external_storage") + val packageManager = shadowOf(application.packageManager) + packageManager.setPackagesForUid(Process.myUid(), application.packageName) + packageManager.setPackagesForUid(application.applicationInfo.uid, application.packageName) + shadowOf(application).grantPermissions( + Manifest.permission.MANAGE_EXTERNAL_STORAGE, + Manifest.permission.WRITE_EXTERNAL_STORAGE + ) +} + +/** + * Robolectric lets every app manage media, a regular install of the app can not. Without this the delete and rename + * helpers of Fossify Commons take the MediaStore request path, which Robolectric does not implement. + */ +internal fun denyManageMedia() { + val appOpsManager = appContext.getSystemService(AppOpsManager::class.java) + shadowOf(appOpsManager) + .setMode("android:manage_media", Process.myUid(), appContext.packageName, AppOpsManager.MODE_ERRORED) +} + +internal fun idleMainLooper() { + shadowOf(Looper.getMainLooper()).idle() +} + +/** The latest view based (Fossify Commons) dialog, if it is currently showing. */ +internal fun latestShownDialog(): Dialog? { + idleMainLooper() + return ShadowDialog.getLatestDialog()?.takeIf { it.isShowing } +} + +internal fun latestAlertDialog(): AlertDialog { + val dialog = latestShownDialog() + check(dialog is AlertDialog) { "Expected a showing AlertDialog but got $dialog" } + return dialog +} + +internal fun ComposeTestRule.waitUntilTrue(timeoutMillis: Long = 5_000, condition: () -> Boolean) { + waitUntil(timeoutMillis) { + idleMainLooper() + condition() + } +} diff --git a/build.gradle.kts b/build.gradle.kts index 360f5f4..7665d2b 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,4 +1,5 @@ plugins { alias(libs.plugins.android).apply(false) + alias(libs.plugins.kotlin.compose).apply(false) alias(libs.plugins.detekt).apply(false) } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 6c71eb8..22f8b5f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -5,16 +5,26 @@ kotlin = "2.3.10" detekt = "1.23.8" detektCompose = "0.4.28" #AndroidX +androidx-activity = "1.12.4" +androidx-compose-foundation = "1.8.1" +androidx-compose-material3 = "1.4.0" +androidx-compose-ui = "1.9.2" androidx-swiperefreshlayout = "1.2.0" androidx-documentfile = "1.1.0" #Fossify commons = "6.1.6" #Other autofittextview = "0.2.1" +kotlinx-collections-immutable = "0.4.0" gestureviews = "2.9.0" rootshell = "bc7e5d398e" roottools = "965c154e20" zip4j = "2.11.6" +#Testing +junit = "4.13.2" +androidx-test-runner = "1.6.2" +androidx-test-espresso = "3.6.1" +robolectric = "4.16" #Gradle gradlePlugins-agp = "9.4.0" #build @@ -25,9 +35,14 @@ app-build-javaVersion = "VERSION_17" app-build-kotlinJVMTarget = "17" [libraries] #AndroidX +androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activity" } androidx-swiperefreshlayout = { module = "androidx.swiperefreshlayout:swiperefreshlayout", version.ref = "androidx-swiperefreshlayout" } androidx-documentfile = { module = "androidx.documentfile:documentfile", version.ref = "androidx-documentfile" } #Compose +androidx-compose-foundation = { module = "androidx.compose.foundation:foundation", version.ref = "androidx-compose-foundation" } +androidx-compose-material3 = { module = "androidx.compose.material3:material3", version.ref = "androidx-compose-material3" } +androidx-compose-ui = { module = "androidx.compose.ui:ui", version.ref = "androidx-compose-ui" } +androidx-compose-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "androidx-compose-ui" } compose-detekt = { module = "io.nlopez.compose.rules:detekt", version.ref = "detektCompose" } #Fossify fossify-commons = { module = "org.fossify:commons", version.ref = "commons" } @@ -37,6 +52,13 @@ gestureviews = { module = "com.alexvasilkov:gesture-views", version.ref = "gestu rootshell = { module = "com.github.naveensingh:RootShell", version.ref = "rootshell" } roottools = { module = "com.github.naveensingh:RootTools", version.ref = "roottools" } zip4j = { module = "net.lingala.zip4j:zip4j", version.ref = "zip4j" } +kotlinx-collections-immutable = { module = "org.jetbrains.kotlinx:kotlinx-collections-immutable", version.ref = "kotlinx-collections-immutable" } +#Testing +junit = { module = "junit:junit", version.ref = "junit" } +androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidx-test-runner" } +androidx-test-espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "androidx-test-espresso" } +robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectric" } [plugins] android = { id = "com.android.application", version.ref = "gradlePlugins-agp" } +kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" }
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 5715433..be0afc1 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -5,6 +5,7 @@ import java.io.FileInputStream
plugins {
alias(libs.plugins.android)
+ alias(libs.plugins.kotlin.compose)
alias(libs.plugins.detekt)
}
@@ -37,6 +38,7 @@ android {
versionCode = project.property("VERSION_CODE").toString().toInt()
multiDexEnabled = true
vectorDrawables.useSupportLibrary = true
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
signingConfigs {
@@ -62,6 +64,14 @@ android {
buildFeatures {
viewBinding = true
buildConfig = true
+ compose = true
+ }
+
+ testOptions {
+ unitTests {
+ isIncludeAndroidResources = true
+ all { it.maxHeapSize = "3g" }
+ }
}
buildTypes {
@@ -89,6 +99,8 @@ android {
sourceSets {
getByName("main").java.directories.add("src/main/kotlin")
+ getByName("test").java.directories.add("src/test/kotlin")
+ getByName("androidTest").java.directories.add("src/androidTest/kotlin")
}
compileOptions {
@@ -145,5 +157,16 @@ dependencies {
implementation(libs.gestureviews)
implementation(libs.autofittextview)
implementation(libs.zip4j)
+ implementation(libs.androidx.activity.compose)
+ implementation(libs.androidx.compose.ui)
+ implementation(libs.androidx.compose.foundation)
+ implementation(libs.androidx.compose.material3)
+ implementation(libs.kotlinx.collections.immutable)
+ testImplementation(libs.junit)
+ testImplementation(libs.robolectric)
+ testImplementation(libs.androidx.compose.ui.test.junit4)
+ androidTestImplementation(libs.androidx.test.runner)
+ androidTestImplementation(libs.androidx.test.espresso.core)
+ androidTestImplementation(libs.androidx.compose.ui.test.junit4)
detektPlugins(libs.compose.detekt)
}
diff --git a/app/src/androidTest/kotlin/org/fossify/filemanager/ui/FilesTabCreateTest.kt b/app/src/androidTest/kotlin/org/fossify/filemanager/ui/FilesTabCreateTest.kt
new file mode 100644
index 0000000..8ddc51b
--- /dev/null
+++ b/app/src/androidTest/kotlin/org/fossify/filemanager/ui/FilesTabCreateTest.kt
@@ -0,0 +1,120 @@
+package org.fossify.filemanager.ui
+
+import android.content.Context
+import android.os.Environment
+import android.os.ParcelFileDescriptor
+import androidx.compose.ui.test.assertIsDisplayed
+import androidx.compose.ui.test.junit4.createEmptyComposeRule
+import androidx.compose.ui.test.onAllNodesWithTag
+import androidx.compose.ui.test.onNodeWithTag
+import androidx.compose.ui.test.onNodeWithText
+import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.performTextInput
+import androidx.test.core.app.ActivityScenario
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import org.fossify.commons.helpers.TAB_FILES
+import org.fossify.filemanager.R
+import org.fossify.filemanager.activities.MainActivity
+import org.fossify.filemanager.compose.FilesTabTestTags
+import org.fossify.filemanager.helpers.Config
+import org.junit.After
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import java.io.File
+
+/**
+ * The Compose "Create new" dialog of the Files tab. Robolectric can't idle while a text field is shown inside a
+ * Compose dialog, so these run on a device or emulator (`connectedFossDebugAndroidTest`).