Yokan / rebuild
Course 1 8624561

LibrarySettingsScreen.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/library/LibrarySettingsScreen.kt

implementation402 lines
1package eu.friedcutlet.yokan.ui.screens.settings.library23import androidx.compose.foundation.layout.padding4import androidx.compose.material3.AlertDialog5import androidx.compose.material3.ExperimentalMaterial3Api6import androidx.compose.material3.Text7import androidx.compose.material3.TextButton8import androidx.compose.material3.TimePicker9import androidx.compose.material3.rememberTimePickerState10import androidx.compose.runtime.Composable11import androidx.compose.runtime.getValue12import androidx.compose.runtime.mutableStateOf13import androidx.compose.runtime.remember14import androidx.compose.runtime.setValue15import androidx.compose.ui.Modifier16import androidx.compose.ui.unit.dp17import androidx.lifecycle.compose.collectAsStateWithLifecycle18import androidx.lifecycle.viewmodel.compose.viewModel19import eu.friedcutlet.yokan.app.YokanRuntime20import eu.friedcutlet.yokan.database.DbSettings21import eu.friedcutlet.yokan.domain.ItemType22import eu.friedcutlet.yokan.data.toDb23import eu.friedcutlet.yokan.database.DbGroupUpdateMode24import eu.friedcutlet.yokan.database.DbSmartUpdateRules25import eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints26import eu.friedcutlet.yokan.database.DbUpdateNetwork27import eu.friedcutlet.yokan.database.DbUnknownNetworkCost28import eu.friedcutlet.yokan.services.scheduling.UpdateDeferral29import org.jetbrains.compose.resources.stringResource30import yokan.composeapp.generated.resources.*31import eu.friedcutlet.yokan.ui.components.ChoiceDialog32import eu.friedcutlet.yokan.ui.components.YokanChipTabs33import eu.friedcutlet.yokan.ui.navigation.SettingsPage34import eu.friedcutlet.yokan.ui.navigation.SettingsPage.Categories35import eu.friedcutlet.yokan.ui.screens.settings.RouteTile36import eu.friedcutlet.yokan.ui.screens.settings.SettingTile37import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold38import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection39import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile4041@Composable42internal fun LibrarySettingsRoute(43    title: String,44    settings: DbSettings,45    onUpdate: ((DbSettings) -> DbSettings) -> Unit,46    onBack: () -> Unit,47    onOpen: (SettingsPage) -> Unit,48    itemType: ItemType,49) {50    val model = viewModel {51        val owner = YokanRuntime.activeSession52        AutomaticUpdateConditionsViewModel(owner.settings, owner.automaticUpdateGate)53    }54    val conditionState by model.state.collectAsStateWithLifecycle()55    val isDesktop = remember { YokanRuntime.bootstrapReport().platform.platformName == "Desktop" }56    LibrarySettingsScreen(57        title, settings, onUpdate, onBack, onOpen, itemType,58        isDesktop = isDesktop,59        onRequestNotificationPermission = { YokanRuntime.notifications.requestPermission() },60        conditionState = conditionState,61        onCheckConditions = model::refresh,62    )63}6465@Composable66internal fun LibrarySettingsScreen(67    title: String,68    settings: DbSettings,69    onUpdate: ((DbSettings) -> DbSettings) -> Unit,70    onBack: () -> Unit,71    onOpen: (SettingsPage) -> Unit,72    initialItemType: ItemType,73    isDesktop: Boolean,74    onRequestNotificationPermission: () -> Unit,75    conditionState: AutomaticUpdateConditionsState = AutomaticUpdateConditionsState(),76    onCheckConditions: () -> Unit = {},77) {78    var selectedType by remember { mutableStateOf(initialItemType) }79    var updateFrequencyDialog by remember { mutableStateOf(false) }80    var updateTimeDialog by remember { mutableStateOf(false) }81    var groupScopeDialog by remember { mutableStateOf(false) }82    var networkDialog by remember { mutableStateOf(false) }83    var costDialog by remember { mutableStateOf(false) }84    val constraints = settings.features.library.deviceConstraints85    fun setConstraints(change: (DbAutomaticUpdateConstraints) -> DbAutomaticUpdateConstraints) = onUpdate { db ->86        db.copy(features = db.features.copy(library = db.features.library.copy(deviceConstraints = change(db.features.library.deviceConstraints))))87    }88    val networkLabels = mapOf(DbUpdateNetwork.Legacy to stringResource(Res.string.update_constraints_legacy),89        DbUpdateNetwork.Connected to stringResource(Res.string.update_constraints_connected),90        DbUpdateNetwork.Unmetered to stringResource(Res.string.update_constraints_unmetered),91        DbUpdateNetwork.Wifi to stringResource(Res.string.update_constraints_wifi))92    val costLabels = mapOf(DbUnknownNetworkCost.Wait to stringResource(Res.string.update_constraints_wait),93        DbUnknownNetworkCost.Metered to stringResource(Res.string.update_constraints_assume_metered),94        DbUnknownNetworkCost.Unmetered to stringResource(Res.string.update_constraints_assume_unmetered))95    if (networkDialog) ChoiceDialog(96        title = stringResource(Res.string.update_constraints_network), options = DbUpdateNetwork.entries,97        selected = constraints.network, label = { networkLabels.getValue(it) },98        onSelect = { value -> setConstraints { it.copy(network = value) } }, onDismiss = { networkDialog = false })99    if (costDialog) ChoiceDialog(100        title = stringResource(Res.string.update_constraints_unknown_cost), options = DbUnknownNetworkCost.entries,101        selected = constraints.unknownNetworkCost, label = { costLabels.getValue(it) },102        onSelect = { value -> setConstraints { it.copy(unknownNetworkCost = value) } }, onDismiss = { costDialog = false })103    val updateRules = settings.features.library.updateRules(selectedType.toDb())104    val groupScope = settings.features.library.updateGroupMode(selectedType.toDb())105    fun setRules(change: (DbSmartUpdateRules) -> DbSmartUpdateRules) = onUpdate { db ->106        db.copy(features = db.features.copy(library = db.features.library.withUpdateRules(selectedType.toDb(),107            change(db.features.library.updateRules(selectedType.toDb())))))108    }109    val groupLabels = mapOf(DbGroupUpdateMode.Global to stringResource(Res.string.library_update_group_global),110        DbGroupUpdateMode.CurrentGroup to stringResource(Res.string.library_update_group_current),111        DbGroupUpdateMode.CurrentExceptUngrouped to stringResource(Res.string.library_update_group_except_ungrouped))112    if (groupScopeDialog) ChoiceDialog(113        title = stringResource(Res.string.library_update_group_scope), options = DbGroupUpdateMode.entries,114        selected = groupScope, label = { groupLabels.getValue(it) }, onSelect = { mode ->115            onUpdate { db -> db.copy(features = db.features.copy(library = db.features.library.withUpdateGroupMode(selectedType.toDb(), mode))) }116        }, onDismiss = { groupScopeDialog = false })117    val updatesEnabled = settings.libraryUpdateFrequencySeconds > 0118    val dailyAt = settings.libraryUpdateDailyAtMinutes119120    if (updateFrequencyDialog) {121        ChoiceDialog(122            title = "Update schedule",123            options = PeriodicTaskFrequencies.drop(1) + DailyAtFixedTime,124            selected = if (dailyAt >= 0) DailyAtFixedTime else settings.libraryUpdateFrequencySeconds,125            label = ::periodicTaskFrequencyLabel,126            onSelect = { value ->127                if (value == DailyAtFixedTime) {128                    updateTimeDialog = true129                } else {130                    onUpdate { it.copy(libraryUpdateFrequencySeconds = value, libraryUpdateDailyAtMinutes = -1) }131                }132            },133            onDismiss = { updateFrequencyDialog = false },134        )135    }136    if (updateTimeDialog) {137        TimeOfDayDialog(138            title = "Update daily at",139            initialMinutes = dailyAt.takeIf { it >= 0 } ?: (3 * 60),140            onConfirm = { minutes ->141                onUpdate { it.copy(libraryUpdateFrequencySeconds = 86400, libraryUpdateDailyAtMinutes = minutes) }142            },143            onDismiss = { updateTimeDialog = false },144        )145    }146147    // Per-type accessors so each toggle reads/writes the field for the148    // currently selected library tab (manga/anime/novel).149    fun showCategoryTabs() = when (selectedType) {150        ItemType.Manga -> settings.libraryShowCategoryTabs151        ItemType.Anime -> settings.animeLibraryShowCategoryTabs152        ItemType.Novel -> settings.novelLibraryShowCategoryTabs153    }154    fun showCounts() = when (selectedType) {155        ItemType.Manga -> settings.libraryShowNumbersOfItems156        ItemType.Anime -> settings.animeLibraryShowNumbersOfItems157        ItemType.Novel -> settings.novelLibraryShowNumbersOfItems158    }159    fun showLanguage() = when (selectedType) {160        ItemType.Manga -> settings.libraryShowLanguage161        ItemType.Anime -> settings.animeLibraryShowLanguage162        ItemType.Novel -> settings.novelLibraryShowLanguage163    }164    fun showSource() = when (selectedType) {165        ItemType.Manga -> settings.libraryShowSource166        ItemType.Anime -> settings.animeLibraryShowSource167        ItemType.Novel -> settings.novelLibraryShowSource168    }169    fun showDownloadBadge() = when (selectedType) {170        ItemType.Manga -> settings.libraryDownloadedChapters171        ItemType.Anime -> settings.animeLibraryDownloadedChapters172        ItemType.Novel -> settings.novelLibraryDownloadedChapters173    }174175    SettingsScaffold(title, onBack) {176        item {177            YokanChipTabs(178                options = ItemType.entries.map { it.label },179                selectedIndex = ItemType.entries.indexOf(selectedType),180                onSelect = { idx -> selectedType = ItemType.entries[idx] },181                modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),182            )183        }184        item { SettingsSection("Background updates") }185        item {186            SwitchTile(187                "Automatic library updates",188                when {189                    !updatesEnabled -> "Off"190                    dailyAt >= 0 -> "Daily at ${timeOfDayLabel(dailyAt)}"191                    else -> periodicTaskFrequencyLabel(settings.libraryUpdateFrequencySeconds)192                },193                updatesEnabled,194                { value ->195                    if (value) onRequestNotificationPermission()196                    onUpdate { it.copy(libraryUpdateFrequencySeconds = if (value) 86400 else 0) }197                },198            )199        }200        if (updatesEnabled) {201            item {202                SettingTile(203                    "Schedule",204                    if (dailyAt >= 0) periodicTaskFrequencyLabel(DailyAtFixedTime) else periodicTaskFrequencyLabel(settings.libraryUpdateFrequencySeconds),205                    onClick = { updateFrequencyDialog = true },206                )207            }208            if (dailyAt >= 0) {209                item { SettingTile("Time", timeOfDayLabel(dailyAt), onClick = { updateTimeDialog = true }) }210            }211            if (isDesktop) {212                item {213                    SwitchTile(214                        "Keep running in the tray",215                        "Closing the window hides Yokan so scheduled updates still run",216                        settings.desktopCloseToTray,217                        { value -> onUpdate { it.copy(desktopCloseToTray = value, desktopLaunchAtLogin = it.desktopLaunchAtLogin && value) } },218                    )219                }220                item {221                    SwitchTile(222                        "Start at login",223                        "Launch Yokan hidden in the tray when you sign in",224                        settings.desktopLaunchAtLogin,225                        { value -> onUpdate { it.copy(desktopLaunchAtLogin = value) } },226                        enabled = settings.desktopCloseToTray,227                    )228                }229            }230        }231        item { SettingsSection(stringResource(Res.string.update_constraints_section)) }232        item { Text(stringResource(Res.string.update_constraints_help), modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) }233        item { SettingTile(stringResource(Res.string.update_constraints_network), networkLabels.getValue(constraints.network), onClick = { networkDialog = true }) }234        item { SwitchTile(stringResource(Res.string.update_constraints_power), stringResource(Res.string.update_constraints_power_help),235            constraints.requireExternalPower, { value -> setConstraints { it.copy(requireExternalPower = value) } }) }236        if (constraints.network == DbUpdateNetwork.Unmetered) {237            item { SettingTile(stringResource(Res.string.update_constraints_unknown_cost), costLabels.getValue(constraints.unknownNetworkCost), onClick = { costDialog = true }) }238            item { Text(stringResource(Res.string.update_constraints_unknown_help), modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) }239        }240        item {241            val admission = conditionState.admission242            val summary = when {243                conditionState.checking -> stringResource(Res.string.update_constraints_checking)244                admission == null -> ""245                admission.allowed -> stringResource(Res.string.update_constraints_allowed)246                else -> stringResource(Res.string.update_constraints_waiting, admission.reasons.map { reason ->247                    stringResource(when (reason) {248                        UpdateDeferral.NetworkUnavailable -> Res.string.update_constraints_no_network249                        UpdateDeferral.NetworkUnknown -> Res.string.update_constraints_unknown_network250                        UpdateDeferral.WifiRequired -> Res.string.update_constraints_need_wifi251                        UpdateDeferral.WifiUnknown -> Res.string.update_constraints_unknown_wifi252                        UpdateDeferral.UnmeteredRequired -> Res.string.update_constraints_need_unmetered253                        UpdateDeferral.NetworkCostUnknown -> Res.string.update_constraints_unknown_metering254                        UpdateDeferral.PowerRequired -> Res.string.update_constraints_need_power255                        UpdateDeferral.PowerUnknown -> Res.string.update_constraints_unknown_power256                    })257                }.joinToString("; "))258            }259            SettingTile(stringResource(Res.string.update_constraints_check), summary, onClick = onCheckConditions, enabled = !conditionState.checking)260        }261        item { SettingsSection(stringResource(Res.string.library_update_rules)) }262        item { SwitchTile(stringResource(Res.string.library_update_skip_completed), "", updateRules.skipCompleted,263            { value -> setRules { it.copy(skipCompleted = value) } }) }264        item { SwitchTile(stringResource(Res.string.library_update_caught_up), stringResource(Res.string.library_update_caught_up_help), updateRules.onlyCaughtUp,265            { value -> setRules { it.copy(onlyCaughtUp = value) } }) }266        item { SwitchTile(stringResource(Res.string.library_update_started), stringResource(Res.string.library_update_started_help), updateRules.onlyStarted,267            { value -> setRules { it.copy(onlyStarted = value) } }) }268        item { SwitchTile(stringResource(Res.string.library_update_release_period), stringResource(Res.string.library_update_release_period_help), updateRules.respectExpectedReleasePeriod,269            { value -> setRules { it.copy(respectExpectedReleasePeriod = value) } }) }270        item { SettingTile(stringResource(Res.string.library_update_group_scope), groupLabels.getValue(groupScope), onClick = { groupScopeDialog = true }) }271        item { Text(stringResource(Res.string.library_update_group_help), modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) }272        item { SettingsSection("Display") }273        item {274            SwitchTile(275                "Display category tabs",276                "Show a tab row for your ${selectedType.label.lowercase()} categories at the top of the library",277                showCategoryTabs(),278                { value ->279                    onUpdate {280                        when (selectedType) {281                            ItemType.Manga -> it.copy(libraryShowCategoryTabs = value)282                            ItemType.Anime -> it.copy(animeLibraryShowCategoryTabs = value)283                            ItemType.Novel -> it.copy(novelLibraryShowCategoryTabs = value)284                        }285                    }286                },287            )288        }289        item {290            SwitchTile(291                "Show number of items",292                "Display the entry count on each category",293                showCounts(),294                { value ->295                    onUpdate {296                        when (selectedType) {297                            ItemType.Manga -> it.copy(libraryShowNumbersOfItems = value)298                            ItemType.Anime -> it.copy(animeLibraryShowNumbersOfItems = value)299                            ItemType.Novel -> it.copy(novelLibraryShowNumbersOfItems = value)300                        }301                    }302                },303            )304        }305        item {306            SwitchTile(307                "Show download badges",308                "Highlight entries with downloaded chapters",309                showDownloadBadge(),310                { value ->311                    onUpdate {312                        when (selectedType) {313                            ItemType.Manga -> it.copy(libraryDownloadedChapters = value)314                            ItemType.Anime -> it.copy(animeLibraryDownloadedChapters = value)315                            ItemType.Novel -> it.copy(novelLibraryDownloadedChapters = value)316                        }317                    }318                },319            )320        }321        item {322            SwitchTile(323                "Show source language",324                "Display the source language on each entry",325                showLanguage(),326                { value ->327                    onUpdate {328                        when (selectedType) {329                            ItemType.Manga -> it.copy(libraryShowLanguage = value)330                            ItemType.Anime -> it.copy(animeLibraryShowLanguage = value)331                            ItemType.Novel -> it.copy(novelLibraryShowLanguage = value)332                        }333                    }334                },335            )336        }337        item {338            SwitchTile(339                "Show source badge",340                "Display the source badge on each library cover",341                showSource(),342                { value ->343                    onUpdate {344                        when (selectedType) {345                            ItemType.Manga -> it.copy(libraryShowSource = value)346                            ItemType.Anime -> it.copy(animeLibraryShowSource = value)347                            ItemType.Novel -> it.copy(novelLibraryShowSource = value)348                        }349                    }350                },351            )352        }353        item { SettingsSection("Organisation") }354        item { RouteTile(Categories, "Categories", "Create and order categories to group library entries", onOpen = onOpen) }355    }356}357358internal val PeriodicTaskFrequencies = listOf(0, 3600, 21600, 43200, 86400, 172800, 604800)359360/** Sentinel option in the schedule picker; the actual time lives in `libraryUpdateDailyAtMinutes`. */361private const val DailyAtFixedTime = -1362363private fun timeOfDayLabel(minutes: Int): String =364    "${(minutes / 60).toString().padStart(2, '0')}:${(minutes % 60).toString().padStart(2, '0')}"365366@OptIn(ExperimentalMaterial3Api::class)367@Composable368private fun TimeOfDayDialog(369    title: String,370    initialMinutes: Int,371    onConfirm: (Int) -> Unit,372    onDismiss: () -> Unit,373) {374    val state = rememberTimePickerState(375        initialHour = initialMinutes / 60,376        initialMinute = initialMinutes % 60,377        is24Hour = true,378    )379    AlertDialog(380        onDismissRequest = onDismiss,381        title = { Text(title) },382        text = { TimePicker(state = state) },383        confirmButton = {384            TextButton(onClick = {385                onConfirm(state.hour * 60 + state.minute)386                onDismiss()387            }) { Text(stringResource(Res.string.ok)) }388        },389        dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },390    )391}392393internal fun periodicTaskFrequencyLabel(seconds: Int): String = when (seconds) {394    DailyAtFixedTime -> "Daily at a fixed time"395    3600 -> "Every hour"396    21600 -> "Every 6 hours"397    43200 -> "Every 12 hours"398    86400 -> "Daily"399    172800 -> "Every 2 days"400    604800 -> "Weekly"401    else -> "Off"402}403

Search chapters, reference and source filenames.