music: share code between music/excluded locations

Co-authored by Claude.
This commit is contained in:
Alexander Capehart
2025-05-31 14:45:13 -06:00
parent 15c1c23b5c
commit 1ad9df3163
18 changed files with 253 additions and 349 deletions
@@ -27,7 +27,6 @@ import javax.inject.Inject
import org.oxycblt.auxio.R import org.oxycblt.auxio.R
import org.oxycblt.auxio.settings.Settings import org.oxycblt.auxio.settings.Settings
import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.OpenedLocation
import timber.log.Timber as L import timber.log.Timber as L
/** /**
@@ -39,9 +38,9 @@ interface MusicSettings : Settings<MusicSettings.Listener> {
/** The current library revision. */ /** The current library revision. */
var revision: UUID? var revision: UUID?
/** The locations of music to load. */ /** The locations of music to load. */
var musicLocations: List<OpenedLocation> var musicLocations: List<Location.Opened>
/** The locations to exclude from music loading. */ /** The locations to exclude from music loading. */
var excludedLocations: List<Location> var excludedLocations: List<Location.Unopened>
/** Whether to exclude non-music audio files from the music library. */ /** Whether to exclude non-music audio files from the music library. */
val excludeNonMusic: Boolean val excludeNonMusic: Boolean
/** Whether to ignore hidden files and directories during music loading. */ /** Whether to ignore hidden files and directories during music loading. */
@@ -78,7 +77,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
} }
} }
override var musicLocations: List<OpenedLocation> override var musicLocations: List<Location.Opened>
get() { get() {
val locations = val locations =
sharedPreferences.getString(getString(R.string.set_key_music_locations), null) sharedPreferences.getString(getString(R.string.set_key_music_locations), null)
@@ -95,12 +94,12 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
} }
} }
override var excludedLocations: List<Location> override var excludedLocations: List<Location.Unopened>
get() { get() {
val locations = val locations =
sharedPreferences.getString(getString(R.string.set_key_excluded_locations), null) sharedPreferences.getString(getString(R.string.set_key_excluded_locations), null)
?: return emptyList() ?: return emptyList()
return locations.toLocations() return locations.toUnopenedLocations()
} }
set(value) { set(value) {
sharedPreferences.edit { sharedPreferences.edit {
@@ -157,17 +156,17 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
} }
} }
private fun List<OpenedLocation>.stringify(): String = private fun List<Location.Opened>.stringify(): String =
joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") }
private fun String.toOpenedLocations(): List<OpenedLocation> = private fun String.toOpenedLocations(): List<Location.Opened> =
splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri())?.open(context) } splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri())?.open(context) }
private fun List<Location>.stringifyLocations(): String = private fun List<Location>.stringifyLocations(): String =
joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") }
private fun String.toLocations(): List<Location> = private fun String.toUnopenedLocations(): List<Location.Unopened> =
splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri()) } splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri()) }
private inline fun String.splitEscaped(selector: (Char) -> Boolean): List<String> { private inline fun String.splitEscaped(selector: (Char) -> Boolean): List<String> {
val split = mutableListOf<String>() val split = mutableListOf<String>()
@@ -18,98 +18,29 @@
package org.oxycblt.auxio.music.locations package org.oxycblt.auxio.music.locations
import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.oxycblt.auxio.databinding.ItemMusicLocationBinding import org.oxycblt.auxio.databinding.ItemMusicLocationBinding
import org.oxycblt.auxio.list.recycler.DialogRecyclerView
import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.inflater import org.oxycblt.auxio.util.inflater
import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Location
import timber.log.Timber as L
/** /**
* [RecyclerView.Adapter] that manages a list of [Location] excluded directory instances. * [LocationAdapter] that manages a list of [Location.Unopened] excluded directory instances.
* *
* @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to. * @param listener A [LocationAdapter.Listener] to bind interactions to.
* @author Alexander Capehart (OxygenCobalt) * @author Alexander Capehart (OxygenCobalt)
*/ */
class ExcludedLocationAdapter(private val listener: Listener) : RecyclerView.Adapter<ExcludedDirViewHolder>() { class ExcludedLocationAdapter(listener: LocationAdapter.Listener<Location.Unopened>) : LocationAdapter<Location.Unopened>(listener) {
private val _locations = mutableListOf<Location>() override fun createViewHolder(parent: ViewGroup): LocationViewHolder<Location.Unopened> =
/** ExcludedLocationViewHolder.from(parent)
* The current list of [Location]s, may not line up with [Location]s due to
* removals.
*/
val locations: List<Location> = _locations
override fun getItemCount() = locations.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ExcludedDirViewHolder.from(parent)
override fun onBindViewHolder(holder: ExcludedDirViewHolder, position: Int) =
holder.bind(locations[position], listener)
/**
* Add a [Location] to the end of the list.
*
* @param location The [Location] to add.
*/
fun add(location: Location) {
if (_locations.contains(location)) return
L.d("Adding $location")
_locations.add(location)
notifyItemInserted(_locations.lastIndex)
}
/**
* Add a list of [Location] instances to the end of the list.
*
* @param locations The [Location] instances to add.
*/
fun addAll(locations: List<Location>) {
L.d("Adding ${locations.size} locations")
val oldLastIndex = _locations.size
_locations.addAll(locations)
notifyItemRangeInserted(oldLastIndex, locations.size)
}
/**
* Remove a [Location] from the list.
*
* @param location The [Location] to remove. Must exist in the list.
*/
fun remove(location: Location) {
L.d("Removing $location")
val idx = _locations.indexOf(location)
_locations.removeAt(idx)
notifyItemRemoved(idx)
}
/** A Listener for [ExcludedLocationAdapter] interactions. */
interface Listener {
/** Called when the delete button on a directory item is clicked. */
fun onRemoveLocation(location: Location)
}
} }
/** /**
* A [RecyclerView.Recycler] that displays a [Location]. Use [from] to create an instance. * A [LocationViewHolder] that displays a [Location.Unopened]. Use [from] to create an instance.
* *
* @author Alexander Capehart (OxygenCobalt) * @author Alexander Capehart (OxygenCobalt)
*/ */
class ExcludedDirViewHolder private constructor(private val binding: ItemMusicLocationBinding) : class ExcludedLocationViewHolder private constructor(binding: ItemMusicLocationBinding) :
DialogRecyclerView.ViewHolder(binding.root) { LocationViewHolder<Location.Unopened>(binding) {
/**
* Bind new data to this instance.
*
* @param location The new [Location] to bind.
* @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to.
*/
fun bind(location: Location, listener: ExcludedLocationAdapter.Listener) {
binding.locationPath.text = location.path.resolve(binding.context)
binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) }
}
companion object { companion object {
/** /**
@@ -119,6 +50,6 @@ class ExcludedDirViewHolder private constructor(private val binding: ItemMusicLo
* @return A new instance. * @return A new instance.
*/ */
fun from(parent: ViewGroup) = fun from(parent: ViewGroup) =
ExcludedDirViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) ExcludedLocationViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false))
} }
} }
@@ -18,25 +18,14 @@
package org.oxycblt.auxio.music.locations package org.oxycblt.auxio.music.locations
import android.content.ActivityNotFoundException import android.content.Context
import android.net.Uri import android.net.Uri
import android.os.Bundle
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 dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.R import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding
import org.oxycblt.auxio.music.MusicSettings import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.showToast
import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Location
import timber.log.Timber as L import javax.inject.Inject
/** /**
* Dialog that manages the excluded locations setting. * Dialog that manages the excluded locations setting.
@@ -44,101 +33,31 @@ import timber.log.Timber as L
* @author Alexander Capehart (OxygenCobalt) * @author Alexander Capehart (OxygenCobalt)
*/ */
@AndroidEntryPoint @AndroidEntryPoint
class ExcludedLocationsDialog : class ExcludedLocationsDialog : LocationsDialog<Location.Unopened>() {
ViewBindingMaterialDialogFragment<DialogMusicLocationsBinding>(), override val locationAdapter = ExcludedLocationAdapter(this)
ExcludedLocationAdapter.Listener,
NewLocationFooterAdapter.Listener {
private val locationAdapter = ExcludedLocationAdapter(this)
private val locationFooterAdapter = NewLocationFooterAdapter(this)
private var openDocumentTreeLauncher: ActivityResultLauncher<Uri?>? = null
@Inject lateinit var musicSettings: MusicSettings
override fun onCreateBinding(inflater: LayoutInflater) = @Inject
DialogMusicLocationsBinding.inflate(inflater) override lateinit var musicSettings: MusicSettings
override fun onConfigDialog(builder: AlertDialog.Builder) { override fun getDialogTitle(): Int = R.string.set_excluded_locations
builder
.setTitle(R.string.set_excluded_locations) override fun getCurrentLocations(): List<Location.Unopened> = musicSettings.excludedLocations
.setNegativeButton(R.string.lbl_cancel, null)
.setPositiveButton(R.string.lbl_save) { _, _ -> override fun saveLocations(locations: List<Location.Unopened>) {
val newDirs = locationAdapter.locations musicSettings.excludedLocations = locations
musicSettings.excludedLocations = newDirs
}
} }
override fun onBindingCreated( override fun getPendingLocationsKey(): String = KEY_PENDING_EXCLUDED_LOCATIONS
binding: DialogMusicLocationsBinding,
savedInstanceState: Bundle?
) {
openDocumentTreeLauncher =
registerForActivityResult(
ActivityResultContracts.OpenDocumentTree(), ::addDocumentTreeUriToDirs)
binding.locationsRecycler.apply { override fun convertUriToLocation(uri: Uri): Location.Unopened? {
adapter = ConcatAdapter(locationAdapter, locationFooterAdapter) return Location.Unopened.from(requireContext(), uri)
itemAnimator = null
}
val locations =
savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull {
Location.from(requireContext(), it.toUri())
} ?: musicSettings.excludedLocations
locationAdapter.addAll(locations)
} }
override fun onSaveInstanceState(outState: Bundle) { override fun createLocationFromUri(context: Context, uri: Uri): Location.Unopened? {
super.onSaveInstanceState(outState) return Location.Unopened.from(context, uri)
outState.putStringArrayList(
KEY_PENDING_LOCATIONS, ArrayList(locationAdapter.locations.map { it.uri.toString() }))
}
override fun onDestroyBinding(binding: DialogMusicLocationsBinding) {
super.onDestroyBinding(binding)
openDocumentTreeLauncher = null
binding.locationsRecycler.adapter = null
}
override fun onRemoveLocation(location: Location) {
locationAdapter.remove(location)
}
override fun onNewLocation() {
L.d("Opening launcher")
val launcher =
requireNotNull(openDocumentTreeLauncher) { "Document tree launcher was not available" }
try {
launcher.launch(null)
} catch (e: ActivityNotFoundException) {
// User doesn't have a capable file manager.
requireContext().showToast(R.string.err_no_app)
}
}
/**
* Add a Document Tree [Uri] chosen by the user to the current [Location]s.
*
* @param uri The document tree [Uri] to add, chosen by the user. Will do nothing if the [Uri]
* is null or not valid.
*/
private fun addDocumentTreeUriToDirs(uri: Uri?) {
if (uri == null) {
// A null URI means that the user left the file picker without picking a directory
L.d("No URI given (user closed the dialog)")
return
}
val context = requireContext()
val location = Location.from(context, uri)
if (location != null) {
locationAdapter.add(location)
} else {
requireContext().showToast(R.string.err_bad_location)
}
} }
private companion object { private companion object {
const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" const val KEY_PENDING_EXCLUDED_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS"
} }
} }
@@ -1,6 +1,6 @@
/* /*
* Copyright (c) 2021 Auxio Project * Copyright (c) 2024 Auxio Project
* LocationAdapter.kt is part of Auxio. * BaseLocationAdapter.kt is part of Auxio.
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -18,107 +18,59 @@
package org.oxycblt.auxio.music.locations package org.oxycblt.auxio.music.locations
import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import org.oxycblt.auxio.databinding.ItemMusicLocationBinding import org.oxycblt.auxio.databinding.ItemMusicLocationBinding
import org.oxycblt.auxio.list.recycler.DialogRecyclerView import org.oxycblt.auxio.list.recycler.DialogRecyclerView
import org.oxycblt.auxio.util.context import org.oxycblt.auxio.util.context
import org.oxycblt.auxio.util.inflater import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.OpenedLocation
import timber.log.Timber as L import timber.log.Timber as L
/** abstract class LocationAdapter<T : Location>(private val listener: Listener<T>) : RecyclerView.Adapter<LocationViewHolder<T>>() {
* [RecyclerView.Adapter] that manages a list of [OpenedLocation] music directory instances. private val _locations = mutableListOf<T>()
* val locations: List<T> = _locations
* @param listener A [LocationAdapter.Listener] to bind interactions to.
* @author Alexander Capehart (OxygenCobalt)
*/
class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter<MusicDirViewHolder>() {
private val _locations = mutableListOf<OpenedLocation>()
/**
* The current list of [OpenedLocation]s, may not line up with [OpenedLocation]s due to
* removals.
*/
val locations: List<OpenedLocation> = _locations
override fun getItemCount() = locations.size override fun getItemCount() = locations.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
MusicDirViewHolder.from(parent) createViewHolder(parent)
override fun onBindViewHolder(holder: MusicDirViewHolder, position: Int) = override fun onBindViewHolder(holder: LocationViewHolder<T>, position: Int) =
holder.bind(locations[position], listener) holder.bind(locations[position], listener)
/** fun add(location: T) {
* Add a [OpenedLocation] to the end of the list.
*
* @param location The [OpenedLocation] to add.
*/
fun add(location: OpenedLocation) {
if (_locations.contains(location)) return if (_locations.contains(location)) return
L.d("Adding $location") L.d("Adding $location")
_locations.add(location) _locations.add(location)
notifyItemInserted(_locations.lastIndex) notifyItemInserted(_locations.lastIndex)
} }
/** fun addAll(locations: List<T>) {
* Add a list of [OpenedLocation] instances to the end of the list.
*
* @param locations The [OpenedLocation] instances to add.
*/
fun addAll(locations: List<OpenedLocation>) {
L.d("Adding ${locations.size} locations") L.d("Adding ${locations.size} locations")
val oldLastIndex = locations.lastIndex val oldSize = _locations.size
_locations.addAll(locations) _locations.addAll(locations)
notifyItemRangeInserted(oldLastIndex, locations.size) notifyItemRangeInserted(oldSize, locations.size)
} }
/** fun remove(location: T) {
* Remove a [OpenedLocation] from the list.
*
* @param location The [OpenedLocation] to remove. Must exist in the list.
*/
fun remove(location: OpenedLocation) {
L.d("Removing $location") L.d("Removing $location")
val idx = _locations.indexOf(location) val idx = _locations.indexOf(location)
_locations.removeAt(idx) _locations.removeAt(idx)
notifyItemRemoved(idx) notifyItemRemoved(idx)
} }
/** A Listener for [LocationAdapter] interactions. */ protected abstract fun createViewHolder(parent: ViewGroup): LocationViewHolder<T>
interface Listener {
/** Called when the delete button on a directory item is clicked. */ interface Listener<T : Location> {
fun onRemoveLocation(location: OpenedLocation) fun onRemoveLocation(location: T)
} }
} }
/** abstract class LocationViewHolder<T : Location>(protected val binding: ItemMusicLocationBinding) :
* A [RecyclerView.Recycler] that displays a [OpenedLocation]. Use [from] to create an instance.
*
* @author Alexander Capehart (OxygenCobalt)
*/
class MusicDirViewHolder private constructor(private val binding: ItemMusicLocationBinding) :
DialogRecyclerView.ViewHolder(binding.root) { DialogRecyclerView.ViewHolder(binding.root) {
/**
* Bind new data to this instance. fun bind(location: T, listener: LocationAdapter.Listener<T>) {
*
* @param location The new [OpenedLocation] to bind.
* @param listener A [LocationAdapter.Listener] to bind interactions to.
*/
fun bind(location: OpenedLocation, listener: LocationAdapter.Listener) {
binding.locationPath.text = location.path.resolve(binding.context) binding.locationPath.text = location.path.resolve(binding.context)
binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } 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 from(parent: View) =
MusicDirViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater))
}
} }
@@ -1,6 +1,6 @@
/* /*
* Copyright (c) 2021 Auxio Project * Copyright (c) 2024 Auxio Project
* MusicSourcesDialog.kt is part of Auxio. * BaseLocationsDialog.kt is part of Auxio.
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@@ -27,43 +27,33 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.recyclerview.widget.ConcatAdapter import androidx.recyclerview.widget.ConcatAdapter
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
import org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.R import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding
import org.oxycblt.auxio.music.MusicSettings import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
import org.oxycblt.auxio.util.showToast import org.oxycblt.auxio.util.showToast
import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.OpenedLocation
import timber.log.Timber as L import timber.log.Timber as L
/** abstract class LocationsDialog<T : Location> :
* Dialog that manages the music locations setting.
*
* @author Alexander Capehart (OxygenCobalt)
*/
@AndroidEntryPoint
class MusicSourcesDialog :
ViewBindingMaterialDialogFragment<DialogMusicLocationsBinding>(), ViewBindingMaterialDialogFragment<DialogMusicLocationsBinding>(),
LocationAdapter.Listener, LocationAdapter.Listener<T>,
NewLocationFooterAdapter.Listener { NewLocationFooterAdapter.Listener {
private val locationAdapter = LocationAdapter(this) protected abstract val locationAdapter: LocationAdapter<T>
private val locationFooterAdapter = NewLocationFooterAdapter(this) private val locationFooterAdapter = NewLocationFooterAdapter(this)
private var openDocumentTreeLauncher: ActivityResultLauncher<Uri?>? = null private var openDocumentTreeLauncher: ActivityResultLauncher<Uri?>? = null
@Inject lateinit var musicSettings: MusicSettings abstract val musicSettings: MusicSettings
override fun onCreateBinding(inflater: LayoutInflater) = override fun onCreateBinding(inflater: LayoutInflater) =
DialogMusicLocationsBinding.inflate(inflater) DialogMusicLocationsBinding.inflate(inflater)
override fun onConfigDialog(builder: AlertDialog.Builder) { override fun onConfigDialog(builder: AlertDialog.Builder) {
builder builder
.setTitle(R.string.set_locations) .setTitle(getDialogTitle())
.setNegativeButton(R.string.lbl_cancel, null) .setNegativeButton(R.string.lbl_cancel, null)
.setPositiveButton(R.string.lbl_save) { _, _ -> .setPositiveButton(R.string.lbl_save) { _, _ ->
val newDirs = locationAdapter.locations val newDirs = locationAdapter.locations
musicSettings.musicLocations = newDirs saveLocations(newDirs)
} }
} }
@@ -81,10 +71,9 @@ class MusicSourcesDialog :
} }
val locations = val locations =
savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull { savedInstanceState?.getStringArrayList(getPendingLocationsKey())?.mapNotNull {
val context = requireContext() convertUriToLocation(it.toUri())
Location.from(context, it.toUri())?.open(context) } ?: getCurrentLocations()
} ?: musicSettings.musicLocations
locationAdapter.addAll(locations) locationAdapter.addAll(locations)
} }
@@ -92,7 +81,7 @@ class MusicSourcesDialog :
override fun onSaveInstanceState(outState: Bundle) { override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState) super.onSaveInstanceState(outState)
outState.putStringArrayList( outState.putStringArrayList(
KEY_PENDING_LOCATIONS, ArrayList(locationAdapter.locations.map { it.uri.toString() })) getPendingLocationsKey(), ArrayList(locationAdapter.locations.map { it.uri.toString() }))
} }
override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { override fun onDestroyBinding(binding: DialogMusicLocationsBinding) {
@@ -101,10 +90,6 @@ class MusicSourcesDialog :
binding.locationsRecycler.adapter = null binding.locationsRecycler.adapter = null
} }
override fun onRemoveLocation(location: OpenedLocation) {
locationAdapter.remove(location)
}
override fun onNewLocation() { override fun onNewLocation() {
L.d("Opening launcher") L.d("Opening launcher")
val launcher = val launcher =
@@ -113,25 +98,17 @@ class MusicSourcesDialog :
try { try {
launcher.launch(null) launcher.launch(null)
} catch (e: ActivityNotFoundException) { } catch (e: ActivityNotFoundException) {
// User doesn't have a capable file manager.
requireContext().showToast(R.string.err_no_app) requireContext().showToast(R.string.err_no_app)
} }
} }
/**
* Add a Document Tree [Uri] chosen by the user to the current [OpenedLocation]s.
*
* @param uri The document tree [Uri] to add, chosen by the user. Will do nothing if the [Uri]
* is null or not valid.
*/
private fun addDocumentTreeUriToDirs(uri: Uri?) { private fun addDocumentTreeUriToDirs(uri: Uri?) {
if (uri == null) { if (uri == null) {
// A null URI means that the user left the file picker without picking a locationectory
L.d("No URI given (user closed the dialog)") L.d("No URI given (user closed the dialog)")
return return
} }
val context = requireContext() val context = requireContext()
val location = Location.from(context, uri)?.open(context) val location = createLocationFromUri(context, uri)
if (location != null) { if (location != null) {
locationAdapter.add(location) locationAdapter.add(location)
@@ -140,7 +117,14 @@ class MusicSourcesDialog :
} }
} }
private companion object { override fun onRemoveLocation(location: T) {
const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_LOCATIONS" locationAdapter.remove(location)
} }
protected abstract fun getDialogTitle(): Int
protected abstract fun getCurrentLocations(): List<T>
protected abstract fun saveLocations(locations: List<T>)
protected abstract fun getPendingLocationsKey(): String
protected abstract fun convertUriToLocation(uri: Uri): T?
protected abstract fun createLocationFromUri(context: android.content.Context, uri: Uri): T?
} }
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2021 Auxio Project
* LocationAdapter.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))
}
}
@@ -0,0 +1,64 @@
/*
* Copyright (c) 2021 Auxio Project
* MusicSourcesDialog.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 org.oxycblt.auxio.BuildConfig
import org.oxycblt.auxio.R
import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.musikr.fs.Location
import javax.inject.Inject
/**
* 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"
}
}
@@ -36,7 +36,7 @@ import org.oxycblt.auxio.music.shim.UpdateTrackerFactory
import org.oxycblt.auxio.playback.state.PlaybackStateManager import org.oxycblt.auxio.playback.state.PlaybackStateManager
import org.oxycblt.auxio.util.getSystemServiceCompat import org.oxycblt.auxio.util.getSystemServiceCompat
import org.oxycblt.musikr.MusicParent import org.oxycblt.musikr.MusicParent
import org.oxycblt.musikr.fs.OpenedLocation import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.track.UpdateTracker import org.oxycblt.musikr.track.UpdateTracker
import timber.log.Timber as L import timber.log.Timber as L
@@ -168,7 +168,7 @@ private constructor(
} }
} }
override fun onUpdate(location: OpenedLocation) { override fun onUpdate(location: Location.Opened) {
if (musicSettings.shouldBeObserving) { if (musicSettings.shouldBeObserving) {
musicRepository.requestIndex(true) musicRepository.requestIndex(true)
} }
+1 -1
View File
@@ -570,7 +570,7 @@
<dialog <dialog
android:id="@+id/music_locations_dialog" android:id="@+id/music_locations_dialog"
android:name="org.oxycblt.auxio.music.locations.MusicSourcesDialog" android:name="org.oxycblt.auxio.music.locations.MusicLocationsDialog"
android:label="music_locations_dialog" android:label="music_locations_dialog"
tools:layout="@layout/dialog_music_locations" /> tools:layout="@layout/dialog_music_locations" />
</navigation> </navigation>
+1 -1
View File
@@ -94,7 +94,7 @@
tools:layout="@layout/dialog_pre_amp" /> tools:layout="@layout/dialog_pre_amp" />
<dialog <dialog
android:id="@+id/music_locations_dialog" android:id="@+id/music_locations_dialog"
android:name="org.oxycblt.auxio.music.locations.MusicSourcesDialog" android:name="org.oxycblt.auxio.music.locations.MusicLocationsDialog"
android:label="music_locations_dialog" android:label="music_locations_dialog"
tools:layout="@layout/dialog_music_locations" /> tools:layout="@layout/dialog_music_locations" />
<dialog <dialog
+1 -1
View File
@@ -38,7 +38,7 @@ graph LR
## Module Structure ## Module Structure
### 1. File System (`fs` package) ### 1. File System (`fs` package)
- **OpenedLocation** - Represents a location to search for music - **Location.Opened** - Represents a location to search for music
- **DeviceFS** - Provides access to device storage - **DeviceFS** - Provides access to device storage
- **FileTreeCache** - Caches filesystem structure for faster indexing - **FileTreeCache** - Caches filesystem structure for faster indexing
@@ -22,13 +22,13 @@ import org.oxycblt.musikr.cache.MutableCache
import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.covers.MutableCovers import org.oxycblt.musikr.covers.MutableCovers
import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.OpenedLocation import org.oxycblt.musikr.fs.Location.Opened
import org.oxycblt.musikr.fs.device.FileTreeCache import org.oxycblt.musikr.fs.device.FileTreeCache
import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.tag.interpret.Naming import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.Separators import org.oxycblt.musikr.tag.interpret.Separators
data class Query(val source: List<OpenedLocation>, val exclude: List<Location>) data class Query(val source: List<Location.Opened>, val exclude: List<Location>)
/** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */ /** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */
data class Storage( data class Storage(
@@ -25,52 +25,52 @@ import android.provider.DocumentsContract
import org.oxycblt.musikr.fs.device.contentResolverSafe import org.oxycblt.musikr.fs.device.contentResolverSafe
import org.oxycblt.musikr.fs.path.DocumentPathFactory import org.oxycblt.musikr.fs.path.DocumentPathFactory
class Location private constructor(val uri: Uri, val path: Path) { sealed class Location(val uri: Uri, val path: Path) {
override fun equals(other: Any?) = other is Location && uri == other.uri override fun equals(other: Any?) = other is Location && uri == other.uri
override fun hashCode() = 31 * uri.hashCode() override fun hashCode() = 31 * uri.hashCode()
override fun toString(): String = uri.toString() override fun toString(): String = uri.toString()
fun open(context: Context): OpenedLocation? { class Unopened private constructor(uri: Uri, path: Path) : Location(uri, path) {
if (isUnopened(context, uri)) { fun open(context: Context): Opened? {
try {
context.contentResolverSafe.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
} catch (e: Exception) {
// Not fully sure what happens if I'm disallowed to take the permission,
// check for both circumstances (error or no-op)
return null
}
if (isUnopened(context, uri)) { if (isUnopened(context, uri)) {
return null try {
context.contentResolverSafe.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
} catch (e: Exception) {
// Not fully sure what happens if I'm disallowed to take the permission,
// check for both circumstances (error or no-op)
return null
}
if (isUnopened(context, uri)) {
return null
}
}
return Opened(uri, path)
}
private fun isUnopened(context: Context, uri: Uri) =
context.contentResolverSafe.persistedUriPermissions.none {
it.uri == uri && it.isReadPermission && it.isWritePermission
}
companion object {
fun from(context: Context, uri: Uri): Unopened? {
if (!DocumentsContract.isTreeUri(uri)) return null
val documentPathFactory = DocumentPathFactory.from(context)
val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null
return Unopened(uri, path)
} }
} }
return OpenedLocation(uri, path)
} }
private fun isUnopened(context: Context, uri: Uri) = class Opened internal constructor(uri: Uri, path: Path) : Location(uri, path) {
context.contentResolverSafe.persistedUriPermissions.none { override fun equals(other: Any?) =
it.uri == uri && it.isReadPermission && it.isWritePermission other is Opened && uri == other.uri && path == other.path
}
companion object { override fun hashCode() = 31 * uri.hashCode() + path.hashCode()
fun from(context: Context, uri: Uri): Location? {
if (!DocumentsContract.isTreeUri(uri)) return null
val documentPathFactory = DocumentPathFactory.from(context)
val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null
return Location(uri, path)
}
} }
} }
class OpenedLocation internal constructor(val uri: Uri, val path: Path) {
override fun equals(other: Any?) =
other is OpenedLocation && uri == other.uri && path == other.path
override fun hashCode() = 31 * uri.hashCode() + path.hashCode()
override fun toString(): String = uri.toString()
}
@@ -8,7 +8,7 @@ The filesystem package provides abstraction layers for accessing music files on
### Core Types ### Core Types
**OpenedLocation** (`OpenedLocation.kt`) **Location.Opened** (`Location.Opened.kt`)
- Represents a location to search for music - Represents a location to search for music
- Can be a device storage location or content URI - Can be a device storage location or content URI
@@ -50,7 +50,7 @@ The filesystem package provides abstraction layers for accessing music files on
## Usage Flow ## Usage Flow
1. User provides `OpenedLocation`s to scan 1. User provides `Location.Opened`s to scan
2. `DeviceFS` traverses these locations 2. `DeviceFS` traverses these locations
3. `FileTreeCache` optimizes subsequent scans 3. `FileTreeCache` optimizes subsequent scans
4. Discovered files are passed to the pipeline for processing 4. Discovered files are passed to the pipeline for processing
@@ -44,7 +44,7 @@ import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.flow.transform import kotlinx.coroutines.flow.transform
import org.oxycblt.musikr.Query import org.oxycblt.musikr.Query
import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.OpenedLocation import org.oxycblt.musikr.fs.Location.Opened
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
internal interface DeviceFS { internal interface DeviceFS {
@@ -68,7 +68,7 @@ private class DeviceFSImpl(
} }
private suspend fun queryRoot( private suspend fun queryRoot(
location: OpenedLocation, location: Location.Opened,
fileTree: FileTree, fileTree: FileTree,
exclude: List<Location> exclude: List<Location>
): DeviceDirectory? { ): DeviceDirectory? {
@@ -49,7 +49,7 @@ The `PipelineItem.kt` defines the data types that flow through the pipeline:
## Pipeline Flow ## Pipeline Flow
``` ```
OpenedLocation → ExploreStep → ExtractStep → EvaluateStep → Library Location.Opened → ExploreStep → ExtractStep → EvaluateStep → Library
``` ```
Data flows through the pipeline using Kotlin's Flow API, with extensive use of parallel processing and buffering to optimize performance. Data flows through the pipeline using Kotlin's Flow API, with extensive use of parallel processing and buffering to optimize performance.
@@ -22,11 +22,11 @@ import android.content.Context
import android.database.ContentObserver import android.database.ContentObserver
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import org.oxycblt.musikr.fs.OpenedLocation import org.oxycblt.musikr.fs.Location
internal class LocationObserver( internal class LocationObserver(
private val context: Context, private val context: Context,
private val location: OpenedLocation, private val location: Location.Opened,
private val listener: UpdateTracker.Callback private val listener: UpdateTracker.Callback
) : ContentObserver(Handler(Looper.getMainLooper())), Runnable { ) : ContentObserver(Handler(Looper.getMainLooper())), Runnable {
private val handler = Handler(Looper.getMainLooper()) private val handler = Handler(Looper.getMainLooper())
@@ -19,15 +19,15 @@
package org.oxycblt.musikr.track package org.oxycblt.musikr.track
import android.content.Context import android.content.Context
import org.oxycblt.musikr.fs.OpenedLocation import org.oxycblt.musikr.fs.Location
interface UpdateTracker { interface UpdateTracker {
fun track(locations: List<OpenedLocation>) fun track(locations: List<Location.Opened>)
fun release() fun release()
interface Callback { interface Callback {
fun onUpdate(location: OpenedLocation) fun onUpdate(location: Location.Opened)
} }
companion object { companion object {
@@ -42,7 +42,7 @@ private class UpdateTrackerImpl(
) : UpdateTracker { ) : UpdateTracker {
private val observers = mutableListOf<LocationObserver>() private val observers = mutableListOf<LocationObserver>()
override fun track(locations: List<OpenedLocation>) { override fun track(locations: List<Location.Opened>) {
release() release()
observers.addAll(locations.map { LocationObserver(context, it, callback) }) observers.addAll(locations.map { LocationObserver(context, it, callback) })
} }