Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
xenonnn4w committed Jul 27, 2024
1 parent 196a6ee commit f662049
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 26 deletions.
23 changes: 14 additions & 9 deletions AnkiDroid/src/main/java/com/ichi2/widget/DeckPickerWidget.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@ import android.content.Context
import android.content.Intent
import android.os.SystemClock
import android.widget.RemoteViews
import com.ichi2.anki.AnkiDroidApp.Companion.applicationScope
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.R
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import timber.log.Timber

Expand All @@ -46,7 +45,7 @@ class DeckPickerWidget : AppWidgetProvider() {
const val ACTION_APPWIDGET_UPDATE = AppWidgetManager.ACTION_APPWIDGET_UPDATE
const val ACTION_UPDATE_WIDGET = "com.ichi2.widget.ACTION_UPDATE_WIDGET"

@OptIn(DelicateCoroutinesApi::class)
// Updates the widget with the deck data
fun updateWidget(
context: Context,
appWidgetManager: AppWidgetManager,
Expand All @@ -56,7 +55,7 @@ class DeckPickerWidget : AppWidgetProvider() {
val remoteViews = RemoteViews(context.packageName, R.layout.widget_deck_picker_large)

// Launch a coroutine to fetch deck stats
GlobalScope.launch(Dispatchers.Main) {
applicationScope.launch(Dispatchers.Main) {
val deckData = getDeckNameAndStats(deckIds.toList())

// Clear previous deck views
Expand All @@ -77,6 +76,7 @@ class DeckPickerWidget : AppWidgetProvider() {
}
}

// Retrieves the selected deck IDs from shared preferences for the widget
private fun getSelectedDeckIdsFromPreferencesDeckPickerWidget(context: Context, appWidgetId: Int): LongArray {
val sharedPreferences = context.getSharedPreferences("DeckPickerWidgetPrefs", Context.MODE_PRIVATE)
val selectedDecksString = sharedPreferences.getString("deck_picker_widget_selected_decks_$appWidgetId", "")
Expand All @@ -87,6 +87,7 @@ class DeckPickerWidget : AppWidgetProvider() {
}
}

// Sets a recurring alarm to update the widget every minute
private fun setRecurringAlarmDeckPickerWidget(context: Context, appWidgetId: Int) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, DeckPickerWidget::class.java).apply {
Expand All @@ -109,6 +110,7 @@ class DeckPickerWidget : AppWidgetProvider() {
}
}

// Cancels the recurring alarm for the widget
private fun cancelRecurringAlarmDeckPickerWidget(context: Context, appWidgetId: Int) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, DeckPickerWidget::class.java).apply {
Expand Down Expand Up @@ -167,6 +169,7 @@ class DeckPickerWidget : AppWidgetProvider() {
}
}

// Triggers the cancel recurring alarm when the widget is deleted
override fun onDeleted(context: Context?, appWidgetIds: IntArray?) {
super.onDeleted(context, appWidgetIds)
appWidgetIds?.forEach { widgetId ->
Expand All @@ -175,11 +178,13 @@ class DeckPickerWidget : AppWidgetProvider() {
}
}

/** This function takes a list of deck IDs and returns a list of data objects containing
*the deck name and statistics (review, learn, and new counts) for each specified deck. It fetches the
* entire deck tree, filters it to include only the specified deck IDs, and maps the relevant data to
* the output list, ensuring the order matches the input list. Currently used in DeckPickerWidget and CardAnalysisExtraWidget
*/
/**
* This function takes a list of deck IDs and returns a list of data objects containing
* the deck name and statistics (review, learn, and new counts) for each specified deck.
* It fetches the entire deck tree, filters it to include only the specified deck IDs,
* and maps the relevant data to the output list, ensuring the order matches the input list.
* Currently used in DeckPickerWidget and CardAnalysisExtraWidget.
*/
suspend fun getDeckNameAndStats(deckIds: List<Long>): List<DeckPickerWidgetData> {
val result = mutableListOf<DeckPickerWidgetData>()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,14 @@ class DeckPickerWidgetAdapter(
val removeButton: ImageButton = itemView.findViewById(R.id.action_button_remove_deck)
}

// Creates and inflates the view for each item in the RecyclerView
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeckViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.widget_item_deck_config, parent, false)
return DeckViewHolder(view)
}

// Binds data to each view holder
override fun onBindViewHolder(holder: DeckViewHolder, position: Int) {
val deck = decks[position]
holder.deckNameTextView.text = deck.displayName
Expand All @@ -48,24 +50,29 @@ class DeckPickerWidgetAdapter(
}
}

// Returns the total number of items in the RecyclerView
override fun getItemCount(): Int = decks.size

// Adds a new deck to the list and notifies the adapter
fun addDeck(deck: SelectableDeck) {
decks.add(deck)
notifyItemInserted(decks.size - 1)
}

// Removes a deck from the list and notifies the adapter
private fun removeDeck(position: Int) {
decks.removeAt(position)
notifyItemRemoved(position)
}

// Moves a deck within the list and notifies the adapter
fun moveDeck(fromPosition: Int, toPosition: Int) {
val deck = decks.removeAt(fromPosition)
decks.add(toPosition, deck)
notifyItemMoved(fromPosition, toPosition)
}

// Sets the entire list of decks and notifies the adapter
fun setDecks(newDecks: List<SelectableDeck>) {
decks.clear()
decks.addAll(newDecks)
Expand Down
17 changes: 13 additions & 4 deletions AnkiDroid/src/main/java/com/ichi2/widget/DeckPickerWidgetConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ class DeckPickerWidgetConfig : FragmentActivity(), DeckSelectionListener {

private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
private lateinit var deckAdapter: DeckPickerWidgetAdapter
private lateinit var deckPreferences: DeckPreferences
private lateinit var DeckPickerWidgetPreferences: WidgetPreferences

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setResult(RESULT_CANCELED)
setContentView(R.layout.widget_deck_picker_config)

deckPreferences = DeckPreferences(this)
DeckPickerWidgetPreferences = WidgetPreferences(this)

val intent = intent
val extras = intent.extras
Expand Down Expand Up @@ -108,19 +108,22 @@ class DeckPickerWidgetConfig : FragmentActivity(), DeckSelectionListener {
unregisterReceiver(widgetRemovedReceiver)
}

// Shows the deck selection dialog
private fun showDeckSelectionDialog() {
lifecycleScope.launch {
val decks = fetchDecks()
displayDeckSelectionDialog(decks)
}
}

// Fetches the list of decks
private suspend fun fetchDecks(): List<SelectableDeck> {
return withContext(Dispatchers.IO) {
SelectableDeck.fromCollection(includeFiltered = false)
}
}

// Displays the deck selection dialog
private fun displayDeckSelectionDialog(decks: List<SelectableDeck>) {
val dialog = DeckSelectionDialog.newInstance(
title = getString(R.string.select_deck_title),
Expand All @@ -131,6 +134,7 @@ class DeckPickerWidgetConfig : FragmentActivity(), DeckSelectionListener {
dialog.show(supportFragmentManager, "DeckSelectionDialog")
}

// Handles the event when a deck is selected
override fun onDeckSelected(deck: SelectableDeck?) {
if (deck != null) {
if (deckAdapter.itemCount >= 5) {
Expand All @@ -142,6 +146,7 @@ class DeckPickerWidgetConfig : FragmentActivity(), DeckSelectionListener {
}
}

// Updates the visibility of UI elements based on the number of selected decks
private fun updateViewVisibility() {
val noDecksPlaceholder = findViewById<View>(R.id.no_decks_placeholder)
val widgetConfigContainer = findViewById<View>(R.id.widgetConfigContainer)
Expand All @@ -155,6 +160,7 @@ class DeckPickerWidgetConfig : FragmentActivity(), DeckSelectionListener {
}
}

// ItemTouchHelper callback for handling drag-and-drop reordering
private val itemTouchHelperCallback = object : ItemTouchHelper.SimpleCallback(
ItemTouchHelper.UP or ItemTouchHelper.DOWN,
0
Expand Down Expand Up @@ -207,8 +213,9 @@ class DeckPickerWidgetConfig : FragmentActivity(), DeckSelectionListener {
sendBroadcast(updateIntent)
}

// Loads the selected decks from SharedPreferences
private fun loadSelectedDecksFromPreferencesDeckPickerWidget() {
val selectedDecks = deckPreferences.loadSelectedDecks(appWidgetId)
val selectedDecks = DeckPickerWidgetPreferences.loadDeckPickerSelectedDecks(appWidgetId)
if (selectedDecks.isNotEmpty()) {
lifecycleScope.launch {
val decks = fetchDecks()
Expand All @@ -219,12 +226,14 @@ class DeckPickerWidgetConfig : FragmentActivity(), DeckSelectionListener {
}
}

// Gets the selected deck IDs
private fun getSelectedDeckIdsDeckPickerWidget(): List<Long> {
return deckAdapter.decks.map { it.deckId }
}

// Deletes widget data for a specific widget
private fun deleteWidgetDataDeckPickerWidget(appWidgetId: Int) {
deckPreferences.deleteWidgetData(appWidgetId)
DeckPickerWidgetPreferences.deleteDeckPickerWidgetData(appWidgetId)
}

// BroadcastReceiver to handle widget removal
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,24 @@ package com.ichi2.widget
import android.content.Context
import androidx.core.content.edit

class DeckPreferences(context: Context) {
class WidgetPreferences(context: Context) {

private val sharedPreferences = context.getSharedPreferences("DeckPickerWidgetPrefs", Context.MODE_PRIVATE)
private val deckPickerSharedPreferences = context.getSharedPreferences("DeckPickerWidgetPrefs", Context.MODE_PRIVATE)

fun saveSelectedDecks(appWidgetId: Int, selectedDecks: List<Long>) {
sharedPreferences.edit {
putString("selected_decks_$appWidgetId", selectedDecks.joinToString(","))
}
}

fun loadSelectedDecks(appWidgetId: Int): List<Long> {
val selectedDecksString = sharedPreferences.getString("selected_decks_$appWidgetId", "")
// Loads the selected deck IDs for a given widget from shared preferences for DeckPickerWidget
fun loadDeckPickerSelectedDecks(appWidgetId: Int): List<Long> {
val selectedDecksString = deckPickerSharedPreferences.getString("deck_picker_widget_selected_decks_$appWidgetId", "")
return if (!selectedDecksString.isNullOrEmpty()) {
selectedDecksString.split(",").map { it.toLong() }
} else {
emptyList()
}
}

fun deleteWidgetData(appWidgetId: Int) {
sharedPreferences.edit {
remove("selected_decks_$appWidgetId")
// Deletes the stored data for a specific widget for DeckPickerWidget
fun deleteDeckPickerWidgetData(appWidgetId: Int) {
deckPickerSharedPreferences.edit {
remove("deck_picker_widget_selected_decks_$appWidgetId")
}
}
}

0 comments on commit f662049

Please sign in to comment.