music: new location dialog

This commit is contained in:
Alexander Capehart
2025-07-04 13:41:33 -06:00
parent 497c35d81a
commit b6b5b3b87d
23 changed files with 1170 additions and 412 deletions
@@ -27,8 +27,20 @@ import javax.inject.Inject
import org.oxycblt.auxio.R
import org.oxycblt.auxio.settings.Settings
import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.mediastore.MediaStoreFS
import org.oxycblt.musikr.fs.saf.SAF
import timber.log.Timber as L
/**
* Represents the mode for loading music locations.
*/
enum class MusicLocationMode {
/** Use Storage Access Framework (file picker) to select specific folders */
SAF,
/** Use system MediaStore database to load all music */
SYSTEM
}
/**
* User configuration specific to music system.
*
@@ -41,6 +53,10 @@ interface MusicSettings : Settings<MusicSettings.Listener> {
var musicLocations: List<Location.Opened>
/** The locations to exclude from music loading. */
var excludedLocations: List<Location.Unopened>
/** The currently configured SAF query (if any) * */
val safQuery: SAF.Query?
/** The currently configured MediaStore query (if any) * */
val mediaStoreQuery: MediaStoreFS.Query?
/** Whether to exclude non-music audio files from the music library. */
val excludeNonMusic: Boolean
/** Whether to ignore hidden files and directories during music loading. */
@@ -53,6 +69,8 @@ interface MusicSettings : Settings<MusicSettings.Listener> {
val intelligentSorting: Boolean
/** Whether to use the file-system cache for improved loading times. */
val useFileTreeCache: Boolean
/** The mode for loading music locations (SAF or System database). */
var locationMode: MusicLocationMode
interface Listener {
/** Called when the current music locations changed. */
@@ -138,6 +156,39 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
override val useFileTreeCache: Boolean
get() = sharedPreferences.getBoolean(getString(R.string.set_key_fs_cache), false)
override var locationMode: MusicLocationMode
get() {
val ordinal = sharedPreferences.getInt(getString(R.string.set_key_saf_mode), 0)
return MusicLocationMode.values().getOrNull(ordinal) ?: MusicLocationMode.SAF
}
set(value) {
sharedPreferences.edit {
putInt(getString(R.string.set_key_saf_mode), value.ordinal)
apply()
}
}
override val safQuery: SAF.Query?
get() {
// SAF query is used when in SAF mode and we have music locations configured
if (locationMode != MusicLocationMode.SAF) return null
val locations = musicLocations
if (locations.isEmpty()) return null
return SAF.Query(
source = locations, exclude = excludedLocations, withHidden = withHidden)
}
override val mediaStoreQuery: MediaStoreFS.Query?
get() {
// MediaStore query is used when in system database mode
if (locationMode != MusicLocationMode.SYSTEM) return null
return MediaStoreFS.Query(
include = emptyList(), // No include filter in system database mode
exclude = excludedLocations,
excludeNonMusic = excludeNonMusic)
}
override fun onSettingChanged(key: String, listener: MusicSettings.Listener) {
// TODO: Differentiate "hard reloads" (Need the cache) and "Soft reloads"
// (just need to manipulate data)
@@ -1,57 +0,0 @@
/*
* Copyright (c) 2021 Auxio Project
* ExcludedLocationAdapter.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.music.locations
import android.view.ViewGroup
import org.oxycblt.auxio.databinding.ItemMusicLocationBinding
import org.oxycblt.auxio.util.inflater
import org.oxycblt.musikr.fs.Location
/**
* [LocationAdapter] that manages a list of [Location.Unopened] excluded directory instances.
*
* @param listener A [LocationAdapter.Listener] to bind interactions to.
* @author Alexander Capehart (OxygenCobalt)
*/
class ExcludedLocationAdapter(listener: LocationAdapter.Listener<Location.Unopened>) :
LocationAdapter<Location.Unopened>(listener) {
override fun createViewHolder(parent: ViewGroup): LocationViewHolder<Location.Unopened> =
ExcludedLocationViewHolder.from(parent)
}
/**
* A [LocationViewHolder] that displays a [Location.Unopened]. Use [from] to create an instance.
*
* @author Alexander Capehart (OxygenCobalt)
*/
class ExcludedLocationViewHolder private constructor(binding: ItemMusicLocationBinding) :
LocationViewHolder<Location.Unopened>(binding) {
companion object {
/**
* Create a new instance.
*
* @param parent The parent to inflate this instance from.
* @return A new instance.
*/
fun from(parent: ViewGroup) =
ExcludedLocationViewHolder(
ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false))
}
}
@@ -1,63 +0,0 @@
/*
* Copyright (c) 2021 Auxio Project
* ExcludedLocationsDialog.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.music.locations
import android.content.Context
import android.net.Uri
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.R
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.musikr.fs.Location
/**
* Dialog that manages the excluded locations setting.
*
* @author Alexander Capehart (OxygenCobalt)
*/
@AndroidEntryPoint
class ExcludedLocationsDialog : LocationsDialog<Location.Unopened>() {
override val locationAdapter = ExcludedLocationAdapter(this)
@Inject override lateinit var musicSettings: MusicSettings
override fun getDialogTitle(): Int = R.string.set_excluded_locations
override fun getCurrentLocations(): List<Location.Unopened> = musicSettings.excludedLocations
override fun saveLocations(locations: List<Location.Unopened>) {
musicSettings.excludedLocations = locations
}
override fun getPendingLocationsKey(): String = KEY_PENDING_EXCLUDED_LOCATIONS
override fun convertUriToLocation(uri: Uri): Location.Unopened? {
return Location.Unopened.from(requireContext(), uri)
}
override fun createLocationFromUri(context: Context, uri: Uri): Location.Unopened? {
return Location.Unopened.from(context, uri)
}
private companion object {
const val KEY_PENDING_EXCLUDED_LOCATIONS =
BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS"
}
}
@@ -20,57 +20,126 @@ package org.oxycblt.auxio.music.locations
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.ItemMusicLocationBinding
import org.oxycblt.auxio.databinding.ItemNoLocationsBinding
import org.oxycblt.auxio.list.recycler.DialogRecyclerView
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.inflater
import org.oxycblt.musikr.fs.Location
import timber.log.Timber as L
abstract class LocationAdapter<T : Location>(private val listener: Listener<T>) :
RecyclerView.Adapter<LocationViewHolder<T>>() {
class LocationAdapter<T : Location>(private val listener: Listener) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val _locations = mutableListOf<T>()
val locations: List<T> = _locations
override fun getItemCount() = locations.size
override fun getItemCount() = if (locations.isEmpty()) 1 else locations.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(parent)
override fun getItemViewType(position: Int): Int {
return if (locations.isEmpty()) VIEW_TYPE_EMPTY else VIEW_TYPE_LOCATION
}
override fun onBindViewHolder(holder: LocationViewHolder<T>, position: Int) =
holder.bind(locations[position], listener)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW_TYPE_EMPTY -> EmptyLocationViewHolder.from(parent)
VIEW_TYPE_LOCATION -> LocationViewHolder.from<T>(parent)
else -> throw IllegalArgumentException("Unknown view type: $viewType")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is LocationViewHolder<*> -> {
@Suppress("UNCHECKED_CAST")
(holder as LocationViewHolder<T>).bind(locations[position], listener)
}
is EmptyLocationViewHolder -> holder.bind()
}
}
fun add(location: T) {
if (_locations.contains(location)) return
L.d("Adding $location")
val wasEmpty = _locations.isEmpty()
_locations.add(location)
notifyItemInserted(_locations.lastIndex)
if (wasEmpty) {
notifyItemChanged(0)
} else {
notifyItemInserted(_locations.lastIndex)
}
}
fun addAll(locations: List<T>) {
L.d("Adding ${locations.size} locations")
val wasEmpty = _locations.isEmpty()
val oldSize = _locations.size
_locations.addAll(locations)
notifyItemRangeInserted(oldSize, locations.size)
if (wasEmpty && locations.isNotEmpty()) {
notifyItemChanged(0)
} else if (locations.isNotEmpty()) {
notifyItemRangeInserted(oldSize, locations.size)
}
}
fun remove(location: T) {
L.d("Removing $location")
val idx = _locations.indexOf(location)
_locations.removeAt(idx)
notifyItemRemoved(idx)
if (_locations.isEmpty()) {
notifyItemChanged(0)
} else {
notifyItemRemoved(idx)
}
}
protected abstract fun createViewHolder(parent: ViewGroup): LocationViewHolder<T>
interface Listener {
fun onRemoveLocation(location: Location)
}
interface Listener<T : Location> {
fun onRemoveLocation(location: T)
companion object {
private const val VIEW_TYPE_EMPTY = 0
private const val VIEW_TYPE_LOCATION = 1
}
}
abstract class LocationViewHolder<T : Location>(protected val binding: ItemMusicLocationBinding) :
class LocationViewHolder<T : Location>(private val binding: ItemMusicLocationBinding) :
DialogRecyclerView.ViewHolder(binding.root) {
fun bind(location: T, listener: LocationAdapter.Listener<T>) {
fun bind(location: T, listener: LocationAdapter.Listener) {
binding.locationPath.text = location.path.resolve(binding.context)
binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) }
}
companion object {
/**
* Create a new instance.
*
* @param parent The parent to inflate this instance from.
* @return A new instance.
*/
fun <T : Location> from(parent: ViewGroup) =
LocationViewHolder<T>(
ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false))
}
}
class EmptyLocationViewHolder(private val binding: ItemNoLocationsBinding) :
DialogRecyclerView.ViewHolder(binding.root) {
fun bind() {
binding.locationPath.text = binding.context.getString(R.string.lbl_no_folders)
}
companion object {
/**
* Create a new instance.
*
* @param parent The parent to inflate this instance from.
* @return A new instance.
*/
fun from(parent: ViewGroup) =
EmptyLocationViewHolder(
ItemNoLocationsBinding.inflate(parent.context.inflater, parent, false))
}
}
@@ -0,0 +1,80 @@
/*
* Copyright (c) 2025 Auxio Project
* LocationConfig.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.music.locations
import android.content.Context
import androidx.core.net.toUri
import org.oxycblt.auxio.util.splitEscaped
import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.mediastore.MediaStoreFS
import org.oxycblt.musikr.fs.saf.SAF
sealed interface LocationConfig {
data class Filesystem(private val query: SAF.Query) : LocationConfig
data class SystemDatabase(private val query: MediaStoreFS.Query) : LocationConfig
companion object {
fun from(context: Context, string: String): LocationConfig? {
val typeSplit = string.splitEscaped('!')
if (typeSplit.size != 2) return null
val type = typeSplit[0]
val args = typeSplit[1].splitEscaped('|')
return when (type) {
"saf" -> {
if (args.size < 3) return null
val source =
args[0]
.splitEscaped(';')
.map { it.toUri() }
.mapNotNull { Location.Unopened.from(context, it)?.open(context) }
val exclude =
args[1]
.splitEscaped(';')
.map { it.toUri() }
.mapNotNull { Location.Unopened.from(context, it) }
val withHidden = args[2].toBoolean()
val query =
SAF.Query(source = source, exclude = exclude, withHidden = withHidden)
Filesystem(query = query)
}
"media" -> {
if (args.size < 3) return null
val include =
args[0]
.splitEscaped(';')
.map { it.toUri() }
.mapNotNull { Location.Unopened.from(context, it) }
val exclude =
args[1]
.splitEscaped(';')
.map { it.toUri() }
.mapNotNull { Location.Unopened.from(context, it) }
val excludeNonMusic = args[1].toBoolean()
SystemDatabase(
MediaStoreFS.Query(
include = include,
exclude = exclude,
excludeNonMusic = excludeNonMusic))
}
else -> null
}
}
}
}
@@ -25,36 +25,68 @@ import android.view.LayoutInflater
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
import androidx.recyclerview.widget.ConcatAdapter
import androidx.core.content.edit
import androidx.core.view.isVisible
import com.google.android.material.R as MR
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding
import org.oxycblt.auxio.music.MusicLocationMode
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.getAttrColorCompat
import org.oxycblt.auxio.util.showToast
import org.oxycblt.musikr.fs.Location
import timber.log.Timber as L
abstract class LocationsDialog<T : Location> :
ViewBindingMaterialDialogFragment<DialogMusicLocationsBinding>(),
LocationAdapter.Listener<T>,
NewLocationFooterAdapter.Listener {
protected abstract val locationAdapter: LocationAdapter<T>
private val locationFooterAdapter = NewLocationFooterAdapter(this)
@AndroidEntryPoint
class LocationsDialog : ViewBindingMaterialDialogFragment<DialogMusicLocationsBinding>() {
private val includeLocationListener =
object : LocationAdapter.Listener {
override fun onRemoveLocation(location: Location) {
includeLocationAdapter.remove(location as Location.Opened)
}
}
private val excludeLocationListener =
object : LocationAdapter.Listener {
override fun onRemoveLocation(location: Location) {
excludeLocationAdapter.remove(location as Location.Unopened)
}
}
private val filterLocationListener =
object : LocationAdapter.Listener {
override fun onRemoveLocation(location: Location) {
filterLocationAdapter.remove(location as Location.Unopened)
}
}
private val includeLocationAdapter: LocationAdapter<Location.Opened> =
LocationAdapter(includeLocationListener)
private val excludeLocationAdapter: LocationAdapter<Location.Unopened> =
LocationAdapter(excludeLocationListener)
private val filterLocationAdapter: LocationAdapter<Location.Unopened> =
LocationAdapter(filterLocationListener)
private var openDocumentTreeLauncher: ActivityResultLauncher<Uri?>? = null
abstract val musicSettings: MusicSettings
@Inject lateinit var musicSettings: MusicSettings
private var isFilePickerMode = true
private var isIncludeMode = true
private var hasStoragePermission = false
private var isExtrasExpanded = false
private var pendingLocationCallback: ((Location.Unopened) -> Unit)? = null
override fun onCreateBinding(inflater: LayoutInflater) =
DialogMusicLocationsBinding.inflate(inflater)
override fun onConfigDialog(builder: AlertDialog.Builder) {
builder
.setTitle(getDialogTitle())
.setTitle(R.string.lbl_music_sources)
.setNegativeButton(R.string.lbl_cancel, null)
.setPositiveButton(R.string.lbl_save) { _, _ ->
val newDirs = locationAdapter.locations
saveLocations(newDirs)
}
.setPositiveButton(R.string.lbl_save) { _, _ -> saveChanges() }
}
override fun onBindingCreated(
@@ -62,36 +94,152 @@ abstract class LocationsDialog<T : Location> :
savedInstanceState: Bundle?
) {
openDocumentTreeLauncher =
registerForActivityResult(
ActivityResultContracts.OpenDocumentTree(), ::addDocumentTreeUriToDirs)
registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
addDocumentTreeUriToDirs(uri)
}
binding.locationsRecycler.apply {
adapter = ConcatAdapter(locationAdapter, locationFooterAdapter)
binding.locationsIncludeRecycler.apply {
adapter = includeLocationAdapter
itemAnimator = null
}
val locations =
savedInstanceState?.getStringArrayList(getPendingLocationsKey())?.mapNotNull {
convertUriToLocation(it.toUri())
} ?: getCurrentLocations()
binding.locationsExcludeRecycler.apply {
adapter = excludeLocationAdapter
itemAnimator = null
}
locationAdapter.addAll(locations)
binding.locationsFilterRecycler.apply {
adapter = filterLocationAdapter
itemAnimator = null
}
// Load initial state from MusicSettings
loadInitialState(binding)
// Set up string resources
binding.locationsModeHeader.setText(R.string.lbl_load_from)
binding.locationsModeExclude.setText(R.string.lbl_file_picker)
binding.locationsModeInclude.setText(R.string.lbl_system_database)
binding.locationsExcludeModeHeader.setText(R.string.lbl_filter_mode)
binding.locationsExcludeModeExclude.setText(R.string.lbl_include)
binding.locationsExcludeModeInclude.setText(R.string.lbl_exclude)
binding.locationsIncludeListHeader.setText(R.string.lbl_folders_to_load)
binding.locationsIncludeAdd.contentDescription = getString(R.string.desc_add_folder)
binding.locationsExcludeAdd.contentDescription = getString(R.string.desc_add_folder)
binding.locationsFilterAdd.contentDescription = getString(R.string.desc_add_folder)
binding.locationsExtrasDropdown.setText(R.string.lbl_extra_settings)
// Set up extras dropdown click listener
binding.locationsExtrasDropdown.setOnClickListener {
isExtrasExpanded = !isExtrasExpanded
updateExtrasVisibility(binding)
}
// Set up mode toggle listener
binding.folderModeGroup.addOnButtonCheckedListener { group, checkedId, isChecked ->
if (!isChecked) return@addOnButtonCheckedListener
when (checkedId) {
R.id.locations_mode_exclude -> {
isFilePickerMode = true
updateModeUI(binding)
}
R.id.locations_mode_include -> {
isFilePickerMode = false
updateModeUI(binding)
}
}
}
// Set up exclude/include mode toggle listener for System Database mode
binding.locationsExcludeModeGroup.addOnButtonCheckedListener { group, checkedId, isChecked
->
if (!isChecked) return@addOnButtonCheckedListener
when (checkedId) {
R.id.locations_exclude_mode_exclude -> {
isIncludeMode = true
updateExcludeModeUI(binding)
}
R.id.locations_exclude_mode_include -> {
isIncludeMode = false
updateExcludeModeUI(binding)
}
}
}
// Set up add folder buttons
binding.locationsIncludeAdd.setOnClickListener {
pendingLocationCallback = { location ->
location.open(requireContext())?.let { opened ->
includeLocationAdapter.add(opened)
}
}
onNewLocation()
}
binding.locationsExcludeAdd.setOnClickListener {
pendingLocationCallback = { location -> excludeLocationAdapter.add(location) }
onNewLocation()
}
binding.locationsFilterAdd.setOnClickListener {
pendingLocationCallback = { location -> filterLocationAdapter.add(location) }
onNewLocation()
}
// Set up grant permission card click
binding.locationsPermsContainer.setOnClickListener {
// TODO: Implement permission request
L.d("Grant permission clicked")
}
// Initialize UI state
updateModeUI(binding)
updateExtrasVisibility(binding)
}
private fun loadInitialState(binding: DialogMusicLocationsBinding) {
// Determine mode based on the locationMode setting
isFilePickerMode = musicSettings.locationMode == MusicLocationMode.SAF
if (isFilePickerMode) {
// File picker mode - load music locations and excluded locations
includeLocationAdapter.addAll(musicSettings.musicLocations)
excludeLocationAdapter.addAll(musicSettings.excludedLocations)
binding.configSwitchFilePicker.isChecked = musicSettings.withHidden
binding.folderModeGroup.check(R.id.locations_mode_exclude)
} else {
// System database mode - load excluded locations
// Filter locations come from exclude list
filterLocationAdapter.addAll(musicSettings.excludedLocations)
binding.configSwitchSystem.isChecked = !musicSettings.excludeNonMusic
// Determine include/exclude mode based on whether we have exclude locations
// If we have exclude locations, we're in exclude mode
isIncludeMode = musicSettings.excludedLocations.isEmpty()
binding.locationsExcludeModeGroup.check(
if (isIncludeMode) R.id.locations_exclude_mode_exclude
else R.id.locations_exclude_mode_include)
binding.folderModeGroup.check(R.id.locations_mode_include)
}
// TODO: Check storage permission status
hasStoragePermission = false
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putStringArrayList(
getPendingLocationsKey(),
ArrayList(locationAdapter.locations.map { it.uri.toString() }))
// TODO
}
override fun onDestroyBinding(binding: DialogMusicLocationsBinding) {
super.onDestroyBinding(binding)
openDocumentTreeLauncher = null
binding.locationsRecycler.adapter = null
binding.locationsIncludeRecycler.adapter = null
binding.locationsExcludeRecycler.adapter = null
binding.locationsFilterRecycler.adapter = null
}
override fun onNewLocation() {
private fun onNewLocation() {
L.d("Opening launcher")
val launcher =
requireNotNull(openDocumentTreeLauncher) { "Document tree launcher was not available" }
@@ -106,31 +254,243 @@ abstract class LocationsDialog<T : Location> :
private fun addDocumentTreeUriToDirs(uri: Uri?) {
if (uri == null) {
L.d("No URI given (user closed the dialog)")
pendingLocationCallback = null
return
}
val context = requireContext()
val location = createLocationFromUri(context, uri)
val location = Location.Unopened.from(context, uri)
if (location != null) {
locationAdapter.add(location)
pendingLocationCallback?.invoke(location)
} else {
requireContext().showToast(R.string.err_bad_location)
}
pendingLocationCallback = null
}
override fun onRemoveLocation(location: T) {
locationAdapter.remove(location)
private fun updateModeUI(binding: DialogMusicLocationsBinding) {
with(binding) {
if (isFilePickerMode) {
// File Picker mode
locationsModeDesc.setText(R.string.desc_file_picker)
// Update permission section
locationsPermsDesc.setText(R.string.lbl_grant_storage_anyway)
locationsPermsSubtitle.setText(R.string.desc_grant_storage_anyway)
// File Picker mode - no need to update switch text as it's set in XML
} else {
// System Database mode
locationsModeDesc.setText(R.string.desc_system_database)
// Update permission section
locationsPermsDesc.setText(R.string.lbl_grant_storage)
locationsPermsSubtitle.setText(R.string.desc_grant_storage_required)
// Update exclude mode description based on selection
updateExcludeModeUI(binding)
// System Database mode - no need to update switch text as it's set in XML
}
// Update enabled state based on permission
updatePermissionDependentUI(binding)
// Update card colors based on mode and permission
updatePermissionCardColors(binding)
// Update permission card visibility
updatePermissionCardVisibility(binding)
// Update extras visibility based on current state
updateExtrasVisibility(binding)
}
}
protected abstract fun getDialogTitle(): Int
private fun updateExcludeModeUI(binding: DialogMusicLocationsBinding) {
with(binding) {
if (isIncludeMode) {
locationsExcludeModeDesc.setText(R.string.desc_include_folders)
} else {
locationsExcludeModeDesc.setText(R.string.desc_exclude_folders)
}
}
}
protected abstract fun getCurrentLocations(): List<T>
private fun updatePermissionDependentUI(binding: DialogMusicLocationsBinding) {
with(binding) {
// Only disable views in System Database mode when permission not granted
// File Picker mode doesn't require storage permission
val isEnabled = isFilePickerMode || hasStoragePermission
protected abstract fun saveLocations(locations: List<T>)
locationsIncludeListHeader.isEnabled = isEnabled
locationsIncludeAdd.isEnabled = isEnabled
locationsIncludeRecycler.isEnabled = isEnabled
protected abstract fun getPendingLocationsKey(): String
locationsExcludeModeHeader.isEnabled = isEnabled
locationsExcludeModeGroup.isEnabled = isEnabled
locationsExcludeModeDesc.isEnabled = isEnabled
locationsExcludeModeExclude.isEnabled = isEnabled
locationsExcludeModeInclude.isEnabled = isEnabled
protected abstract fun convertUriToLocation(uri: Uri): T?
locationsExcludeListHeader.isEnabled = isEnabled
locationsExcludeAdd.isEnabled = isEnabled
locationsExcludeRecycler.isEnabled = isEnabled
protected abstract fun createLocationFromUri(context: android.content.Context, uri: Uri): T?
locationsFilterListHeader.isEnabled = isEnabled
locationsFilterAdd.isEnabled = isEnabled
locationsFilterRecycler.isEnabled = isEnabled
configSwitchFilePicker.isEnabled = isEnabled
configSwitchSystem.isEnabled = isEnabled
}
}
private fun updatePermissionCardColors(binding: DialogMusicLocationsBinding) {
val context = requireContext()
with(binding.locationsPermsCard) {
if (isFilePickerMode) {
// File Picker mode - use secondary colors
setCardBackgroundColor(context.getAttrColorCompat(MR.attr.colorSecondaryContainer))
binding.locationsPermsDesc.setTextColor(
context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer))
binding.locationsPermsSubtitle.setTextColor(
context.getAttrColorCompat(MR.attr.colorSecondary))
binding.locationsPermsOpen.imageTintList =
context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)
} else {
// System Database mode - use error colors if no permission, secondary colors if
// granted
if (hasStoragePermission) {
// Has permission - use secondary colors
setCardBackgroundColor(
context.getAttrColorCompat(MR.attr.colorSecondaryContainer))
binding.locationsPermsDesc.setTextColor(
context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer))
binding.locationsPermsSubtitle.setTextColor(
context.getAttrColorCompat(MR.attr.colorSecondary))
binding.locationsPermsOpen.imageTintList =
context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)
} else {
setCardBackgroundColor(context.getAttrColorCompat(MR.attr.colorErrorContainer))
binding.locationsPermsDesc.setTextColor(
context.getAttrColorCompat(MR.attr.colorOnErrorContainer))
binding.locationsPermsSubtitle.setTextColor(
context.getAttrColorCompat(MR.attr.colorError))
binding.locationsPermsOpen.imageTintList =
context.getAttrColorCompat(MR.attr.colorOnErrorContainer)
}
}
}
}
private fun updatePermissionCardVisibility(binding: DialogMusicLocationsBinding) {
with(binding) {
// Hide the permission card when permissions are granted
locationsPermsContainer.isVisible = !hasStoragePermission
}
}
private fun updateExtrasVisibility(binding: DialogMusicLocationsBinding) {
with(binding) {
// Update dropdown icon rotation
locationsExtrasDropdownIcon.rotation = if (isExtrasExpanded) 180f else 0f
if (isFilePickerMode) {
// File Picker mode - show include/exclude lists when expanded
// Include section
locationsIncludeListHeaderDivider.isVisible = true
locationsIncludeListHeader.isVisible = true
locationsIncludeAdd.isVisible = true
locationsIncludeRecycler.isVisible = true
// Show dividers and exclude section only when expanded
locationsExcludeListHeader.isVisible = isExtrasExpanded
locationsExcludeAdd.isVisible = isExtrasExpanded
locationsExcludeRecycler.isVisible = isExtrasExpanded
// Hide filter mode section completely
locationsExcludeModeHeader.isVisible = false
locationsExcludeModeGroup.isVisible = false
locationsExcludeModeDesc.isVisible = false
locationsFilterModeDivider.isVisible = false
locationsFilterListHeader.isVisible = false
locationsFilterAdd.isVisible = false
locationsFilterRecycler.isVisible = false
locationsExcludeListDivider.isVisible = false
// Config section
configDivider.isVisible = isExtrasExpanded
configSwitchFilePicker.isVisible = isExtrasExpanded
configSwitchSystem.isVisible = false
} else {
// System Database mode - show filter mode when expanded
// Hide include section
locationsIncludeListHeaderDivider.isVisible = false
locationsIncludeListHeader.isVisible = false
locationsIncludeAdd.isVisible = false
locationsIncludeRecycler.isVisible = false
// Hide exclude section (at bottom)
locationsExcludeListDivider.isVisible = false
locationsExcludeListHeader.isVisible = false
locationsExcludeAdd.isVisible = false
locationsExcludeRecycler.isVisible = false
// Show filter mode section only when expanded
locationsExcludeModeHeader.isVisible = isExtrasExpanded
locationsExcludeModeGroup.isVisible = isExtrasExpanded
locationsExcludeModeDesc.isVisible = isExtrasExpanded
locationsFilterModeDivider.isVisible = isExtrasExpanded
locationsFilterListHeader.isVisible = isExtrasExpanded
locationsFilterAdd.isVisible = isExtrasExpanded
locationsFilterRecycler.isVisible = isExtrasExpanded
// Config section
configDivider.isVisible = isExtrasExpanded
configSwitchFilePicker.isVisible = false
configSwitchSystem.isVisible = isExtrasExpanded
}
}
}
private fun saveChanges() {
val binding = requireBinding()
// Save the mode setting
musicSettings.locationMode = if (isFilePickerMode) MusicLocationMode.SAF else MusicLocationMode.SYSTEM
if (isFilePickerMode) {
// File picker mode - save include and exclude locations
musicSettings.musicLocations = includeLocationAdapter.locations
musicSettings.excludedLocations = excludeLocationAdapter.locations
// Update withHidden setting
val withHidden = binding.configSwitchFilePicker.isChecked
if (musicSettings.withHidden != withHidden) {
binding.root.context.getSharedPreferences("auxio_preferences", 0).edit {
putBoolean(getString(R.string.set_key_with_hidden), withHidden)
apply()
}
}
} else {
// System database mode - clear music locations and save filter locations
musicSettings.musicLocations = emptyList()
// In include mode, we don't have any excluded locations
// In exclude mode, we save the filter locations as excluded
musicSettings.excludedLocations =
if (isIncludeMode) {
emptyList()
} else {
filterLocationAdapter.locations
}
// Update excludeNonMusic setting
val excludeNonMusic = !binding.configSwitchSystem.isChecked
if (musicSettings.excludeNonMusic != excludeNonMusic) {
binding.root.context.getSharedPreferences("auxio_preferences", 0).edit {
putBoolean(getString(R.string.set_key_exclude_non_music), excludeNonMusic)
apply()
}
}
}
}
}
@@ -1,57 +0,0 @@
/*
* Copyright (c) 2021 Auxio Project
* MusicLocationAdapter.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.music.locations
import android.view.ViewGroup
import org.oxycblt.auxio.databinding.ItemMusicLocationBinding
import org.oxycblt.auxio.util.inflater
import org.oxycblt.musikr.fs.Location
/**
* [LocationAdapter] that manages a list of [Location.Opened] music directory instances.
*
* @param listener A [LocationAdapter.Listener] to bind interactions to.
* @author Alexander Capehart (OxygenCobalt)
*/
class MusicLocationAdapter(listener: LocationAdapter.Listener<Location.Opened>) :
LocationAdapter<Location.Opened>(listener) {
override fun createViewHolder(parent: ViewGroup): LocationViewHolder<Location.Opened> =
MusicLocationViewHolder.from(parent)
}
/**
* A [LocationViewHolder] that displays a [Location.Opened]. Use [from] to create an instance.
*
* @author Alexander Capehart (OxygenCobalt)
*/
class MusicLocationViewHolder private constructor(binding: ItemMusicLocationBinding) :
LocationViewHolder<Location.Opened>(binding) {
companion object {
/**
* Create a new instance.
*
* @param parent The parent to inflate this instance from.
* @return A new instance.
*/
fun from(parent: ViewGroup) =
MusicLocationViewHolder(
ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false))
}
}
@@ -1,63 +0,0 @@
/*
* Copyright (c) 2021 Auxio Project
* MusicLocationsDialog.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.music.locations
import android.content.Context
import android.net.Uri
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.R
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.musikr.fs.Location
/**
* Dialog that manages the music locations setting.
*
* @author Alexander Capehart (OxygenCobalt)
*/
@AndroidEntryPoint
class MusicLocationsDialog : LocationsDialog<Location.Opened>() {
override val locationAdapter = MusicLocationAdapter(this)
@Inject override lateinit var musicSettings: MusicSettings
override fun getDialogTitle(): Int = R.string.set_locations
override fun getCurrentLocations(): List<Location.Opened> = musicSettings.musicLocations
override fun saveLocations(locations: List<Location.Opened>) {
musicSettings.musicLocations = locations
}
override fun getPendingLocationsKey(): String = KEY_PENDING_LOCATIONS
override fun convertUriToLocation(uri: Uri): Location.Opened? {
val context = requireContext()
return Location.Unopened.from(context, uri)?.open(context)
}
override fun createLocationFromUri(context: Context, uri: Uri): Location.Opened? {
return Location.Unopened.from(context, uri)?.open(context)
}
private companion object {
const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_LOCATIONS"
}
}
@@ -1,82 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* NewLocationFooterAdapter.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.music.locations
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.oxycblt.auxio.databinding.ItemNewMusicLocationBinding
import org.oxycblt.auxio.list.recycler.DialogRecyclerView
import org.oxycblt.auxio.music.decision.AddToPlaylistDialog
import org.oxycblt.auxio.util.inflater
/**
* A purely-visual [RecyclerView.Adapter] that acts as a footer providing a "New Playlist" choice in
* [AddToPlaylistDialog].
*
* @author Alexander Capehart (OxygenCobalt)
*/
class NewLocationFooterAdapter(private val listener: Listener) :
RecyclerView.Adapter<NewLocationFooterViewHolder>() {
override fun getItemCount() = 1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
NewLocationFooterViewHolder.from(parent)
override fun onBindViewHolder(holder: NewLocationFooterViewHolder, position: Int) {
holder.bind(listener)
}
/** A listener for [NewLocationFooterAdapter] interactions. */
interface Listener {
/** Called when the footer has been pressed, requesting to create a new location. */
fun onNewLocation()
}
}
/**
* A [RecyclerView.ViewHolder] that displays a "New Playlist" choice in [NewLocationFooterAdapter].
* Use [from] to create an instance.
*
* @author Alexander Capehart (OxygenCobalt)
*/
class NewLocationFooterViewHolder
private constructor(private val binding: ItemNewMusicLocationBinding) :
DialogRecyclerView.ViewHolder(binding.root) {
/**
* Bind new data to this instance.
*
* @param listener A [NewLocationFooterAdapter.Listener] to bind interactions to.
*/
fun bind(listener: NewLocationFooterAdapter.Listener) {
binding.root.setOnClickListener { listener.onNewLocation() }
}
companion object {
/**
* Create a new instance.
*
* @param parent The parent to inflate this instance from.
* @return A new instance.
*/
fun from(parent: View) =
NewLocationFooterViewHolder(
ItemNewMusicLocationBinding.inflate(parent.context.inflater))
}
}
@@ -56,10 +56,6 @@ class RootPreferenceFragment : BasePreferenceFragment(R.xml.preferences_root) {
findNavController()
.navigateSafe(RootPreferenceFragmentDirections.musicLocationsSettings())
}
getString(R.string.set_key_excluded_dirs) -> {
findNavController()
.navigateSafe(RootPreferenceFragmentDirections.excludedLocationsSettings())
}
}
}
@@ -63,3 +63,48 @@ fun lazyReflectedMethod(clazz: KClass<*>, method: String, vararg params: KClass<
it.isAccessible = true
}
}
/**
* Split a [String] by the given selector, automatically handling escaped characters that satisfy
* the selector.
*
* @param selector A block that determines if the string should be split at a given character.
* @return One or more [String]s split by the selector.
*/
internal fun String.splitEscaped(selector: Char): List<String> {
val split = mutableListOf<String>()
var currentString = ""
var i = 0
while (i < length) {
val a = get(i)
val b = getOrNull(i + 1)
if (a == selector) {
// Non-escaped separator, split the string here, making sure any stray whitespace
// is removed.
split.add(currentString)
currentString = ""
i++
continue
}
if (b != null && a == '\\' && a == selector) {
// Is an escaped character, add the non-escaped variant and skip two
// characters to move on to the next one.
currentString += b
i += 2
} else {
// Non-escaped, increment normally.
currentString += a
i++
}
}
if (currentString.isNotEmpty()) {
// Had an in-progress split string that is now terminated, add it.
split.add(currentString)
}
return split
}