Download tasks/efflora__fossify-viewmodel-layer/solution/solution.patch from efflora/android-bench-sample: direct link, hf CLI and curl.
- Browser
- Download file 216 kB
-
https://huggingface.co/datasets/efflora/android-bench-sample/resolve/main/tasks/efflora__fossify-viewmodel-layer/solution/solution.patch
- Command line
-
hf download hf://datasets/efflora/android-bench-sample/tasks/efflora__fossify-viewmodel-layer/solution/solution.patch
-
curl -L -o solution.patch https://huggingface.co/datasets/efflora/android-bench-sample/resolve/main/tasks/efflora__fossify-viewmodel-layer/solution/solution.patch
216 kB
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 5715433..4acbe05 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -89,6 +89,7 @@ android {
sourceSets {
getByName("main").java.directories.add("src/main/kotlin")
+ getByName("test").java.directories.add("src/test/kotlin")
}
compileOptions {
@@ -140,10 +141,18 @@ dependencies {
implementation(libs.fossify.commons)
implementation(libs.androidx.documentfile)
implementation(libs.androidx.swiperefreshlayout)
+ implementation(libs.androidx.activity.ktx)
+ implementation(libs.androidx.lifecycle.runtime.ktx)
+ implementation(libs.androidx.lifecycle.viewmodel.ktx)
+ implementation(libs.androidx.lifecycle.viewmodel.savedstate)
+ implementation(libs.kotlinx.coroutines.android)
implementation(libs.roottools)
implementation(libs.rootshell)
implementation(libs.gestureviews)
implementation(libs.autofittextview)
implementation(libs.zip4j)
detektPlugins(libs.compose.detekt)
+
+ testImplementation(libs.junit)
+ testImplementation(libs.kotlinx.coroutines.test)
}
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..ddc34ef 100644
--- a/app/src/main/kotlin/org/fossify/filemanager/activities/MainActivity.kt
+++ b/app/src/main/kotlin/org/fossify/filemanager/activities/MainActivity.kt
@@ -79,7 +79,6 @@ class MainActivity : SimpleActivity() {
companion object {
private const val BACK_PRESS_TIMEOUT = 5000
- private const val PICKED_PATH = "picked_path"
}
private val binding by viewBinding(ActivityMainBinding::inflate)
@@ -260,21 +259,31 @@ class MainActivity : SimpleActivity() {
}
}
- override fun onSaveInstanceState(outState: Bundle) {
- super.onSaveInstanceState(outState)
- outState.putString(PICKED_PATH, getItemsFragment()?.currentPath ?: "")
- }
-
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
- val path = savedInstanceState.getString(PICKED_PATH) ?: internalStoragePath
-
+ // the tabs' ViewModels keep (or restore from their saved state) the folder, search and selection
if (binding.mainViewPager.adapter == null) {
binding.mainViewPager.onGlobalLayout {
- openPath(path, true)
+ restoreTabsState()
}
} else {
- openPath(path, true)
+ restoreTabsState()
+ }
+ }
+
+ private fun restoreTabsState() {
+ getItemsFragment()?.openInitialPathIfNeeded(internalStoragePath)
+ val query = getCurrentFragment()?.getSearchQuery().orEmpty()
+ if (query.isNotEmpty() && !binding.mainMenu.isSearchOpen) {
+ // the search field only opens the search once its focus listener is set, which MySearchMenu does in a post
+ binding.mainMenu.post {
+ binding.mainMenu.focusView()
+ binding.mainMenu.binding.topToolbarSearch.apply {
+ setText(query)
+ setSelection(query.length)
+ }
+ hideKeyboard()
+ }
}
}
@@ -456,7 +465,7 @@ class MainActivity : SimpleActivity() {
}
}
- private fun openPath(path: String, forceRefresh: Boolean = false) {
+ private fun openPath(path: String) {
var newPath = path
val file = File(path)
if (config.OTGPath.isNotEmpty() && config.OTGPath == path.trimEnd('/')) {
@@ -467,7 +476,7 @@ class MainActivity : SimpleActivity() {
newPath = internalStoragePath
}
- getItemsFragment()?.openPath(newPath, forceRefresh)
+ getItemsFragment()?.openPath(newPath)
}
private fun goHome() {
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..1564475 100644
--- a/app/src/main/kotlin/org/fossify/filemanager/adapters/ItemsAdapter.kt
+++ b/app/src/main/kotlin/org/fossify/filemanager/adapters/ItemsAdapter.kt
@@ -152,6 +152,8 @@ class ItemsAdapter(
}
private val isListViewType = viewType == VIEW_TYPE_LIST
private var displayFilenamesInGrid = config.displayFilenames
+ private var lastReportedSelection = emptySet<String>()
+ private var isRestoringSelection = false
companion object {
private const val TYPE_FILE = 1
@@ -183,6 +185,7 @@ class ItemsAdapter(
checkHideBtnVisibility(this)
}
+ reportSelection()
}
override fun actionItemPressed(id: Int) {
@@ -234,6 +237,46 @@ class ItemsAdapter(
override fun onActionModeDestroyed() {
swipeRefreshLayout?.isEnabled = config.enablePullToRefresh
+ reportSelection()
+ }
+
+ private fun reportSelection() {
+ if (isRestoringSelection) {
+ return
+ }
+
+ val selection = getSelectedPaths()
+ if (selection != lastReportedSelection) {
+ lastReportedSelection = selection
+ listener?.selectionChanged(selection)
+ }
+ }
+
+ fun getSelectedPaths(): Set<String> = getSelectedFileDirItems().mapTo(LinkedHashSet()) { it.path }
+
+ fun hasActiveSelection() = actMode != null && selectedKeys.isNotEmpty()
+
+ /** Re-selects the items with the given paths after the screen was recreated, starting the action mode if needed. */
+ fun restoreSelection(paths: Set<String>) {
+ val positions = listItems.indices.filter {
+ val item = listItems[it]
+ !item.isSectionTitle && !item.isGridTypeDivider && item.path in paths
+ }
+
+ if (positions.isEmpty() || getSelectedPaths() == paths) {
+ return
+ }
+
+ isRestoringSelection = true
+ try {
+ if (actMode == null) {
+ activity.startActionMode(actModeCallback)
+ }
+ positions.forEach { toggleItemSelection(true, it) }
+ } finally {
+ isRestoringSelection = false
+ }
+ reportSelection()
}
override fun getItemViewType(position: Int): Int {
@@ -955,10 +998,10 @@ class ItemsAdapter(
positions.sortDescending()
activity.runOnUiThread {
removeSelectedItems(positions)
- listener?.deleteFiles(files)
positions.forEach {
listItems.removeAt(it)
}
+ listener?.deleteFiles(files)
}
}
}
@@ -985,6 +1028,13 @@ class ItemsAdapter(
}
}
+ /** Replaces items whose paths did not change (e.g. updated child counts), keeping the selection and scroll. */
+ fun replaceItemsInPlace(newItems: List<ListItem>) {
+ listItems = ArrayList(newItems)
+ currentItemsHash = listItems.hashCode()
+ notifyItemRangeChanged(0, listItems.size, Unit)
+ }
+
fun updateFontSizes() {
fontSize = activity.getTextSize()
smallerFontSize = fontSize * 0.8f
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..88d15be 100644
--- a/app/src/main/kotlin/org/fossify/filemanager/fragments/ItemsFragment.kt
+++ b/app/src/main/kotlin/org/fossify/filemanager/fragments/ItemsFragment.kt
@@ -1,14 +1,28 @@
package org.fossify.filemanager.fragments
-import android.annotation.SuppressLint
import android.content.Context
-import android.os.Parcelable
import android.util.AttributeSet
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.launch
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.adjustAlpha
+import org.fossify.commons.extensions.areSystemAnimationsEnabled
+import org.fossify.commons.extensions.beGone
+import org.fossify.commons.extensions.beVisible
+import org.fossify.commons.extensions.beVisibleIf
+import org.fossify.commons.extensions.getProperPrimaryColor
+import org.fossify.commons.extensions.getTextSize
+import org.fossify.commons.extensions.toast
+import org.fossify.commons.extensions.updateTextColors
+import org.fossify.commons.helpers.LOWER_ALPHA
+import org.fossify.commons.helpers.VIEW_TYPE_GRID
import org.fossify.commons.models.FileDirItem
import org.fossify.commons.views.Breadcrumbs
import org.fossify.commons.views.MyGridLayoutManager
@@ -20,24 +34,38 @@ import org.fossify.filemanager.adapters.ItemsAdapter
import org.fossify.filemanager.databinding.ItemsFragmentBinding
import org.fossify.filemanager.dialogs.CreateNewItemDialog
import org.fossify.filemanager.extensions.config
-import org.fossify.filemanager.extensions.isPathOnRoot
import org.fossify.filemanager.helpers.MAX_COLUMN_COUNT
-import org.fossify.filemanager.helpers.RootHelpers
import org.fossify.filemanager.interfaces.ItemOperationsListener
+import org.fossify.filemanager.models.FileItem
import org.fossify.filemanager.models.ListItem
-import java.io.File
-
-class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerFragment<MyViewPagerFragment.ItemsInnerBinding>(context, attributeSet),
+import org.fossify.filemanager.viewmodels.ItemsEvent
+import org.fossify.filemanager.viewmodels.ItemsUiState
+import org.fossify.filemanager.viewmodels.ItemsViewModel
+import org.fossify.filemanager.viewmodels.ScrollPosition
+
+/**
+ * The Files tab. It renders [ItemsUiState] from the activity scoped [ItemsViewModel] and forwards user actions to it.
+ */
+class ItemsFragment(context: Context, attributeSet: AttributeSet) :
+ MyViewPagerFragment<MyViewPagerFragment.ItemsInnerBinding>(context, attributeSet),
ItemOperationsListener,
Breadcrumbs.BreadcrumbsListener {
- private var showHidden = false
- private var lastSearchedText = ""
- private var scrollStates = HashMap<String, Parcelable>()
+ private lateinit var binding: ItemsFragmentBinding
+ private lateinit var viewModel: ItemsViewModel
+ private var observeJob: Job? = null
private var zoomListener: MyRecyclerView.MyZoomListener? = null
- private var storedItems = ArrayList<ListItem>()
- private var itemsIgnoringSearch = ArrayList<ListItem>()
- private lateinit var binding: ItemsFragmentBinding
+ // what is currently on screen, to only touch the views that need to change
+ private var renderedListingPath: String? = null
+ private var renderedItems: List<FileItem>? = null
+ private var renderedHighlight = ""
+ private var renderedQuery: String? = null
+ private var renderedCurrentPath: String? = null
+ private var renderedListing: List<FileItem>? = null
+ private var requestedSafAccessPath: String? = null
+
+ override val currentPath: String
+ get() = if (::viewModel.isInitialized) viewModel.uiState.value.currentPath else ""
override fun onFinishInflate() {
super.onFinishInflate()
@@ -46,24 +74,67 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF
}
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()
+ if (this.activity != null) {
+ return
+ }
+
+ this.activity = activity
+ val factory = ItemsViewModel.factory(activity.applicationContext, wantedMimeTypes)
+ viewModel = ViewModelProvider(activity, factory)[ItemsViewModel::class.java]
+
+ binding.apply {
+ breadcrumbs.listener = this@ItemsFragment
+ itemsSwipeRefresh.setOnRefreshListener { refreshFragment() }
+ itemsFab.setOnClickListener {
+ if (isCreateDocumentIntent) {
+ (activity as MainActivity).createDocumentConfirmed(currentPath)
+ } else {
+ createNewItem()
+ }
+ }
+ itemsList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
+ override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
+ if (newState == RecyclerView.SCROLL_STATE_IDLE) {
+ saveScrollPosition()
}
}
+ })
+ }
+
+ observeViewModel()
+ }
+
+ private fun observeViewModel() {
+ val owner = activity ?: return
+ observeJob?.cancel()
+ observeJob = owner.lifecycleScope.launch {
+ owner.repeatOnLifecycle(Lifecycle.State.STARTED) {
+ launch {
+ viewModel.events.collect { handleEvent(it) }
+ }
+ viewModel.uiState.collect { render(it) }
}
}
}
+ override fun onAttachedToWindow() {
+ super.onAttachedToWindow()
+ if (::viewModel.isInitialized && observeJob == null) {
+ observeViewModel()
+ }
+ }
+
+ override fun onDetachedFromWindow() {
+ if (::viewModel.isInitialized) {
+ saveScrollPosition()
+ }
+ observeJob?.cancel()
+ observeJob = null
+ super.onDetachedFromWindow()
+ }
+
override fun onResume(textColor: Int) {
- context!!.updateTextColors(this)
+ context.updateTextColors(this)
getRecyclerAdapter()?.apply {
updatePrimaryColor()
updateTextColor(textColor)
@@ -71,7 +142,7 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF
}
binding.apply {
- val properPrimaryColor = context!!.getProperPrimaryColor()
+ val properPrimaryColor = context.getProperPrimaryColor()
itemsFastscroller.updateColors(properPrimaryColor)
progressBar.setIndicatorColor(properPrimaryColor)
progressBar.trackColor = properPrimaryColor.adjustAlpha(LOWER_ALPHA)
@@ -80,14 +151,14 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF
breadcrumbs.updateColor(textColor)
}
- itemsSwipeRefresh.isEnabled = lastSearchedText.isEmpty() && activity?.config?.enablePullToRefresh != false
+ itemsSwipeRefresh.isEnabled = getSearchQuery().isEmpty() && isPullToRefreshEnabled()
}
}
override fun setupFontSize() {
getRecyclerAdapter()?.updateFontSizes()
if (currentPath != "") {
- binding.breadcrumbs.updateFontSize(context!!.getTextSize(), false)
+ binding.breadcrumbs.updateFontSize(context.getTextSize(), false)
}
}
@@ -99,325 +170,214 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF
getRecyclerAdapter()?.finishActMode()
}
- fun openPath(path: String, forceRefresh: Boolean = false) {
- if ((activity as? BaseSimpleActivity)?.isAskingPermissions == true) {
- return
- }
+ // region rendering
+ private fun render(state: ItemsUiState) {
+ requestSafAccessIfNeeded(state)
+ renderProgress(state)
+ renderSearch(state)
+ renderItems(state)
+ renderSelection(state)
- var realPath = path.trimEnd('/')
- if (realPath.isEmpty()) {
- realPath = "/"
+ // the menu depends on the folder and on settings (e.g. hidden items) that a new listing reflects
+ if (state.currentPath != renderedCurrentPath || state.items !== renderedListing) {
+ renderedCurrentPath = state.currentPath
+ renderedListing = state.items
+ (activity as? MainActivity)?.refreshMenuItems()
}
+ }
- scrollStates[currentPath] = getScrollState()!!
- currentPath = realPath
- showHidden = context!!.config.shouldShowHidden()
- showProgressBar()
- getItems(currentPath) { originalPath, listItems ->
- if (currentPath != originalPath) {
- return@getItems
- }
-
- FileDirItem.sorting = context!!.config.getFolderSorting(currentPath)
- listItems.sort()
-
- 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) {
- val sectionTitle = ListItem("", "", false, 0, 0, 0, false, true)
- listItems.add(firstFileIndex, sectionTitle)
- }
- }
- }
-
- itemsIgnoringSearch = listItems
- activity?.runOnUiThread {
- (activity as? MainActivity)?.refreshMenuItems()
- addItems(listItems, forceRefresh)
- if (context != null && currentViewType != context!!.config.getFolderViewType(currentPath)) {
- setupLayoutManager()
- }
- hideProgressBar()
+ private fun requestSafAccessIfNeeded(state: ItemsUiState) {
+ val path = state.pendingSafAccessPath
+ if (path == null) {
+ requestedSafAccessPath = null
+ } else if (path != requestedSafAccessPath) {
+ requestedSafAccessPath = path
+ activity?.handleAndroidSAFDialog(path, openInSystemAppAllowed = true) { granted ->
+ viewModel.onSafAccessResult(path, granted)
}
}
}
- private fun addItems(items: ArrayList<ListItem>, forceRefresh: Boolean = false) {
- activity?.runOnUiThread {
- binding.itemsSwipeRefresh.isRefreshing = false
- binding.breadcrumbs.setBreadcrumb(currentPath)
- 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()
- }
+ private fun renderProgress(state: ItemsUiState) {
+ if (state.isLoading || state.search.isSearching) {
+ binding.progressBar.show()
+ } else {
+ binding.progressBar.hide()
+ }
- getRecyclerLayoutManager().onRestoreInstanceState(scrollStates[currentPath])
+ if (!state.isLoading) {
+ binding.itemsSwipeRefresh.isRefreshing = false
}
}
- private fun getScrollState() = getRecyclerLayoutManager().onSaveInstanceState()
+ private fun renderSearch(state: ItemsUiState) {
+ val search = state.search
+ if (search.query != renderedQuery) {
+ renderedQuery = search.query
+ binding.itemsSwipeRefresh.isEnabled = search.query.isEmpty() && isPullToRefreshEnabled()
+ }
- private fun getRecyclerLayoutManager() = (binding.itemsList.layoutManager as MyGridLayoutManager)
+ binding.apply {
+ when {
+ !search.isActive -> {
+ itemsFastscroller.beVisible()
+ itemsPlaceholder.beGone()
+ itemsPlaceholder2.beGone()
+ }
- @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
- if (context.isRestrictedSAFOnlyRoot(path)) {
- activity?.runOnUiThread { hideProgressBar() }
- activity?.handleAndroidSAFDialog(path, openInSystemAppAllowed = true) {
- if (!it) {
- activity?.toast(R.string.no_storage_permissions)
- return@handleAndroidSAFDialog
- }
- 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) {
- callback(path, getListItemsFromFileDirItems(it))
- }
- } else if (!config.enableRootAccess || !context!!.isPathOnRoot(path)) {
- getRegularItemsOf(path, callback)
- } else {
- RootHelpers(activity!!).getFiles(path, callback)
+ search.needsMoreCharacters -> {
+ itemsFastscroller.beGone()
+ itemsPlaceholder.beVisible()
+ itemsPlaceholder2.beVisible()
+ }
+
+ search.resultsQuery != null -> {
+ val hasResults = search.results.isNotEmpty()
+ itemsFastscroller.beVisibleIf(hasResults)
+ itemsPlaceholder.beVisibleIf(!hasResults)
+ itemsPlaceholder2.beGone()
}
}
}
}
- 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) {
- callback(path, items)
+ private fun renderItems(state: ItemsUiState) {
+ val items = state.displayedItems
+ if (items == null || state.listingPath.isEmpty()) {
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)
-
- for (file in files) {
- val listItem = getListItemFromFile(file, isSortingBySize, lastModifieds, false)
- if (listItem != null) {
- if (wantedMimeTypes.any { isProperMimeType(it, file.absolutePath, file.isDirectory) }) {
- items.add(listItem)
- }
+ FileDirItem.sorting = state.sorting
+ val highlight = state.highlightedText
+ val adapter = getRecyclerAdapter()
+ when {
+ adapter == null || state.listingPath != renderedListingPath || state.viewType != currentViewType -> {
+ showNewListing(state, items, highlight)
}
- }
- // send out the initial item list asap, get proper child count asynchronously as it can be slow
- callback(path, items)
-
- 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)
- }
- }
+ items != renderedItems -> {
+ val listItems = ArrayList(items.map { it.toListItem() })
+ if (items.map { it.path } == renderedItems?.map { it.path }) {
+ adapter.replaceItemsInPlace(listItems)
+ } else {
+ adapter.updateItems(listItems, highlight)
}
}
+
+ highlight != renderedHighlight -> adapter.updateItems(ArrayList(items.map { it.toListItem() }), highlight)
}
+
+ renderedItems = items
+ renderedHighlight = highlight
}
- 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(".")) {
- return null
+ private fun showNewListing(state: ItemsUiState, items: List<FileItem>, highlight: String) {
+ val activity = activity ?: return
+ saveScrollPosition()
+ getRecyclerAdapter()?.finishActMode()
+ if (state.viewType != currentViewType) {
+ setupLayoutManager(state.viewType)
}
- var lastModified = lastModifieds.remove(curPath)
- val isDirectory = file.isDirectory
- val children = if (isDirectory && getProperChildCount) file.getDirectChildrenCount(context, showHidden) else 0
- val size = if (isDirectory) {
- if (isSortingBySize) {
- file.getProperSize(showHidden)
- } else {
- 0L
- }
- } else {
- file.length()
+ if (binding.itemsList.adapter == null) {
+ binding.breadcrumbs.updateFontSize(context.getTextSize(), true)
+ }
+ binding.breadcrumbs.setBreadcrumb(state.listingPath)
+
+ val listItems = ArrayList(items.map { it.toListItem() })
+ ItemsAdapter(activity, listItems, this, binding.itemsList, isPickMultipleIntent, binding.itemsSwipeRefresh) {
+ itemClicked(it as ListItem)
+ }.apply {
+ setupZoomListener(zoomListener)
+ binding.itemsList.adapter = this
+ updateItems(listItems, highlight)
}
- if (lastModified == null) {
- lastModified = file.lastModified()
+ if (context.areSystemAnimationsEnabled) {
+ binding.itemsList.scheduleLayoutAnimation()
}
- return ListItem(curPath, curName, isDirectory, children, size, lastModified, false, false)
- }
+ renderedListingPath = state.listingPath
+ renderedHighlight = highlight
+ viewModel.scrollPositions[scrollKey()]?.let {
+ getRecyclerLayoutManager().scrollToPositionWithOffset(it.index, it.offset)
+ }
- private fun getListItemsFromFileDirItems(fileDirItems: ArrayList<FileDirItem>): ArrayList<ListItem> {
- val listItems = ArrayList<ListItem>()
- fileDirItems.forEach {
- val listItem = ListItem(it.path, it.name, it.isDirectory, it.children, it.size, it.modified, false, false)
- if (wantedMimeTypes.any { mimeType -> isProperMimeType(mimeType, it.path, it.isDirectory) }) {
- listItems.add(listItem)
+ if (state.selectedPaths.isNotEmpty()) {
+ // the action mode can only be started once the list is attached and laid out
+ post {
+ getRecyclerAdapter()?.restoreSelection(viewModel.uiState.value.selectedPaths)
}
}
- return listItems
}
- private fun itemClicked(item: FileDirItem) {
- if (item.isDirectory) {
- openDirectory(item.path)
- } else {
- clickedPath(item.path)
+ private fun renderSelection(state: ItemsUiState) {
+ val adapter = getRecyclerAdapter() ?: return
+ if (state.selectedPaths.isEmpty() && adapter.hasActiveSelection()) {
+ adapter.finishActMode()
}
}
- private fun openDirectory(path: String) {
- (activity as? MainActivity)?.apply {
- openedDirectory()
+ private fun handleEvent(event: ItemsEvent) {
+ when (event) {
+ ItemsEvent.StorageAccessDenied -> activity?.toast(R.string.no_storage_permissions)
}
- openPath(path)
}
+ // endregion
- override fun searchQueryChanged(text: String) {
- lastSearchedText = text
- if (context == null) {
+ private fun scrollKey(): String {
+ val path = renderedListingPath.orEmpty()
+ return if (renderedHighlight.isEmpty()) path else "$path$SEARCH_SCROLL_KEY_SUFFIX"
+ }
+
+ private fun saveScrollPosition() {
+ if (renderedListingPath == null) {
return
}
- 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 -> {
- itemsFastscroller.beGone()
- itemsPlaceholder.beVisible()
- itemsPlaceholder2.beVisible()
- hideProgressBar()
- }
-
- else -> {
- showProgressBar()
- ensureBackgroundThread {
- val files = searchFiles(text, currentPath)
- files.sortBy { it.getParentPath() }
-
- if (lastSearchedText != text) {
- return@ensureBackgroundThread
- }
-
- 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)
- }
- }
-
- activity?.runOnUiThread {
- getRecyclerAdapter()?.updateItems(listItems, text)
- itemsFastscroller.beVisibleIf(listItems.isNotEmpty())
- itemsPlaceholder.beVisibleIf(listItems.isEmpty())
- itemsPlaceholder2.beGone()
- hideProgressBar()
- }
- }
- }
- }
+ val layoutManager = getRecyclerLayoutManager()
+ val index = layoutManager.findFirstVisibleItemPosition()
+ if (index != RecyclerView.NO_POSITION) {
+ val offset = (layoutManager.findViewByPosition(index)?.top ?: 0) - binding.itemsList.paddingTop
+ viewModel.scrollPositions[scrollKey()] = ScrollPosition(index, offset)
}
}
- private fun searchFiles(text: String, path: String): ArrayList<ListItem> {
- val files = ArrayList<ListItem>()
- if (context == null) {
- return files
+ private fun getRecyclerLayoutManager() = (binding.itemsList.layoutManager as MyGridLayoutManager)
+
+ fun openPath(path: String) {
+ if ((activity as? BaseSimpleActivity)?.isAskingPermissions == true || !::viewModel.isInitialized) {
+ return
}
- val normalizedText = text.normalizeString()
- 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) {
- return@forEach
- }
+ saveScrollPosition()
+ (activity as? MainActivity)?.openedDirectory()
+ viewModel.openPath(path)
+ }
- if (it.isDirectory) {
- if (it.name.normalizeString().contains(normalizedText, true)) {
- val fileDirItem = getListItemFromFile(it, isSortingBySize, HashMap(), false)
- if (fileDirItem != null) {
- files.add(fileDirItem)
- }
- }
+ /** Opens [path] unless the ViewModel already has a folder, e.g. because it survived a configuration change. */
+ fun openInitialPathIfNeeded(path: String) {
+ if (::viewModel.isInitialized) {
+ viewModel.openInitialPathIfNeeded(path)
+ }
+ }
- files.addAll(searchFiles(text, it.absolutePath))
- } else {
- if (it.name.normalizeString().contains(normalizedText, true)) {
- val fileDirItem = getListItemFromFile(it, isSortingBySize, HashMap(), false)
- if (fileDirItem != null) {
- files.add(fileDirItem)
- }
- }
- }
+ private fun itemClicked(item: ListItem) {
+ if (item.isSectionTitle || item.isDirectory) {
+ openPath(item.path)
+ } else {
+ clickedPath(item.path)
}
- return files
}
- private fun searchClosed() {
- binding.apply {
- lastSearchedText = ""
- itemsSwipeRefresh.isEnabled = activity?.config?.enablePullToRefresh != false
- itemsFastscroller.beVisible()
- itemsPlaceholder.beGone()
- itemsPlaceholder2.beGone()
- hideProgressBar()
+ override fun searchQueryChanged(text: String) {
+ if (::viewModel.isInitialized) {
+ viewModel.onSearchQueryChanged(text)
}
}
+ override fun getSearchQuery(): String = if (::viewModel.isInitialized) viewModel.uiState.value.search.query else ""
+
private fun createNewItem() {
CreateNewItemDialog(activity as SimpleActivity, currentPath) {
if (it) {
@@ -430,27 +390,26 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF
private fun getRecyclerAdapter() = binding.itemsList.adapter as? ItemsAdapter
- private fun setupLayoutManager() {
- if (context!!.config.getFolderViewType(currentPath) == VIEW_TYPE_GRID) {
- currentViewType = VIEW_TYPE_GRID
+ private fun setupLayoutManager(viewType: Int) {
+ currentViewType = viewType
+ if (viewType == VIEW_TYPE_GRID) {
setupGridLayoutManager()
} else {
- currentViewType = VIEW_TYPE_LIST
setupListLayoutManager()
}
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.spanCount = context.config.fileColumnCnt
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
- return if (getRecyclerAdapter()?.isASectionTitle(position) == true || getRecyclerAdapter()?.isGridTypeDivider(position) == true) {
+ val adapter = getRecyclerAdapter()
+ return if (adapter?.isASectionTitle(position) == true || adapter?.isGridTypeDivider(position) == true) {
layoutManager.spanCount
} else {
1
@@ -466,7 +425,7 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF
}
private fun initZoomListener() {
- if (context?.config?.getFolderViewType(currentPath) == VIEW_TYPE_GRID) {
+ if (currentViewType == VIEW_TYPE_GRID) {
val layoutManager = binding.itemsList.layoutManager as MyGridLayoutManager
zoomListener = object : MyRecyclerView.MyZoomListener {
override fun zoomIn() {
@@ -490,34 +449,26 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF
private fun increaseColumnCount() {
if (currentViewType == VIEW_TYPE_GRID) {
- context!!.config.fileColumnCnt += 1
+ context.config.fileColumnCnt += 1
(activity as? MainActivity)?.updateFragmentColumnCounts()
}
}
private fun reduceColumnCount() {
if (currentViewType == VIEW_TYPE_GRID) {
- context!!.config.fileColumnCnt -= 1
+ context.config.fileColumnCnt -= 1
(activity as? MainActivity)?.updateFragmentColumnCounts()
}
}
override fun columnCountChanged() {
- (binding.itemsList.layoutManager as MyGridLayoutManager).spanCount = context!!.config.fileColumnCnt
+ (binding.itemsList.layoutManager as MyGridLayoutManager).spanCount = context.config.fileColumnCnt
(activity as? MainActivity)?.refreshMenuItems()
getRecyclerAdapter()?.apply {
notifyItemRangeChanged(0, listItems.size)
}
}
- fun showProgressBar() {
- binding.progressBar.show()
- }
-
- private fun hideProgressBar() {
- binding.progressBar.hide()
- }
-
fun getBreadcrumbs() = binding.breadcrumbs
override fun toggleFilenameVisibility() {
@@ -526,7 +477,7 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF
override fun breadcrumbClicked(id: Int) {
if (id == 0) {
- StoragePickerDialog(activity as SimpleActivity, currentPath, context!!.config.enableRootAccess, true) {
+ StoragePickerDialog(activity as SimpleActivity, currentPath, context.config.enableRootAccess, true) {
getRecyclerAdapter()?.finishActMode()
openPath(it)
}
@@ -537,15 +488,29 @@ class ItemsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerF
}
override fun refreshFragment() {
- openPath(currentPath)
+ if (::viewModel.isInitialized) {
+ viewModel.refresh()
+ }
}
override fun deleteFiles(files: ArrayList<FileDirItem>) {
val hasFolder = files.any { it.isDirectory }
handleFileDeleting(files, hasFolder)
+ viewModel.onItemsDeleted(files.map { it.path })
+ }
+
+ override fun selectionChanged(selectedPaths: Set<String>) {
+ // the action mode is torn down on configuration changes, the ViewModel keeps the selection for the new list
+ if (activity?.isChangingConfigurations != true && ::viewModel.isInitialized) {
+ viewModel.onSelectionChanged(selectedPaths)
+ }
}
override fun selectedPaths(paths: ArrayList<String>) {
(activity as MainActivity).pickedPaths(paths)
}
+
+ private companion object {
+ const val SEARCH_SCROLL_KEY_SUFFIX = "\u0000search"
+ }
}
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..92855c8 100644
--- a/app/src/main/kotlin/org/fossify/filemanager/fragments/MyViewPagerFragment.kt
+++ b/app/src/main/kotlin/org/fossify/filemanager/fragments/MyViewPagerFragment.kt
@@ -13,6 +13,7 @@ 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.config
import org.fossify.filemanager.extensions.isPathOnRoot
import org.fossify.filemanager.extensions.tryOpenPathIntent
import org.fossify.filemanager.helpers.RootHelpers
@@ -22,7 +23,10 @@ abstract class MyViewPagerFragment<BINDING : MyViewPagerFragment.InnerBinding>(c
protected var activity: SimpleActivity? = null
protected var currentViewType = VIEW_TYPE_LIST
- var currentPath = ""
+ /** The folder shown by this tab, empty for tabs that are not bound to a folder. */
+ open val currentPath: String
+ get() = ""
+
var isGetContentIntent = false
var isGetRingtonePicker = false
var isPickMultipleIntent = false
@@ -67,26 +71,13 @@ abstract class MyViewPagerFragment<BINDING : MyViewPagerFragment.InnerBinding>(c
} else {
(activity as SimpleActivity).deleteFiles(files, hasFolder) {
if (!it) {
- activity!!.runOnUiThread {
- activity!!.toast(R.string.unknown_error_occurred)
- }
+ activity?.toast(R.string.unknown_error_occurred)
}
}
}
}
- protected fun isProperMimeType(wantedMimeType: String, path: String, isDirectory: Boolean): Boolean {
- return if (wantedMimeType.isEmpty() || wantedMimeType == "*/*" || isDirectory) {
- true
- } else {
- val fileMimeType = path.getMimeType()
- if (wantedMimeType.endsWith("/*")) {
- fileMimeType.substringBefore("/").equals(wantedMimeType.substringBefore("/"), true)
- } else {
- fileMimeType.equals(wantedMimeType, true)
- }
- }
- }
+ protected fun isPullToRefreshEnabled() = activity?.config?.enablePullToRefresh != false
abstract fun setupFragment(activity: SimpleActivity)
@@ -96,6 +87,9 @@ abstract class MyViewPagerFragment<BINDING : MyViewPagerFragment.InnerBinding>(c
abstract fun searchQueryChanged(text: String)
+ /** The search query of this tab, used to reopen the search bar after the screen is recreated. */
+ open fun getSearchQuery(): String = ""
+
interface InnerBinding {
val itemsFab: MyFloatingActionButton?
}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/fragments/RecentsFragment.kt b/app/src/main/kotlin/org/fossify/filemanager/fragments/RecentsFragment.kt
index 910877a..4715dd5 100644
--- a/app/src/main/kotlin/org/fossify/filemanager/fragments/RecentsFragment.kt
+++ b/app/src/main/kotlin/org/fossify/filemanager/fragments/RecentsFragment.kt
@@ -1,22 +1,18 @@
package org.fossify.filemanager.fragments
-import android.content.ContentResolver
import android.content.Context
-import android.provider.MediaStore.Files
-import android.provider.MediaStore.Files.FileColumns
import android.util.AttributeSet
-import androidx.core.os.bundleOf
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
+import androidx.recyclerview.widget.RecyclerView
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.launch
import org.fossify.commons.extensions.areSystemAnimationsEnabled
import org.fossify.commons.extensions.beVisibleIf
-import org.fossify.commons.extensions.getDoesFilePathExist
-import org.fossify.commons.extensions.getFilenameFromPath
-import org.fossify.commons.extensions.getLongValue
-import org.fossify.commons.extensions.getStringValue
-import org.fossify.commons.extensions.normalizeString
import org.fossify.commons.extensions.showErrorToast
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.MyGridLayoutManager
import org.fossify.commons.views.MyRecyclerView
@@ -25,19 +21,27 @@ import org.fossify.filemanager.activities.SimpleActivity
import org.fossify.filemanager.adapters.ItemsAdapter
import org.fossify.filemanager.databinding.RecentsFragmentBinding
import org.fossify.filemanager.extensions.config
-import org.fossify.filemanager.extensions.isPathInHiddenFolder
import org.fossify.filemanager.helpers.MAX_COLUMN_COUNT
import org.fossify.filemanager.interfaces.ItemOperationsListener
-import org.fossify.filemanager.models.ListItem
-import java.io.File
-
-class RecentsFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerFragment<MyViewPagerFragment.RecentsInnerBinding>(context, attributeSet),
+import org.fossify.filemanager.models.FileItem
+import org.fossify.filemanager.viewmodels.RecentsEvent
+import org.fossify.filemanager.viewmodels.RecentsUiState
+import org.fossify.filemanager.viewmodels.RecentsViewModel
+import org.fossify.filemanager.viewmodels.ScrollPosition
+
+/**
+ * The Recents tab. It renders [RecentsUiState] from the activity scoped [RecentsViewModel] and forwards user
+ * actions to it.
+ */
+class RecentsFragment(context: Context, attributeSet: AttributeSet) :
+ MyViewPagerFragment<MyViewPagerFragment.RecentsInnerBinding>(context, attributeSet),
ItemOperationsListener {
- private val RECENTS_LIMIT = 50
- private var filesIgnoringSearch = ArrayList<ListItem>()
- private var lastSearchedText = ""
- private var zoomListener: MyRecyclerView.MyZoomListener? = null
private lateinit var binding: RecentsFragmentBinding
+ private lateinit var viewModel: RecentsViewModel
+ private var observeJob: Job? = null
+ private var zoomListener: MyRecyclerView.MyZoomListener? = null
+ private var renderedItems: List<FileItem>? = null
+ private var renderedQuery: String? = null
override fun onFinishInflate() {
super.onFinishInflate()
@@ -48,46 +52,125 @@ class RecentsFragment(context: Context, attributeSet: AttributeSet) : MyViewPage
override fun setupFragment(activity: SimpleActivity) {
if (this.activity == null) {
this.activity = activity
+ val factory = RecentsViewModel.factory(activity.applicationContext, wantedMimeTypes)
+ viewModel = ViewModelProvider(activity, factory)[RecentsViewModel::class.java]
binding.recentsSwipeRefresh.setOnRefreshListener { refreshFragment() }
+ binding.recentsList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
+ override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
+ if (newState == RecyclerView.SCROLL_STATE_IDLE) {
+ saveScrollPosition()
+ }
+ }
+ })
+ observeViewModel()
}
- refreshFragment()
+ viewModel.loadIfNeeded()
}
- override fun refreshFragment() {
- ensureBackgroundThread {
- getRecents { recents ->
- binding.apply {
- recentsSwipeRefresh.isRefreshing = false
- recentsList.beVisibleIf(recents.isNotEmpty())
- recentsPlaceholder.beVisibleIf(recents.isEmpty())
- }
- filesIgnoringSearch = recents
- addItems(recents, false)
-
- if (context != null && currentViewType != context!!.config.getFolderViewType("")) {
- setupLayoutManager()
+ private fun observeViewModel() {
+ val owner = activity ?: return
+ observeJob?.cancel()
+ observeJob = owner.lifecycleScope.launch {
+ owner.repeatOnLifecycle(Lifecycle.State.STARTED) {
+ launch {
+ viewModel.events.collect { handleEvent(it) }
}
+ viewModel.uiState.collect { render(it) }
}
}
}
- private fun addItems(recents: ArrayList<ListItem>, forceRefresh: Boolean) {
- if (!forceRefresh && recents.hashCode() == (binding.recentsList.adapter as? ItemsAdapter)?.listItems.hashCode()) {
+ override fun onAttachedToWindow() {
+ super.onAttachedToWindow()
+ if (::viewModel.isInitialized && observeJob == null) {
+ observeViewModel()
+ }
+ }
+
+ override fun onDetachedFromWindow() {
+ if (::viewModel.isInitialized) {
+ saveScrollPosition()
+ }
+ observeJob?.cancel()
+ observeJob = null
+ super.onDetachedFromWindow()
+ }
+
+ override fun refreshFragment() {
+ if (::viewModel.isInitialized) {
+ viewModel.refresh()
+ }
+ }
+
+ // region rendering
+ private fun render(state: RecentsUiState) {
+ if (!state.isLoading) {
+ binding.recentsSwipeRefresh.isRefreshing = false
+ }
+
+ if (state.query != renderedQuery) {
+ renderedQuery = state.query
+ binding.recentsSwipeRefresh.isEnabled = state.query.isEmpty() && isPullToRefreshEnabled()
+ }
+
+ if (!state.isLoaded) {
return
}
- ItemsAdapter(activity as SimpleActivity, recents, this, binding.recentsList, isPickMultipleIntent, binding.recentsSwipeRefresh, false) {
+ binding.recentsList.beVisibleIf(state.visibleItems.isNotEmpty())
+ binding.recentsPlaceholder.beVisibleIf(state.visibleItems.isEmpty())
+
+ val adapter = getRecyclerAdapter()
+ if (adapter == null || state.viewType != currentViewType) {
+ showNewList(state)
+ } else if (state.visibleItems != renderedItems) {
+ adapter.updateItems(ArrayList(state.visibleItems.map { it.toListItem() }), state.query)
+ }
+ renderedItems = state.visibleItems
+
+ if (state.selectedPaths.isEmpty() && getRecyclerAdapter()?.hasActiveSelection() == true) {
+ getRecyclerAdapter()?.finishActMode()
+ }
+ }
+
+ private fun showNewList(state: RecentsUiState) {
+ val activity = activity ?: return
+ getRecyclerAdapter()?.finishActMode()
+ if (state.viewType != currentViewType) {
+ setupLayoutManager(state.viewType)
+ }
+
+ val listItems = ArrayList(state.visibleItems.map { it.toListItem() })
+ ItemsAdapter(activity, listItems, this, binding.recentsList, isPickMultipleIntent, binding.recentsSwipeRefresh, false) {
clickedPath((it as FileDirItem).path)
}.apply {
setupZoomListener(zoomListener)
binding.recentsList.adapter = this
+ updateItems(listItems, state.query)
}
if (context.areSystemAnimationsEnabled) {
binding.recentsList.scheduleLayoutAnimation()
}
+
+ viewModel.scrollPosition?.let {
+ getRecyclerLayoutManager().scrollToPositionWithOffset(it.index, it.offset)
+ }
+
+ if (state.selectedPaths.isNotEmpty()) {
+ post {
+ getRecyclerAdapter()?.restoreSelection(viewModel.uiState.value.selectedPaths)
+ }
+ }
+ }
+
+ private fun handleEvent(event: RecentsEvent) {
+ when (event) {
+ is RecentsEvent.Error -> activity?.showErrorToast(event.message)
+ }
}
+ // endregion
override fun onResume(textColor: Int) {
binding.recentsPlaceholder.setTextColor(textColor)
@@ -98,38 +181,40 @@ class RecentsFragment(context: Context, attributeSet: AttributeSet) : MyViewPage
initDrawables()
}
- binding.recentsSwipeRefresh.isEnabled = lastSearchedText.isEmpty() && activity?.config?.enablePullToRefresh != false
+ binding.recentsSwipeRefresh.isEnabled = getSearchQuery().isEmpty() && isPullToRefreshEnabled()
}
- private fun setupLayoutManager() {
- if (context!!.config.getFolderViewType("") == VIEW_TYPE_GRID) {
- currentViewType = VIEW_TYPE_GRID
- setupGridLayoutManager()
- } else {
- currentViewType = VIEW_TYPE_LIST
- setupListLayoutManager()
+ private fun getRecyclerLayoutManager() = binding.recentsList.layoutManager as MyGridLayoutManager
+
+ private fun saveScrollPosition() {
+ if (getRecyclerAdapter() == null) {
+ return
}
- val oldItems = (binding.recentsList.adapter as? ItemsAdapter)?.listItems?.toMutableList() as ArrayList<ListItem>
- binding.recentsList.adapter = null
- initZoomListener()
- addItems(oldItems, true)
+ val layoutManager = getRecyclerLayoutManager()
+ val index = layoutManager.findFirstVisibleItemPosition()
+ if (index != RecyclerView.NO_POSITION) {
+ val offset = (layoutManager.findViewByPosition(index)?.top ?: 0) - binding.recentsList.paddingTop
+ viewModel.scrollPosition = ScrollPosition(index, offset)
+ }
}
- private fun setupGridLayoutManager() {
- val layoutManager = binding.recentsList.layoutManager as MyGridLayoutManager
- layoutManager.spanCount = context?.config?.fileColumnCnt ?: 3
- }
+ private fun setupLayoutManager(viewType: Int) {
+ currentViewType = viewType
+ val layoutManager = getRecyclerLayoutManager()
+ if (viewType == VIEW_TYPE_GRID) {
+ layoutManager.spanCount = context.config.fileColumnCnt
+ } else {
+ layoutManager.spanCount = 1
+ }
- private fun setupListLayoutManager() {
- val layoutManager = binding.recentsList.layoutManager as MyGridLayoutManager
- layoutManager.spanCount = 1
- zoomListener = null
+ binding.recentsList.adapter = null
+ initZoomListener()
}
private fun initZoomListener() {
- if (context?.config?.getFolderViewType("") == VIEW_TYPE_GRID) {
- val layoutManager = binding.recentsList.layoutManager as MyGridLayoutManager
+ if (currentViewType == VIEW_TYPE_GRID) {
+ val layoutManager = getRecyclerLayoutManager()
zoomListener = object : MyRecyclerView.MyZoomListener {
override fun zoomIn() {
if (layoutManager.spanCount > 1) {
@@ -150,56 +235,6 @@ class RecentsFragment(context: Context, attributeSet: AttributeSet) : MyViewPage
}
}
- private fun getRecents(callback: (recents: ArrayList<ListItem>) -> Unit) {
- val showHidden = context?.config?.shouldShowHidden() ?: return
- val listItems = arrayListOf<ListItem>()
-
- val uri = Files.getContentUri("external")
- val projection = arrayOf(
- FileColumns.DATA,
- FileColumns.DISPLAY_NAME,
- FileColumns.DATE_MODIFIED,
- FileColumns.SIZE
- )
-
- try {
- val queryArgs = bundleOf(
- ContentResolver.QUERY_ARG_LIMIT to RECENTS_LIMIT,
- ContentResolver.QUERY_ARG_SORT_COLUMNS to arrayOf(FileColumns.DATE_MODIFIED),
- ContentResolver.QUERY_ARG_SORT_DIRECTION to ContentResolver.QUERY_SORT_DIRECTION_DESCENDING
- )
-
- context?.contentResolver?.query(uri, projection, queryArgs, null)?.use { cursor ->
- if (cursor.moveToFirst()) {
- do {
- val path = cursor.getStringValue(FileColumns.DATA)
- if (File(path).isDirectory) {
- continue
- }
-
- val name = cursor.getStringValue(FileColumns.DISPLAY_NAME) ?: path.getFilenameFromPath()
- val size = cursor.getLongValue(FileColumns.SIZE)
- val modified = cursor.getLongValue(FileColumns.DATE_MODIFIED) * 1000
- val isHiddenFile = name.startsWith(".")
- val shouldShow = showHidden || (!isHiddenFile && !path.isPathInHiddenFolder())
- if (shouldShow && activity?.getDoesFilePathExist(path) == true) {
- if (wantedMimeTypes.any { isProperMimeType(it, path, false) }) {
- val fileDirItem = ListItem(path, name, false, 0, size, modified, false, false)
- listItems.add(fileDirItem)
- }
- }
- } while (cursor.moveToNext())
- }
- }
- } catch (e: Exception) {
- activity?.showErrorToast(e)
- }
-
- activity?.runOnUiThread {
- callback(listItems)
- }
- }
-
private fun getRecyclerAdapter() = binding.recentsList.adapter as? ItemsAdapter
override fun toggleFilenameVisibility() {
@@ -208,20 +243,20 @@ class RecentsFragment(context: Context, attributeSet: AttributeSet) : MyViewPage
private fun increaseColumnCount() {
if (currentViewType == VIEW_TYPE_GRID) {
- context!!.config.fileColumnCnt += 1
+ context.config.fileColumnCnt += 1
(activity as? MainActivity)?.updateFragmentColumnCounts()
}
}
private fun reduceColumnCount() {
if (currentViewType == VIEW_TYPE_GRID) {
- context!!.config.fileColumnCnt -= 1
+ context.config.fileColumnCnt -= 1
(activity as? MainActivity)?.updateFragmentColumnCounts()
}
}
override fun columnCountChanged() {
- (binding.recentsList.layoutManager as MyGridLayoutManager).spanCount = context!!.config.fileColumnCnt
+ getRecyclerLayoutManager().spanCount = context.config.fileColumnCnt
(activity as? MainActivity)?.refreshMenuItems()
getRecyclerAdapter()?.apply {
notifyItemRangeChanged(0, listItems.size)
@@ -242,22 +277,23 @@ class RecentsFragment(context: Context, attributeSet: AttributeSet) : MyViewPage
override fun deleteFiles(files: ArrayList<FileDirItem>) {
handleFileDeleting(files, false)
+ viewModel.onItemsDeleted(files.map { it.path })
+ }
+
+ override fun selectionChanged(selectedPaths: Set<String>) {
+ if (activity?.isChangingConfigurations != true && ::viewModel.isInitialized) {
+ viewModel.onSelectionChanged(selectedPaths)
+ }
}
override fun searchQueryChanged(text: String) {
- lastSearchedText = text
- val normalizedText = text.normalizeString()
- val filtered = filesIgnoringSearch.filter {
- it.mName.normalizeString().contains(normalizedText, true)
- }.toMutableList() as ArrayList<ListItem>
-
- binding.apply {
- (recentsList.adapter as? ItemsAdapter)?.updateItems(filtered, text)
- recentsPlaceholder.beVisibleIf(filtered.isEmpty())
- recentsSwipeRefresh.isEnabled = lastSearchedText.isEmpty() && activity?.config?.enablePullToRefresh != false
+ if (::viewModel.isInitialized) {
+ viewModel.onSearchQueryChanged(text)
}
}
+ override fun getSearchQuery(): String = if (::viewModel.isInitialized) viewModel.uiState.value.query else ""
+
override fun finishActMode() {
getRecyclerAdapter()?.finishActMode()
}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/fragments/StorageFragment.kt b/app/src/main/kotlin/org/fossify/filemanager/fragments/StorageFragment.kt
index f8a8bf9..72c09b6 100644
--- a/app/src/main/kotlin/org/fossify/filemanager/fragments/StorageFragment.kt
+++ b/app/src/main/kotlin/org/fossify/filemanager/fragments/StorageFragment.kt
@@ -1,21 +1,20 @@
package org.fossify.filemanager.fragments
-import android.annotation.SuppressLint
-import android.app.Activity
-import android.app.usage.StorageStatsManager
-import android.content.ContentResolver
+import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
-import android.os.Handler
-import android.os.Looper
-import android.os.storage.StorageManager
-import android.provider.MediaStore
import android.provider.Settings
import android.util.AttributeSet
-import androidx.appcompat.app.AppCompatActivity
-import androidx.core.os.bundleOf
+import android.widget.TextView
import androidx.core.view.children
-import androidx.core.view.isVisible
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
+import androidx.recyclerview.widget.RecyclerView
+import com.google.android.material.progressindicator.LinearProgressIndicator
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.launch
import org.fossify.commons.extensions.adjustAlpha
import org.fossify.commons.extensions.applyColorFilter
import org.fossify.commons.extensions.beGone
@@ -23,20 +22,13 @@ import org.fossify.commons.extensions.beVisible
import org.fossify.commons.extensions.beVisibleIf
import org.fossify.commons.extensions.fadeIn
import org.fossify.commons.extensions.formatSize
-import org.fossify.commons.extensions.getIsPathDirectory
-import org.fossify.commons.extensions.getLongValue
import org.fossify.commons.extensions.getProperBackgroundColor
import org.fossify.commons.extensions.getProperPrimaryColor
-import org.fossify.commons.extensions.getStringValue
-import org.fossify.commons.extensions.normalizeString
-import org.fossify.commons.extensions.queryCursor
import org.fossify.commons.extensions.showErrorToast
import org.fossify.commons.extensions.updateTextColors
import org.fossify.commons.helpers.LOWER_ALPHA
import org.fossify.commons.helpers.SHORT_ANIMATION_DURATION
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.MyGridLayoutManager
import org.fossify.filemanager.R
@@ -46,33 +38,37 @@ import org.fossify.filemanager.adapters.ItemsAdapter
import org.fossify.filemanager.databinding.ItemStorageVolumeBinding
import org.fossify.filemanager.databinding.StorageFragmentBinding
import org.fossify.filemanager.extensions.config
-import org.fossify.filemanager.extensions.getAllVolumeNames
import org.fossify.filemanager.helpers.ARCHIVES
import org.fossify.filemanager.helpers.AUDIO
import org.fossify.filemanager.helpers.DOCUMENTS
import org.fossify.filemanager.helpers.IMAGES
import org.fossify.filemanager.helpers.OTHERS
-import org.fossify.filemanager.helpers.PRIMARY_VOLUME_NAME
import org.fossify.filemanager.helpers.SHOW_MIMETYPE
import org.fossify.filemanager.helpers.VIDEOS
import org.fossify.filemanager.helpers.VOLUME_NAME
-import org.fossify.filemanager.helpers.archiveMimeTypes
-import org.fossify.filemanager.helpers.extraAudioMimeTypes
-import org.fossify.filemanager.helpers.extraDocumentMimeTypes
-import org.fossify.filemanager.helpers.getListItemsFromFileDirItems
import org.fossify.filemanager.interfaces.ItemOperationsListener
-import org.fossify.filemanager.models.ListItem
-import java.util.Locale
-
+import org.fossify.filemanager.models.FileItem
+import org.fossify.filemanager.viewmodels.ScrollPosition
+import org.fossify.filemanager.viewmodels.StorageEvent
+import org.fossify.filemanager.viewmodels.StorageUiState
+import org.fossify.filemanager.viewmodels.StorageViewModel
+import org.fossify.filemanager.viewmodels.VolumeUsage
+
+/**
+ * The Storage tab. It renders [StorageUiState] from the activity scoped [StorageViewModel] (the usage of every
+ * volume and file type, the search through all device files and its selection) and forwards user actions to it.
+ */
class StorageFragment(
context: Context,
attributeSet: AttributeSet
) : MyViewPagerFragment<MyViewPagerFragment.StorageInnerBinding>(context, attributeSet), ItemOperationsListener {
- private val SIZE_DIVIDER = 100000
- private var allDeviceListItems = ArrayList<ListItem>()
- private var lastSearchedText = ""
private lateinit var binding: StorageFragmentBinding
- private val volumes = mutableMapOf<String, ItemStorageVolumeBinding>()
+ private lateinit var viewModel: StorageViewModel
+ private var observeJob: Job? = null
+ private val volumeBindings = LinkedHashMap<String, ItemStorageVolumeBinding>()
+ private var renderedVolumes: StorageUiState? = null
+ private var renderedQuery = ""
+ private var renderedResults: List<FileItem>? = null
override fun onFinishInflate() {
super.onFinishInflate()
@@ -83,394 +79,328 @@ class StorageFragment(
override fun setupFragment(activity: SimpleActivity) {
if (this.activity == null) {
this.activity = activity
- }
-
- val volumeNames = activity.getAllVolumeNames()
- volumeNames.forEach { volumeName ->
- val volumeBinding = ItemStorageVolumeBinding.inflate(activity.layoutInflater)
- volumes[volumeName] = volumeBinding
- volumeBinding.apply {
- if (volumeName == PRIMARY_VOLUME_NAME) {
- storageName.setText(R.string.internal)
- } else {
- storageName.setText(R.string.sd_card)
- }
-
- totalSpace.text = String.format(context.getString(R.string.total_storage), "…")
-
- if (volumeNames.size > 1) {
- root.children.forEach { it.beGone() }
- freeSpaceHolder.beVisible()
- expandButton.applyColorFilter(context.getProperPrimaryColor())
- expandButton.setImageResource(R.drawable.ic_arrow_down_vector)
-
- expandButton.setOnClickListener { _ ->
- if (imagesHolder.isVisible) {
- root.children.filterNot { it == freeSpaceHolder }.forEach { it.beGone() }
- expandButton.setImageResource(R.drawable.ic_arrow_down_vector)
- } else {
- root.children.filterNot { it == freeSpaceHolder }.forEach { it.beVisible() }
- expandButton.setImageResource(R.drawable.ic_arrow_up_vector)
- }
+ val factory = StorageViewModel.factory(activity.applicationContext)
+ viewModel = ViewModelProvider(activity, factory)[StorageViewModel::class.java]
+ binding.searchResultsList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
+ override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
+ if (newState == RecyclerView.SCROLL_STATE_IDLE) {
+ saveScrollPosition()
}
- } else {
- expandButton.beGone()
}
+ })
+ observeViewModel()
+ }
- freeSpaceHolder.setOnClickListener {
- try {
- val storageSettingsIntent = Intent(Settings.ACTION_INTERNAL_STORAGE_SETTINGS)
- activity.startActivity(storageSettingsIntent)
- } catch (e: Exception) {
- activity.showErrorToast(e)
- }
- }
+ viewModel.loadIfNeeded()
+ }
- imagesHolder.setOnClickListener { launchMimetypeActivity(IMAGES, volumeName) }
- videosHolder.setOnClickListener { launchMimetypeActivity(VIDEOS, volumeName) }
- audioHolder.setOnClickListener { launchMimetypeActivity(AUDIO, volumeName) }
- documentsHolder.setOnClickListener { launchMimetypeActivity(DOCUMENTS, volumeName) }
- archivesHolder.setOnClickListener { launchMimetypeActivity(ARCHIVES, volumeName) }
- othersHolder.setOnClickListener { launchMimetypeActivity(OTHERS, volumeName) }
+ private fun observeViewModel() {
+ val owner = activity ?: return
+ observeJob?.cancel()
+ observeJob = owner.lifecycleScope.launch {
+ owner.repeatOnLifecycle(Lifecycle.State.STARTED) {
+ launch {
+ viewModel.events.collect { handleEvent(it) }
+ }
+ viewModel.uiState.collect { render(it) }
}
- binding.storageVolumesHolder.addView(volumeBinding.root)
}
+ }
- ensureBackgroundThread {
- getVolumeStorageStats(context)
+ override fun onAttachedToWindow() {
+ super.onAttachedToWindow()
+ if (::viewModel.isInitialized && observeJob == null) {
+ observeViewModel()
}
+ }
- Handler(Looper.getMainLooper()).postDelayed({
- refreshFragment()
- }, 2000)
+ override fun onDetachedFromWindow() {
+ if (::viewModel.isInitialized) {
+ saveScrollPosition()
+ }
+ observeJob?.cancel()
+ observeJob = null
+ super.onDetachedFromWindow()
}
override fun onResume(textColor: Int) {
context.updateTextColors(binding.root)
+ volumeBindings.values.forEach { applyVolumeColors(it) }
val properPrimaryColor = context.getProperPrimaryColor()
- val redColor = context.resources.getColor(R.color.md_red_700)
- val greenColor = context.resources.getColor(R.color.md_green_700)
- val lightBlueColor = context.resources.getColor(R.color.md_light_blue_700)
- val yellowColor = context.resources.getColor(R.color.md_yellow_700)
- val tealColor = context.resources.getColor(R.color.md_teal_700)
- val pinkColor = context.resources.getColor(R.color.md_pink_700)
-
- volumes.values.forEach { volumeBinding ->
- volumeBinding.apply {
- mainStorageUsageProgressbar.setIndicatorColor(properPrimaryColor)
- mainStorageUsageProgressbar.trackColor = properPrimaryColor.adjustAlpha(LOWER_ALPHA)
-
- imagesProgressbar.setIndicatorColor(redColor)
- imagesProgressbar.trackColor = redColor.adjustAlpha(LOWER_ALPHA)
-
- videosProgressbar.setIndicatorColor(greenColor)
- videosProgressbar.trackColor = greenColor.adjustAlpha(LOWER_ALPHA)
-
- audioProgressbar.setIndicatorColor(lightBlueColor)
- audioProgressbar.trackColor = lightBlueColor.adjustAlpha(LOWER_ALPHA)
-
- documentsProgressbar.setIndicatorColor(yellowColor)
- documentsProgressbar.trackColor = yellowColor.adjustAlpha(LOWER_ALPHA)
-
- archivesProgressbar.setIndicatorColor(tealColor)
- archivesProgressbar.trackColor = tealColor.adjustAlpha(LOWER_ALPHA)
-
- othersProgressbar.setIndicatorColor(pinkColor)
- othersProgressbar.trackColor = pinkColor.adjustAlpha(LOWER_ALPHA)
-
- expandButton.applyColorFilter(context.getProperPrimaryColor())
- }
- }
-
binding.apply {
searchHolder.setBackgroundColor(context.getProperBackgroundColor())
progressBar.setIndicatorColor(properPrimaryColor)
progressBar.trackColor = properPrimaryColor.adjustAlpha(LOWER_ALPHA)
}
- ensureBackgroundThread {
- getVolumeStorageStats(context)
+ getRecyclerAdapter()?.apply {
+ updatePrimaryColor()
+ updateTextColor(textColor)
+ initDrawables()
}
- }
- private fun launchMimetypeActivity(mimetype: String, volumeName: String) {
- Intent(context, MimeTypesActivity::class.java).apply {
- putExtra(SHOW_MIMETYPE, mimetype)
- putExtra(VOLUME_NAME, volumeName)
- context.startActivity(this)
+ // the usage may have changed while the app was in the background
+ if (::viewModel.isInitialized) {
+ viewModel.refreshUsage()
}
}
- private fun getSizes(volumeName: String) {
- ensureBackgroundThread {
- val filesSize = getSizesByMimeType(volumeName)
- val fileSizeImages = filesSize[IMAGES]!!
- val fileSizeVideos = filesSize[VIDEOS]!!
- val fileSizeAudios = filesSize[AUDIO]!!
- val fileSizeDocuments = filesSize[DOCUMENTS]!!
- val fileSizeArchives = filesSize[ARCHIVES]!!
- val fileSizeOthers = filesSize[OTHERS]!!
-
- post {
- volumes[volumeName]!!.apply {
- imagesSize.text = fileSizeImages.formatSize()
- imagesProgressbar.progress = (fileSizeImages / SIZE_DIVIDER).toInt()
+ override fun refreshFragment() {
+ if (::viewModel.isInitialized) {
+ viewModel.refresh()
+ }
+ }
- videosSize.text = fileSizeVideos.formatSize()
- videosProgressbar.progress = (fileSizeVideos / SIZE_DIVIDER).toInt()
+ // region rendering
+ private fun render(state: StorageUiState) {
+ val volumesState = renderedVolumes
+ if (volumesState == null || volumesState.volumes != state.volumes ||
+ volumesState.expandedVolumes != state.expandedVolumes
+ ) {
+ renderVolumes(state)
+ renderedVolumes = state
+ }
- audioSize.text = fileSizeAudios.formatSize()
- audioProgressbar.progress = (fileSizeAudios / SIZE_DIVIDER).toInt()
+ renderSearch(state)
+ }
- documentsSize.text = fileSizeDocuments.formatSize()
- documentsProgressbar.progress = (fileSizeDocuments / SIZE_DIVIDER).toInt()
+ private fun renderVolumes(state: StorageUiState) {
+ val names = state.volumes.map { it.name }
+ if (names != volumeBindings.keys.toList()) {
+ createVolumeViews(names)
+ }
- archivesSize.text = fileSizeArchives.formatSize()
- archivesProgressbar.progress = (fileSizeArchives / SIZE_DIVIDER).toInt()
+ state.volumes.forEach { usage ->
+ volumeBindings[usage.name]?.let { renderVolume(it, usage, state) }
+ }
+ }
- othersSize.text = fileSizeOthers.formatSize()
- othersProgressbar.progress = (fileSizeOthers / SIZE_DIVIDER).toInt()
- }
+ private fun createVolumeViews(volumeNames: List<String>) {
+ val activity = activity ?: return
+ binding.storageVolumesHolder.removeAllViews()
+ volumeBindings.clear()
+ volumeNames.forEach { volumeName ->
+ val volumeBinding = ItemStorageVolumeBinding.inflate(activity.layoutInflater)
+ volumeBindings[volumeName] = volumeBinding
+ volumeBinding.apply {
+ expandButton.setOnClickListener { viewModel.onVolumeExpandToggled(volumeName) }
+ freeSpaceHolder.setOnClickListener { openStorageSettings() }
+ imagesHolder.setOnClickListener { launchMimetypeActivity(IMAGES, volumeName) }
+ videosHolder.setOnClickListener { launchMimetypeActivity(VIDEOS, volumeName) }
+ audioHolder.setOnClickListener { launchMimetypeActivity(AUDIO, volumeName) }
+ documentsHolder.setOnClickListener { launchMimetypeActivity(DOCUMENTS, volumeName) }
+ archivesHolder.setOnClickListener { launchMimetypeActivity(ARCHIVES, volumeName) }
+ othersHolder.setOnClickListener { launchMimetypeActivity(OTHERS, volumeName) }
}
+
+ context.updateTextColors(volumeBinding.root)
+ applyVolumeColors(volumeBinding)
+ binding.storageVolumesHolder.addView(volumeBinding.root)
}
}
- private fun getSizesByMimeType(volumeName: String): HashMap<String, Long> {
- val uri = MediaStore.Files.getContentUri(volumeName)
- val projection = arrayOf(
- MediaStore.Files.FileColumns.SIZE,
- MediaStore.Files.FileColumns.MIME_TYPE,
- MediaStore.Files.FileColumns.DATA
- )
+ private fun renderVolume(volumeBinding: ItemStorageVolumeBinding, usage: VolumeUsage, state: StorageUiState) {
+ volumeBinding.storageName.setText(if (usage.isPrimary) R.string.internal else R.string.sd_card)
+ renderExpansion(volumeBinding, state.hasSeveralVolumes, state.isExpanded(usage.name))
+ if (usage.hasStats) {
+ renderUsage(volumeBinding, usage)
+ } else {
+ volumeBinding.totalSpace.text = context.getString(R.string.total_storage, "…")
+ }
+ }
- var imagesSize = 0L
- var videosSize = 0L
- var audioSize = 0L
- var documentsSize = 0L
- var archivesSize = 0L
- var othersSize = 0L
- try {
- context.queryCursor(uri, projection) { cursor ->
- try {
- val mimeType =
- cursor.getStringValue(MediaStore.Files.FileColumns.MIME_TYPE)?.lowercase(Locale.getDefault())
- val size = cursor.getLongValue(MediaStore.Files.FileColumns.SIZE)
- if (mimeType == null) {
- if (size > 0 && size != 4096L) {
- val path = cursor.getStringValue(MediaStore.Files.FileColumns.DATA)
- if (!context.getIsPathDirectory(path)) {
- othersSize += size
- }
- }
- return@queryCursor
- }
+ private fun renderExpansion(volumeBinding: ItemStorageVolumeBinding, isExpandable: Boolean, isExpanded: Boolean) {
+ val expandButton = volumeBinding.expandButton
+ if (!isExpandable) {
+ expandButton.beGone()
+ return
+ }
- when (mimeType.substringBefore("/")) {
- "image" -> imagesSize += size
- "video" -> videosSize += size
- "audio" -> audioSize += size
- "text" -> documentsSize += size
- else -> {
- when {
- extraDocumentMimeTypes.contains(mimeType) -> documentsSize += size
- extraAudioMimeTypes.contains(mimeType) -> audioSize += size
- archiveMimeTypes.contains(mimeType) -> archivesSize += size
- else -> othersSize += size
- }
- }
- }
- } catch (e: Exception) {
- }
- }
- } catch (e: Exception) {
- }
-
- val mimeTypeSizes = HashMap<String, Long>().apply {
- put(IMAGES, imagesSize)
- put(VIDEOS, videosSize)
- put(AUDIO, audioSize)
- put(DOCUMENTS, documentsSize)
- put(ARCHIVES, archivesSize)
- put(OTHERS, othersSize)
- }
-
- return mimeTypeSizes
- }
-
- @SuppressLint("NewApi")
- private fun getVolumeStorageStats(context: Context) {
- val externalDirs = context.getExternalFilesDirs(null)
- val storageManager = context.getSystemService(AppCompatActivity.STORAGE_SERVICE) as StorageManager
-
- externalDirs.forEach { file ->
- val volumeName: String
- val totalStorageSpace: Long
- val freeStorageSpace: Long
- val storageVolume = storageManager.getStorageVolume(file) ?: return
- if (storageVolume.isPrimary) {
- // internal storage
- volumeName = PRIMARY_VOLUME_NAME
- val storageStatsManager =
- context.getSystemService(AppCompatActivity.STORAGE_STATS_SERVICE) as StorageStatsManager
- val uuid = StorageManager.UUID_DEFAULT
- totalStorageSpace = storageStatsManager.getTotalBytes(uuid)
- freeStorageSpace = storageStatsManager.getFreeBytes(uuid)
- } else {
- volumeName = storageVolume.uuid!!.lowercase(Locale.US)
- totalStorageSpace = file.totalSpace
- freeStorageSpace = file.freeSpace
- }
+ val freeSpaceHolder = volumeBinding.freeSpaceHolder
+ volumeBinding.root.children.filterNot { it == freeSpaceHolder }.forEach { it.beVisibleIf(isExpanded) }
+ freeSpaceHolder.beVisible()
+ expandButton.beVisible()
+ expandButton.setImageResource(
+ if (isExpanded) R.drawable.ic_arrow_up_vector else R.drawable.ic_arrow_down_vector
+ )
+ }
- post {
- volumes[volumeName]?.apply {
- arrayOf(
- mainStorageUsageProgressbar,
- imagesProgressbar,
- videosProgressbar,
- audioProgressbar,
- documentsProgressbar,
- archivesProgressbar,
- othersProgressbar
- ).forEach {
- it.max = (totalStorageSpace / SIZE_DIVIDER).toInt()
- }
+ private fun renderUsage(volumeBinding: ItemStorageVolumeBinding, usage: VolumeUsage) {
+ val max = (usage.totalBytes / SIZE_DIVIDER).toInt()
+ volumeBinding.mainStorageUsageProgressbar.apply {
+ this.max = max
+ progress = (usage.usedBytes / SIZE_DIVIDER).toInt()
+ beVisible()
+ }
- mainStorageUsageProgressbar.progress =
- ((totalStorageSpace - freeStorageSpace) / SIZE_DIVIDER).toInt()
+ volumeBinding.freeSpaceValue.text = usage.freeBytes.formatSize()
+ volumeBinding.totalSpace.text = context.getString(R.string.total_storage, usage.totalBytes.formatSize())
+ volumeBinding.freeSpaceLabel.beVisible()
- mainStorageUsageProgressbar.beVisible()
- freeSpaceValue.text = freeStorageSpace.formatSize()
- totalSpace.text =
- String.format(context.getString(R.string.total_storage), totalStorageSpace.formatSize())
- freeSpaceLabel.beVisible()
- getSizes(volumeName)
- }
+ val hasTypeSizes = usage.typeSizes.isNotEmpty()
+ volumeBinding.fileTypeViews().forEach { (fileType, sizeView, progressBar) ->
+ progressBar.max = max
+ if (hasTypeSizes) {
+ sizeView.text = usage.sizeOf(fileType).formatSize()
+ progressBar.progress = (usage.sizeOf(fileType) / SIZE_DIVIDER).toInt()
}
}
}
- override fun searchQueryChanged(text: String) {
- val normalizedText = text.normalizeString()
- lastSearchedText = text
- binding.apply {
- if (text.isNotEmpty()) {
- if (searchHolder.alpha < 1f) {
- searchHolder.fadeIn()
- }
- } else {
- searchHolder.animate().alpha(0f).setDuration(SHORT_ANIMATION_DURATION).withEndAction {
- searchHolder.beGone()
- (searchResultsList.adapter as? ItemsAdapter)?.updateItems(allDeviceListItems, text)
- }.start()
- }
+ private fun ItemStorageVolumeBinding.fileTypeViews(): List<Triple<String, TextView, LinearProgressIndicator>> =
+ listOf(
+ Triple(IMAGES, imagesSize, imagesProgressbar),
+ Triple(VIDEOS, videosSize, videosProgressbar),
+ Triple(AUDIO, audioSize, audioProgressbar),
+ Triple(DOCUMENTS, documentsSize, documentsProgressbar),
+ Triple(ARCHIVES, archivesSize, archivesProgressbar),
+ Triple(OTHERS, othersSize, othersProgressbar)
+ )
- if (text.length == 1) {
- searchResultsList.beGone()
- searchPlaceholder.beVisible()
- searchPlaceholder2.beVisible()
- hideProgressBar()
- } else if (text.isEmpty()) {
- searchResultsList.beGone()
- hideProgressBar()
- } else {
- showProgressBar()
- ensureBackgroundThread {
- val filtered = allDeviceListItems.filter {
- it.mName.normalizeString().contains(normalizedText, true)
- }.toMutableList() as ArrayList<ListItem>
-
- if (lastSearchedText != text) {
- return@ensureBackgroundThread
- }
+ private fun renderSearch(state: StorageUiState) {
+ val search = state.search
+ val wasSearching = renderedQuery.isNotEmpty()
+ renderedQuery = search.query
+ when {
+ !search.isActive -> hideSearch(animate = wasSearching)
+ search.needsMoreCharacters -> showTypeMoreCharactersHint()
+ else -> showSearch(state)
+ }
- (context as? Activity)?.runOnUiThread {
- (searchResultsList.adapter as? ItemsAdapter)?.updateItems(filtered, text)
- searchResultsList.beVisible()
- searchPlaceholder.beVisibleIf(filtered.isEmpty())
- searchPlaceholder2.beGone()
- hideProgressBar()
- }
- }
- }
+ if (state.selectedPaths.isEmpty() && getRecyclerAdapter()?.hasActiveSelection() == true) {
+ getRecyclerAdapter()?.finishActMode()
}
}
- private fun setupLayoutManager() {
- if (context!!.config.getFolderViewType("") == VIEW_TYPE_GRID) {
- currentViewType = VIEW_TYPE_GRID
- setupGridLayoutManager()
+ private fun hideSearch(animate: Boolean) {
+ binding.searchResultsList.beGone()
+ hideProgressBar()
+ if (animate) {
+ binding.searchHolder.animate().alpha(0f).setDuration(SHORT_ANIMATION_DURATION).withEndAction {
+ binding.searchHolder.beGone()
+ }.start()
+ }
+ }
+
+ private fun showTypeMoreCharactersHint() {
+ showSearchHolder()
+ binding.searchResultsList.beGone()
+ binding.searchPlaceholder.beVisible()
+ binding.searchPlaceholder2.beVisible()
+ hideProgressBar()
+ }
+
+ private fun showSearch(state: StorageUiState) {
+ val search = state.search
+ showSearchHolder()
+ if (search.isSearching) {
+ showProgressBar()
} else {
- currentViewType = VIEW_TYPE_LIST
- setupListLayoutManager()
+ hideProgressBar()
}
- binding.searchResultsList.adapter = null
- addItems()
+ // until the first results arrive, the list keeps what it showed
+ if (search.resultsQuery != null) {
+ renderResults(state)
+ binding.searchResultsList.beVisible()
+ binding.searchPlaceholder.beVisibleIf(search.results.isEmpty())
+ binding.searchPlaceholder2.beGone()
+ }
}
- private fun setupGridLayoutManager() {
- val layoutManager = binding.searchResultsList.layoutManager as MyGridLayoutManager
- layoutManager.spanCount = context?.config?.fileColumnCnt ?: 3
+ private fun showSearchHolder() {
+ if (binding.searchHolder.alpha < 1f) {
+ binding.searchHolder.fadeIn()
+ }
}
- private fun setupListLayoutManager() {
- val layoutManager = binding.searchResultsList.layoutManager as MyGridLayoutManager
- layoutManager.spanCount = 1
+ private fun renderResults(state: StorageUiState) {
+ val adapter = getRecyclerAdapter()
+ val results = state.search.results
+ if (adapter == null || state.viewType != currentViewType) {
+ showNewList(state)
+ } else if (results != renderedResults) {
+ adapter.updateItems(ArrayList(results.map { it.toListItem() }), state.search.resultsQuery.orEmpty())
+ }
+ renderedResults = results
}
- private fun addItems() {
- ItemsAdapter(context as SimpleActivity, ArrayList(), this, binding.searchResultsList, false, null, false) {
+ private fun showNewList(state: StorageUiState) {
+ val activity = activity ?: return
+ getRecyclerAdapter()?.finishActMode()
+ setupLayoutManager(state.viewType)
+
+ val listItems = ArrayList(state.search.results.map { it.toListItem() })
+ ItemsAdapter(activity, listItems, this, binding.searchResultsList, false, null, false) {
clickedPath((it as FileDirItem).path)
}.apply {
binding.searchResultsList.adapter = this
+ updateItems(listItems, state.search.resultsQuery.orEmpty())
+ }
+
+ viewModel.scrollPosition?.let {
+ getRecyclerLayoutManager().scrollToPositionWithOffset(it.index, it.offset)
+ }
+
+ if (state.selectedPaths.isNotEmpty()) {
+ post {
+ getRecyclerAdapter()?.restoreSelection(viewModel.uiState.value.selectedPaths)
+ }
}
}
- private fun getAllFiles(volumeName: String): ArrayList<FileDirItem> {
- val fileDirItems = ArrayList<FileDirItem>()
- val showHidden = context?.config?.shouldShowHidden() ?: return fileDirItems
- val uri = MediaStore.Files.getContentUri(volumeName)
- val projection = arrayOf(
- MediaStore.Files.FileColumns.DATA,
- MediaStore.Files.FileColumns.DISPLAY_NAME,
- MediaStore.Files.FileColumns.SIZE,
- MediaStore.Files.FileColumns.DATE_MODIFIED
- )
+ private fun handleEvent(event: StorageEvent) {
+ when (event) {
+ is StorageEvent.Error -> activity?.showErrorToast(event.message)
+ }
+ }
+ // endregion
- try {
- val queryArgs = bundleOf(
- ContentResolver.QUERY_ARG_SORT_COLUMNS to arrayOf(MediaStore.Files.FileColumns.DATE_MODIFIED),
- ContentResolver.QUERY_ARG_SORT_DIRECTION to ContentResolver.QUERY_SORT_DIRECTION_DESCENDING
+ private fun applyVolumeColors(volumeBinding: ItemStorageVolumeBinding) {
+ val properPrimaryColor = context.getProperPrimaryColor()
+ volumeBinding.apply {
+ mainStorageUsageProgressbar.setIndicatorColor(properPrimaryColor)
+ mainStorageUsageProgressbar.trackColor = properPrimaryColor.adjustAlpha(LOWER_ALPHA)
+ val typeColors = listOf(
+ R.color.md_red_700,
+ R.color.md_green_700,
+ R.color.md_light_blue_700,
+ R.color.md_yellow_700,
+ R.color.md_teal_700,
+ R.color.md_pink_700
)
- context?.contentResolver?.query(uri, projection, queryArgs, null)?.use { cursor ->
- if (cursor.moveToFirst()) {
- do {
- try {
- val name = cursor.getStringValue(MediaStore.Files.FileColumns.DISPLAY_NAME)
- if (!showHidden && name.startsWith(".")) {
- continue
- }
-
- val size = cursor.getLongValue(MediaStore.Files.FileColumns.SIZE)
- if (size == 0L) {
- continue
- }
-
- val path = cursor.getStringValue(MediaStore.Files.FileColumns.DATA)
- val lastModified = cursor.getLongValue(MediaStore.Files.FileColumns.DATE_MODIFIED) * 1000
- fileDirItems.add(FileDirItem(path, name, false, 0, size, lastModified))
- } catch (e: Exception) {
- }
- } while (cursor.moveToNext())
- }
+ fileTypeViews().zip(typeColors).forEach { (views, colorId) ->
+ val color = context.resources.getColor(colorId, context.theme)
+ views.third.setIndicatorColor(color)
+ views.third.trackColor = color.adjustAlpha(LOWER_ALPHA)
}
- } catch (e: Exception) {
- context?.showErrorToast(e)
+
+ expandButton.applyColorFilter(properPrimaryColor)
+ }
+ }
+
+ private fun openStorageSettings() {
+ try {
+ context.startActivity(Intent(Settings.ACTION_INTERNAL_STORAGE_SETTINGS))
+ } catch (e: ActivityNotFoundException) {
+ activity?.showErrorToast(e)
+ }
+ }
+
+ private fun launchMimetypeActivity(mimetype: String, volumeName: String) {
+ Intent(context, MimeTypesActivity::class.java).apply {
+ putExtra(SHOW_MIMETYPE, mimetype)
+ putExtra(VOLUME_NAME, volumeName)
+ context.startActivity(this)
}
+ }
- return fileDirItems
+ private fun setupLayoutManager(viewType: Int) {
+ currentViewType = viewType
+ getRecyclerLayoutManager().spanCount = if (viewType == VIEW_TYPE_GRID) context.config.fileColumnCnt else 1
+ binding.searchResultsList.adapter = null
}
private fun showProgressBar() {
@@ -481,21 +411,45 @@ class StorageFragment(
binding.progressBar.hide()
}
+ private fun getRecyclerLayoutManager() = binding.searchResultsList.layoutManager as MyGridLayoutManager
+
private fun getRecyclerAdapter() = binding.searchResultsList.adapter as? ItemsAdapter
- override fun refreshFragment() {
- ensureBackgroundThread {
- val fileDirItems = volumes.keys.map { getAllFiles(it) }.flatten()
- allDeviceListItems = getListItemsFromFileDirItems(ArrayList(fileDirItems))
+ private fun saveScrollPosition() {
+ if (getRecyclerAdapter() == null) {
+ return
+ }
+
+ val layoutManager = getRecyclerLayoutManager()
+ val index = layoutManager.findFirstVisibleItemPosition()
+ if (index != RecyclerView.NO_POSITION) {
+ val offset = (layoutManager.findViewByPosition(index)?.top ?: 0) - binding.searchResultsList.paddingTop
+ viewModel.scrollPosition = ScrollPosition(index, offset)
+ }
+ }
+
+ override fun searchQueryChanged(text: String) {
+ if (::viewModel.isInitialized) {
+ viewModel.onSearchQueryChanged(text)
}
- setupLayoutManager()
}
+ override fun getSearchQuery(): String = if (::viewModel.isInitialized) viewModel.uiState.value.search.query else ""
+
override fun deleteFiles(files: ArrayList<FileDirItem>) {
handleFileDeleting(files, false)
+ viewModel.onItemsDeleted(files.map { it.path })
}
- override fun selectedPaths(paths: ArrayList<String>) {}
+ override fun selectionChanged(selectedPaths: Set<String>) {
+ if (activity?.isChangingConfigurations != true && ::viewModel.isInitialized) {
+ viewModel.onSelectionChanged(selectedPaths)
+ }
+ }
+
+ override fun selectedPaths(paths: ArrayList<String>) {
+ // the storage search results are not offered for picking files
+ }
override fun setupDateTimeFormat() {
getRecyclerAdapter()?.updateDateTimeFormat()
@@ -510,7 +464,9 @@ class StorageFragment(
}
override fun columnCountChanged() {
- (binding.searchResultsList.layoutManager as MyGridLayoutManager).spanCount = context!!.config.fileColumnCnt
+ if (currentViewType == VIEW_TYPE_GRID) {
+ getRecyclerLayoutManager().spanCount = context.config.fileColumnCnt
+ }
getRecyclerAdapter()?.apply {
notifyItemRangeChanged(0, listItems.size)
}
@@ -519,4 +475,9 @@ class StorageFragment(
override fun finishActMode() {
getRecyclerAdapter()?.finishActMode()
}
+
+ private companion object {
+ /** The progress bars count in units of 100 kB so that big volumes fit into an Int. */
+ const val SIZE_DIVIDER = 100_000
+ }
}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/helpers/RootHelpers.kt b/app/src/main/kotlin/org/fossify/filemanager/helpers/RootHelpers.kt
index e5844e9..f728d84 100644
--- a/app/src/main/kotlin/org/fossify/filemanager/helpers/RootHelpers.kt
+++ b/app/src/main/kotlin/org/fossify/filemanager/helpers/RootHelpers.kt
@@ -1,6 +1,6 @@
package org.fossify.filemanager.helpers
-import android.app.Activity
+import android.content.Context
import com.stericson.RootShell.execution.Command
import com.stericson.RootTools.RootTools
import org.fossify.commons.extensions.areDigitsOnly
@@ -13,7 +13,7 @@ import org.fossify.filemanager.extensions.config
import org.fossify.filemanager.models.ListItem
import java.io.File
-class RootHelpers(val activity: Activity) {
+class RootHelpers(val context: Context) {
fun askRootIfNeeded(callback: (success: Boolean) -> Unit) {
val cmd = "ls -lA"
val command = object : Command(0, cmd) {
@@ -26,7 +26,7 @@ class RootHelpers(val activity: Activity) {
try {
RootTools.getShell(true).add(command)
} catch (exception: Exception) {
- activity.showErrorToast(exception)
+ context.showErrorToast(exception)
callback(false)
}
}
@@ -36,7 +36,7 @@ class RootHelpers(val activity: Activity) {
val fullLines = it
val files = ArrayList<ListItem>()
- val hiddenArgument = if (activity.config.shouldShowHidden()) "-A " else ""
+ val hiddenArgument = if (context.config.shouldShowHidden()) "-A " else ""
val cmd = "ls $hiddenArgument$path"
val command = object : Command(0, cmd) {
@@ -66,7 +66,7 @@ class RootHelpers(val activity: Activity) {
private fun getFullLines(path: String, callback: (ArrayList<String>) -> Unit) {
val fullLines = ArrayList<String>()
- val hiddenArgument = if (activity.config.shouldShowHidden()) "-Al " else "-l "
+ val hiddenArgument = if (context.config.shouldShowHidden()) "-Al " else "-l "
val cmd = "ls $hiddenArgument$path"
val command = object : Command(0, cmd) {
@@ -85,7 +85,7 @@ class RootHelpers(val activity: Activity) {
}
private fun getChildrenCount(files: ArrayList<ListItem>, path: String, callback: (originalPath: String, listItems: ArrayList<ListItem>) -> Unit) {
- val hiddenArgument = if (activity.config.shouldShowHidden()) "-A " else ""
+ val hiddenArgument = if (context.config.shouldShowHidden()) "-A " else ""
var cmd = ""
files.filter { it.isDirectory }.forEach {
cmd += "ls $hiddenArgument${it.path} |wc -l;"
@@ -107,7 +107,7 @@ class RootHelpers(val activity: Activity) {
}
}
- if (activity.config.getFolderSorting(path) and SORT_BY_SIZE == 0) {
+ if (context.config.getFolderSorting(path) and SORT_BY_SIZE == 0) {
callback(path, files)
} else {
getFileSizes(files, path, callback)
@@ -158,13 +158,13 @@ class RootHelpers(val activity: Activity) {
try {
RootTools.getShell(true).add(command)
} catch (e: Exception) {
- activity.showErrorToast(e)
+ context.showErrorToast(e)
}
}
fun createFileFolder(path: String, isFile: Boolean, callback: (success: Boolean) -> Unit) {
if (!RootTools.isRootAvailable()) {
- activity.toast(R.string.rooted_device_only)
+ context.toast(R.string.rooted_device_only)
return
}
@@ -248,7 +248,7 @@ class RootHelpers(val activity: Activity) {
fun deleteFiles(fileDirItems: ArrayList<FileDirItem>) {
if (!RootTools.isRootAvailable()) {
- activity.toast(R.string.rooted_device_only)
+ context.toast(R.string.rooted_device_only)
return
}
@@ -270,7 +270,7 @@ class RootHelpers(val activity: Activity) {
fun copyMoveFiles(fileDirItems: ArrayList<FileDirItem>, destination: String, isCopyOperation: Boolean, successes: Int = 0, callback: (Int) -> Unit) {
if (!RootTools.isRootAvailable()) {
- activity.toast(R.string.rooted_device_only)
+ context.toast(R.string.rooted_device_only)
return
}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/interfaces/ItemOperationsListener.kt b/app/src/main/kotlin/org/fossify/filemanager/interfaces/ItemOperationsListener.kt
index 2812527..2cc9d91 100644
--- a/app/src/main/kotlin/org/fossify/filemanager/interfaces/ItemOperationsListener.kt
+++ b/app/src/main/kotlin/org/fossify/filemanager/interfaces/ItemOperationsListener.kt
@@ -18,4 +18,9 @@ interface ItemOperationsListener {
fun columnCountChanged()
fun finishActMode()
+
+ /** Called whenever the set of selected items changes; an empty set means the selection mode ended. */
+ fun selectionChanged(selectedPaths: Set<String>) {
+ // only the screens that keep their selection in a ViewModel need this
+ }
}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/models/FileItem.kt b/app/src/main/kotlin/org/fossify/filemanager/models/FileItem.kt
new file mode 100644
index 0000000..9352509
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/models/FileItem.kt
@@ -0,0 +1,27 @@
+package org.fossify.filemanager.models
+
+import org.fossify.commons.models.FileDirItem
+
+/**
+ * Immutable description of one row of a file list, as exposed by the ViewModels' UI state.
+ * [isSectionTitle] marks folder headers in search results,
+ * [isGridTypeDivider] the divider between folders and files in grid mode.
+ */
+data class FileItem(
+ val path: String,
+ val name: String,
+ val isDirectory: Boolean = false,
+ val children: Int = 0,
+ val size: Long = 0L,
+ val modified: Long = 0L,
+ val isSectionTitle: Boolean = false,
+ val isGridTypeDivider: Boolean = false,
+) {
+ val parentPath: String
+ get() = path.removeSuffix("/${path.substringAfterLast('/')}")
+
+ /** Creates a fresh, adapter-owned [ListItem]; the adapter may mutate it without affecting the UI state. */
+ fun toListItem() = ListItem(path, name, isDirectory, children, size, modified, isSectionTitle, isGridTypeDivider)
+}
+
+fun FileDirItem.toFileItem() = FileItem(path, name, isDirectory, children, size, modified)
diff --git a/app/src/main/kotlin/org/fossify/filemanager/repositories/ConfigFileListSettings.kt b/app/src/main/kotlin/org/fossify/filemanager/repositories/ConfigFileListSettings.kt
new file mode 100644
index 0000000..6138ca3
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/repositories/ConfigFileListSettings.kt
@@ -0,0 +1,15 @@
+package org.fossify.filemanager.repositories
+
+import android.content.Context
+import org.fossify.filemanager.extensions.config
+
+/** [FileListSettings] read from the app's shared preferences. */
+class ConfigFileListSettings(context: Context) : FileListSettings {
+ private val context = context.applicationContext
+
+ override fun getFolderSorting(path: String) = context.config.getFolderSorting(path)
+
+ override fun getFolderViewType(path: String) = context.config.getFolderViewType(path)
+
+ override fun shouldShowHidden() = context.config.shouldShowHidden()
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/repositories/DeviceFilesRepository.kt b/app/src/main/kotlin/org/fossify/filemanager/repositories/DeviceFilesRepository.kt
new file mode 100644
index 0000000..c523f0f
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/repositories/DeviceFilesRepository.kt
@@ -0,0 +1,124 @@
+package org.fossify.filemanager.repositories
+
+import android.annotation.SuppressLint
+import android.content.Context
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.suspendCancellableCoroutine
+import org.fossify.commons.extensions.getAndroidSAFFileItems
+import org.fossify.commons.extensions.getFolderLastModifieds
+import org.fossify.commons.extensions.getMimeType
+import org.fossify.commons.extensions.getOTGItems
+import org.fossify.commons.extensions.getProperSize
+import org.fossify.commons.extensions.humanizePath
+import org.fossify.commons.extensions.isPathOnOTG
+import org.fossify.commons.extensions.isRestrictedSAFOnlyRoot
+import org.fossify.commons.helpers.SORT_BY_SIZE
+import org.fossify.commons.helpers.VIEW_TYPE_LIST
+import org.fossify.commons.models.FileDirItem
+import org.fossify.filemanager.extensions.config
+import org.fossify.filemanager.extensions.isPathOnRoot
+import org.fossify.filemanager.helpers.RootHelpers
+import org.fossify.filemanager.models.FileItem
+import org.fossify.filemanager.models.toFileItem
+import java.io.File
+import kotlin.coroutines.resume
+
+/** [FilesRepository] backed by the device storage: regular files, SAF-only folders, OTG devices and root. */
+class DeviceFilesRepository(context: Context) : FilesRepository {
+ private val context = context.applicationContext
+
+ override fun requiresSafAccess(path: String) = context.isRestrictedSAFOnlyRoot(path)
+
+ @SuppressLint("NewApi")
+ override suspend fun listFolder(path: String, request: FolderRequest): List<FileItem> {
+ val config = context.config
+ val isSortingBySize = request.sorting and SORT_BY_SIZE != 0
+ return when {
+ context.isRestrictedSAFOnlyRoot(path) -> {
+ var items = emptyList<FileItem>()
+ val getProperChildCount = request.viewType == VIEW_TYPE_LIST
+ context.getAndroidSAFFileItems(path, request.showHidden, getProperChildCount) { fileItems ->
+ items = fileItems.map { it.toFileItem() }
+ }
+ items
+ }
+
+ context.isPathOnOTG(path) && config.OTGTreeUri.isNotEmpty() -> {
+ var items = emptyList<FileItem>()
+ context.getOTGItems(path, request.showHidden, isSortingBySize) { fileItems ->
+ items = fileItems.map { it.toFileItem() }
+ }
+ items
+ }
+
+ !config.enableRootAccess || !context.isPathOnRoot(path) -> {
+ listRegularFolder(path, request.showHidden, isSortingBySize)
+ }
+
+ else -> listRootFolder(path)
+ }
+ }
+
+ private fun listRegularFolder(path: String, showHidden: Boolean, isSortingBySize: Boolean): List<FileItem> {
+ val files = File(path).listFiles()?.filterNotNull() ?: return emptyList()
+ val lastModifieds = context.getFolderLastModifieds(path)
+ return files.filter { showHidden || !it.name.startsWith(".") }.map { file ->
+ val isDirectory = file.isDirectory
+ val size = when {
+ !isDirectory -> file.length()
+ isSortingBySize -> file.getProperSize(showHidden)
+ else -> 0L
+ }
+ val lastModified = lastModifieds.remove(file.absolutePath) ?: file.lastModified()
+ FileItem(file.absolutePath, file.name, isDirectory, 0, size, lastModified)
+ }
+ }
+
+ private suspend fun listRootFolder(path: String): List<FileItem> = suspendCancellableCoroutine { continuation ->
+ RootHelpers(context).getFiles(path) { _, listItems ->
+ if (continuation.isActive) {
+ continuation.resume(listItems.map { it.toFileItem() })
+ }
+ }
+ }
+
+ override suspend fun countDirectChildren(path: String, showHidden: Boolean): Int {
+ return FileDirItem(path, isDirectory = true).getDirectChildrenCount(context, showHidden)
+ }
+
+ override suspend fun search(rootPath: String, showHidden: Boolean, matches: (String) -> Boolean): List<FileItem> {
+ val results = ArrayList<FileItem>()
+ searchIn(File(rootPath), showHidden, matches, results)
+ return results
+ }
+
+ private suspend fun searchIn(
+ folder: File,
+ showHidden: Boolean,
+ matches: (String) -> Boolean,
+ results: MutableList<FileItem>,
+ ) {
+ currentCoroutineContext().ensureActive()
+ val children = folder.listFiles()?.sortedBy { it.isDirectory } ?: return
+ for (file in children) {
+ if (!showHidden && file.isHidden) {
+ continue
+ }
+
+ val isDirectory = file.isDirectory
+ if (matches(file.name)) {
+ val size = if (isDirectory) 0L else file.length()
+ results.add(FileItem(file.absolutePath, file.name, isDirectory, 0, size, file.lastModified()))
+ }
+
+ if (isDirectory) {
+ searchIn(file, showHidden, matches, results)
+ }
+ }
+ }
+
+ override fun humanizePath(path: String) = context.humanizePath(path)
+
+ override fun getMimeType(path: String) = path.getMimeType()
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/repositories/FilesRepository.kt b/app/src/main/kotlin/org/fossify/filemanager/repositories/FilesRepository.kt
new file mode 100644
index 0000000..d3bc182
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/repositories/FilesRepository.kt
@@ -0,0 +1,49 @@
+package org.fossify.filemanager.repositories
+
+import org.fossify.filemanager.models.FileItem
+
+/** Parameters of a folder listing that influence what the storage layer has to compute. */
+data class FolderRequest(
+ val showHidden: Boolean,
+ val sorting: Int,
+ val viewType: Int,
+)
+
+/**
+ * File system access for the Files tab. All functions may block and are called from the ViewModel's IO dispatcher.
+ */
+interface FilesRepository {
+ /** True when [path] can only be read through the Storage Access Framework (Android/data, Android/obb). */
+ fun requiresSafAccess(path: String): Boolean
+
+ /** Lists the direct children of [path]. The result is unsorted and may still contain hidden items. */
+ suspend fun listFolder(path: String, request: FolderRequest): List<FileItem>
+
+ /** Counts the direct children of the folder at [path]. */
+ suspend fun countDirectChildren(path: String, showHidden: Boolean): Int
+
+ /** Recursively walks [rootPath] and returns every file and folder whose name satisfies [matches]. */
+ suspend fun search(rootPath: String, showHidden: Boolean, matches: (String) -> Boolean): List<FileItem>
+
+ /** A user friendly version of [path], e.g. "Internal storage/Download". */
+ fun humanizePath(path: String): String
+
+ fun getMimeType(path: String): String
+}
+
+/** Recently modified files, for the Recents tab. */
+interface RecentsRepository {
+ /** Returns up to [limit] of the most recently modified existing files, newest first. */
+ suspend fun getRecentFiles(limit: Int): List<FileItem>
+
+ fun getMimeType(path: String): String
+}
+
+/** The user preferences the file lists depend on. */
+interface FileListSettings {
+ fun getFolderSorting(path: String): Int
+
+ fun getFolderViewType(path: String): Int
+
+ fun shouldShowHidden(): Boolean
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/repositories/MediaStoreRecentsRepository.kt b/app/src/main/kotlin/org/fossify/filemanager/repositories/MediaStoreRecentsRepository.kt
new file mode 100644
index 0000000..28a6730
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/repositories/MediaStoreRecentsRepository.kt
@@ -0,0 +1,63 @@
+package org.fossify.filemanager.repositories
+
+import android.content.ContentResolver
+import android.content.Context
+import android.database.Cursor
+import android.provider.MediaStore.Files
+import android.provider.MediaStore.Files.FileColumns
+import androidx.core.os.bundleOf
+import org.fossify.commons.extensions.getDoesFilePathExist
+import org.fossify.commons.extensions.getFilenameFromPath
+import org.fossify.commons.extensions.getLongValue
+import org.fossify.commons.extensions.getMimeType
+import org.fossify.commons.extensions.getStringValue
+import org.fossify.filemanager.models.FileItem
+import java.io.File
+
+/** [RecentsRepository] reading the most recently modified files from the MediaStore. */
+class MediaStoreRecentsRepository(context: Context) : RecentsRepository {
+ private val context = context.applicationContext
+
+ override suspend fun getRecentFiles(limit: Int): List<FileItem> {
+ val items = ArrayList<FileItem>()
+ val uri = Files.getContentUri("external")
+ val projection = arrayOf(
+ FileColumns.DATA,
+ FileColumns.DISPLAY_NAME,
+ FileColumns.DATE_MODIFIED,
+ FileColumns.SIZE
+ )
+
+ val queryArgs = bundleOf(
+ ContentResolver.QUERY_ARG_LIMIT to limit,
+ ContentResolver.QUERY_ARG_SORT_COLUMNS to arrayOf(FileColumns.DATE_MODIFIED),
+ ContentResolver.QUERY_ARG_SORT_DIRECTION to ContentResolver.QUERY_SORT_DIRECTION_DESCENDING
+ )
+
+ context.contentResolver.query(uri, projection, queryArgs, null)?.use { cursor ->
+ while (cursor.moveToNext()) {
+ readExistingFile(cursor)?.let { items.add(it) }
+ }
+ }
+
+ return items
+ }
+
+ private fun readExistingFile(cursor: Cursor): FileItem? {
+ val path = cursor.getStringValue(FileColumns.DATA)
+ if (path == null || File(path).isDirectory || !context.getDoesFilePathExist(path)) {
+ return null
+ }
+
+ val name = cursor.getStringValue(FileColumns.DISPLAY_NAME) ?: path.getFilenameFromPath()
+ val size = cursor.getLongValue(FileColumns.SIZE)
+ val modified = cursor.getLongValue(FileColumns.DATE_MODIFIED) * MILLIS_IN_SECOND
+ return FileItem(path, name, false, 0, size, modified)
+ }
+
+ override fun getMimeType(path: String) = path.getMimeType()
+
+ private companion object {
+ const val MILLIS_IN_SECOND = 1000L
+ }
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/repositories/MediaStoreStorageRepository.kt b/app/src/main/kotlin/org/fossify/filemanager/repositories/MediaStoreStorageRepository.kt
new file mode 100644
index 0000000..3e1bd80
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/repositories/MediaStoreStorageRepository.kt
@@ -0,0 +1,116 @@
+package org.fossify.filemanager.repositories
+
+import android.app.usage.StorageStatsManager
+import android.content.ContentResolver
+import android.content.Context
+import android.database.Cursor
+import android.os.storage.StorageManager
+import android.provider.MediaStore.Files
+import android.provider.MediaStore.Files.FileColumns
+import androidx.core.os.bundleOf
+import org.fossify.commons.extensions.getIsPathDirectory
+import org.fossify.commons.extensions.getLongValue
+import org.fossify.commons.extensions.getStringValue
+import org.fossify.commons.extensions.queryCursor
+import org.fossify.filemanager.extensions.getAllVolumeNames
+import org.fossify.filemanager.helpers.OTHERS
+import org.fossify.filemanager.helpers.PRIMARY_VOLUME_NAME
+import org.fossify.filemanager.models.FileItem
+import org.fossify.filemanager.viewmodels.StorageUsageRules
+import java.util.Locale
+
+/**
+ * [StorageRepository] reading the volume capacities from the system and the files and their usage per file type
+ * from the MediaStore.
+ */
+class MediaStoreStorageRepository(context: Context) : StorageRepository {
+ private val context = context.applicationContext
+
+ override fun getVolumeNames(): List<String> = context.getAllVolumeNames()
+
+ override suspend fun getVolumeStats(): List<VolumeStats> {
+ val storageManager = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
+ return context.getExternalFilesDirs(null).filterNotNull().mapNotNull { file ->
+ val storageVolume = storageManager.getStorageVolume(file) ?: return@mapNotNull null
+ if (storageVolume.isPrimary) {
+ // internal storage
+ val storageStatsManager =
+ context.getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager
+ val uuid = StorageManager.UUID_DEFAULT
+ VolumeStats(
+ volumeName = PRIMARY_VOLUME_NAME,
+ totalBytes = storageStatsManager.getTotalBytes(uuid),
+ freeBytes = storageStatsManager.getFreeBytes(uuid)
+ )
+ } else {
+ val uuid = storageVolume.uuid ?: return@mapNotNull null
+ VolumeStats(uuid.lowercase(Locale.US), file.totalSpace, file.freeSpace)
+ }
+ }
+ }
+
+ override suspend fun getSizesByFileType(volumeName: String): Map<String, Long> {
+ val sizes = StorageUsageRules.FILE_TYPES.associateWithTo(LinkedHashMap()) { 0L }
+ val projection = arrayOf(FileColumns.SIZE, FileColumns.MIME_TYPE, FileColumns.DATA)
+ context.queryCursor(Files.getContentUri(volumeName), projection) { cursor ->
+ // a row that cannot be read is skipped, as a file whose type is unknown
+ runCatching { fileTypeOf(cursor) }.getOrNull()?.let { (fileType, size) ->
+ sizes[fileType] = sizes.getValue(fileType) + size
+ }
+ }
+
+ return sizes
+ }
+
+ private fun fileTypeOf(cursor: Cursor): Pair<String, Long>? {
+ val size = cursor.getLongValue(FileColumns.SIZE)
+ val mimeType = cursor.getStringValue(FileColumns.MIME_TYPE)?.lowercase(Locale.getDefault())
+ return when {
+ mimeType != null -> StorageUsageRules.fileTypeOf(mimeType) to size
+ StorageUsageRules.mayBeUntypedFile(size) &&
+ !context.getIsPathDirectory(cursor.getStringValue(FileColumns.DATA)) -> OTHERS to size
+
+ else -> null
+ }
+ }
+
+ override suspend fun getFiles(volumeName: String, showHidden: Boolean): List<FileItem> {
+ val items = ArrayList<FileItem>()
+ val projection = arrayOf(
+ FileColumns.DATA,
+ FileColumns.DISPLAY_NAME,
+ FileColumns.SIZE,
+ FileColumns.DATE_MODIFIED
+ )
+
+ val queryArgs = bundleOf(
+ ContentResolver.QUERY_ARG_SORT_COLUMNS to arrayOf(FileColumns.DATE_MODIFIED),
+ ContentResolver.QUERY_ARG_SORT_DIRECTION to ContentResolver.QUERY_SORT_DIRECTION_DESCENDING
+ )
+
+ context.contentResolver.query(Files.getContentUri(volumeName), projection, queryArgs, null)?.use { cursor ->
+ while (cursor.moveToNext()) {
+ // a row that cannot be read is skipped
+ runCatching { readFile(cursor, showHidden) }.getOrNull()?.let { items.add(it) }
+ }
+ }
+
+ return items
+ }
+
+ private fun readFile(cursor: Cursor, showHidden: Boolean): FileItem? {
+ val name = cursor.getStringValue(FileColumns.DISPLAY_NAME)
+ val size = cursor.getLongValue(FileColumns.SIZE)
+ if ((!showHidden && name.startsWith(".")) || size == 0L) {
+ return null
+ }
+
+ val path = cursor.getStringValue(FileColumns.DATA)
+ val modified = cursor.getLongValue(FileColumns.DATE_MODIFIED) * MILLIS_IN_SECOND
+ return FileItem(path, name, false, 0, size, modified)
+ }
+
+ private companion object {
+ const val MILLIS_IN_SECOND = 1000L
+ }
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/repositories/StorageRepository.kt b/app/src/main/kotlin/org/fossify/filemanager/repositories/StorageRepository.kt
new file mode 100644
index 0000000..8c42f50
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/repositories/StorageRepository.kt
@@ -0,0 +1,32 @@
+package org.fossify.filemanager.repositories
+
+import org.fossify.filemanager.models.FileItem
+
+/** Capacity of one storage volume, in bytes. */
+data class VolumeStats(
+ val volumeName: String,
+ val totalBytes: Long,
+ val freeBytes: Long,
+)
+
+/**
+ * Storage volumes and the media store, for the Storage tab. All functions may block and are called from the
+ * ViewModel's IO dispatcher.
+ */
+interface StorageRepository {
+ /** Media store names of the mounted volumes, the primary (internal) one first. */
+ fun getVolumeNames(): List<String>
+
+ /** Capacity of every mounted volume whose size can be read. */
+ suspend fun getVolumeStats(): List<VolumeStats>
+
+ /**
+ * Bytes used on [volumeName] by each file type, keyed by
+ * [org.fossify.filemanager.helpers.IMAGES], [org.fossify.filemanager.helpers.VIDEOS], ... and
+ * [org.fossify.filemanager.helpers.OTHERS].
+ */
+ suspend fun getSizesByFileType(volumeName: String): Map<String, Long>
+
+ /** Every non-empty file the media store knows on [volumeName], newest first. */
+ suspend fun getFiles(volumeName: String, showHidden: Boolean): List<FileItem>
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/viewmodels/FileListRules.kt b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/FileListRules.kt
new file mode 100644
index 0000000..ad5aec9
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/FileListRules.kt
@@ -0,0 +1,77 @@
+package org.fossify.filemanager.viewmodels
+
+import org.fossify.commons.helpers.AlphanumericComparator
+import org.fossify.commons.helpers.SORT_BY_DATE_MODIFIED
+import org.fossify.commons.helpers.SORT_BY_NAME
+import org.fossify.commons.helpers.SORT_BY_SIZE
+import org.fossify.commons.helpers.SORT_DESCENDING
+import org.fossify.commons.helpers.SORT_USE_NUMERIC_VALUE
+import org.fossify.filemanager.models.FileItem
+import java.text.Normalizer
+
+/**
+ * Pure (Android-free) listing rules shared by the ViewModels: sorting, name matching, hidden and mime type filtering.
+ */
+internal object FileListRules {
+ private val combiningMarks = "\\p{InCombiningDiacriticalMarks}+".toRegex()
+ private val alphanumericComparator = AlphanumericComparator()
+
+ /** Same order as [org.fossify.commons.models.FileDirItem.compareTo]: folders first, then by the sorting flags. */
+ fun comparator(sorting: Int): Comparator<FileItem> = Comparator { first, second ->
+ when {
+ first.isDirectory && !second.isDirectory -> -1
+ !first.isDirectory && second.isDirectory -> 1
+ else -> {
+ val result = compareSameKind(first, second, sorting)
+ if (sorting and SORT_DESCENDING != 0) -result else result
+ }
+ }
+ }
+
+ private fun compareSameKind(first: FileItem, second: FileItem, sorting: Int): Int = when {
+ sorting and SORT_BY_NAME != 0 -> {
+ val firstName = first.name.normalize().lowercase()
+ val secondName = second.name.normalize().lowercase()
+ if (sorting and SORT_USE_NUMERIC_VALUE != 0) {
+ alphanumericComparator.compare(firstName, secondName)
+ } else {
+ firstName.compareTo(secondName)
+ }
+ }
+
+ sorting and SORT_BY_SIZE != 0 -> first.size.compareTo(second.size).coerceIn(-1, 1)
+ sorting and SORT_BY_DATE_MODIFIED != 0 -> first.modified.compareTo(second.modified).coerceIn(-1, 1)
+ else -> first.extension().lowercase().compareTo(second.extension().lowercase())
+ }
+
+ private fun FileItem.extension() = if (isDirectory) name else path.substringAfterLast('.', "")
+
+ fun String.normalize(): String = Normalizer.normalize(this, Normalizer.Form.NFD).replace(combiningMarks, "")
+
+ /** Case and diacritics insensitive "contains" matcher, as used by the search fields. */
+ fun nameMatcher(query: String): (String) -> Boolean {
+ val normalizedQuery = query.normalize()
+ return { name -> name.normalize().contains(normalizedQuery, ignoreCase = true) }
+ }
+
+ fun isHiddenName(name: String) = name.startsWith(".")
+
+ /** Whether a file matches one of the mime types requested by a GET_CONTENT / PICK intent. */
+ fun matchesMimeTypes(
+ wantedMimeTypes: List<String>,
+ path: String,
+ isDirectory: Boolean,
+ mimeTypeOf: (String) -> String,
+ ): Boolean = wantedMimeTypes.any { wanted ->
+ if (wanted.isEmpty() || wanted == "*/*" || isDirectory) {
+ true
+ } else {
+ val fileMimeType = mimeTypeOf(path)
+ if (wanted.endsWith("/*")) {
+ fileMimeType.substringBefore("/").equals(wanted.substringBefore("/"), true)
+ } else {
+ fileMimeType.equals(wanted, true)
+ }
+ }
+ }
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/viewmodels/ItemsListing.kt b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/ItemsListing.kt
new file mode 100644
index 0000000..51fc272
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/ItemsListing.kt
@@ -0,0 +1,63 @@
+package org.fossify.filemanager.viewmodels
+
+import org.fossify.commons.helpers.VIEW_TYPE_GRID
+import org.fossify.filemanager.models.FileItem
+import org.fossify.filemanager.repositories.FilesRepository
+
+/**
+ * Turns what the [repository] returns into the rows of the Files tab: the folder listing as it is shown, the child
+ * counts of its folders and the search results grouped by folder. Kept apart from [ItemsViewModel], which holds the
+ * state and decides when to load; the functions that call the [repository] may block and run on its IO dispatcher.
+ */
+internal class ItemsListing(
+ private val repository: FilesRepository,
+ private val wantedMimeTypes: List<String>,
+) {
+ /** Filtered (hidden items, wanted mime types), sorted and, in grid mode, with a divider before the first file. */
+ fun listing(rawItems: List<FileItem>, sorting: Int, viewType: Int, showHidden: Boolean): List<FileItem> {
+ val items = rawItems
+ .filter { showHidden || !FileListRules.isHiddenName(it.name) }
+ .filter { matchesWantedMimeTypes(it) }
+ .sortedWith(FileListRules.comparator(sorting))
+ .toMutableList()
+
+ if (viewType == VIEW_TYPE_GRID && items.none { it.isSectionTitle }) {
+ val firstFileIndex = items.indexOfFirst { !it.isDirectory }
+ if (firstFileIndex > 0) {
+ items.add(firstFileIndex, FileItem(path = "", name = "", isGridTypeDivider = true))
+ }
+ }
+ return items
+ }
+
+ /** Child counts of the listed folders that have none yet, by path; folders without children are left out. */
+ suspend fun childCounts(items: List<FileItem>, showHidden: Boolean): Map<String, Int> =
+ items
+ .filter { it.isDirectory && !it.isSectionTitle && it.children == 0 }
+ .associate { it.path to repository.countDirectChildren(it.path, showHidden) }
+ .filterValues { it != 0 }
+
+ /** Groups the hits by folder: every file is preceded by a section title with its (humanized) parent folder. */
+ fun searchResults(hits: List<FileItem>): List<FileItem> {
+ val results = ArrayList<FileItem>()
+ var previousParent = ""
+ hits.sortedBy { it.parentPath }.forEach { hit ->
+ val parent = hit.parentPath
+ if (hit.isDirectory) {
+ val title = repository.humanizePath(hit.path)
+ results.add(FileItem(hit.path, title, isDirectory = true, isSectionTitle = true))
+ previousParent = parent
+ } else {
+ if (parent != previousParent) {
+ results.add(FileItem(parent, repository.humanizePath(parent), isSectionTitle = true))
+ previousParent = parent
+ }
+ results.add(hit)
+ }
+ }
+ return results
+ }
+
+ private fun matchesWantedMimeTypes(item: FileItem) =
+ FileListRules.matchesMimeTypes(wantedMimeTypes, item.path, item.isDirectory, repository::getMimeType)
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/viewmodels/ItemsUiState.kt b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/ItemsUiState.kt
new file mode 100644
index 0000000..04b2f45
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/ItemsUiState.kt
@@ -0,0 +1,89 @@
+package org.fossify.filemanager.viewmodels
+
+import org.fossify.commons.helpers.VIEW_TYPE_LIST
+import org.fossify.filemanager.models.FileItem
+
+/** Minimum query length that starts a recursive search; shorter non-empty queries show a hint instead. */
+const val MIN_SEARCH_QUERY_LENGTH = 2
+
+/**
+ * Everything the Files tab shows.
+ *
+ * @property currentPath the folder the user navigated to (may still be loading)
+ * @property listingPath the folder [items] belong to
+ * @property items the listing as it is shown: filtered, sorted and, in grid mode, with a folders/files divider
+ * @property pendingSafAccessPath a SAF-only folder that needs the user's permission before it can be listed
+ */
+data class ItemsUiState(
+ val currentPath: String = "",
+ val listingPath: String = "",
+ val items: List<FileItem> = emptyList(),
+ val sorting: Int = 0,
+ val viewType: Int = VIEW_TYPE_LIST,
+ val showHidden: Boolean = false,
+ val isLoading: Boolean = false,
+ val search: SearchState = SearchState(),
+ val selectedPaths: Set<String> = emptySet(),
+ val pendingSafAccessPath: String? = null,
+) {
+ /**
+ * The rows to display, or null when the list should be hidden (a too short search query)
+ * or keep its content (the first search is still running).
+ */
+ val displayedItems: List<FileItem>?
+ get() = when {
+ !search.isActive -> items
+ search.needsMoreCharacters -> null
+ search.resultsQuery != null -> search.results
+ else -> null
+ }
+
+ /** The text to highlight in the displayed rows. */
+ val highlightedText: String
+ get() = if (search.isActive) search.resultsQuery.orEmpty() else ""
+
+ /** The listing of [path] with the folder child [counts] filled in; unchanged when another folder is shown. */
+ fun withChildCounts(path: String, counts: Map<String, Int>): ItemsUiState =
+ if (counts.isEmpty() || listingPath != path) {
+ this
+ } else {
+ copy(items = items.map { item -> counts[item.path]?.let { item.copy(children = it) } ?: item })
+ }
+}
+
+/**
+ * @property query the current search text, empty when not searching
+ * @property results the search results with folder section titles, computed for [resultsQuery]
+ * @property isSearching whether a search for [query] is still running
+ */
+data class SearchState(
+ val query: String = "",
+ val results: List<FileItem> = emptyList(),
+ val resultsQuery: String? = null,
+ val isSearching: Boolean = false,
+) {
+ val isActive: Boolean
+ get() = query.isNotEmpty()
+
+ val needsMoreCharacters: Boolean
+ get() = query.isNotEmpty() && query.length < MIN_SEARCH_QUERY_LENGTH
+}
+
+/** Scroll offset of a list, restored when the user comes back to a folder or the screen is recreated. */
+data class ScrollPosition(val index: Int, val offset: Int)
+
+/** Scroll positions by key (a folder, or the search results in a folder). */
+class ScrollPositions {
+ private val positions = HashMap<String, ScrollPosition>()
+
+ operator fun get(key: String): ScrollPosition? = positions[key]
+
+ operator fun set(key: String, position: ScrollPosition) {
+ positions[key] = position
+ }
+}
+
+sealed interface ItemsEvent {
+ /** The user refused access to a SAF-only folder. */
+ data object StorageAccessDenied : ItemsEvent
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/viewmodels/ItemsViewModel.kt b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/ItemsViewModel.kt
new file mode 100644
index 0000000..dd3ecef
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/ItemsViewModel.kt
@@ -0,0 +1,242 @@
+package org.fossify.filemanager.viewmodels
+
+import android.content.Context
+import androidx.lifecycle.SavedStateHandle
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.createSavedStateHandle
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.receiveAsFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import org.fossify.commons.helpers.VIEW_TYPE_LIST
+import org.fossify.filemanager.repositories.ConfigFileListSettings
+import org.fossify.filemanager.repositories.DeviceFilesRepository
+import org.fossify.filemanager.repositories.FileListSettings
+import org.fossify.filemanager.repositories.FilesRepository
+import org.fossify.filemanager.repositories.FolderRequest
+
+/**
+ * State holder of the Files tab: the current folder and its listing, the search and the selection.
+ *
+ * The current folder and search query are kept in the [SavedStateHandle], so they survive process death.
+ * All file system work runs on [ioDispatcher]; turning it into rows is [ItemsListing]'s job.
+ */
+class ItemsViewModel(
+ private val savedStateHandle: SavedStateHandle,
+ private val repository: FilesRepository,
+ private val settings: FileListSettings,
+ wantedMimeTypes: List<String> = listOf(""),
+ private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
+) : ViewModel() {
+ private val _uiState = MutableStateFlow(
+ ItemsUiState(
+ currentPath = savedStateHandle.get<String>(KEY_CURRENT_PATH).orEmpty(),
+ search = SearchState(query = savedStateHandle.get<String>(KEY_SEARCH_QUERY).orEmpty())
+ )
+ )
+ val uiState: StateFlow<ItemsUiState> = _uiState.asStateFlow()
+
+ private val _events = Channel<ItemsEvent>(Channel.BUFFERED)
+ val events: Flow<ItemsEvent> = _events.receiveAsFlow()
+
+ private val listing = ItemsListing(repository, wantedMimeTypes)
+ private var loadJob: Job? = null
+ private var searchJob: Job? = null
+
+ /** Where the list was scrolled to in each folder and in its search results, kept when the screen is recreated. */
+ val scrollPositions = ScrollPositions()
+
+ init {
+ val restoredPath = _uiState.value.currentPath
+ if (restoredPath.isNotEmpty()) {
+ requestListing(restoredPath)
+ val restoredQuery = _uiState.value.search.query
+ if (restoredQuery.length >= MIN_SEARCH_QUERY_LENGTH) {
+ startSearch(restoredQuery)
+ }
+ }
+ }
+
+ /** Navigates to [path], closing any search. */
+ fun openPath(path: String) {
+ val realPath = path.trimEnd('/').ifEmpty { "/" }
+ searchJob?.cancel()
+ savedStateHandle[KEY_SEARCH_QUERY] = ""
+ _uiState.update { it.copy(search = SearchState()) }
+ requestListing(realPath)
+ }
+
+ /** Opens [path] unless a folder is already shown or being restored. */
+ fun openInitialPathIfNeeded(path: String) {
+ if (_uiState.value.currentPath.isEmpty()) {
+ openPath(path)
+ }
+ }
+
+ /** Reloads the current folder (and re-runs an active search), e.g. after pull-to-refresh or a file operation. */
+ fun refresh() {
+ viewModelScope.launch {
+ val state = _uiState.value
+ if (state.currentPath.isNotEmpty()) {
+ requestListing(state.currentPath)
+ if (state.search.query.length >= MIN_SEARCH_QUERY_LENGTH) {
+ startSearch(state.search.query)
+ }
+ }
+ }
+ }
+
+ /** Result of the SAF permission request triggered by [ItemsUiState.pendingSafAccessPath]. */
+ fun onSafAccessResult(path: String, granted: Boolean) {
+ val state = _uiState.value
+ if (state.pendingSafAccessPath != path) {
+ return
+ }
+
+ if (granted) {
+ _uiState.update { it.copy(pendingSafAccessPath = null) }
+ loadListing(path)
+ } else {
+ val previousPath = state.listingPath.ifEmpty { path }
+ savedStateHandle[KEY_CURRENT_PATH] = previousPath
+ _uiState.update { it.copy(pendingSafAccessPath = null, isLoading = false, currentPath = previousPath) }
+ _events.trySend(ItemsEvent.StorageAccessDenied)
+ }
+ }
+
+ fun onSearchQueryChanged(query: String) {
+ if (query == _uiState.value.search.query) {
+ return
+ }
+
+ searchJob?.cancel()
+ savedStateHandle[KEY_SEARCH_QUERY] = query
+ when {
+ query.isEmpty() -> _uiState.update { it.copy(search = SearchState()) }
+ query.length < MIN_SEARCH_QUERY_LENGTH -> _uiState.update { it.copy(search = SearchState(query = query)) }
+ else -> startSearch(query)
+ }
+ }
+
+ /** The selection as reported by the list; an empty set ends the selection mode. */
+ fun onSelectionChanged(paths: Set<String>) {
+ _uiState.update { if (it.selectedPaths == paths) it else it.copy(selectedPaths = paths) }
+ }
+
+ /** Removes deleted items from the listing and the search results right away, without reloading. */
+ fun onItemsDeleted(paths: Collection<String>) {
+ val deleted = paths.toSet()
+ viewModelScope.launch {
+ _uiState.update { state ->
+ state.copy(
+ items = state.items.filterNot { it.path in deleted },
+ search = state.search.copy(results = state.search.results.filterNot { it.path in deleted }),
+ selectedPaths = state.selectedPaths - deleted
+ )
+ }
+ }
+ }
+
+ private fun requestListing(path: String) {
+ loadJob?.cancel()
+ savedStateHandle[KEY_CURRENT_PATH] = path
+ _uiState.update { state ->
+ state.copy(
+ currentPath = path,
+ isLoading = true,
+ pendingSafAccessPath = null,
+ selectedPaths = if (path == state.listingPath) state.selectedPaths else emptySet()
+ )
+ }
+
+ if (repository.requiresSafAccess(path)) {
+ _uiState.update { it.copy(isLoading = false, pendingSafAccessPath = path) }
+ } else {
+ loadListing(path)
+ }
+ }
+
+ private fun loadListing(path: String) {
+ loadJob?.cancel()
+ _uiState.update { it.copy(isLoading = true) }
+ loadJob = viewModelScope.launch {
+ val showHidden = settings.shouldShowHidden()
+ val sorting = settings.getFolderSorting(path)
+ val viewType = settings.getFolderViewType(path)
+ val rawItems = withContext(ioDispatcher) {
+ repository.listFolder(path, FolderRequest(showHidden, sorting, viewType))
+ }
+
+ val items = listing.listing(rawItems, sorting, viewType, showHidden)
+ val itemPaths = items.mapTo(HashSet()) { it.path }
+ _uiState.update { state ->
+ state.copy(
+ listingPath = path,
+ items = items,
+ sorting = sorting,
+ viewType = viewType,
+ showHidden = showHidden,
+ isLoading = false,
+ selectedPaths = state.selectedPaths.filterTo(HashSet()) { it in itemPaths }
+ )
+ }
+
+ // the listing is shown right away; folder child counts can be slow, so they are filled in afterwards
+ if (viewType == VIEW_TYPE_LIST) {
+ val counts = withContext(ioDispatcher) { listing.childCounts(items, showHidden) }
+ _uiState.update { it.withChildCounts(path, counts) }
+ }
+ }
+ }
+
+ private fun startSearch(query: String) {
+ searchJob?.cancel()
+ _uiState.update { it.copy(search = it.search.copy(query = query, isSearching = true)) }
+ val rootPath = _uiState.value.currentPath
+ searchJob = viewModelScope.launch {
+ val showHidden = settings.shouldShowHidden()
+ val results = withContext(ioDispatcher) {
+ val hits = repository.search(rootPath, showHidden, FileListRules.nameMatcher(query))
+ listing.searchResults(hits)
+ }
+
+ _uiState.update { state ->
+ if (state.search.query != query) {
+ state
+ } else {
+ state.copy(
+ search = SearchState(query = query, results = results, resultsQuery = query),
+ selectedPaths = emptySet()
+ )
+ }
+ }
+ }
+ }
+
+ companion object {
+ const val KEY_CURRENT_PATH = "items_current_path"
+ const val KEY_SEARCH_QUERY = "items_search_query"
+
+ fun factory(context: Context, wantedMimeTypes: List<String>) = viewModelFactory {
+ initializer {
+ ItemsViewModel(
+ savedStateHandle = createSavedStateHandle(),
+ repository = DeviceFilesRepository(context),
+ settings = ConfigFileListSettings(context),
+ wantedMimeTypes = wantedMimeTypes
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/viewmodels/RecentsViewModel.kt b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/RecentsViewModel.kt
new file mode 100644
index 0000000..60560cc
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/RecentsViewModel.kt
@@ -0,0 +1,169 @@
+package org.fossify.filemanager.viewmodels
+
+import android.content.Context
+import androidx.lifecycle.SavedStateHandle
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.createSavedStateHandle
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.receiveAsFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import org.fossify.commons.helpers.VIEW_TYPE_LIST
+import org.fossify.filemanager.extensions.isPathInHiddenFolder
+import org.fossify.filemanager.models.FileItem
+import org.fossify.filemanager.repositories.ConfigFileListSettings
+import org.fossify.filemanager.repositories.FileListSettings
+import org.fossify.filemanager.repositories.MediaStoreRecentsRepository
+import org.fossify.filemanager.repositories.RecentsRepository
+
+/**
+ * Everything the Recents tab shows.
+ *
+ * @property items all recent files that may be shown (hidden and mime type filters applied)
+ * @property visibleItems [items] filtered by the search [query]
+ */
+data class RecentsUiState(
+ val items: List<FileItem> = emptyList(),
+ val query: String = "",
+ val visibleItems: List<FileItem> = emptyList(),
+ val viewType: Int = VIEW_TYPE_LIST,
+ val isLoading: Boolean = false,
+ val isLoaded: Boolean = false,
+ val selectedPaths: Set<String> = emptySet(),
+)
+
+sealed interface RecentsEvent {
+ data class Error(val message: String) : RecentsEvent
+}
+
+/** State holder of the Recents tab: the recent files, their search and the selection. */
+class RecentsViewModel(
+ private val savedStateHandle: SavedStateHandle,
+ private val repository: RecentsRepository,
+ private val settings: FileListSettings,
+ private val wantedMimeTypes: List<String> = listOf(""),
+ private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
+) : ViewModel() {
+ private val _uiState = MutableStateFlow(
+ RecentsUiState(query = savedStateHandle.get<String>(KEY_SEARCH_QUERY).orEmpty())
+ )
+ val uiState: StateFlow<RecentsUiState> = _uiState.asStateFlow()
+
+ private val _events = Channel<RecentsEvent>(Channel.BUFFERED)
+ val events: Flow<RecentsEvent> = _events.receiveAsFlow()
+
+ private var loadJob: Job? = null
+
+ /** Scroll position of the list, restored when the screen is recreated. */
+ var scrollPosition: ScrollPosition? = null
+
+ /** Loads the recent files unless they are already loaded, e.g. when the screen is recreated. */
+ fun loadIfNeeded() {
+ val state = _uiState.value
+ if (!state.isLoaded && !state.isLoading) {
+ refresh()
+ }
+ }
+
+ fun refresh() {
+ viewModelScope.launch {
+ loadJob?.cancel()
+ _uiState.update { it.copy(isLoading = true) }
+ loadJob = launch { load() }
+ }
+ }
+
+ private suspend fun load() {
+ val showHidden = settings.shouldShowHidden()
+ val viewType = settings.getFolderViewType("")
+ val recents = readOrElse(ioDispatcher, onFailure = {
+ _events.trySend(RecentsEvent.Error(it.toString()))
+ emptyList()
+ }) { repository.getRecentFiles(RECENTS_LIMIT) }
+
+ val items = recents.filter { item ->
+ val isShown = showHidden || (!FileListRules.isHiddenName(item.name) && !item.path.isPathInHiddenFolder())
+ isShown && FileListRules.matchesMimeTypes(wantedMimeTypes, item.path, false, repository::getMimeType)
+ }
+
+ val itemPaths = items.mapTo(HashSet()) { it.path }
+ _uiState.update { state ->
+ state.copy(
+ items = items,
+ visibleItems = filter(items, state.query),
+ viewType = viewType,
+ isLoading = false,
+ isLoaded = true,
+ selectedPaths = state.selectedPaths.filterTo(HashSet()) { it in itemPaths }
+ )
+ }
+ }
+
+ fun onSearchQueryChanged(query: String) {
+ if (query == _uiState.value.query) {
+ return
+ }
+
+ savedStateHandle[KEY_SEARCH_QUERY] = query
+ _uiState.update { state ->
+ val visibleItems = filter(state.items, query)
+ state.copy(
+ query = query,
+ visibleItems = visibleItems,
+ selectedPaths = if (visibleItems == state.visibleItems) state.selectedPaths else emptySet()
+ )
+ }
+ }
+
+ fun onSelectionChanged(paths: Set<String>) {
+ _uiState.update { if (it.selectedPaths == paths) it else it.copy(selectedPaths = paths) }
+ }
+
+ fun onItemsDeleted(paths: Collection<String>) {
+ val deleted = paths.toSet()
+ viewModelScope.launch {
+ _uiState.update { state ->
+ state.copy(
+ items = state.items.filterNot { it.path in deleted },
+ visibleItems = state.visibleItems.filterNot { it.path in deleted },
+ selectedPaths = state.selectedPaths - deleted
+ )
+ }
+ }
+ }
+
+ private fun filter(items: List<FileItem>, query: String): List<FileItem> {
+ if (query.isEmpty()) {
+ return items
+ }
+
+ val matches = FileListRules.nameMatcher(query)
+ return items.filter { matches(it.name) }
+ }
+
+ companion object {
+ const val KEY_SEARCH_QUERY = "recents_search_query"
+ const val RECENTS_LIMIT = 50
+
+ fun factory(context: Context, wantedMimeTypes: List<String>) = viewModelFactory {
+ initializer {
+ RecentsViewModel(
+ savedStateHandle = createSavedStateHandle(),
+ repository = MediaStoreRecentsRepository(context),
+ settings = ConfigFileListSettings(context),
+ wantedMimeTypes = wantedMimeTypes
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/viewmodels/RepositoryReads.kt b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/RepositoryReads.kt
new file mode 100644
index 0000000..e2ed9e2
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/RepositoryReads.kt
@@ -0,0 +1,32 @@
+package org.fossify.filemanager.viewmodels
+
+import android.database.SQLException
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.withContext
+import java.io.IOException
+
+/**
+ * Runs a repository [read] on [dispatcher] and returns [onFailure]'s value when it fails the way the platform APIs
+ * behind the repositories do (media store queries and storage statistics on a missing volume, a revoked permission
+ * or an unavailable provider). Anything else is a programming error and is not caught; cancellation is passed on.
+ */
+internal suspend fun <T> readOrElse(
+ dispatcher: CoroutineDispatcher,
+ onFailure: (Exception) -> T,
+ read: suspend () -> T,
+): T = try {
+ withContext(dispatcher) { read() }
+} catch (e: CancellationException) {
+ throw e
+} catch (e: IOException) {
+ onFailure(e)
+} catch (e: SecurityException) {
+ onFailure(e)
+} catch (e: IllegalArgumentException) {
+ onFailure(e)
+} catch (e: IllegalStateException) {
+ onFailure(e)
+} catch (e: SQLException) {
+ onFailure(e)
+}
diff --git a/app/src/main/kotlin/org/fossify/filemanager/viewmodels/StorageViewModel.kt b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/StorageViewModel.kt
new file mode 100644
index 0000000..22fc4c6
--- /dev/null
+++ b/app/src/main/kotlin/org/fossify/filemanager/viewmodels/StorageViewModel.kt
@@ -0,0 +1,307 @@
+package org.fossify.filemanager.viewmodels
+
+import android.content.Context
+import androidx.lifecycle.SavedStateHandle
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.createSavedStateHandle
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.receiveAsFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import org.fossify.commons.helpers.VIEW_TYPE_LIST
+import org.fossify.filemanager.helpers.ARCHIVES
+import org.fossify.filemanager.helpers.AUDIO
+import org.fossify.filemanager.helpers.DOCUMENTS
+import org.fossify.filemanager.helpers.IMAGES
+import org.fossify.filemanager.helpers.OTHERS
+import org.fossify.filemanager.helpers.PRIMARY_VOLUME_NAME
+import org.fossify.filemanager.helpers.VIDEOS
+import org.fossify.filemanager.helpers.archiveMimeTypes
+import org.fossify.filemanager.helpers.extraAudioMimeTypes
+import org.fossify.filemanager.helpers.extraDocumentMimeTypes
+import org.fossify.filemanager.models.FileItem
+import org.fossify.filemanager.repositories.ConfigFileListSettings
+import org.fossify.filemanager.repositories.FileListSettings
+import org.fossify.filemanager.repositories.MediaStoreStorageRepository
+import org.fossify.filemanager.repositories.StorageRepository
+
+/**
+ * Usage of one storage volume.
+ *
+ * @property name the media store volume name, [PRIMARY_VOLUME_NAME] for the internal storage
+ * @property hasStats whether [totalBytes] and [freeBytes] are known yet
+ * @property typeSizes bytes used per file type ([IMAGES], [VIDEOS], [AUDIO], [DOCUMENTS], [ARCHIVES], [OTHERS]),
+ * empty until computed
+ */
+data class VolumeUsage(
+ val name: String,
+ val hasStats: Boolean = false,
+ val totalBytes: Long = 0L,
+ val freeBytes: Long = 0L,
+ val typeSizes: Map<String, Long> = emptyMap(),
+) {
+ val isPrimary: Boolean
+ get() = name == PRIMARY_VOLUME_NAME
+
+ val usedBytes: Long
+ get() = totalBytes - freeBytes
+
+ fun sizeOf(fileType: String) = typeSizes[fileType] ?: 0L
+}
+
+/**
+ * Everything the Storage tab shows.
+ *
+ * @property volumes the mounted volumes with their usage, the internal storage first
+ * @property expandedVolumes the volumes whose usage per file type is expanded (only used with several volumes)
+ * @property isFilesLoaded whether the device files that the search looks through are loaded
+ * @property search the search through all device files, see [SearchState]
+ * @property viewType list or grid, for the search results
+ */
+data class StorageUiState(
+ val volumes: List<VolumeUsage> = emptyList(),
+ val expandedVolumes: Set<String> = emptySet(),
+ val isFilesLoaded: Boolean = false,
+ val search: SearchState = SearchState(),
+ val viewType: Int = VIEW_TYPE_LIST,
+ val selectedPaths: Set<String> = emptySet(),
+) {
+ val hasSeveralVolumes: Boolean
+ get() = volumes.size > 1
+
+ fun isExpanded(volumeName: String) = !hasSeveralVolumes || volumeName in expandedVolumes
+
+ /** This state with the volume [name] changed by [transform]. */
+ fun withVolume(name: String, transform: (VolumeUsage) -> VolumeUsage): StorageUiState =
+ copy(volumes = volumes.map { if (it.name == name) transform(it) else it })
+}
+
+sealed interface StorageEvent {
+ data class Error(val message: String) : StorageEvent
+}
+
+/**
+ * State holder of the Storage tab: the usage of each volume and file type, the search through all device files
+ * and the selection in its results.
+ */
+class StorageViewModel(
+ private val savedStateHandle: SavedStateHandle,
+ private val repository: StorageRepository,
+ private val settings: FileListSettings,
+ private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
+) : ViewModel() {
+ private val _uiState = MutableStateFlow(
+ StorageUiState(
+ search = savedStateHandle.get<String>(KEY_SEARCH_QUERY).orEmpty().let { query ->
+ SearchState(query = query, isSearching = query.length >= MIN_SEARCH_QUERY_LENGTH)
+ },
+ expandedVolumes = savedStateHandle.get<Array<String>>(KEY_EXPANDED_VOLUMES)?.toSet().orEmpty()
+ )
+ )
+ val uiState: StateFlow<StorageUiState> = _uiState.asStateFlow()
+
+ private val _events = Channel<StorageEvent>(Channel.BUFFERED)
+ val events: Flow<StorageEvent> = _events.receiveAsFlow()
+
+ /** Every file the search looks through, newest first. */
+ private var deviceFiles = emptyList<FileItem>()
+ private var isStarted = false
+ private var usageJob: Job? = null
+ private var filesJob: Job? = null
+ private var searchJob: Job? = null
+
+ /** Scroll position of the search results, restored when the screen is recreated. */
+ var scrollPosition: ScrollPosition? = null
+
+ /** Loads the storage usage and the searchable files, unless done already (e.g. when the screen is recreated). */
+ fun loadIfNeeded() {
+ if (!isStarted) {
+ isStarted = true
+ refreshUsage()
+ refreshFiles()
+ }
+ }
+
+ /** Reloads everything, e.g. after files were changed or the hidden files setting was toggled. */
+ fun refresh() {
+ isStarted = true
+ refreshUsage()
+ refreshFiles()
+ }
+
+ /** Recomputes the usage of every volume and file type. */
+ fun refreshUsage() {
+ usageJob?.cancel()
+ usageJob = viewModelScope.launch { loadUsage() }
+ }
+
+ /** A volume or file type whose usage cannot be read is shown without it; the tab reports no error for it. */
+ private suspend fun loadUsage() {
+ val names = readOrElse(ioDispatcher, onFailure = { emptyList() }) { repository.getVolumeNames() }
+ _uiState.update { state ->
+ state.copy(volumes = names.map { name -> state.volumes.find { it.name == name } ?: VolumeUsage(name) })
+ }
+
+ val stats = readOrElse(ioDispatcher, onFailure = { emptyList() }) { repository.getVolumeStats() }
+ stats.filter { it.volumeName in names }.forEach { volumeStats ->
+ _uiState.update { state ->
+ state.withVolume(volumeStats.volumeName) {
+ it.copy(hasStats = true, totalBytes = volumeStats.totalBytes, freeBytes = volumeStats.freeBytes)
+ }
+ }
+
+ val typeSizes = readOrElse(ioDispatcher, onFailure = { emptyMap() }) {
+ repository.getSizesByFileType(volumeStats.volumeName)
+ }
+ val allTypeSizes = StorageUsageRules.FILE_TYPES.associateWith { typeSizes[it] ?: 0L }
+ _uiState.update { state ->
+ state.withVolume(volumeStats.volumeName) { it.copy(typeSizes = allTypeSizes) }
+ }
+ }
+ }
+
+ private fun refreshFiles() {
+ filesJob?.cancel()
+ filesJob = viewModelScope.launch {
+ val showHidden = settings.shouldShowHidden()
+ val viewType = settings.getFolderViewType("")
+ val names = readOrElse(ioDispatcher, onFailure = { emptyList() }) { repository.getVolumeNames() }
+ deviceFiles = names.flatMap { name ->
+ readOrElse(ioDispatcher, onFailure = {
+ _events.trySend(StorageEvent.Error(it.toString()))
+ emptyList()
+ }) { repository.getFiles(name, showHidden) }
+ }
+
+ _uiState.update { it.copy(isFilesLoaded = true, viewType = viewType) }
+ val search = _uiState.value.search
+ if (search.isActive && !search.needsMoreCharacters) {
+ startSearch(search.query)
+ }
+ }
+ }
+
+ fun onSearchQueryChanged(query: String) {
+ if (query == _uiState.value.search.query) {
+ return
+ }
+
+ savedStateHandle[KEY_SEARCH_QUERY] = query
+ searchJob?.cancel()
+ val needsSearch = query.length >= MIN_SEARCH_QUERY_LENGTH
+ _uiState.update { state ->
+ if (needsSearch) {
+ state.copy(search = state.search.copy(query = query, isSearching = true))
+ } else {
+ // no search, or a hint to type more characters: nothing is listed, so nothing stays selected
+ state.copy(search = SearchState(query = query), selectedPaths = emptySet())
+ }
+ }
+
+ if (needsSearch && _uiState.value.isFilesLoaded) {
+ startSearch(query)
+ }
+ }
+
+ private fun startSearch(query: String) {
+ searchJob?.cancel()
+ val files = deviceFiles
+ searchJob = viewModelScope.launch {
+ val matches = FileListRules.nameMatcher(query)
+ val results = withContext(ioDispatcher) { files.filter { matches(it.name) } }
+ _uiState.update { state ->
+ if (state.search.query != query) {
+ state
+ } else {
+ val isSameSearch = state.search.resultsQuery == query
+ val resultPaths = results.mapTo(HashSet()) { it.path }
+ state.copy(
+ search = state.search.copy(results = results, resultsQuery = query, isSearching = false),
+ selectedPaths = when {
+ // refreshed results keep the selected files that still exist
+ isSameSearch || results == state.search.results ->
+ state.selectedPaths.filterTo(HashSet()) { it in resultPaths }
+
+ else -> emptySet()
+ }
+ )
+ }
+ }
+ }
+ }
+
+ fun onSelectionChanged(paths: Set<String>) {
+ _uiState.update { if (it.selectedPaths == paths) it else it.copy(selectedPaths = paths) }
+ }
+
+ fun onVolumeExpandToggled(volumeName: String) {
+ val current = _uiState.value.expandedVolumes
+ val expanded = if (volumeName in current) current - volumeName else current + volumeName
+ savedStateHandle[KEY_EXPANDED_VOLUMES] = expanded.toTypedArray()
+ _uiState.update { it.copy(expandedVolumes = expanded) }
+ }
+
+ fun onItemsDeleted(paths: Collection<String>) {
+ val deleted = paths.toSet()
+ deviceFiles = deviceFiles.filterNot { it.path in deleted }
+ _uiState.update { state ->
+ state.copy(
+ search = state.search.copy(results = state.search.results.filterNot { it.path in deleted }),
+ selectedPaths = state.selectedPaths - deleted
+ )
+ }
+ refreshUsage()
+ }
+
+ companion object {
+ const val KEY_SEARCH_QUERY = "storage_search_query"
+ const val KEY_EXPANDED_VOLUMES = "storage_expanded_volumes"
+
+ fun factory(context: Context) = viewModelFactory {
+ initializer {
+ StorageViewModel(
+ savedStateHandle = createSavedStateHandle(),
+ repository = MediaStoreStorageRepository(context),
+ settings = ConfigFileListSettings(context)
+ )
+ }
+ }
+ }
+}
+
+/** Pure (Android-free) rules of the storage usage: which file type a mime type counts as. */
+internal object StorageUsageRules {
+ /** The file types the usage is split into, in the order they are shown. */
+ val FILE_TYPES = listOf(IMAGES, VIDEOS, AUDIO, DOCUMENTS, ARCHIVES, OTHERS)
+
+ /** Size the media store reports for folders on most file systems. */
+ private const val FOLDER_BLOCK_SIZE = 4096L
+
+ /** The file type a file with the given lowercase [mimeType] counts as. */
+ fun fileTypeOf(mimeType: String): String = when (mimeType.substringBefore("/")) {
+ "image" -> IMAGES
+ "video" -> VIDEOS
+ "audio" -> AUDIO
+ "text" -> DOCUMENTS
+ else -> when (mimeType) {
+ in extraDocumentMimeTypes -> DOCUMENTS
+ in extraAudioMimeTypes -> AUDIO
+ in archiveMimeTypes -> ARCHIVES
+ else -> OTHERS
+ }
+ }
+
+ /** Whether a media store entry without a mime type of this [size] may be a file (and not a folder). */
+ fun mayBeUntypedFile(size: Long) = size > 0 && size != FOLDER_BLOCK_SIZE
+}
diff --git a/app/src/test/kotlin/org/fossify/filemanager/viewmodels/Fakes.kt b/app/src/test/kotlin/org/fossify/filemanager/viewmodels/Fakes.kt
new file mode 100644
index 0000000..acd9371
--- /dev/null
+++ b/app/src/test/kotlin/org/fossify/filemanager/viewmodels/Fakes.kt
@@ -0,0 +1,174 @@
+package org.fossify.filemanager.viewmodels
+
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.test.TestDispatcher
+import kotlinx.coroutines.test.UnconfinedTestDispatcher
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.setMain
+import org.fossify.commons.helpers.SORT_BY_NAME
+import org.fossify.commons.helpers.VIEW_TYPE_LIST
+import org.fossify.filemanager.helpers.PRIMARY_VOLUME_NAME
+import org.fossify.filemanager.models.FileItem
+import org.fossify.filemanager.repositories.FileListSettings
+import org.fossify.filemanager.repositories.FilesRepository
+import org.fossify.filemanager.repositories.FolderRequest
+import org.fossify.filemanager.repositories.RecentsRepository
+import org.fossify.filemanager.repositories.StorageRepository
+import org.fossify.filemanager.repositories.VolumeStats
+import org.junit.rules.TestWatcher
+import org.junit.runner.Description
+
+/** Replaces Dispatchers.Main (used by viewModelScope) with a test dispatcher. */
+@OptIn(ExperimentalCoroutinesApi::class)
+class MainDispatcherRule(val dispatcher: TestDispatcher = UnconfinedTestDispatcher()) : TestWatcher() {
+ override fun starting(description: Description) {
+ Dispatchers.setMain(dispatcher)
+ }
+
+ override fun finished(description: Description) {
+ Dispatchers.resetMain()
+ }
+}
+
+fun file(path: String, size: Long = 0L, modified: Long = 0L) =
+ FileItem(path = path, name = path.substringAfterLast('/'), isDirectory = false, size = size, modified = modified)
+
+fun folder(path: String, size: Long = 0L, modified: Long = 0L) =
+ FileItem(path = path, name = path.substringAfterLast('/'), isDirectory = true, size = size, modified = modified)
+
+/** An in-memory file system: every folder path maps to its direct children. */
+class FakeFilesRepository : FilesRepository {
+ val folders = mutableMapOf<String, List<FileItem>>()
+ val safOnlyPaths = mutableSetOf<String>()
+ val listedPaths = mutableListOf<String>()
+ var lastRequest: FolderRequest? = null
+
+ /** When set, searches suspend until the gate is completed. */
+ var searchGate: CompletableDeferred<Unit>? = null
+ val searchedRoots = mutableListOf<String>()
+
+ fun addFolder(path: String, vararg children: FileItem) {
+ folders[path] = children.toList()
+ }
+
+ override fun requiresSafAccess(path: String) = path in safOnlyPaths
+
+ override suspend fun listFolder(path: String, request: FolderRequest): List<FileItem> {
+ listedPaths.add(path)
+ lastRequest = request
+ return folders[path].orEmpty()
+ }
+
+ override suspend fun countDirectChildren(path: String, showHidden: Boolean): Int {
+ return folders[path].orEmpty().count { showHidden || !it.name.startsWith(".") }
+ }
+
+ override suspend fun search(rootPath: String, showHidden: Boolean, matches: (String) -> Boolean): List<FileItem> {
+ searchedRoots.add(rootPath)
+ searchGate?.await()
+ val results = mutableListOf<FileItem>()
+ collect(rootPath, showHidden, matches, results)
+ return results
+ }
+
+ private fun collect(
+ path: String,
+ showHidden: Boolean,
+ matches: (String) -> Boolean,
+ results: MutableList<FileItem>,
+ ) {
+ folders[path].orEmpty().sortedBy { it.isDirectory }.forEach { child ->
+ if (!showHidden && child.name.startsWith(".")) {
+ return@forEach
+ }
+
+ if (matches(child.name)) {
+ results.add(child)
+ }
+
+ if (child.isDirectory) {
+ collect(child.path, showHidden, matches, results)
+ }
+ }
+ }
+
+ override fun humanizePath(path: String) = path.replace(ROOT, "Internal")
+
+ override fun getMimeType(path: String) = mimeTypeOf(path)
+
+ companion object {
+ const val ROOT = "/storage/emulated/0"
+ }
+}
+
+class FakeRecentsRepository : RecentsRepository {
+ var recents = listOf<FileItem>()
+ var error: Exception? = null
+ var calls = 0
+ var requestedLimit = 0
+
+ override suspend fun getRecentFiles(limit: Int): List<FileItem> {
+ calls++
+ requestedLimit = limit
+ error?.let { throw it }
+ return recents
+ }
+
+ override fun getMimeType(path: String) = mimeTypeOf(path)
+}
+
+/** Storage volumes and the media store of a fake device. */
+class FakeStorageRepository : StorageRepository {
+ var volumes = listOf(PRIMARY_VOLUME_NAME)
+ var stats = listOf<VolumeStats>()
+ val typeSizes = mutableMapOf<String, Map<String, Long>>()
+
+ /** All files of each volume, including hidden ones, newest first. */
+ val files = mutableMapOf<String, List<FileItem>>()
+ var filesError: Exception? = null
+
+ /** When set, loading the files suspends until the gate is completed. */
+ var filesGate: CompletableDeferred<Unit>? = null
+ var statsCalls = 0
+ val fileCalls = mutableListOf<String>()
+
+ override fun getVolumeNames() = volumes
+
+ override suspend fun getVolumeStats(): List<VolumeStats> {
+ statsCalls++
+ return stats
+ }
+
+ override suspend fun getSizesByFileType(volumeName: String) = typeSizes[volumeName].orEmpty()
+
+ override suspend fun getFiles(volumeName: String, showHidden: Boolean): List<FileItem> {
+ fileCalls.add(volumeName)
+ filesGate?.await()
+ filesError?.let { throw it }
+ return files[volumeName].orEmpty().filter { showHidden || !it.name.startsWith(".") }
+ }
+}
+
+class FakeSettings : FileListSettings {
+ var sorting = SORT_BY_NAME
+ val folderSortings = mutableMapOf<String, Int>()
+ var viewType = VIEW_TYPE_LIST
+ val folderViewTypes = mutableMapOf<String, Int>()
+ var showHidden = false
+
+ override fun getFolderSorting(path: String) = folderSortings[path] ?: sorting
+
+ override fun getFolderViewType(path: String) = folderViewTypes[path] ?: viewType
+
+ override fun shouldShowHidden() = showHidden
+}
+
+private fun mimeTypeOf(path: String) = when (path.substringAfterLast('.', "").lowercase()) {
+ "jpg", "jpeg" -> "image/jpeg"
+ "png" -> "image/png"
+ "mp3" -> "audio/mpeg"
+ "txt" -> "text/plain"
+ else -> ""
+}
diff --git a/app/src/test/kotlin/org/fossify/filemanager/viewmodels/ItemsViewModelTest.kt b/app/src/test/kotlin/org/fossify/filemanager/viewmodels/ItemsViewModelTest.kt
new file mode 100644
index 0000000..1369e17
--- /dev/null
+++ b/app/src/test/kotlin/org/fossify/filemanager/viewmodels/ItemsViewModelTest.kt
@@ -0,0 +1,536 @@
+package org.fossify.filemanager.viewmodels
+
+import androidx.lifecycle.SavedStateHandle
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.test.runTest
+import org.fossify.commons.helpers.SORT_BY_DATE_MODIFIED
+import org.fossify.commons.helpers.SORT_BY_EXTENSION
+import org.fossify.commons.helpers.SORT_BY_NAME
+import org.fossify.commons.helpers.SORT_BY_SIZE
+import org.fossify.commons.helpers.SORT_DESCENDING
+import org.fossify.commons.helpers.SORT_USE_NUMERIC_VALUE
+import org.fossify.commons.helpers.VIEW_TYPE_GRID
+import org.fossify.commons.helpers.VIEW_TYPE_LIST
+import org.fossify.filemanager.models.FileItem
+import org.fossify.filemanager.viewmodels.FakeFilesRepository.Companion.ROOT
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+
+class ItemsViewModelTest {
+ @get:Rule
+ val mainDispatcherRule = MainDispatcherRule()
+
+ private val repository = FakeFilesRepository()
+ private val settings = FakeSettings()
+ private val docs = "$ROOT/Documents"
+ private val music = "$ROOT/Music"
+
+ @Before
+ fun setUp() {
+ repository.addFolder(
+ ROOT,
+ file("$ROOT/b.txt", size = 30, modified = 300),
+ folder(music),
+ file("$ROOT/a.jpg", size = 10, modified = 100),
+ file("$ROOT/.nomedia", size = 1, modified = 50),
+ folder(docs),
+ folder("$ROOT/.hidden"),
+ file("$ROOT/C.mp3", size = 20, modified = 200),
+ )
+ repository.addFolder(docs, file("$docs/report.txt"), file("$docs/notes.txt"), folder("$docs/Reports"))
+ repository.addFolder("$docs/Reports", file("$docs/Reports/report-2024.txt"))
+ repository.addFolder(music, file("$music/song.mp3"), file("$music/.secret-report.txt"))
+ repository.addFolder("$ROOT/.hidden", file("$ROOT/.hidden/report-hidden.txt"))
+ }
+
+ private fun createViewModel(
+ savedStateHandle: SavedStateHandle = SavedStateHandle(),
+ wantedMimeTypes: List<String> = listOf(""),
+ ) = ItemsViewModel(savedStateHandle, repository, settings, wantedMimeTypes, mainDispatcherRule.dispatcher)
+
+ private fun ItemsViewModel.names() = uiState.value.items.map { it.name }
+
+ // region listing
+ @Test
+ fun openPathListsFoldersFirstSortedByName() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+
+ val state = viewModel.uiState.value
+ assertEquals(ROOT, state.currentPath)
+ assertEquals(ROOT, state.listingPath)
+ assertFalse(state.isLoading)
+ assertEquals(listOf("Documents", "Music", "a.jpg", "b.txt", "C.mp3"), viewModel.names())
+ }
+
+ @Test
+ fun openPathNormalizesTrailingSlashes() {
+ val viewModel = createViewModel()
+ viewModel.openPath("$ROOT/")
+ assertEquals(ROOT, viewModel.uiState.value.currentPath)
+
+ viewModel.openPath("/")
+ assertEquals("/", viewModel.uiState.value.currentPath)
+ }
+
+ @Test
+ fun childCountsAreFilledInListView() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+
+ val documents = viewModel.uiState.value.items.first { it.path == docs }
+ val musicFolder = viewModel.uiState.value.items.first { it.path == music }
+ assertEquals(3, documents.children)
+ assertEquals(1, musicFolder.children)
+ }
+
+ @Test
+ fun navigatingToAnotherFolderReplacesTheListing() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.openPath(docs)
+
+ assertEquals(docs, viewModel.uiState.value.listingPath)
+ assertEquals(listOf("Reports", "notes.txt", "report.txt"), viewModel.names())
+ }
+
+ @Test
+ fun mimeTypeFilterKeepsFoldersAndMatchingFiles() {
+ val viewModel = createViewModel(wantedMimeTypes = listOf("image/*", "audio/mpeg"))
+ viewModel.openPath(ROOT)
+
+ assertEquals(listOf("Documents", "Music", "a.jpg", "C.mp3"), viewModel.names())
+ }
+ // endregion
+
+ // region sorting
+ @Test
+ fun sortsBySizeDescendingKeepingFoldersFirst() {
+ settings.sorting = SORT_BY_SIZE or SORT_DESCENDING
+ repository.addFolder(
+ ROOT,
+ folder(docs, size = 5),
+ folder(music, size = 50),
+ file("$ROOT/a.jpg", 10),
+ file("$ROOT/b.txt", 30),
+ )
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+
+ assertEquals(listOf("Music", "Documents", "b.txt", "a.jpg"), viewModel.names())
+ assertEquals(SORT_BY_SIZE or SORT_DESCENDING, viewModel.uiState.value.sorting)
+ assertEquals(SORT_BY_SIZE or SORT_DESCENDING, repository.lastRequest?.sorting)
+ }
+
+ @Test
+ fun sortsByDateModified() {
+ settings.sorting = SORT_BY_DATE_MODIFIED
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+
+ assertEquals(listOf("a.jpg", "C.mp3", "b.txt"), viewModel.names().drop(2))
+ }
+
+ @Test
+ fun sortsByExtension() {
+ settings.sorting = SORT_BY_EXTENSION
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+
+ assertEquals(listOf("a.jpg", "C.mp3", "b.txt"), viewModel.names().drop(2))
+ }
+
+ @Test
+ fun numericSortingOrdersNumbersByValue() {
+ repository.addFolder(ROOT, file("$ROOT/img10.jpg"), file("$ROOT/img2.jpg"), file("$ROOT/img1.jpg"))
+ val viewModel = createViewModel()
+
+ settings.sorting = SORT_BY_NAME
+ viewModel.openPath(ROOT)
+ assertEquals(listOf("img1.jpg", "img10.jpg", "img2.jpg"), viewModel.names())
+
+ settings.sorting = SORT_BY_NAME or SORT_USE_NUMERIC_VALUE
+ viewModel.refresh()
+ assertEquals(listOf("img1.jpg", "img2.jpg", "img10.jpg"), viewModel.names())
+ }
+
+ @Test
+ fun usesTheSortingOfTheOpenedFolder() {
+ settings.folderSortings[ROOT] = SORT_BY_NAME or SORT_DESCENDING
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+
+ assertEquals(listOf("Music", "Documents", "C.mp3", "b.txt", "a.jpg"), viewModel.names())
+ }
+
+ @Test
+ fun sortingNormalizesAccents() {
+ repository.addFolder(ROOT, file("$ROOT/b.txt"), file("$ROOT/Ábc.txt"), file("$ROOT/c.txt"))
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+
+ assertEquals(listOf("Ábc.txt", "b.txt", "c.txt"), viewModel.names())
+ }
+ // endregion
+
+ // region hidden items and view types
+ @Test
+ fun hiddenItemsAreShownOnlyWhenEnabled() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ assertTrue(viewModel.names().none { it.startsWith(".") })
+ assertFalse(viewModel.uiState.value.showHidden)
+
+ settings.showHidden = true
+ viewModel.refresh()
+ assertEquals(listOf(".hidden", "Documents", "Music", ".nomedia", "a.jpg", "b.txt", "C.mp3"), viewModel.names())
+ assertTrue(viewModel.uiState.value.showHidden)
+ assertEquals(true, repository.lastRequest?.showHidden)
+ }
+
+ @Test
+ fun gridViewSeparatesFoldersFromFiles() {
+ settings.folderViewTypes[ROOT] = VIEW_TYPE_GRID
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+
+ val items = viewModel.uiState.value.items
+ assertEquals(VIEW_TYPE_GRID, viewModel.uiState.value.viewType)
+ assertEquals(6, items.size)
+ assertTrue(items[2].isGridTypeDivider)
+ assertEquals(1, items.count { it.isGridTypeDivider })
+ // child counts are only needed by the list view
+ assertTrue(items.filter { it.isDirectory }.all { it.children == 0 })
+ }
+
+ @Test
+ fun listViewHasNoDivider() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+
+ assertEquals(VIEW_TYPE_LIST, viewModel.uiState.value.viewType)
+ assertTrue(viewModel.uiState.value.items.none { it.isGridTypeDivider })
+ }
+
+ @Test
+ fun gridFolderWithOnlyFilesHasNoDivider() {
+ settings.viewType = VIEW_TYPE_GRID
+ val viewModel = createViewModel()
+ viewModel.openPath(music)
+
+ assertTrue(viewModel.uiState.value.items.none { it.isGridTypeDivider })
+ }
+
+ @Test
+ fun changingTheViewTypeIsPickedUpOnRefresh() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ settings.folderViewTypes[ROOT] = VIEW_TYPE_GRID
+ viewModel.refresh()
+
+ assertEquals(VIEW_TYPE_GRID, viewModel.uiState.value.viewType)
+ }
+ // endregion
+
+ // region search
+ @Test
+ fun singleCharacterQueryDoesNotSearch() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSearchQueryChanged("r")
+
+ val state = viewModel.uiState.value
+ assertTrue(state.search.needsMoreCharacters)
+ assertTrue(repository.searchedRoots.isEmpty())
+ assertNull(state.displayedItems)
+ }
+
+ @Test
+ fun searchGroupsResultsByFolder() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSearchQueryChanged("REPORT")
+
+ val search = viewModel.uiState.value.search
+ assertEquals("REPORT", search.resultsQuery)
+ assertFalse(search.isSearching)
+ val expected = listOf(
+ FileItem(docs, "Internal/Documents", isSectionTitle = true),
+ file("$docs/report.txt"),
+ FileItem("$docs/Reports", "Internal/Documents/Reports", isDirectory = true, isSectionTitle = true),
+ FileItem("$docs/Reports", "Internal/Documents/Reports", isSectionTitle = true),
+ file("$docs/Reports/report-2024.txt"),
+ )
+ assertEquals(expected, search.results)
+ assertEquals(expected, viewModel.uiState.value.displayedItems)
+ assertEquals("REPORT", viewModel.uiState.value.highlightedText)
+ }
+
+ @Test
+ fun searchIgnoresAccentsAndHiddenItems() {
+ repository.addFolder(ROOT, file("$ROOT/Résumé.txt"), file("$ROOT/.resume.txt"))
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSearchQueryChanged("resume")
+
+ val names = viewModel.uiState.value.search.results.filterNot { it.isSectionTitle }.map { it.name }
+ assertEquals(listOf("Résumé.txt"), names)
+ }
+
+ @Test
+ fun searchIncludesHiddenItemsWhenShown() {
+ settings.showHidden = true
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSearchQueryChanged("report")
+
+ val names = viewModel.uiState.value.search.results.filterNot { it.isSectionTitle }.map { it.name }
+ assertTrue("report-hidden.txt" in names)
+ assertTrue(".secret-report.txt" in names)
+ }
+
+ @Test
+ fun searchWithoutResultsIsEmpty() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSearchQueryChanged("nothing matches")
+
+ assertEquals(emptyList<FileItem>(), viewModel.uiState.value.displayedItems)
+ }
+
+ @Test
+ fun clearingTheQueryShowsTheListingAgain() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ val listing = viewModel.uiState.value.items
+ viewModel.onSearchQueryChanged("report")
+ viewModel.onSearchQueryChanged("")
+
+ val state = viewModel.uiState.value
+ assertFalse(state.search.isActive)
+ assertEquals(listing, state.displayedItems)
+ assertEquals("", state.highlightedText)
+ }
+
+ @Test
+ fun newQueryReplacesARunningSearch() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ val gate = CompletableDeferred<Unit>()
+ repository.searchGate = gate
+
+ viewModel.onSearchQueryChanged("rep")
+ assertTrue(viewModel.uiState.value.search.isSearching)
+ assertNull(viewModel.uiState.value.displayedItems)
+
+ viewModel.onSearchQueryChanged("song")
+ gate.complete(Unit)
+
+ val search = viewModel.uiState.value.search
+ assertEquals("song", search.resultsQuery)
+ assertEquals(listOf("$music/song.mp3"), search.results.filterNot { it.isSectionTitle }.map { it.path })
+ }
+
+ @Test
+ fun openingAFolderClosesTheSearch() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSearchQueryChanged("report")
+ viewModel.openPath(docs)
+
+ val state = viewModel.uiState.value
+ assertFalse(state.search.isActive)
+ assertEquals(docs, state.listingPath)
+ }
+
+ @Test
+ fun refreshRerunsAnActiveSearch() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSearchQueryChanged("notes")
+ repository.addFolder(docs, file("$docs/notes-2.txt"))
+ viewModel.refresh()
+
+ val names = viewModel.uiState.value.search.results.filterNot { it.isSectionTitle }.map { it.name }
+ assertEquals(listOf("notes-2.txt"), names)
+ }
+ // endregion
+
+ // region selection
+ @Test
+ fun selectionIsKeptInTheState() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSelectionChanged(setOf("$ROOT/a.jpg", "$ROOT/b.txt"))
+
+ assertEquals(setOf("$ROOT/a.jpg", "$ROOT/b.txt"), viewModel.uiState.value.selectedPaths)
+ }
+
+ @Test
+ fun navigatingClearsTheSelection() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSelectionChanged(setOf("$ROOT/a.jpg"))
+ viewModel.openPath(docs)
+
+ assertTrue(viewModel.uiState.value.selectedPaths.isEmpty())
+ }
+
+ @Test
+ fun refreshKeepsTheSelectionOfItemsThatStillExist() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSelectionChanged(setOf("$ROOT/a.jpg", "$ROOT/b.txt"))
+ repository.addFolder(ROOT, file("$ROOT/a.jpg"), file("$ROOT/new.txt"))
+ viewModel.refresh()
+
+ assertEquals(setOf("$ROOT/a.jpg"), viewModel.uiState.value.selectedPaths)
+ }
+
+ @Test
+ fun deletedItemsDisappearFromListingAndSelection() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSelectionChanged(setOf("$ROOT/a.jpg", "$ROOT/b.txt"))
+ viewModel.onItemsDeleted(listOf("$ROOT/a.jpg", "$ROOT/b.txt"))
+
+ val state = viewModel.uiState.value
+ assertEquals(listOf("Documents", "Music", "C.mp3"), viewModel.names())
+ assertTrue(state.selectedPaths.isEmpty())
+ }
+
+ @Test
+ fun searchResultsResetTheSelection() {
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.onSelectionChanged(setOf("$ROOT/a.jpg"))
+ viewModel.onSearchQueryChanged("report")
+
+ assertTrue(viewModel.uiState.value.selectedPaths.isEmpty())
+ viewModel.onSelectionChanged(setOf("$docs/report.txt"))
+ assertEquals(setOf("$docs/report.txt"), viewModel.uiState.value.selectedPaths)
+ }
+ // endregion
+
+ // region state restoration
+ @Test
+ fun folderAndQueryAreWrittenToTheSavedState() {
+ val handle = SavedStateHandle()
+ val viewModel = createViewModel(handle)
+ viewModel.openPath(docs)
+ viewModel.onSearchQueryChanged("rep")
+
+ assertEquals(docs, handle.get<String>(ItemsViewModel.KEY_CURRENT_PATH))
+ assertEquals("rep", handle.get<String>(ItemsViewModel.KEY_SEARCH_QUERY))
+
+ viewModel.openPath(ROOT)
+ assertEquals(ROOT, handle.get<String>(ItemsViewModel.KEY_CURRENT_PATH))
+ assertEquals("", handle.get<String>(ItemsViewModel.KEY_SEARCH_QUERY))
+ }
+
+ @Test
+ fun restoresFolderAndSearchAfterProcessDeath() {
+ val handle = SavedStateHandle(
+ mapOf(ItemsViewModel.KEY_CURRENT_PATH to docs, ItemsViewModel.KEY_SEARCH_QUERY to "report")
+ )
+ val viewModel = createViewModel(handle)
+
+ val state = viewModel.uiState.value
+ assertEquals(docs, state.currentPath)
+ assertEquals(docs, state.listingPath)
+ assertEquals(listOf("Reports", "notes.txt", "report.txt"), viewModel.names())
+ assertEquals("report", state.search.query)
+ assertEquals("report", state.search.resultsQuery)
+ assertEquals(listOf(docs), repository.searchedRoots)
+ assertEquals(
+ listOf("$docs/report.txt", "$docs/Reports/report-2024.txt"),
+ state.search.results.filterNot { it.isSectionTitle }.map { it.path }
+ )
+ }
+
+ @Test
+ fun restoresShortQueryWithoutSearching() {
+ val handle = SavedStateHandle(
+ mapOf(ItemsViewModel.KEY_CURRENT_PATH to docs, ItemsViewModel.KEY_SEARCH_QUERY to "r")
+ )
+ val viewModel = createViewModel(handle)
+
+ assertTrue(viewModel.uiState.value.search.needsMoreCharacters)
+ assertTrue(repository.searchedRoots.isEmpty())
+ }
+
+ @Test
+ fun initialPathDoesNotOverrideARestoredFolder() {
+ val viewModel = createViewModel(SavedStateHandle(mapOf(ItemsViewModel.KEY_CURRENT_PATH to docs)))
+ viewModel.openInitialPathIfNeeded(ROOT)
+ assertEquals(docs, viewModel.uiState.value.currentPath)
+
+ val freshViewModel = createViewModel()
+ freshViewModel.openInitialPathIfNeeded(ROOT)
+ assertEquals(ROOT, freshViewModel.uiState.value.currentPath)
+ }
+
+ @Test
+ fun newViewModelWithoutSavedStateStartsEmpty() {
+ val viewModel = createViewModel()
+
+ assertEquals(ItemsUiState(), viewModel.uiState.value)
+ assertTrue(repository.listedPaths.isEmpty())
+ }
+
+ @Test
+ fun scrollPositionsAreRememberedPerFolder() {
+ val viewModel = createViewModel()
+ viewModel.scrollPositions[ROOT] = ScrollPosition(12, -40)
+ viewModel.scrollPositions[docs] = ScrollPosition(3, 0)
+
+ assertEquals(ScrollPosition(12, -40), viewModel.scrollPositions[ROOT])
+ assertEquals(ScrollPosition(3, 0), viewModel.scrollPositions[docs])
+ assertNull(viewModel.scrollPositions[music])
+ }
+ // endregion
+
+ // region storage access framework
+ @Test
+ fun safOnlyFolderWaitsForPermission() {
+ val androidData = "$ROOT/Android/data"
+ repository.safOnlyPaths.add(androidData)
+ repository.addFolder(androidData, folder("$androidData/org.fossify.gallery"))
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.openPath(androidData)
+
+ assertEquals(androidData, viewModel.uiState.value.pendingSafAccessPath)
+ assertEquals(ROOT, viewModel.uiState.value.listingPath)
+ assertFalse(androidData in repository.listedPaths)
+
+ viewModel.onSafAccessResult(androidData, granted = true)
+ val state = viewModel.uiState.value
+ assertNull(state.pendingSafAccessPath)
+ assertEquals(androidData, state.listingPath)
+ assertEquals(listOf("org.fossify.gallery"), viewModel.names())
+ }
+
+ @Test
+ fun deniedSafAccessStaysInThePreviousFolder() = runTest {
+ val androidData = "$ROOT/Android/data"
+ repository.safOnlyPaths.add(androidData)
+ val viewModel = createViewModel()
+ viewModel.openPath(ROOT)
+ viewModel.openPath(androidData)
+ viewModel.onSafAccessResult(androidData, granted = false)
+
+ val state = viewModel.uiState.value
+ assertNull(state.pendingSafAccessPath)
+ assertEquals(ROOT, state.currentPath)
+ assertEquals(ROOT, state.listingPath)
+ assertEquals(ItemsEvent.StorageAccessDenied, viewModel.events.first())
+ }
+ // endregion
+}
diff --git a/app/src/test/kotlin/org/fossify/filemanager/viewmodels/RecentsViewModelTest.kt b/app/src/test/kotlin/org/fossify/filemanager/viewmodels/RecentsViewModelTest.kt
new file mode 100644
index 0000000..ccbeef0
--- /dev/null
+++ b/app/src/test/kotlin/org/fossify/filemanager/viewmodels/RecentsViewModelTest.kt
@@ -0,0 +1,187 @@
+package org.fossify.filemanager.viewmodels
+
+import androidx.lifecycle.SavedStateHandle
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.test.runTest
+import org.fossify.commons.helpers.VIEW_TYPE_GRID
+import org.fossify.filemanager.viewmodels.FakeFilesRepository.Companion.ROOT
+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 java.io.IOException
+
+class RecentsViewModelTest {
+ @get:Rule
+ val mainDispatcherRule = MainDispatcherRule()
+
+ private val repository = FakeRecentsRepository()
+ private val settings = FakeSettings()
+
+ @Before
+ fun setUp() {
+ repository.recents = listOf(
+ file("$ROOT/DCIM/Camera/IMG_2.jpg", modified = 400),
+ file("$ROOT/Download/Résumé.txt", modified = 300),
+ file("$ROOT/Download/.partial", modified = 250),
+ file("$ROOT/.thumbnails/thumb.jpg", modified = 200),
+ file("$ROOT/Music/song.mp3", modified = 100),
+ )
+ }
+
+ private fun createViewModel(
+ savedStateHandle: SavedStateHandle = SavedStateHandle(),
+ wantedMimeTypes: List<String> = listOf(""),
+ ) = RecentsViewModel(savedStateHandle, repository, settings, wantedMimeTypes, mainDispatcherRule.dispatcher)
+
+ private fun RecentsViewModel.visibleNames() = uiState.value.visibleItems.map { it.name }
+
+ @Test
+ fun loadsRecentFilesWithoutHiddenOnes() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ val state = viewModel.uiState.value
+ assertTrue(state.isLoaded)
+ assertFalse(state.isLoading)
+ assertEquals(listOf("IMG_2.jpg", "Résumé.txt", "song.mp3"), viewModel.visibleNames())
+ assertEquals(RecentsViewModel.RECENTS_LIMIT, repository.requestedLimit)
+ }
+
+ @Test
+ fun showsHiddenFilesWhenEnabled() {
+ settings.showHidden = true
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ assertEquals(5, viewModel.uiState.value.items.size)
+ }
+
+ @Test
+ fun loadsOnlyOnceUnlessRefreshed() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.loadIfNeeded()
+ assertEquals(1, repository.calls)
+
+ repository.recents = listOf(file("$ROOT/new.txt"))
+ viewModel.refresh()
+ assertEquals(2, repository.calls)
+ assertEquals(listOf("new.txt"), viewModel.visibleNames())
+ }
+
+ @Test
+ fun usesTheRecentsViewType() {
+ settings.folderViewTypes[""] = VIEW_TYPE_GRID
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ assertEquals(VIEW_TYPE_GRID, viewModel.uiState.value.viewType)
+ }
+
+ @Test
+ fun mimeTypeFilterIsApplied() {
+ val viewModel = createViewModel(wantedMimeTypes = listOf("image/*"))
+ viewModel.loadIfNeeded()
+
+ assertEquals(listOf("IMG_2.jpg"), viewModel.visibleNames())
+ }
+
+ @Test
+ fun searchFiltersByNameIgnoringCaseAndAccents() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ viewModel.onSearchQueryChanged("RESUME")
+ assertEquals(listOf("Résumé.txt"), viewModel.visibleNames())
+ assertEquals("RESUME", viewModel.uiState.value.query)
+
+ viewModel.onSearchQueryChanged("xyz")
+ assertTrue(viewModel.uiState.value.visibleItems.isEmpty())
+
+ viewModel.onSearchQueryChanged("")
+ assertEquals(3, viewModel.uiState.value.visibleItems.size)
+ }
+
+ @Test
+ fun searchAppliesToRefreshedItems() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("song")
+ repository.recents = repository.recents + file("$ROOT/Music/song2.mp3")
+ viewModel.refresh()
+
+ assertEquals(listOf("song.mp3", "song2.mp3"), viewModel.visibleNames())
+ }
+
+ @Test
+ fun selectionIsKeptAndPrunedOnRefresh() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ val selection = setOf("$ROOT/DCIM/Camera/IMG_2.jpg", "$ROOT/Music/song.mp3")
+ viewModel.onSelectionChanged(selection)
+ assertEquals(selection, viewModel.uiState.value.selectedPaths)
+
+ repository.recents = repository.recents.filterNot { it.name == "song.mp3" }
+ viewModel.refresh()
+ assertEquals(setOf("$ROOT/DCIM/Camera/IMG_2.jpg"), viewModel.uiState.value.selectedPaths)
+ }
+
+ @Test
+ fun changingTheSearchResultsClearsTheSelection() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSelectionChanged(setOf("$ROOT/Music/song.mp3"))
+ viewModel.onSearchQueryChanged("song")
+ assertTrue(viewModel.uiState.value.selectedPaths.isEmpty())
+
+ viewModel.onSelectionChanged(setOf("$ROOT/Music/song.mp3"))
+ viewModel.onSearchQueryChanged("son")
+ assertEquals(setOf("$ROOT/Music/song.mp3"), viewModel.uiState.value.selectedPaths)
+ }
+
+ @Test
+ fun deletedItemsAreRemoved() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSelectionChanged(setOf("$ROOT/Music/song.mp3"))
+ viewModel.onItemsDeleted(listOf("$ROOT/Music/song.mp3"))
+
+ assertEquals(listOf("IMG_2.jpg", "Résumé.txt"), viewModel.visibleNames())
+ assertTrue(viewModel.uiState.value.selectedPaths.isEmpty())
+ }
+
+ @Test
+ fun queryIsSavedAndRestored() {
+ val handle = SavedStateHandle()
+ createViewModel(handle).onSearchQueryChanged("song")
+ assertEquals("song", handle.get<String>(RecentsViewModel.KEY_SEARCH_QUERY))
+
+ val restored = createViewModel(SavedStateHandle(mapOf(RecentsViewModel.KEY_SEARCH_QUERY to "song")))
+ restored.loadIfNeeded()
+ assertEquals("song", restored.uiState.value.query)
+ assertEquals(listOf("song.mp3"), restored.visibleNames())
+ }
+
+ @Test
+ fun scrollPositionIsKept() {
+ val viewModel = createViewModel()
+ viewModel.scrollPosition = ScrollPosition(7, -12)
+
+ assertEquals(ScrollPosition(7, -12), viewModel.scrollPosition)
+ }
+
+ @Test
+ fun errorsAreReportedAsEvents() = runTest {
+ repository.error = IOException("broken media store")
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ val state = viewModel.uiState.value
+ assertTrue(state.isLoaded)
+ assertTrue(state.items.isEmpty())
+ assertEquals(RecentsEvent.Error("java.io.IOException: broken media store"), viewModel.events.first())
+ }
+}
diff --git a/app/src/test/kotlin/org/fossify/filemanager/viewmodels/StorageViewModelTest.kt b/app/src/test/kotlin/org/fossify/filemanager/viewmodels/StorageViewModelTest.kt
new file mode 100644
index 0000000..3ba9e68
--- /dev/null
+++ b/app/src/test/kotlin/org/fossify/filemanager/viewmodels/StorageViewModelTest.kt
@@ -0,0 +1,345 @@
+package org.fossify.filemanager.viewmodels
+
+import androidx.lifecycle.SavedStateHandle
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.test.runTest
+import org.fossify.commons.helpers.VIEW_TYPE_GRID
+import org.fossify.filemanager.helpers.ARCHIVES
+import org.fossify.filemanager.helpers.AUDIO
+import org.fossify.filemanager.helpers.DOCUMENTS
+import org.fossify.filemanager.helpers.IMAGES
+import org.fossify.filemanager.helpers.OTHERS
+import org.fossify.filemanager.helpers.PRIMARY_VOLUME_NAME
+import org.fossify.filemanager.helpers.VIDEOS
+import org.fossify.filemanager.repositories.VolumeStats
+import org.fossify.filemanager.viewmodels.FakeFilesRepository.Companion.ROOT
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import java.io.IOException
+
+class StorageViewModelTest {
+ @get:Rule
+ val mainDispatcherRule = MainDispatcherRule()
+
+ private val repository = FakeStorageRepository()
+ private val settings = FakeSettings()
+
+ @Before
+ fun setUp() {
+ repository.volumes = listOf(PRIMARY_VOLUME_NAME, SD_CARD)
+ repository.stats = listOf(
+ VolumeStats(PRIMARY_VOLUME_NAME, totalBytes = 64_000, freeBytes = 16_000),
+ VolumeStats(SD_CARD, totalBytes = 32_000, freeBytes = 30_000),
+ )
+ repository.typeSizes[PRIMARY_VOLUME_NAME] = mapOf(IMAGES to 20_000L, VIDEOS to 15_000L, AUDIO to 5_000L)
+ repository.typeSizes[SD_CARD] = mapOf(DOCUMENTS to 1_500L, ARCHIVES to 500L)
+ repository.files[PRIMARY_VOLUME_NAME] = listOf(
+ file("$ROOT/Music/song.mp3", size = 10, modified = 500),
+ file("$ROOT/Download/Résumé.pdf", size = 20, modified = 400),
+ file("$ROOT/Download/.secret.txt", size = 30, modified = 300),
+ )
+ repository.files[SD_CARD] = listOf(
+ file("/storage/$SD_CARD/Music/Song Two.mp3", size = 40, modified = 200),
+ file("/storage/$SD_CARD/Docs/resume-old.pdf", size = 50, modified = 100),
+ )
+ }
+
+ private fun createViewModel(savedStateHandle: SavedStateHandle = SavedStateHandle()) =
+ StorageViewModel(savedStateHandle, repository, settings, mainDispatcherRule.dispatcher)
+
+ private fun StorageViewModel.resultNames() = uiState.value.search.results.map { it.name }
+
+ private fun StorageViewModel.volume(name: String) = uiState.value.volumes.first { it.name == name }
+
+ @Test
+ fun loadsTheUsageOfEveryVolume() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ val state = viewModel.uiState.value
+ assertEquals(listOf(PRIMARY_VOLUME_NAME, SD_CARD), state.volumes.map { it.name })
+ assertTrue(state.hasSeveralVolumes)
+
+ val internal = viewModel.volume(PRIMARY_VOLUME_NAME)
+ assertTrue(internal.isPrimary)
+ assertTrue(internal.hasStats)
+ assertEquals(64_000L, internal.totalBytes)
+ assertEquals(16_000L, internal.freeBytes)
+ assertEquals(48_000L, internal.usedBytes)
+
+ val sdCard = viewModel.volume(SD_CARD)
+ assertFalse(sdCard.isPrimary)
+ assertEquals(2_000L, sdCard.usedBytes)
+ }
+
+ @Test
+ fun usageIsSplitIntoEveryFileType() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ val internal = viewModel.volume(PRIMARY_VOLUME_NAME)
+ assertEquals(StorageUsageRules.FILE_TYPES, internal.typeSizes.keys.toList())
+ assertEquals(20_000L, internal.sizeOf(IMAGES))
+ assertEquals(15_000L, internal.sizeOf(VIDEOS))
+ assertEquals(5_000L, internal.sizeOf(AUDIO))
+ assertEquals(0L, internal.sizeOf(DOCUMENTS))
+
+ val sdCard = viewModel.volume(SD_CARD)
+ assertEquals(1_500L, sdCard.sizeOf(DOCUMENTS))
+ assertEquals(500L, sdCard.sizeOf(ARCHIVES))
+ assertEquals(0L, sdCard.sizeOf(OTHERS))
+ }
+
+ @Test
+ fun volumeWithoutStatsWaitsForThem() {
+ repository.stats = repository.stats.filter { it.volumeName == PRIMARY_VOLUME_NAME }
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ val sdCard = viewModel.volume(SD_CARD)
+ assertFalse(sdCard.hasStats)
+ assertTrue(sdCard.typeSizes.isEmpty())
+ assertTrue(viewModel.volume(PRIMARY_VOLUME_NAME).hasStats)
+ }
+
+ @Test
+ fun refreshingTheUsageUpdatesTheNumbers() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ repository.stats = listOf(VolumeStats(PRIMARY_VOLUME_NAME, totalBytes = 64_000, freeBytes = 4_000))
+ repository.typeSizes[PRIMARY_VOLUME_NAME] = mapOf(IMAGES to 32_000L)
+
+ viewModel.refreshUsage()
+ val internal = viewModel.volume(PRIMARY_VOLUME_NAME)
+ assertEquals(4_000L, internal.freeBytes)
+ assertEquals(32_000L, internal.sizeOf(IMAGES))
+ assertEquals(1, repository.fileCalls.count { it == PRIMARY_VOLUME_NAME })
+ }
+
+ @Test
+ fun mimeTypesAreCountedAsTheirFileType() {
+ assertEquals(IMAGES, StorageUsageRules.fileTypeOf("image/png"))
+ assertEquals(VIDEOS, StorageUsageRules.fileTypeOf("video/mp4"))
+ assertEquals(AUDIO, StorageUsageRules.fileTypeOf("audio/mpeg"))
+ assertEquals(AUDIO, StorageUsageRules.fileTypeOf("application/ogg"))
+ assertEquals(DOCUMENTS, StorageUsageRules.fileTypeOf("text/plain"))
+ assertEquals(DOCUMENTS, StorageUsageRules.fileTypeOf("application/pdf"))
+ assertEquals(ARCHIVES, StorageUsageRules.fileTypeOf("application/zip"))
+ assertEquals(OTHERS, StorageUsageRules.fileTypeOf("application/x-unknown"))
+
+ assertFalse(StorageUsageRules.mayBeUntypedFile(0))
+ assertFalse(StorageUsageRules.mayBeUntypedFile(4096))
+ assertTrue(StorageUsageRules.mayBeUntypedFile(1234))
+ }
+
+ @Test
+ fun searchLooksThroughTheFilesOfAllVolumesIgnoringCaseAndAccents() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("RESUME")
+
+ val search = viewModel.uiState.value.search
+ assertEquals("RESUME", search.query)
+ assertEquals("RESUME", search.resultsQuery)
+ assertFalse(search.isSearching)
+ assertEquals(listOf("Résumé.pdf", "resume-old.pdf"), viewModel.resultNames())
+
+ viewModel.onSearchQueryChanged("song")
+ assertEquals(listOf("song.mp3", "Song Two.mp3"), viewModel.resultNames())
+
+ viewModel.onSearchQueryChanged("nothing like this")
+ assertTrue(viewModel.uiState.value.search.results.isEmpty())
+ }
+
+ @Test
+ fun hiddenFilesAreOnlySearchedWhenShown() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("secret")
+ assertTrue(viewModel.uiState.value.search.results.isEmpty())
+
+ settings.showHidden = true
+ viewModel.refresh()
+ assertEquals(listOf(".secret.txt"), viewModel.resultNames())
+ }
+
+ @Test
+ fun aSingleCharacterAsksForMore() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("s")
+
+ val search = viewModel.uiState.value.search
+ assertTrue(search.isActive)
+ assertTrue(search.needsMoreCharacters)
+ assertFalse(search.isSearching)
+ assertNull(search.resultsQuery)
+ }
+
+ @Test
+ fun searchWaitsForTheFilesToLoad() {
+ val gate = CompletableDeferred<Unit>()
+ repository.filesGate = gate
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("song")
+
+ assertFalse(viewModel.uiState.value.isFilesLoaded)
+ assertTrue(viewModel.uiState.value.search.isSearching)
+ assertNull(viewModel.uiState.value.search.resultsQuery)
+
+ gate.complete(Unit)
+ assertTrue(viewModel.uiState.value.isFilesLoaded)
+ assertFalse(viewModel.uiState.value.search.isSearching)
+ assertEquals(listOf("song.mp3", "Song Two.mp3"), viewModel.resultNames())
+ }
+
+ @Test
+ fun closingTheSearchClearsResultsAndSelection() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("song")
+ viewModel.onSelectionChanged(setOf("$ROOT/Music/song.mp3"))
+
+ viewModel.onSearchQueryChanged("")
+ val state = viewModel.uiState.value
+ assertFalse(state.search.isActive)
+ assertTrue(state.search.results.isEmpty())
+ assertTrue(state.selectedPaths.isEmpty())
+ }
+
+ @Test
+ fun selectionIsClearedWhenOtherResultsAreShown() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("song")
+ viewModel.onSelectionChanged(setOf("$ROOT/Music/song.mp3"))
+ assertEquals(setOf("$ROOT/Music/song.mp3"), viewModel.uiState.value.selectedPaths)
+
+ // the same results for a longer query keep the selection
+ viewModel.onSearchQueryChanged("son")
+ assertEquals(setOf("$ROOT/Music/song.mp3"), viewModel.uiState.value.selectedPaths)
+
+ viewModel.onSearchQueryChanged("resume")
+ assertTrue(viewModel.uiState.value.selectedPaths.isEmpty())
+ }
+
+ @Test
+ fun refreshedResultsKeepTheSelectedFilesThatStillExist() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("song")
+ val selection = setOf("$ROOT/Music/song.mp3", "/storage/$SD_CARD/Music/Song Two.mp3")
+ viewModel.onSelectionChanged(selection)
+
+ repository.files[SD_CARD] = emptyList()
+ viewModel.refresh()
+ assertEquals(listOf("song.mp3"), viewModel.resultNames())
+ assertEquals(setOf("$ROOT/Music/song.mp3"), viewModel.uiState.value.selectedPaths)
+ }
+
+ @Test
+ fun deletedFilesAreRemovedFromResultsAndSelection() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("song")
+ viewModel.onSelectionChanged(setOf("$ROOT/Music/song.mp3"))
+ val statsCalls = repository.statsCalls
+
+ viewModel.onItemsDeleted(listOf("$ROOT/Music/song.mp3"))
+ assertEquals(listOf("Song Two.mp3"), viewModel.resultNames())
+ assertTrue(viewModel.uiState.value.selectedPaths.isEmpty())
+ assertEquals("the usage is recomputed", statsCalls + 1, repository.statsCalls)
+
+ viewModel.onSearchQueryChanged("so")
+ assertEquals(listOf("Song Two.mp3"), viewModel.resultNames())
+ }
+
+ @Test
+ fun stateIsKeptForARecreatedScreen() {
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("song")
+ viewModel.onSelectionChanged(setOf("$ROOT/Music/song.mp3"))
+ viewModel.scrollPosition = ScrollPosition(3, -8)
+ val before = viewModel.uiState.value
+
+ // the recreated view attaches to the same ViewModel and asks for its content again
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("song")
+
+ assertEquals(before, viewModel.uiState.value)
+ assertEquals(listOf(PRIMARY_VOLUME_NAME, SD_CARD), repository.fileCalls)
+ assertEquals(ScrollPosition(3, -8), viewModel.scrollPosition)
+ }
+
+ @Test
+ fun queryAndExpandedVolumesAreSavedAndRestored() {
+ val handle = SavedStateHandle()
+ val viewModel = createViewModel(handle)
+ viewModel.loadIfNeeded()
+ viewModel.onSearchQueryChanged("resume")
+ viewModel.onVolumeExpandToggled(SD_CARD)
+ assertEquals("resume", handle.get<String>(StorageViewModel.KEY_SEARCH_QUERY))
+ assertTrue(viewModel.uiState.value.isExpanded(SD_CARD))
+ assertFalse(viewModel.uiState.value.isExpanded(PRIMARY_VOLUME_NAME))
+
+ val savedExpandedVolumes = handle.get<Array<String>>(StorageViewModel.KEY_EXPANDED_VOLUMES)
+ val restored = createViewModel(
+ SavedStateHandle(
+ mapOf(
+ StorageViewModel.KEY_SEARCH_QUERY to "resume",
+ StorageViewModel.KEY_EXPANDED_VOLUMES to savedExpandedVolumes
+ )
+ )
+ )
+ assertTrue(restored.uiState.value.search.isSearching)
+ restored.loadIfNeeded()
+ assertEquals("resume", restored.uiState.value.search.query)
+ assertEquals(listOf("Résumé.pdf", "resume-old.pdf"), restored.resultNames())
+ assertTrue(restored.uiState.value.isExpanded(SD_CARD))
+
+ restored.onVolumeExpandToggled(SD_CARD)
+ assertFalse(restored.uiState.value.isExpanded(SD_CARD))
+ }
+
+ @Test
+ fun aSingleVolumeIsAlwaysExpanded() {
+ repository.volumes = listOf(PRIMARY_VOLUME_NAME)
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ assertFalse(viewModel.uiState.value.hasSeveralVolumes)
+ assertTrue(viewModel.uiState.value.isExpanded(PRIMARY_VOLUME_NAME))
+ }
+
+ @Test
+ fun usesTheRecentsViewTypeForResults() {
+ settings.folderViewTypes[""] = VIEW_TYPE_GRID
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ assertEquals(VIEW_TYPE_GRID, viewModel.uiState.value.viewType)
+ }
+
+ @Test
+ fun errorsWhileLoadingFilesAreReportedAsEvents() = runTest {
+ repository.filesError = IOException("media store unavailable")
+ val viewModel = createViewModel()
+ viewModel.loadIfNeeded()
+
+ assertTrue(viewModel.uiState.value.isFilesLoaded)
+ assertTrue(viewModel.volume(PRIMARY_VOLUME_NAME).hasStats)
+ assertEquals(StorageEvent.Error("java.io.IOException: media store unavailable"), viewModel.events.first())
+ }
+
+ private companion object {
+ const val SD_CARD = "1234-abcd"
+ }
+}
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 6c71eb8..9761776 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -5,10 +5,16 @@ kotlin = "2.3.10"
detekt = "1.23.8"
detektCompose = "0.4.28"
#AndroidX
+androidx-activity = "1.12.4"
+androidx-lifecycle = "2.10.0"
androidx-swiperefreshlayout = "1.2.0"
androidx-documentfile = "1.1.0"
#Fossify
commons = "6.1.6"
+#KotlinX
+kotlinx-coroutines = "1.9.0"
+#Testing
+junit = "4.13.2"
#Other
autofittextview = "0.2.1"
gestureviews = "2.9.0"
@@ -25,12 +31,21 @@ app-build-javaVersion = "VERSION_17"
app-build-kotlinJVMTarget = "17"
[libraries]
#AndroidX
+androidx-activity-ktx = { module = "androidx.activity:activity-ktx", version.ref = "androidx-activity" }
+androidx-lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "androidx-lifecycle" }
+androidx-lifecycle-viewmodel-ktx = { module = "androidx.lifecycle:lifecycle-viewmodel-ktx", version.ref = "androidx-lifecycle" }
+androidx-lifecycle-viewmodel-savedstate = { module = "androidx.lifecycle:lifecycle-viewmodel-savedstate", version.ref = "androidx-lifecycle" }
androidx-swiperefreshlayout = { module = "androidx.swiperefreshlayout:swiperefreshlayout", version.ref = "androidx-swiperefreshlayout" }
androidx-documentfile = { module = "androidx.documentfile:documentfile", version.ref = "androidx-documentfile" }
#Compose
compose-detekt = { module = "io.nlopez.compose.rules:detekt", version.ref = "detektCompose" }
#Fossify
fossify-commons = { module = "org.fossify:commons", version.ref = "commons" }
+#KotlinX
+kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinx-coroutines" }
+kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
+#Testing
+junit = { module = "junit:junit", version.ref = "junit" }
#Other
autofittextview = { module = "me.grantland:autofittextview", version.ref = "autofittextview" }
gestureviews = { module = "com.alexvasilkov:gesture-views", version.ref = "gestureviews" }
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 5715433..4acbe05 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
android {
sourceSets {
getByName("main").java.directories.add("src/main/kotlin")
+ getByName("test").java.directories.add("src/test/kotlin")
}
compileOptions {
dependencies {
implementation(libs.fossify.commons)
implementation(libs.androidx.documentfile)
implementation(libs.androidx.swiperefreshlayout)
+ implementation(libs.androidx.activity.ktx)
+ implementation(libs.androidx.lifecycle.runtime.ktx)
+ implementation(libs.androidx.lifecycle.viewmodel.ktx)
+ implementation(libs.androidx.lifecycle.viewmodel.savedstate)
+ implementation(libs.kotlinx.coroutines.android)
implementation(libs.roottools)
implementation(libs.rootshell)
implementation(libs.gestureviews)
implementation(libs.autofittextview)
implementation(libs.zip4j)
detektPlugins(libs.compose.detekt)
+
+ testImplementation(libs.junit)
+ testImplementation(libs.kotlinx.coroutines.test)
}
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..ddc34ef 100644
--- a/app/src/main/kotlin/org/fossify/filemanager/activities/MainActivity.kt
+++ b/app/src/main/kotlin/org/fossify/filemanager/activities/MainActivity.kt
class MainActivity : SimpleActivity() {
companion object {
private const val BACK_PRESS_TIMEOUT = 5000
- private const val PICKED_PATH = "picked_path"
}
private val binding by viewBinding(ActivityMainBinding::inflate)
class MainActivity : SimpleActivity() {
}
}
- override fun onSaveInstanceState(outState: Bundle) {
- super.onSaveInstanceState(outState)
- outState.putString(PICKED_PATH, getItemsFragment()?.currentPath ?: "")
- }
-
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
- val path = savedInstanceState.getString(PICKED_PATH) ?: internalStoragePath
-
+ // the tabs' ViewModels keep (or restore from their saved state) the folder, search and selection
if (binding.mainViewPager.adapter == null) {
binding.mainViewPager.onGlobalLayout {
- openPath(path, true)
+ restoreTabsState()
}
} else {
- openPath(path, true)
+ restoreTabsState()
+ }
+ }
+
+ private fun restoreTabsState() {
+ getItemsFragment()?.openInitialPathIfNeeded(internalStoragePath)
+ val query = getCurrentFragment()?.getSearchQuery().orEmpty()
+ if (query.isNotEmpty() && !binding.mainMenu.isSearchOpen) {
+ // the search field only opens the search once its focus listener is set, which MySearchMenu does in a post
+ binding.mainMenu.post {
+ binding.mainMenu.focusView()
+ binding.mainMenu.binding.topToolbarSearch.apply {
+ setText(query)
+ setSelection(query.length)
+ }
+ hideKeyboard()
+ }
}
}
class MainActivity : SimpleActivity() {
}
}
- private fun openPath(path: String, forceRefresh: Boolean = false) {
+ private fun openPath(path: String) {
var newPath = path
val file = File(path)
if (config.OTGPath.isNotEmpty() && config.OTGPath == path.trimEnd('/')) {
class MainActivity : SimpleActivity() {
newPath = internalStoragePath
}
- getItemsFragment()?.openPath(newPath, forceRefresh)
+ getItemsFragment()?.openPath(newPath)
}