Skip to content

Commit

Permalink
Remember all torrent adding parameters, not just download directory
Browse files Browse the repository at this point in the history
  • Loading branch information
equeim committed Dec 2, 2023
1 parent 1112c90 commit f7961cf
Show file tree
Hide file tree
Showing 11 changed files with 138 additions and 52 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

### Changed
- RPC client is rewritten to use OkHttp library instead of Qt
- All torrent adding parameters are now remembered together with download directory

## [2.9.1] - 2023-03-26
### Fixed
Expand Down
127 changes: 93 additions & 34 deletions app/src/main/kotlin/org/equeim/tremotesf/ui/Settings.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.equeim.tremotesf.R
import org.equeim.tremotesf.TremotesfApplication
import org.equeim.tremotesf.torrentfile.rpc.requests.torrentproperties.TorrentLimits
import org.equeim.tremotesf.ui.Settings.Property
import org.equeim.tremotesf.ui.torrentslistfragment.TorrentsListFragmentViewModel
import timber.log.Timber
Expand Down Expand Up @@ -106,31 +107,58 @@ object Settings {
putString(colorTheme.key, newValue)
}
}
context.getString(R.string.deprecated_prefs_remember_download_directory_key)
.let { deprecatedRememberDownloadDirectoryKey ->
if (preferences.contains(deprecatedRememberDownloadDirectoryKey)) {
preferences.edit {
putBoolean(
rememberAddTorrentParameters.key,
preferences.getBoolean(deprecatedRememberDownloadDirectoryKey, false)
)
remove(deprecatedRememberDownloadDirectoryKey)
}
}
}
migrated = true
}
}
}

private class EnumPrefsMapper<T : Enum<T>>(
private val enumClass: Class<T>,
@StringRes private val keyResId: Int,
@StringRes private val defaultValueResId: Int,
val enumToPrefsValue: (T) -> String,
) {
private val enumValues = requireNotNull(enumClass.enumConstants)

fun prefsValueToEnum(prefsValue: String): T {
enumValues.find { enumToPrefsValue(it) == prefsValue }?.let { return it }
val key = context.getString(keyResId)
Timber.e("Unknown prefs value $prefsValue for key $key and enum $enumClass")
val defaultPrefsValue = context.getString(defaultValueResId)
return enumValues.find { enumToPrefsValue(it) == defaultPrefsValue }
?: throw IllegalStateException("Did not find value of enum $enumClass for default prefs value $defaultPrefsValue and key $key")
}
}

private inline fun <reified T : Enum<T>> EnumPrefsMapper(
@StringRes keyResId: Int,
@StringRes defaultValueResId: Int,
noinline enumToPrefsValue: (T) -> String,
): EnumPrefsMapper<T> =
EnumPrefsMapper(T::class.java, keyResId, defaultValueResId, enumToPrefsValue)

private interface MappedPrefsEnum {
val prefsValue: String

companion object {
inline fun <reified T> fromPrefsValueProvider(
@StringRes keyResId: Int,
@StringRes defaultValueResId: Int,
): (String) -> T where T : MappedPrefsEnum, T : Enum<T> {
val values = enumValues<T>()
return { prefsValue ->
values.find { it.prefsValue == prefsValue } ?: run {
Timber.e("Unknown value $prefsValue for key ${context.getString(keyResId)}")
val defaultPrefsValue = context.getString(defaultValueResId)
values.single { it.prefsValue == defaultPrefsValue }
}
}
}
}
}

private inline fun <reified T> EnumPrefsMapper(
@StringRes keyResId: Int,
@StringRes defaultValueResId: Int,
): EnumPrefsMapper<T> where T : MappedPrefsEnum, T : Enum<T> =
EnumPrefsMapper(T::class.java, keyResId, defaultValueResId, MappedPrefsEnum::prefsValue)

enum class ColorTheme(
@StringRes prefsValueResId: Int,
@StyleRes val activityThemeResId: Int = 0,
Expand All @@ -140,20 +168,15 @@ object Settings {
Teal(R.string.prefs_color_theme_value_teal, R.style.AppTheme_Teal);

override val prefsValue = context.getString(prefsValueResId)

companion object {
val fromPrefsValue = MappedPrefsEnum.fromPrefsValueProvider<ColorTheme>(
R.string.prefs_color_theme_key,
R.string.prefs_color_theme_default_value
)
}
}

private val colorThemeMapper =
EnumPrefsMapper<ColorTheme>(R.string.prefs_color_theme_key, R.string.prefs_color_theme_default_value)
val colorTheme: MutableProperty<ColorTheme> = mutableProperty<String>(
R.string.prefs_color_theme_key,
R.string.prefs_color_theme_default_value
).map(
transformGetter = ColorTheme.fromPrefsValue,
transformGetter = colorThemeMapper::prefsValueToEnum,
transformSetter = { it.prefsValue }
)

Expand All @@ -171,20 +194,17 @@ object Settings {
Off(R.string.prefs_dark_theme_mode_value_off, AppCompatDelegate.MODE_NIGHT_NO);

override val prefsValue = context.getString(prefsValueResId)

companion object {
val fromPrefsValue = MappedPrefsEnum.fromPrefsValueProvider<DarkThemeMode>(
R.string.prefs_dark_theme_mode_key,
R.string.prefs_dark_theme_mode_default_value
)
}
}

private val darkThemeModeMapper = EnumPrefsMapper<DarkThemeMode>(
R.string.prefs_dark_theme_mode_key,
R.string.prefs_dark_theme_mode_default_value
)
val darkThemeMode: Property<DarkThemeMode> =
property<String>(
R.string.prefs_dark_theme_mode_key,
R.string.prefs_dark_theme_mode_default_value
).map(DarkThemeMode.fromPrefsValue)
).map(darkThemeModeMapper::prefsValueToEnum)

val torrentCompactView: Property<Boolean> = property(
R.string.prefs_torrent_compact_view_key,
Expand Down Expand Up @@ -247,8 +267,47 @@ object Settings {
val fillTorrentLinkFromKeyboard: Property<Boolean> =
property(R.string.prefs_link_from_clipboard_key, R.bool.prefs_link_from_clipboard_default_value)

val rememberDownloadDirectory: Property<Boolean> =
property(R.string.prefs_remember_download_directory_key, R.bool.prefs_remember_download_directory_default_value)
val rememberAddTorrentParameters: Property<Boolean> =
property(
R.string.prefs_remember_add_torrent_parameters_key,
R.bool.prefs_remember_add_torrent_parameters_default_value
)

enum class StartTorrentAfterAdding(override val prefsValue: String) : MappedPrefsEnum {
Start("start"),
DontStart("dont_start"),
Unknown("unknown")
}

private val startTorrentAfterAddingMapper = EnumPrefsMapper<StartTorrentAfterAdding>(
R.string.prefs_last_add_torrent_start_after_adding_key,
R.string.prefs_last_add_torrent_start_after_adding_default_value
)
val lastAddTorrentStartAfterAdding: MutableProperty<StartTorrentAfterAdding> = mutableProperty<String>(
R.string.prefs_last_add_torrent_start_after_adding_key,
R.string.prefs_last_add_torrent_start_after_adding_default_value
).map(
transformGetter = startTorrentAfterAddingMapper::prefsValueToEnum,
transformSetter = startTorrentAfterAddingMapper.enumToPrefsValue
)

private val bandwidthPriorityMapper = EnumPrefsMapper<TorrentLimits.BandwidthPriority>(
R.string.prefs_last_add_torrent_priority_key,
R.string.prefs_last_add_torrent_priority_default_value
) {
when (it) {
TorrentLimits.BandwidthPriority.Low -> "low"
TorrentLimits.BandwidthPriority.Normal -> "normal"
TorrentLimits.BandwidthPriority.High -> "high"
}
}
val lastAddTorrentPriority: MutableProperty<TorrentLimits.BandwidthPriority> = mutableProperty<String>(
R.string.prefs_last_add_torrent_priority_key,
R.string.prefs_last_add_torrent_priority_default_value
).map(
transformGetter = bandwidthPriorityMapper::prefsValueToEnum,
transformSetter = bandwidthPriorityMapper.enumToPrefsValue
)

val torrentsSortMode: MutableProperty<TorrentsListFragmentViewModel.SortMode> =
mutableProperty<Int>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ class AddTorrentFileFragment : AddTorrentFragment(
0
) {
private val args: AddTorrentFileFragmentArgs by navArgs()
val model: AddTorrentFileModel by viewModels<AddTorrentFileModelImpl> {
val model: AddTorrentFileModelImpl by viewModels {
viewModelFactory {
initializer {
AddTorrentFileModelImpl(
Expand Down Expand Up @@ -323,15 +323,14 @@ class AddTorrentFileFragment : AddTorrentFragment(
if (model.shouldSetInitialRpcInputs) {
val downloadingSettings = it.downloadingSettings.response
downloadDirectoryLayout.downloadDirectoryEdit.setText(
model.getInitialDownloadDirectory(
downloadingSettings
)
model.getInitialDownloadDirectory(downloadingSettings)
)
startDownloadingCheckBox.isChecked = downloadingSettings.startAddedTorrents
startDownloadingCheckBox.isChecked = model.getInitialStartAfterAdding(downloadingSettings)
model.shouldSetInitialRpcInputs = false
}
if (model.shouldSetInitialLocalInputs) {
priorityView.setText(R.string.normal_priority)
val parent = requireParentFragment() as AddTorrentFileFragment
priorityView.setText(parent.priorityItems[parent.priorityItemEnums.indexOf(model.getInitialPriority())])
model.shouldSetInitialLocalInputs = false
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,12 +203,12 @@ class AddTorrentLinkFragment : AddTorrentFragment(
private suspend fun showView(downloadingSettings: DownloadingServerSettings) = with(binding) {
if (model.shouldSetInitialRpcInputs) {
downloadDirectoryLayout.downloadDirectoryEdit.setText(model.getInitialDownloadDirectory(downloadingSettings))
startDownloadingCheckBox.isChecked = downloadingSettings.startAddedTorrents
startDownloadingCheckBox.isChecked = model.getInitialStartAfterAdding(downloadingSettings)
model.shouldSetInitialRpcInputs = false
}
if (model.shouldSetInitialLocalInputs) {
torrentLinkEdit.setText(model.getInitialTorrentLink())
priorityView.setText(R.string.normal_priority)
priorityView.setText(priorityItems[priorityItemEnums.indexOf(model.getInitialPriority())])
model.shouldSetInitialLocalInputs = false
}
scrollView.isVisible = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import org.equeim.tremotesf.torrentfile.rpc.requests.FileSize
import org.equeim.tremotesf.torrentfile.rpc.requests.getFreeSpaceInDirectory
import org.equeim.tremotesf.torrentfile.rpc.requests.serversettings.DownloadingServerSettings
import org.equeim.tremotesf.torrentfile.rpc.requests.serversettings.getDownloadingServerSettings
import org.equeim.tremotesf.torrentfile.rpc.requests.torrentproperties.TorrentLimits
import org.equeim.tremotesf.torrentfile.rpc.stateIn
import org.equeim.tremotesf.torrentfile.rpc.toNativeSeparators
import org.equeim.tremotesf.ui.Settings
Expand All @@ -34,7 +35,7 @@ abstract class BaseAddTorrentModel(application: Application) : AndroidViewModel(
.stateIn(GlobalRpcClient, viewModelScope)

suspend fun getInitialDownloadDirectory(settings: DownloadingServerSettings): String {
return if (Settings.rememberDownloadDirectory.get()) {
return if (Settings.rememberAddTorrentParameters.get()) {
GlobalServers.serversState.value.currentServer
?.lastDownloadDirectory
?.takeIf { it.isNotEmpty() }
Expand All @@ -45,6 +46,24 @@ abstract class BaseAddTorrentModel(application: Application) : AndroidViewModel(
}.toNativeSeparators()
}

suspend fun getInitialStartAfterAdding(settings: DownloadingServerSettings): Boolean =
if (Settings.rememberAddTorrentParameters.get()) {
when (Settings.lastAddTorrentStartAfterAdding.get()) {
Settings.StartTorrentAfterAdding.Start -> true
Settings.StartTorrentAfterAdding.DontStart -> false
Settings.StartTorrentAfterAdding.Unknown -> settings.startAddedTorrents
}
} else {
settings.startAddedTorrents
}

suspend fun getInitialPriority(): TorrentLimits.BandwidthPriority =
if (Settings.rememberAddTorrentParameters.get()) {
Settings.lastAddTorrentPriority.get()
} else {
TorrentLimits.BandwidthPriority.Normal
}

suspend fun getFreeSpace(directory: String): FileSize? = try {
GlobalRpcClient.getFreeSpaceInDirectory(directory)
} catch (e: RpcRequestError) {
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/values-de-rDE/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ SPDX-License-Identifier: GPL-3.0-or-later

<string name="prefs_delete_files_title">Lösche Dateien auf der Festplatte, wenn der Torrent gelöscht wird</string>
<string name="prefs_link_from_clipboard_title">Beim Hinzufügen eines Torrent-Links automatisch den Link aus der Zwischenablage ausfüllen</string>
<string name="prefs_remember_download_directory_title">Letztes Download-Verzeichnis merken</string>
<string name="prefs_remember_add_torrent_parameters_title">Letztes Download-Verzeichnis merken</string>

<string name="alternative_speed_limits">Alternative Geschwindigkeitslimitierungen</string>

Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/values-fr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ SPDX-License-Identifier: GPL-3.0-or-later

<string name="prefs_delete_files_title">Supprimer les fichiers du disque lors de la suppression du torrent</string>
<string name="prefs_link_from_clipboard_title">Remplir automatiquement le lien depuis le presse-papiers lors de l\'ajout d\'un lien torrent</string>
<string name="prefs_remember_download_directory_title">Se souvenir du dernier répertoire de téléchargement</string>
<string name="prefs_remember_add_torrent_parameters_title">Se souvenir du dernier répertoire de téléchargement</string>

<string name="alternative_speed_limits">Limites de vitesse alternatives</string>

Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/values-ru/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ SPDX-License-Identifier: GPL-3.0-or-later

<string name="prefs_delete_files_title">Удалять файлы на жестком диске при удалении торрента</string>
<string name="prefs_link_from_clipboard_title">Автоматически копировать ссылку из буфера обмена при добавлении ссылки на торрент</string>
<string name="prefs_remember_download_directory_title">Запоминать последний каталог загрузки</string>
<string name="prefs_remember_add_torrent_parameters_title">Запоминать последний каталог загрузки</string>

<string name="alternative_speed_limits">Альтернативные ограничения скорости</string>

Expand Down
12 changes: 10 additions & 2 deletions app/src/main/res/values/prefs_constants.xml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@ SPDX-License-Identifier: GPL-3.0-or-later

<string name="notification_permission_key" translatable="false">notificationPermission</string>

<string name="prefs_remember_download_directory_key" translatable="false">rememberDownloadDirectory</string>
<bool name="prefs_remember_download_directory_default_value">true</bool>
<string name="deprecated_prefs_remember_download_directory_key" translatable="false">rememberDownloadDirectory</string>

<string name="prefs_remember_add_torrent_parameters_key">rememberAddTorrentParameters</string>
<bool name="prefs_remember_add_torrent_parameters_default_value">true</bool>

<string name="prefs_last_add_torrent_start_after_adding_key">lastAddTorrentStartAfterAdding</string>
<string name="prefs_last_add_torrent_start_after_adding_default_value">unknown</string>

<string name="prefs_last_add_torrent_priority_key">lastAddTorrentPriority</string>
<string name="prefs_last_add_torrent_priority_default_value">normal</string>
</resources>
2 changes: 1 addition & 1 deletion app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,7 @@ SPDX-License-Identifier: GPL-3.0-or-later

<string name="prefs_delete_files_title">Delete files on the hard disk when removing torrent</string>
<string name="prefs_link_from_clipboard_title">Automatically fill link from clipboard when adding torrent link</string>
<string name="prefs_remember_download_directory_title">Remember last download directory</string>
<string name="prefs_remember_add_torrent_parameters_title">Remember parameters of last added torrent</string>

<string name="alternative_speed_limits">Alternative speed limits</string>

Expand Down
6 changes: 3 additions & 3 deletions app/src/main/res/xml/preferences.xml
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ SPDX-License-Identifier: GPL-3.0-or-later
app:singleLineTitle="false" />

<CheckBoxPreference
android:defaultValue="@bool/prefs_remember_download_directory_default_value"
android:key="@string/prefs_remember_download_directory_key"
android:title="@string/prefs_remember_download_directory_title"
android:defaultValue="@bool/prefs_remember_add_torrent_parameters_default_value"
android:key="@string/prefs_remember_add_torrent_parameters_key"
android:title="@string/prefs_remember_add_torrent_parameters_title"
app:singleLineTitle="false" />
</PreferenceCategory>

Expand Down

0 comments on commit f7961cf

Please sign in to comment.