Implementation chapter · Coverage index
Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.
Pinned baseline for comparison. Use the reviewed listings in the implementation chapters and the reviewed source archive when reconstructing the app. See the architecture review for changes.
composeApp/src/androidHostTest/kotlin/eu/friedcutlet/yokan/services/scheduling/LibraryWorkConstraintsTest.kt
- Source · test / fixture · 41 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
10: class LibraryWorkConstraintsTest {
Exact file bytes / download · SHA-256 779542b45fb61b63736c88783a9c8c0c7d61f11c70559a76b67e10c3ad66581b.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.ListenableWorker
import eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints
import eu.friedcutlet.yokan.database.DbUpdateNetwork
import kotlin.test.*
class LibraryWorkConstraintsTest {
@Test fun constraintDeferralDoesNotExhaustTheOrdinaryFailureRetryLimit() {
val deferred = ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Deferred, "Waiting"))
assertEquals(ListenableWorker.Result.retry(), periodicWorkerResult(deferred, 100))
val failed = ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Failed, "Failed"))
assertEquals(ListenableWorker.Result.retry(), periodicWorkerResult(failed, 2))
assertEquals(ListenableWorker.Result.failure(), periodicWorkerResult(failed, 3))
assertEquals(ListenableWorker.Result.retry(), periodicWorkerResult(ProfileWorkResult.Retry, 2))
assertEquals(ListenableWorker.Result.failure(), periodicWorkerResult(ProfileWorkResult.Retry, 3))
assertEquals(ListenableWorker.Result.success(), periodicWorkerResult(ProfileWorkResult.Skipped, 100))
assertEquals(ListenableWorker.Result.success(), periodicWorkerResult(ProfileWorkResult.Completed(
PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Done")), 100))
}
@Test fun explicitLibraryConstraintsOverrideDownloadNetworkPolicyAndPreserveWifiVsCostDistinction() {
assertEquals(NetworkType.UNMETERED, libraryWorkConstraints(true, DbAutomaticUpdateConstraints()).requiredNetworkType)
assertEquals(NetworkType.CONNECTED, libraryWorkConstraints(false, DbAutomaticUpdateConstraints()).requiredNetworkType)
assertEquals(NetworkType.CONNECTED, libraryWorkConstraints(true, DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected)).requiredNetworkType)
assertEquals(NetworkType.CONNECTED, libraryWorkConstraints(true, DbAutomaticUpdateConstraints(DbUpdateNetwork.Wifi)).requiredNetworkType)
val constrained = libraryWorkConstraints(false, DbAutomaticUpdateConstraints(DbUpdateNetwork.Unmetered, requireExternalPower = true))
assertEquals(NetworkType.UNMETERED, constrained.requiredNetworkType)
assertTrue(constrained.requiresCharging())
assertFalse(libraryWorkConstraints(false, DbAutomaticUpdateConstraints()).requiresCharging())
}
@Test fun dailySettingsUpdatesReplaceConstraintsWithoutResettingTheTimeAnchor() {
val daily = 1440L to 180
assertEquals(ExistingPeriodicWorkPolicy.UPDATE, libraryWorkPolicy(null, daily))
assertEquals(ExistingPeriodicWorkPolicy.UPDATE, libraryWorkPolicy(daily, daily))
assertEquals(ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, libraryWorkPolicy(daily, 1440L to 240))
assertEquals(ExistingPeriodicWorkPolicy.UPDATE, libraryWorkPolicy(daily, 60L to -1))
}
}
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/appicons/AppIconService.android.kt
- Source · implementation · 55 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: actual fun createPlatformAppIconService(): AppIconService = AndroidAppIconService()
14: private class AndroidAppIconService : AppIconService {
20: private fun component(selection: AppIconSelection) = ComponentName(context, when (selection) {
26: private fun enabled(selection: AppIconSelection): Boolean = when (manager.getComponentEnabledSetting(component(selection))) {
31: override suspend fun current(): AppIconSelection? = withContext(Dispatchers.IO) {
34: override suspend fun apply(selection: AppIconSelection) = withContext(Dispatchers.IO) {
Exact file bytes / download · SHA-256 0af8ae89339b8b9c80a07ce953f457c9f3dccecc6ec613df546d46729bbcc4ee.
Complete file
package eu.friedcutlet.yokan.services.appicons
import android.content.ComponentName
import android.content.pm.PackageManager
import android.os.Build
import eu.friedcutlet.yokan.AndroidAppContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
actual fun createPlatformAppIconService(): AppIconService = AndroidAppIconService()
private class AndroidAppIconService : AppIconService {
override val capabilities = AppIconCapabilities(AppIconPlatform.Android, ExplicitAppIcons)
private val mutex = Mutex()
private val context get() = checkNotNull(AndroidAppContext.appContext) { "Android context unavailable" }
private val manager get() = context.packageManager
// Stable names must be retained across upgrades; never disable the deep-link target activity.
private fun component(selection: AppIconSelection) = ComponentName(context, when (selection) {
AppIconSelection.Default -> "eu.friedcutlet.yokan.LauncherDefault"
ExplicitAppIcons[1] -> "eu.friedcutlet.yokan.LauncherToriiLight"
ExplicitAppIcons[2] -> "eu.friedcutlet.yokan.LauncherToriiDark"
else -> error("Unsupported icon")
})
private fun enabled(selection: AppIconSelection): Boolean = when (manager.getComponentEnabledSetting(component(selection))) {
PackageManager.COMPONENT_ENABLED_STATE_DEFAULT -> selection == AppIconSelection.Default
PackageManager.COMPONENT_ENABLED_STATE_ENABLED -> true
else -> false
}
override suspend fun current(): AppIconSelection? = withContext(Dispatchers.IO) {
mutex.withLock { ExplicitAppIcons.filter(::enabled).singleOrNull() }
}
override suspend fun apply(selection: AppIconSelection) = withContext(Dispatchers.IO) {
require(selection in capabilities.choices)
mutex.withLock {
if (Build.VERSION.SDK_INT >= 33) {
manager.setComponentEnabledSettings(ExplicitAppIcons.map { icon ->
PackageManager.ComponentEnabledSetting(component(icon),
if (icon == selection) PackageManager.COMPONENT_ENABLED_STATE_ENABLED
else PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP)
})
} else {
// Older OS versions have no atomic batch. Enable the destination first so a
// failure can leave duplicate icons, but never an installation without a launcher.
manager.setComponentEnabledSetting(component(selection), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP)
ExplicitAppIcons.filter { it != selection }.forEach { icon ->
manager.setComponentEnabledSetting(component(icon), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP)
}
}
check(ExplicitAppIcons.filter(::enabled).singleOrNull() == selection)
}
}
}
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/applock/AppLockController.android.kt
- Source · implementation · 71 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: actual fun createPlatformAppLockController(): AppLockController = AndroidAppLockController()
15: object AndroidAppLockBridge {
22: fun deliverResult(success: Boolean) {
28: internal class AndroidAppLockController : BaseAppLockController() {
41: override fun requestUnlock(onResult: (Boolean) -> Unit) {
Exact file bytes / download · SHA-256 75b4e0d703ce95239ef91dd59a0be65b3c2e767b3d233e339ff0ba0c001f8ffd.
Complete file
package eu.friedcutlet.yokan.services.applock
import eu.friedcutlet.yokan.AndroidForegroundActivity
import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
actual fun createPlatformAppLockController(): AppLockController = AndroidAppLockController()
/**
* Bridges the singleton controller to the foreground activity's
* `registerForActivityResult` launcher: the launcher must be registered in
* `onCreate`, long before any unlock request happens.
*/
object AndroidAppLockBridge {
/** Launches the confirm-credential intent; returns false when no launcher is registered. */
var launch: ((Intent) -> Boolean)? = null
/** Invoked by the activity when the credential activity finishes. */
var onResult: ((Boolean) -> Unit)? = null
fun deliverResult(success: Boolean) {
onResult?.invoke(success)
onResult = null
}
}
internal class AndroidAppLockController : BaseAppLockController() {
override val isSupported: Boolean
get() {
val context = AndroidForegroundActivity.activity ?: return false
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager
?: return false
return keyguard.isDeviceSecure
}
init {
_unlocked.value = true
}
override fun requestUnlock(onResult: (Boolean) -> Unit) {
val activity = AndroidForegroundActivity.activity
if (activity == null || !isSupported) {
// No secure lock screen configured — nothing to authenticate against.
_unlocked.value = true
onResult(true)
return
}
val keyguard = activity.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
@Suppress("DEPRECATION")
val intent: Intent? = keyguard.createConfirmDeviceCredentialIntent(
"Unlock Yokan",
"Verify it's you to continue",
)
if (intent == null) {
_unlocked.value = true
onResult(true)
return
}
AndroidAppLockBridge.onResult = { success ->
_unlocked.value = success
onResult(success)
}
val launched = AndroidAppLockBridge.launch?.invoke(intent) ?: false
if (!launched) {
// Cannot present the credential UI — stay locked instead of silently passing.
AndroidAppLockBridge.onResult = null
onResult(false)
}
}
}
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/discord/DiscordRpcService.android.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun createPlatformDiscordRpcService(): DiscordRpcService = GatewayDiscordRpcService()
Exact file bytes / download · SHA-256 5548c3380213603626cba50be66efdaa666d0a0c05bf4bb749a70e5e110ad193.
Complete file
package eu.friedcutlet.yokan.services.discord
actual fun createPlatformDiscordRpcService(): DiscordRpcService = GatewayDiscordRpcService()
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/notifications/NotificationService.android.kt
- Source · implementation · 75 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
14: actual fun createPlatformNotificationService(profileId: ProfileId): NotificationService = AndroidNotificationService(profileId)
23: private data class ChannelInfo(val id: String, val label: String)
26: internal fun NotificationManager.ensureChannel(channel: NotificationChannel): String? {
34: private class AndroidNotificationService(profileId: ProfileId) : NotificationService {
36: override fun supported(): Boolean = AndroidAppContext.appContext != null
37: override fun requestPermission() {
45: override fun notify(payload: NotificationPayload) {
65: override fun cancel(channel: NotificationChannel, tag: String?) {
72: private fun hasNotificationPermission(context: Context): Boolean =
Exact file bytes / download · SHA-256 549b55b8d98dba328f5158e065e38df4fa0be8904bc898e5030e99a0449b3b14.
Complete file
package eu.friedcutlet.yokan.services.notifications
import eu.friedcutlet.yokan.AndroidAppContext
import eu.friedcutlet.yokan.AndroidForegroundActivity
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel as AndroidChannel
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import eu.friedcutlet.yokan.domain.ProfileId
actual fun createPlatformNotificationService(profileId: ProfileId): NotificationService = AndroidNotificationService(profileId)
private val ChannelDefinitions = mapOf(
NotificationChannel.Downloads to ChannelInfo("yokan_downloads", "Downloads"),
NotificationChannel.LibraryUpdates to ChannelInfo("yokan_library_updates", "Library updates"),
NotificationChannel.Backup to ChannelInfo("yokan_backup", "Backup"),
NotificationChannel.Sync to ChannelInfo("yokan_sync", "Sync"),
)
private data class ChannelInfo(val id: String, val label: String)
/** The Android id of [channel], created on first use; the download foreground service posts on it too. */
internal fun NotificationManager.ensureChannel(channel: NotificationChannel): String? {
val info = ChannelDefinitions[channel] ?: return null
if (getNotificationChannel(info.id) == null) {
createNotificationChannel(AndroidChannel(info.id, info.label, NotificationManager.IMPORTANCE_LOW))
}
return info.id
}
private class AndroidNotificationService(profileId: ProfileId) : NotificationService {
private val namespace = ProfileNotificationNamespace(profileId)
override fun supported(): Boolean = AndroidAppContext.appContext != null
override fun requestPermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
val activity = AndroidForegroundActivity.activity ?: return
if (activity.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
activity.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1001)
}
}
override fun notify(payload: NotificationPayload) {
val context = AndroidAppContext.appContext ?: return
if (!hasNotificationPermission(context)) return
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
val channelId = manager.ensureChannel(payload.channel) ?: return
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(context, channelId)
} else {
@Suppress("DEPRECATION") Notification.Builder(context)
}
builder
.setContentTitle(payload.title)
.setContentText(payload.message)
.setSmallIcon(context.applicationInfo.icon)
.setAutoCancel(true)
runCatching {
manager.notify(namespace.androidTag(payload.channel, payload.tag), namespace.androidId(channelId, payload.tag), builder.build())
}
}
override fun cancel(channel: NotificationChannel, tag: String?) {
val context = AndroidAppContext.appContext ?: return
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
val info = ChannelDefinitions[channel] ?: return
manager.cancel(namespace.androidTag(channel, tag), namespace.androidId(info.id, tag))
}
private fun hasNotificationPermission(context: Context): Boolean =
Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
}
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundScheduler.android.kt
- Source · implementation · 185 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler = AndroidBackgroundScheduler(profileId)
27: interface BackgroundTaskHost {
28: suspend fun runBackgroundTask(owner: String?, task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome): ProfileWorkResult<PeriodicTaskOutcome>
39: internal fun libraryWorkConstraints(requireUnmetered: Boolean,
54: internal fun libraryWorkPolicy(previous: Pair<Long, Int>?, next: Pair<Long, Int>): ExistingPeriodicWorkPolicy =
58: internal fun periodicWorkerResult(outcome: ProfileWorkResult<PeriodicTaskOutcome>, attempt: Int): ListenableWorker.Result = when {
65: private class AndroidBackgroundScheduler(profileId: ProfileId) : BackgroundScheduler {
71: override fun schedule(
144: override fun cancelAll() {
158: class MetadataRefreshWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
159: override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::refreshMetadata)
162: class LibraryUpdateWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
163: override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::updateLibrary)
166: class AutoSyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
167: override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::sync)
170: class AutoBackupWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
171: override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::backup)
174: private suspend fun CoroutineWorker.runPeriodicTask(
Exact file bytes / download · SHA-256 ce78858fe2999035239831819726428a0f671614a53ee9c266fe9f236a3149c4.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.AndroidAppContext
import android.content.Context
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ListenableWorker
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.YokanDatabase
import java.util.concurrent.TimeUnit
actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler = AndroidBackgroundScheduler(profileId)
/**
* Implemented by the `Application`: a worker in a cold process bootstraps the app through it and gets
* a profile-bound execution path, like WorkManager's `Configuration.Provider` lookup.
*/
interface BackgroundTaskHost {
suspend fun runBackgroundTask(owner: String?, task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome): ProfileWorkResult<PeriodicTaskOutcome>
}
private const val METADATA_REFRESH_WORK = "yokan.metadata_refresh"
private const val LIBRARY_UPDATE_WORK = "yokan.library_update"
private const val AUTO_SYNC_WORK = "yokan.auto_sync"
private const val AUTO_BACKUP_WORK = "yokan.auto_backup"
/** Retries within one period before giving up until the next scheduled run. */
private const val MAX_WORKER_RETRIES = 3
internal fun libraryWorkConstraints(requireUnmetered: Boolean,
config: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints): Constraints {
val network = when (config.network) {
eu.friedcutlet.yokan.database.DbUpdateNetwork.Legacy -> if (requireUnmetered) NetworkType.UNMETERED else NetworkType.CONNECTED
eu.friedcutlet.yokan.database.DbUpdateNetwork.Unmetered -> NetworkType.UNMETERED
else -> NetworkType.CONNECTED
}
val builder = Constraints.Builder().setRequiredNetworkType(network).setRequiresCharging(config.requireExternalPower)
if (config.network == eu.friedcutlet.yokan.database.DbUpdateNetwork.Wifi && Build.VERSION.SDK_INT >= 28) {
builder.setRequiredNetworkRequest(NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), NetworkType.CONNECTED)
}
return builder.build()
}
internal fun libraryWorkPolicy(previous: Pair<Long, Int>?, next: Pair<Long, Int>): ExistingPeriodicWorkPolicy =
if (next.second >= 0 && previous != null && previous != next) ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE
else ExistingPeriodicWorkPolicy.UPDATE
internal fun periodicWorkerResult(outcome: ProfileWorkResult<PeriodicTaskOutcome>, attempt: Int): ListenableWorker.Result = when {
!outcome.shouldRetry -> ListenableWorker.Result.success()
outcome is ProfileWorkResult.Completed && outcome.value.status == PeriodicTaskStatus.Deferred -> ListenableWorker.Result.retry()
attempt < MAX_WORKER_RETRIES -> ListenableWorker.Result.retry()
else -> ListenableWorker.Result.failure()
}
private class AndroidBackgroundScheduler(profileId: ProfileId) : BackgroundScheduler {
private val names = ProfileWorkNamespace(profileId)
private val owner = workDataOf(ProfileWorkNamespace.OwnerKey to profileId.value)
/** Last (minutes, dailyAt) applied in this process; a change re-anchors instead of UPDATE-ing in place. */
private var appliedLibrarySchedule: Pair<Long, Int>? = null
override fun schedule(
metadataRefreshMinutes: Long,
libraryUpdateMinutes: Long,
libraryUpdateDailyAtMinutes: Int,
autoSyncMinutes: Long,
autoBackupHours: Long,
requireUnmetered: Boolean,
libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,
) {
val ctx = AndroidAppContext.appContext ?: return
val wm = WorkManager.getInstance(ctx)
val constraints = Constraints.Builder()
.setRequiredNetworkType(if (requireUnmetered) NetworkType.UNMETERED else NetworkType.CONNECTED)
.build()
if (metadataRefreshMinutes > 0) {
wm.enqueueUniquePeriodicWork(
names.uniqueName(METADATA_REFRESH_WORK),
ExistingPeriodicWorkPolicy.UPDATE,
PeriodicWorkRequestBuilder<MetadataRefreshWorker>(metadataRefreshMinutes, TimeUnit.MINUTES)
.setInputData(owner)
.setConstraints(constraints)
.build(),
)
} else {
wm.cancelUniqueWork(names.uniqueName(METADATA_REFRESH_WORK))
}
if (libraryUpdateMinutes > 0) {
val libraryOnlyConstraints = libraryWorkConstraints(requireUnmetered, libraryConstraints)
val daily = libraryUpdateDailyAtMinutes >= 0
val schedule = libraryUpdateMinutes to libraryUpdateDailyAtMinutes
// UPDATE keeps the existing period anchor, so a changed daily time must cancel and re-enqueue;
// interval mode keeps UPDATE so every settings save does not push the next run further out.
val policy = libraryWorkPolicy(appliedLibrarySchedule, schedule)
appliedLibrarySchedule = schedule
// ponytail: WorkManager re-anchors each period on the previous run's start, so a daily slot drifts
// by however long constraints/Doze delayed the last run; switch to a self-rescheduling
// OneTimeWorkRequest if users report drift.
val request = PeriodicWorkRequestBuilder<LibraryUpdateWorker>(
if (daily) 24L * 60L else libraryUpdateMinutes,
TimeUnit.MINUTES,
).setConstraints(libraryOnlyConstraints).setInputData(owner)
if (daily) request.setInitialDelay(nextDailySlotDelayMillis(libraryUpdateDailyAtMinutes), TimeUnit.MILLISECONDS)
wm.enqueueUniquePeriodicWork(names.uniqueName(LIBRARY_UPDATE_WORK), policy, request.build())
} else {
appliedLibrarySchedule = null
wm.cancelUniqueWork(names.uniqueName(LIBRARY_UPDATE_WORK))
}
if (autoSyncMinutes > 0) {
wm.enqueueUniquePeriodicWork(
names.uniqueName(AUTO_SYNC_WORK),
ExistingPeriodicWorkPolicy.UPDATE,
PeriodicWorkRequestBuilder<AutoSyncWorker>(autoSyncMinutes, TimeUnit.MINUTES)
.setInputData(owner)
.setConstraints(constraints)
.build(),
)
} else {
wm.cancelUniqueWork(names.uniqueName(AUTO_SYNC_WORK))
}
if (autoBackupHours > 0) {
wm.enqueueUniquePeriodicWork(
names.uniqueName(AUTO_BACKUP_WORK),
ExistingPeriodicWorkPolicy.UPDATE,
PeriodicWorkRequestBuilder<AutoBackupWorker>(autoBackupHours, TimeUnit.HOURS)
.setInputData(owner)
.setConstraints(Constraints.NONE)
.build(),
)
} else {
wm.cancelUniqueWork(names.uniqueName(AUTO_BACKUP_WORK))
}
}
override fun cancelAll() {
val ctx = AndroidAppContext.appContext ?: return
val wm = WorkManager.getInstance(ctx)
wm.cancelUniqueWork(names.uniqueName(METADATA_REFRESH_WORK))
wm.cancelUniqueWork(names.uniqueName(LIBRARY_UPDATE_WORK))
wm.cancelUniqueWork(names.uniqueName(AUTO_SYNC_WORK))
wm.cancelUniqueWork(names.uniqueName(AUTO_BACKUP_WORK))
}
}
/**
* WorkManager workers delegate to the shared runner so a killed UI process
* produces the same outcome and notification as an in-app periodic tick.
*/
class MetadataRefreshWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::refreshMetadata)
}
class LibraryUpdateWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::updateLibrary)
}
class AutoSyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::sync)
}
class AutoBackupWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::backup)
}
private suspend fun CoroutineWorker.runPeriodicTask(
task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome,
): ListenableWorker.Result {
// YokanApplication normally sets this; never let a worker fail on a missing context.
if (AndroidAppContext.appContext == null) AndroidAppContext.appContext = applicationContext
// Missing data belongs only to pre-profile Default jobs. A present but non-string ID is invalid.
val owner = if (inputData.keyValueMap.containsKey(ProfileWorkNamespace.OwnerKey)) {
inputData.getString(ProfileWorkNamespace.OwnerKey) ?: ""
} else null
val outcome = (applicationContext as BackgroundTaskHost).runBackgroundTask(owner, task)
return periodicWorkerResult(outcome, runAttemptCount)
}
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/scheduling/UpdateDeviceConditions.android.kt
- Source · implementation · 30 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions {
Exact file bytes / download · SHA-256 daea1cc02aaddab2ce5932a2aef19a0308b22e21673eece75e94a4795734caaf.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.BatteryManager
import eu.friedcutlet.yokan.AndroidAppContext
actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions {
val context = AndroidAppContext.appContext ?: return UpdateDeviceConditions()
val network = runCatching {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
?: return@runCatching UpdateDeviceConditions()
val active = manager.activeNetwork ?: return@runCatching UpdateDeviceConditions(connected = false, wifi = false, unmetered = false)
val capabilities = manager.getNetworkCapabilities(active) ?: return@runCatching UpdateDeviceConditions()
val connected = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
UpdateDeviceConditions(connected = connected,
wifi = connected && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI),
unmetered = connected && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED))
}.getOrElse { UpdateDeviceConditions() }
val power = if (!needPower) null else runCatching {
context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))?.let { battery ->
battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1).takeIf { it >= 0 }?.let { it != 0 }
}
}.getOrNull()
return network.copy(externalPower = power)
}
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/system/DeviceCapabilities.android.kt
- Source · implementation · 17 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: actual fun isTvDevice(): Boolean {
15: internal actual fun isLocalLibraryManagerSupported(): Boolean = true
17: internal actual fun processMemoryUsage(): ProcessMemoryUsage? = Runtime.getRuntime().let { ProcessMemoryUsage(it.totalMemory() - it.freeMemory(), it.maxMemory()) }
Exact file bytes / download · SHA-256 3135c2c940f076bbc723c6d90460b8a304d5b2620e299e914e29ea5f7b1914ab.
Complete file
package eu.friedcutlet.yokan.services.system
import eu.friedcutlet.yokan.AndroidAppContext
import android.app.UiModeManager
import android.content.res.Configuration
actual fun isTvDevice(): Boolean {
val context = AndroidAppContext.appContext ?: return false
val manager = context.getSystemService(UiModeManager::class.java)
return manager?.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION ||
context.resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK ==
Configuration.UI_MODE_TYPE_TELEVISION
}
internal actual fun isLocalLibraryManagerSupported(): Boolean = true
internal actual fun processMemoryUsage(): ProcessMemoryUsage? = Runtime.getRuntime().let { ProcessMemoryUsage(it.totalMemory() - it.freeMemory(), it.maxMemory()) }
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/system/SystemIntegration.android.kt
- Source · implementation · 77 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: actual fun openSystemBrowser(url: String): Boolean {
26: actual fun applyAppLanguage(languageCode: String?) {
43: actual fun isOnUnmeteredNetwork(): Boolean {
60: actual fun createNetworkMonitor(): NetworkMonitor = runCatching {
64: override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
68: override fun onLost(network: Network) {
72: object : NetworkMonitor {
77: private fun NetworkCapabilities.isUnmetered(): Boolean = hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
Exact file bytes / download · SHA-256 9884c812e3e4408fefd2102f043e5aefb6e926553c152210e80a51f59929df2b.
Complete file
package eu.friedcutlet.yokan.services.system
import eu.friedcutlet.yokan.AndroidAppContext
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
actual fun openSystemBrowser(url: String): Boolean {
val context = AndroidAppContext.appContext ?: return false
if (url.isBlank()) return false
return runCatching {
val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))
.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
true
}.getOrDefault(false)
}
private val systemDefaultLocale: java.util.Locale = java.util.Locale.getDefault()
actual fun applyAppLanguage(languageCode: String?) {
val locale = if (languageCode.isNullOrBlank()) {
systemDefaultLocale
} else {
runCatching { java.util.Locale.forLanguageTag(languageCode) }.getOrDefault(systemDefaultLocale)
}
// setDefault drives Compose Multiplatform Resources' locale lookup on
// recomposition; the caller is responsible for keying the UI on the
// change so cached String resources get re-resolved.
java.util.Locale.setDefault(locale)
// On Android 33+ the per-app locale API is the recommended path, but it
// requires the AppCompat/androidx.core-i18n compat layer and a config
// change that recreates the activity. Locale.setDefault + a Compose
// `key()` block triggers a recomposition without that round-trip,
// which is good enough for in-app text + Compose Resources lookups.
}
actual fun isOnUnmeteredNetwork(): Boolean {
val context = AndroidAppContext.appContext ?: return true
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
?: return true
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val active = manager.activeNetwork ?: return false
val capabilities = manager.getNetworkCapabilities(active) ?: return false
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) &&
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
}
@Suppress("DEPRECATION")
val info = manager.activeNetworkInfo
@Suppress("DEPRECATION")
return info != null && info.type == ConnectivityManager.TYPE_WIFI
}
/** Follows the default network; without a context or network-state access it reports unmetered, like [isOnUnmeteredNetwork]. */
actual fun createNetworkMonitor(): NetworkMonitor = runCatching {
val manager = checkNotNull(AndroidAppContext.appContext?.getSystemService(ConnectivityManager::class.java))
val state = MutableStateFlow(manager.getNetworkCapabilities(manager.activeNetwork)?.isUnmetered() == true)
manager.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
state.value = capabilities.isUnmetered()
}
override fun onLost(network: Network) {
state.value = false
}
})
object : NetworkMonitor {
override val unmetered: StateFlow<Boolean> = state.asStateFlow()
}
}.getOrElse { UnmeteredNetwork }
private fun NetworkCapabilities.isUnmetered(): Boolean = hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/tts/TextToSpeechService.android.kt
- Source · implementation · 102 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: actual fun createPlatformTextToSpeechService(): TextToSpeechService = AndroidTextToSpeechService()
21: private class AndroidTextToSpeechService : TextToSpeechService {
25: private suspend fun engine(): TextToSpeech? = engineLock.withLock {
46: override suspend fun voices(language: String?): List<String> {
58: override suspend fun speak(
75: override fun onStart(id: String?) = Unit
76: override fun onDone(id: String?) {
80: override fun onError(id: String?) {
83: override fun onRangeStart(id: String?, start: Int, end: Int, frame: Int) {
92: override suspend fun stop() {
96: override suspend fun closeAndJoin() = engineLock.withLock {
Exact file bytes / download · SHA-256 64faade76b2ce731dddbd74d9080c642fac84baab7abf2a6320f2a4cf5a349e8.
Complete file
package eu.friedcutlet.yokan.services.tts
import eu.friedcutlet.yokan.AndroidAppContext
import android.os.Build
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import java.util.Locale
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.coroutines.resume
actual fun createPlatformTextToSpeechService(): TextToSpeechService = AndroidTextToSpeechService()
/**
* Holds one engine bound to the application context until its owner closes;
* init is single-flight so concurrent callers never bind (and leak) extra engines.
*/
private class AndroidTextToSpeechService : TextToSpeechService {
private val engineLock = Mutex()
@Volatile private var tts: TextToSpeech? = null
private suspend fun engine(): TextToSpeech? = engineLock.withLock {
tts?.let { return@withLock it }
val context = AndroidAppContext.appContext ?: return@withLock null
val ready = CompletableDeferred<Boolean>()
val instance = TextToSpeech(context) { status ->
ready.complete(status == TextToSpeech.SUCCESS)
}
val ok = try {
ready.await()
} catch (cancelled: CancellationException) {
instance.shutdown()
throw cancelled
}
if (ok) {
instance.also { tts = it }
} else {
instance.shutdown()
null
}
}
override suspend fun voices(language: String?): List<String> {
val engine = engine() ?: return emptyList()
val all = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
engine.voices.orEmpty()
} else {
emptyList()
}
return all.filter { language.isNullOrBlank() || it.locale.language.equals(language, ignoreCase = true) }
.map { it.name }
.distinct()
}
override suspend fun speak(
text: String,
request: TextToSpeechRequest,
onProgress: (startOffset: Int, endOffset: Int) -> Unit,
) {
val engine = engine() ?: return
if (!request.language.isNullOrBlank()) {
engine.language = Locale.forLanguageTag(request.language)
}
if (!request.voice.isNullOrBlank() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
engine.voices?.firstOrNull { it.name == request.voice }?.let { engine.voice = it }
}
engine.setSpeechRate(request.speechRate.toFloat())
engine.setPitch(request.pitch.toFloat())
suspendCancellableCoroutine<Unit> { continuation ->
val utteranceId = "${text.hashCode()}:${System.nanoTime()}"
engine.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onStart(id: String?) = Unit
override fun onDone(id: String?) {
if (id == utteranceId && continuation.isActive) continuation.resume(Unit)
}
@Deprecated("Required override")
override fun onError(id: String?) {
if (id == utteranceId && continuation.isActive) continuation.resume(Unit)
}
override fun onRangeStart(id: String?, start: Int, end: Int, frame: Int) {
if (id == utteranceId) onProgress(start, end)
}
})
engine.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId)
continuation.invokeOnCancellation { engine.stop() }
}
}
override suspend fun stop() {
tts?.stop()
}
override suspend fun closeAndJoin() = engineLock.withLock {
val engine = tts ?: return@withLock
engine.stop()
engine.shutdown()
tts = null
}
}
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/updates/PackageInstaller.android.kt
- Source · implementation · 33 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: actual fun installPackageFromFile(path: String): Boolean {
Exact file bytes / download · SHA-256 242d4729ec3c5dd9ca2efdf6b715132931487dcfbeb32080159be2f263c9ab15.
Complete file
package eu.friedcutlet.yokan.services.updates
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import eu.friedcutlet.yokan.AndroidAppContext
import eu.friedcutlet.yokan.services.logging.AppLogger
import java.io.File
actual fun installPackageFromFile(path: String): Boolean {
val context = AndroidAppContext.appContext ?: return false
if (path.isBlank()) return false
val file = File(path.removePrefix("file://"))
if (!file.exists() || !file.isFile) return false
return runCatching {
val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val authority = "${context.packageName}.fileprovider"
runCatching { FileProvider.getUriForFile(context, authority, file) }
.getOrElse { Uri.fromFile(file) }
} else {
Uri.fromFile(file)
}
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/vnd.android.package-archive")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
true
}.onFailure { AppLogger.warn("[update] launching package installer failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
.getOrDefault(false)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/appicons/AppIconService.kt
- Source · implementation · 42 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
4: enum class AppIconDesign { Default, Torii }
5: enum class AppIconAppearance { Light, Dark, System }
6: data class AppIconSelection(
20: enum class AppIconPlatform { Android, Ios, Static }
21: data class AppIconCapabilities(
26: interface AppIconService {
29: suspend fun current(): AppIconSelection?
31: suspend fun apply(selection: AppIconSelection)
34: class StaticAppIconService : AppIconService {
36: override suspend fun current() = AppIconSelection.Default
37: override suspend fun apply(selection: AppIconSelection) {
42: expect fun createPlatformAppIconService(): AppIconService
Exact file bytes / download · SHA-256 bcf6cd1e96aafc068b9fc03bf2fe7317459feab7c540216eb4f9a0501e1b18bf.
Complete file
package eu.friedcutlet.yokan.services.appicons
/** Installation-owned state, deliberately absent from profile settings, sync, and backups. */
enum class AppIconDesign { Default, Torii }
enum class AppIconAppearance { Light, Dark, System }
data class AppIconSelection(
val design: AppIconDesign = AppIconDesign.Default,
val appearance: AppIconAppearance = AppIconAppearance.Light,
) {
companion object { val Default = AppIconSelection() }
}
val ExplicitAppIcons = listOf(
AppIconSelection.Default,
AppIconSelection(AppIconDesign.Torii, AppIconAppearance.Light),
AppIconSelection(AppIconDesign.Torii, AppIconAppearance.Dark),
)
val SystemAppIcon = AppIconSelection(AppIconDesign.Torii, AppIconAppearance.System)
enum class AppIconPlatform { Android, Ios, Static }
data class AppIconCapabilities(
val platform: AppIconPlatform,
val choices: List<AppIconSelection>,
) { val canChange: Boolean get() = choices.size > 1 }
interface AppIconService {
val capabilities: AppIconCapabilities
/** Read OS-owned selection; null means unknown or inconsistent, never an invented default. */
suspend fun current(): AppIconSelection?
/** Returns only after OS completion. Implementations serialize changes and read back the result. */
suspend fun apply(selection: AppIconSelection)
}
class StaticAppIconService : AppIconService {
override val capabilities = AppIconCapabilities(AppIconPlatform.Static, listOf(AppIconSelection.Default))
override suspend fun current() = AppIconSelection.Default
override suspend fun apply(selection: AppIconSelection) {
require(selection == AppIconSelection.Default)
}
}
expect fun createPlatformAppIconService(): AppIconService
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/applock/AppLockController.kt
- Source · implementation · 33 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: interface AppLockController {
9: fun requestUnlock(onResult: (Boolean) -> Unit = {})
10: fun reset()
13: abstract class BaseAppLockController : AppLockController {
17: override fun reset() {
22: class NoOpAppLockController : BaseAppLockController() {
27: override fun requestUnlock(onResult: (Boolean) -> Unit) {
33: expect fun createPlatformAppLockController(): AppLockController
Exact file bytes / download · SHA-256 b0120144146592573aadb251db0414de49bb0f76c3daea1a99dd0f4cd7d1b50b.
Complete file
package eu.friedcutlet.yokan.services.applock
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
interface AppLockController {
val isUnlocked: StateFlow<Boolean>
val isSupported: Boolean
fun requestUnlock(onResult: (Boolean) -> Unit = {})
fun reset()
}
abstract class BaseAppLockController : AppLockController {
protected val _unlocked = MutableStateFlow(true)
override val isUnlocked: StateFlow<Boolean> = _unlocked
override fun reset() {
_unlocked.value = false
}
}
class NoOpAppLockController : BaseAppLockController() {
override val isSupported: Boolean = false
init { _unlocked.value = true }
override fun requestUnlock(onResult: (Boolean) -> Unit) {
_unlocked.value = true
onResult(true)
}
}
expect fun createPlatformAppLockController(): AppLockController
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/discord/DiscordActivity.kt
- Source · implementation · 62 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: data class DiscordPresenceRequest(
18: data class DiscordActivity(
34: fun discordActivity(settings: DbSettings, request: DiscordPresenceRequest?, startedAtMillis: Long): DiscordActivity? {
55: internal fun discordRequestIsPrivate(settings: DbSettings, request: DiscordPresenceRequest): Boolean {
Exact file bytes / download · SHA-256 6fb6f135b5388ae487ac2833c8b1d3f728f532576447697032f506dabb572066.
Complete file
package eu.friedcutlet.yokan.services.discord
import eu.friedcutlet.yokan.database.DbDiscordButton
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.UncategorizedActivityCategoryId
/** What the reader/player is showing; privacy rules decide how much of it reaches Discord. */
data class DiscordPresenceRequest(
val title: String,
val detail: String?,
val coverUrl: String?,
val watching: Boolean,
val sourceId: Long? = null,
val categoryIds: List<Long> = emptyList(),
)
/** Transport-neutral presence: the desktop IPC client and the gateway both serialize this. */
data class DiscordActivity(
val details: String,
val state: String,
val watching: Boolean,
val startedAtMillis: Long?,
val coverUrl: String?,
val buttons: List<DbDiscordButton>,
)
private const val Placeholder = "-----"
/**
* Applies the user's Discord settings to [request]. Null means "publish nothing" (global incognito
* with hide-in-incognito); a private title (always-private, incognito source, private category)
* becomes the idle activity so nothing about it leaks.
*/
fun discordActivity(settings: DbSettings, request: DiscordPresenceRequest?, startedAtMillis: Long): DiscordActivity? {
if (settings.incognitoMode && settings.hideDiscordRpcInIncognito) return null
val prefs = settings.features.discord
val custom = prefs.customMessage.trim().take(128)
val buttons = if (prefs.showButtons) prefs.buttons.filter { it.label.isNotBlank() && it.url.startsWith("http") }.take(2) else emptyList()
val started = startedAtMillis.takeIf { prefs.showTimestamp }
val visible = request?.takeUnless { discordRequestIsPrivate(settings, it) }
if (visible == null || !settings.rpcShowTitle) {
return DiscordActivity(custom.ifEmpty { "Idle" }, Placeholder, request?.watching ?: true, started, null, buttons)
}
val action = if (visible.watching) "Watching" else "Reading"
return DiscordActivity(
details = custom.ifEmpty { "$action ${visible.title}" }.take(128),
state = visible.detail?.takeIf { settings.rpcShowReadingWatchingProgress && it.isNotBlank() }?.take(128) ?: Placeholder,
watching = visible.watching,
startedAtMillis = started,
coverUrl = visible.coverUrl?.takeIf { settings.rpcShowCoverImage && it.startsWith("http") },
buttons = buttons,
)
}
internal fun discordRequestIsPrivate(settings: DbSettings, request: DiscordPresenceRequest): Boolean {
val prefs = settings.features.discord
if (prefs.alwaysPrivate) return true
// Incognito sources (Security settings) never reveal their titles either.
if (request.sourceId != null && request.sourceId in settings.features.privacy.incognitoSourceIds) return true
val categories = request.categoryIds.ifEmpty { listOf(UncategorizedActivityCategoryId) }
return categories.any { it in prefs.privateCategoryIds }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/discord/DiscordGateway.kt
- Source · implementation · 270 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
55: private data class GatewayPresence(val activity: DiscordActivity?, val status: DbDiscordStatus)
62: internal class DiscordGatewayClient(
79: fun publish(activity: DiscordActivity?, status: DbDiscordStatus) {
84: fun close() {
91: private suspend fun run() {
116: private suspend fun DefaultClientWebSocketSession.session() {
157: internal suspend fun mediaProxyAsset(url: String): String? {
171: internal fun heartbeatPayload(sequence: Long?): JsonObject = buildJsonObject {
176: internal fun gatewayIdentify(token: String): JsonObject = buildJsonObject {
191: internal fun gatewayPresenceUpdate(activity: DiscordActivity?, coverAsset: String?, status: DbDiscordStatus, sinceMillis: Long): JsonObject = buildJsonObject {
218: internal fun parseExternalAssetPath(body: String): String? = runCatching {
223: class DiscordLoginException(message: String) : Exception(message)
230: internal suspend fun resolveDiscordAccount(token: String, engine: HttpClientEngine): DbDiscordAccount {
248: internal fun discordAccountFromProfile(body: String, token: String): DbDiscordAccount? = runCatching {
264: internal fun discordAccountFromToken(token: String): DbDiscordAccount? {
Exact file bytes / download · SHA-256 e9ca701261b8e58fcee02b64b7aefe6c208259e337336814bef22ad36e0e3910.
Complete file
package eu.friedcutlet.yokan.services.discord
import eu.friedcutlet.yokan.database.DbDiscordAccount
import eu.friedcutlet.yokan.database.DbDiscordStatus
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.util.nowMillis
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession
import io.ktor.client.plugins.websocket.WebSockets
import io.ktor.client.plugins.websocket.webSocket
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.content.TextContent
import io.ktor.websocket.Frame
import io.ktor.websocket.readText
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put
/** Yokan's own Discord application; activities are attributed to it on every transport. */
internal const val DiscordApplicationId = "1395040506677039157"
private const val GatewayUrl = "wss://gateway.discord.gg/?v=10&encoding=json"
private const val ApiBase = "https://discord.com/api/v10"
/** Close codes after which retrying with the same token cannot succeed. */
private val FatalCloseCodes = setOf<Short>(4004, 4010, 4011, 4012, 4013, 4014)
private data class GatewayPresence(val activity: DiscordActivity?, val status: DbDiscordStatus)
/**
* Rich Presence through the Discord gateway with the user's own login token, so presence works
* where no local Discord client exposes IPC (Android, iOS, web, or desktop with a chosen account).
* Holds one websocket, re-sending the latest presence after every (re)connect.
*/
internal class DiscordGatewayClient(
private val token: String,
private val engine: HttpClientEngine,
private val scope: CoroutineScope,
private val onRejected: () -> Unit,
) {
private val client = HttpClient(engine) {
expectSuccess = false
install(WebSockets)
}
private val presence = MutableStateFlow<GatewayPresence?>(null)
private val _connected = MutableStateFlow(false)
val connected: StateFlow<Boolean> = _connected.asStateFlow()
// ponytail: unbounded per-session cache of cover URL → media proxy path; covers are few per session.
private val assets = mutableMapOf<String, String?>()
private var job: Job? = null
fun publish(activity: DiscordActivity?, status: DbDiscordStatus) {
presence.value = GatewayPresence(activity, status)
if (job == null) job = scope.launch { run() }
}
fun close() {
job?.cancel()
_connected.value = false
client.close()
engine.close()
}
private suspend fun run() {
var backoff = 2_000L
while (kotlinx.coroutines.currentCoroutineContext().isActive) {
var rejected = false
try {
client.webSocket(GatewayUrl) {
session()
rejected = closeReason.await()?.code in FatalCloseCodes
}
backoff = 2_000L
} catch (cancelled: CancellationException) {
throw cancelled
} catch (_: Throwable) {
// Network loss: reconnect below.
}
_connected.value = false
if (rejected) {
onRejected()
return
}
delay(backoff)
backoff = (backoff * 2).coerceAtMost(120_000L)
}
}
private suspend fun DefaultClientWebSocketSession.session() {
var sequence: Long? = null
var heartbeat: Job? = null
var sender: Job? = null
try {
for (frame in incoming) {
val message = (frame as? Frame.Text)?.readText()?.let { runCatching { Json.parseToJsonElement(it).jsonObject }.getOrNull() } ?: continue
message["s"]?.jsonPrimitive?.longOrNull?.let { sequence = it }
when (message["op"]?.jsonPrimitive?.intOrNull) {
10 -> {
val interval = message["d"]?.jsonObject?.get("heartbeat_interval")?.jsonPrimitive?.longOrNull ?: 41_250L
heartbeat = launch {
while (isActive) {
delay(interval)
send(Frame.Text(heartbeatPayload(sequence).toString()))
}
}
send(Frame.Text(gatewayIdentify(token).toString()))
}
1 -> send(Frame.Text(heartbeatPayload(sequence).toString()))
0 -> if (message["t"]?.jsonPrimitive?.contentOrNull == "READY" && sender == null) {
_connected.value = true
sender = launch {
presence.collect { next ->
next ?: return@collect
val cover = next.activity?.coverUrl?.let { mediaProxyAsset(it) }
send(Frame.Text(gatewayPresenceUpdate(next.activity, cover, next.status, nowMillis()).toString()))
}
}
}
// Reconnect request / invalid session: start over with a fresh identify.
7, 9 -> return
}
}
} finally {
heartbeat?.cancel()
sender?.cancel()
}
}
/** User-token presences only render images hosted on Discord's media proxy (`mp:`). Cancelled lookups are not cached. */
internal suspend fun mediaProxyAsset(url: String): String? {
if (url in assets) return assets[url]
val path = catchingNonCancellation {
val response = client.post("$ApiBase/applications/$DiscordApplicationId/external-assets") {
header(HttpHeaders.Authorization, token)
setBody(TextContent(buildJsonObject { put("urls", buildJsonArray { add(JsonPrimitive(url)) }) }.toString(), ContentType.Application.Json))
}
if (response.status.value in 200..299) parseExternalAssetPath(response.bodyAsText()) else null
}.getOrNull()
assets[url] = path
return path
}
}
internal fun heartbeatPayload(sequence: Long?): JsonObject = buildJsonObject {
put("op", 1)
put("d", sequence?.let(::JsonPrimitive) ?: JsonNull)
}
internal fun gatewayIdentify(token: String): JsonObject = buildJsonObject {
put("op", 2)
put("d", buildJsonObject {
put("token", token)
put("capabilities", 65)
put("compress", false)
put("properties", buildJsonObject {
put("os", "Windows")
put("browser", "Discord Client")
put("device", "Yokan")
})
})
}
/** Gateway op 3. User-token activities carry button labels and URLs in separate fields. */
internal fun gatewayPresenceUpdate(activity: DiscordActivity?, coverAsset: String?, status: DbDiscordStatus, sinceMillis: Long): JsonObject = buildJsonObject {
put("op", 3)
put("d", buildJsonObject {
put("since", sinceMillis)
put("afk", true)
put("status", status.gatewayValue)
put("activities", buildJsonArray {
if (activity != null) add(buildJsonObject {
put("name", "Yokan")
put("type", if (activity.watching) 3 else 0)
put("application_id", DiscordApplicationId)
put("details", activity.details)
put("state", activity.state)
activity.startedAtMillis?.let { start -> put("timestamps", buildJsonObject { put("start", start) }) }
if (coverAsset != null) put("assets", buildJsonObject {
put("large_image", coverAsset)
put("large_text", activity.details)
})
if (activity.buttons.isNotEmpty()) {
put("buttons", JsonArray(activity.buttons.map { JsonPrimitive(it.label.take(32)) }))
put("metadata", buildJsonObject { put("button_urls", JsonArray(activity.buttons.map { JsonPrimitive(it.url) })) })
}
})
})
})
}
internal fun parseExternalAssetPath(body: String): String? = runCatching {
val path = (Json.parseToJsonElement(body) as JsonArray).first().jsonObject["external_asset_path"]?.jsonPrimitive?.contentOrNull
path?.takeIf { it.isNotBlank() }?.let { "mp:$it" }
}.getOrNull()
class DiscordLoginException(message: String) : Exception(message)
/**
* Resolves the account behind [token]. When the profile lookup cannot be reached (offline, or a
* browser blocking the cross-origin call) the user id is read from the token's first segment;
* an explicit 401 means the token is wrong. Owns [engine].
*/
internal suspend fun resolveDiscordAccount(token: String, engine: HttpClientEngine): DbDiscordAccount {
val cleaned = token.trim().removeSurrounding("\"")
if (cleaned.isBlank()) throw DiscordLoginException("Discord token is empty.")
val client = HttpClient(engine) { expectSuccess = false }
val fromApi = try {
catchingNonCancellation {
val response = client.get("$ApiBase/users/@me") { header(HttpHeaders.Authorization, cleaned) }
if (response.status.value == 401) throw DiscordLoginException("Discord rejected this token.")
response.takeIf { it.status.value in 200..299 }?.bodyAsText()
}.onFailure { if (it is DiscordLoginException) throw it }.getOrNull()
} finally {
client.close()
engine.close()
}
return fromApi?.let { discordAccountFromProfile(it, cleaned) } ?: discordAccountFromToken(cleaned)
?: throw DiscordLoginException("Not a Discord token.")
}
internal fun discordAccountFromProfile(body: String, token: String): DbDiscordAccount? = runCatching {
val json = Json.parseToJsonElement(body).jsonObject
val id = json["id"]?.jsonPrimitive?.content ?: return@runCatching null
val username = json["username"]?.jsonPrimitive?.content ?: return@runCatching null
val avatar = json["avatar"]?.jsonPrimitive?.contentOrNull
DbDiscordAccount(
id = id,
username = username,
displayName = json["global_name"]?.jsonPrimitive?.contentOrNull ?: username,
avatarUrl = avatar?.let { "https://cdn.discordapp.com/avatars/$id/$it.png" },
token = token,
)
}.getOrNull()
/** A user token's first dot-separated segment is the base64 user id. */
@OptIn(ExperimentalEncodingApi::class)
internal fun discordAccountFromToken(token: String): DbDiscordAccount? {
val segment = token.substringBefore('.', missingDelimiterValue = "").takeIf { token.count { it == '.' } == 2 } ?: return null
val id = runCatching {
Base64.UrlSafe.withPadding(Base64.PaddingOption.PRESENT_OPTIONAL).decode(segment.replace('+', '-').replace('/', '_')).decodeToString()
}.getOrNull()?.takeIf { it.isNotEmpty() && it.all(Char::isDigit) } ?: return null
return DbDiscordAccount(id = id, username = "Discord user $id", token = token)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/discord/DiscordRpcService.kt
- Source · implementation · 89 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: data class DiscordRpcStatus(
19: interface DiscordRpcService {
20: fun initialize(settings: DbSettings): DiscordRpcStatus
21: fun showIdle(settings: DbSettings): DiscordRpcStatus
22: fun showActivity(settings: DbSettings, request: DiscordPresenceRequest): DiscordRpcStatus
23: fun shutdown()
24: fun status(): DiscordRpcStatus
27: expect fun createPlatformDiscordRpcService(): DiscordRpcService
30: class GatewayDiscordRpcService internal constructor(
43: override fun initialize(settings: DbSettings): DiscordRpcStatus = publish(settings, null)
44: override fun showIdle(settings: DbSettings): DiscordRpcStatus = publish(settings, null)
45: override fun showActivity(settings: DbSettings, request: DiscordPresenceRequest): DiscordRpcStatus = publish(settings, request)
47: override fun shutdown() = lock.withLock { closeClient() }
49: override fun status(): DiscordRpcStatus = lock.withLock {
53: internal fun publish(settings: DbSettings, request: DiscordPresenceRequest?): DiscordRpcStatus = lock.withLock {
84: private fun closeClient() {
Exact file bytes / download · SHA-256 a6a81913f874ca6cde99db5e1cb0ba679e701fe8504cfdd5b7f6d7000bae94c6.
Complete file
package eu.friedcutlet.yokan.services.discord
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.http.createDefaultPlatformHttpClientEngine
import eu.friedcutlet.yokan.util.PlatformLock
import eu.friedcutlet.yokan.util.nowMillis
import io.ktor.client.engine.HttpClientEngine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
data class DiscordRpcStatus(
val supported: Boolean,
val enabled: Boolean,
val connected: Boolean,
val message: String,
)
interface DiscordRpcService {
fun initialize(settings: DbSettings): DiscordRpcStatus
fun showIdle(settings: DbSettings): DiscordRpcStatus
fun showActivity(settings: DbSettings, request: DiscordPresenceRequest): DiscordRpcStatus
fun shutdown()
fun status(): DiscordRpcStatus
}
expect fun createPlatformDiscordRpcService(): DiscordRpcService
/** Presence through the active Discord account's gateway session; shared by every platform. */
class GatewayDiscordRpcService internal constructor(
private val engineFactory: () -> HttpClientEngine,
private val scope: CoroutineScope,
) : DiscordRpcService {
constructor() : this(::createDefaultPlatformHttpClientEngine, CoroutineScope(SupervisorJob() + Dispatchers.Default))
private val lock = PlatformLock()
private val startedAt = nowMillis()
private var client: DiscordGatewayClient? = null
private var clientToken: String? = null
private var rejectedToken: String? = null
private var current = DiscordRpcStatus(true, enabled = false, connected = false, message = "Discord presence not initialized.")
override fun initialize(settings: DbSettings): DiscordRpcStatus = publish(settings, null)
override fun showIdle(settings: DbSettings): DiscordRpcStatus = publish(settings, null)
override fun showActivity(settings: DbSettings, request: DiscordPresenceRequest): DiscordRpcStatus = publish(settings, request)
override fun shutdown() = lock.withLock { closeClient() }
override fun status(): DiscordRpcStatus = lock.withLock {
current.copy(connected = client?.connected?.value == true)
}
internal fun publish(settings: DbSettings, request: DiscordPresenceRequest?): DiscordRpcStatus = lock.withLock {
val account = settings.features.discord.activeAccount
current = when {
!settings.enableDiscordRpc -> {
closeClient()
DiscordRpcStatus(true, enabled = false, connected = false, message = "Discord presence disabled in settings.")
}
account == null -> {
closeClient()
DiscordRpcStatus(true, enabled = true, connected = false, message = "Log in to a Discord account to show presence.")
}
account.token == rejectedToken -> {
closeClient()
DiscordRpcStatus(true, enabled = true, connected = false, message = "Discord rejected ${account.displayName}'s login; log in again.")
}
else -> {
if (clientToken != account.token) {
closeClient()
val token = account.token
client = DiscordGatewayClient(token, engineFactory(), scope) {
lock.withLock { if (clientToken == token) rejectedToken = token }
}
clientToken = token
}
checkNotNull(client).publish(discordActivity(settings, request, startedAt), settings.features.discord.status)
DiscordRpcStatus(true, enabled = true, connected = client?.connected?.value == true, message = "Discord presence for ${account.displayName}.")
}
}
current
}
private fun closeClient() {
client?.close()
client = null
clientToken = null
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/logging/CrashReportStore.kt
- Source · implementation · 30 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: object CrashReportStore {
9: fun record(files: LocalFileService, throwable: Throwable) {
14: fun read(files: LocalFileService): String? = runCatching {
19: fun delete(files: LocalFileService) {
23: internal fun redact(value: String): String = value
28: private fun CrashReportPath(files: LocalFileService): String =
Exact file bytes / download · SHA-256 ea110cfc7db4fe1d4bd4d260794729cf77ec8293a2696a2b502b2a3aaffc482b.
Complete file
package eu.friedcutlet.yokan.services.logging
import eu.friedcutlet.yokan.services.files.LocalFileService
private const val CrashReportPath = "crash/latest.txt"
private const val MaxCrashReportBytes = 32 * 1024
object CrashReportStore {
fun record(files: LocalFileService, throwable: Throwable) {
val report = redact(throwable.stackTraceToString()).encodeToByteArray()
files.writeBytes(CrashReportPath(files), report.copyOf(report.size.coerceAtMost(MaxCrashReportBytes)))
}
fun read(files: LocalFileService): String? = runCatching {
files.readBytes(CrashReportPath(files)).decodeToString()
.takeIf { it.isNotBlank() }
}.getOrNull()
fun delete(files: LocalFileService) {
runCatching { files.deleteRecursively(CrashReportPath(files)) }
}
internal fun redact(value: String): String = value
.replace(Regex("(?im)(authorization\\s*[:=]\\s*(?:bearer\\s+)?)[^\\s]+"), "$1[REDACTED]")
.replace(Regex("(?i)(password|token|access_token|refresh_token)(\\s*[:=]\\s*)[^\\s,;]+"), "$1$2[REDACTED]")
.replace(Regex("(?i)([?&](?:token|password|access_token|refresh_token)=)[^&\\s]+"), "$1[REDACTED]")
private fun CrashReportPath(files: LocalFileService): String =
"${files.cacheRoot.trimEnd('/', 92.toChar())}/$CrashReportPath"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/logging/Diagnostics.kt
- Source · implementation · 47 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
9: internal data class NetworkStats(
18: internal data class ImageStats(
28: internal object Diagnostics {
37: fun recordResponse(statusCode: Int, bytes: Long) = _network.update {
41: fun recordRequestFailure() = _network.update { it.copy(requests = it.requests + 1, failures = it.failures + 1) }
43: fun recordImageMemoryHit() = _images.update { it.copy(memoryHits = it.memoryHits + 1) }
44: fun recordImageDiskHit() = _images.update { it.copy(diskHits = it.diskHits + 1) }
45: fun recordImageNetworkLoad() = _images.update { it.copy(networkLoads = it.networkLoads + 1) }
46: fun recordImageError() = _images.update { it.copy(errors = it.errors + 1) }
Exact file bytes / download · SHA-256 a2eb8e4b800adffcd522c32d83f2d9685d2ff7a2d1e4c235b77570a141070c50.
Complete file
package eu.friedcutlet.yokan.services.logging
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
internal data class NetworkStats(
val requests: Long = 0,
/** Transport failures (DNS, connect, timeout, cancellation), not HTTP status codes. */
val failures: Long = 0,
/** Responses outside 200..399. */
val httpErrors: Long = 0,
val bytesReceived: Long = 0,
)
internal data class ImageStats(
val memoryHits: Long = 0,
val diskHits: Long = 0,
val networkLoads: Long = 0,
val errors: Long = 0,
) {
val loads: Long get() = memoryHits + diskHits + networkLoads
}
/** Process-lifetime counters for Settings → Developer. Lock-free; they only ever grow. */
internal object Diagnostics {
val startedAtMillis: Long = nowMillis()
private val _network = MutableStateFlow(NetworkStats())
val network: StateFlow<NetworkStats> = _network.asStateFlow()
private val _images = MutableStateFlow(ImageStats())
val images: StateFlow<ImageStats> = _images.asStateFlow()
fun recordResponse(statusCode: Int, bytes: Long) = _network.update {
it.copy(requests = it.requests + 1, httpErrors = it.httpErrors + if (statusCode in 200..399) 0 else 1, bytesReceived = it.bytesReceived + bytes)
}
fun recordRequestFailure() = _network.update { it.copy(requests = it.requests + 1, failures = it.failures + 1) }
fun recordImageMemoryHit() = _images.update { it.copy(memoryHits = it.memoryHits + 1) }
fun recordImageDiskHit() = _images.update { it.copy(diskHits = it.diskHits + 1) }
fun recordImageNetworkLoad() = _images.update { it.copy(networkLoads = it.networkLoads + 1) }
fun recordImageError() = _images.update { it.copy(errors = it.errors + 1) }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/logging/LogSink.kt
- Source · implementation · 150 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: internal data class LogEntry(val seq: Long, val timeMillis: Long, val level: String, val message: String) {
14: fun format(): String = "${formatLogTimestamp(timeMillis)} $level: $message"
32: internal object LogSink {
46: private class FileTarget(val files: LocalFileService, val path: String, val enabled: () -> Boolean) {
56: fun attach(files: LocalFileService, fileLoggingEnabled: () -> Boolean): Any? {
62: fun detach(token: Any?) = fileLock.withLock {
66: fun write(level: String, message: String) {
90: fun recentEntries(): List<LogEntry> = memoryLock.withLock { recent.toList() }
91: fun problemEntries(): List<LogEntry> = memoryLock.withLock { problems.toList() }
93: fun clearMemory() {
101: fun logFilePath(): String? = target?.path
104: fun logFileBytes(): Long {
111: private fun <T> ArrayDeque<T>.addBounded(value: T, max: Int) {
118: internal fun formatLogTimestamp(timeMillis: Long): String {
135: internal fun rotatedLogPath(path: String) = "$path.1"
142: internal fun appendRotatingLog(files: LocalFileService, path: String, knownSize: Long, bytes: ByteArray, maxBytes: Long = LogSink.MaxLogFileBytes): Long {
Exact file bytes / download · SHA-256 8bfed65d228d40eb5b052c63e5c247eb43bd207f2fb186533cb4c204ebb5d5d9.
Complete file
package eu.friedcutlet.yokan.services.logging
import eu.friedcutlet.yokan.util.nowMillis
import eu.friedcutlet.yokan.util.PlatformLock
import eu.friedcutlet.yokan.services.files.LocalFileService
import kotlin.concurrent.Volatile
import kotlin.time.ExperimentalTime
import kotlin.time.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
/** [seq] is unique and increasing for the process, so UIs can key rows by it. */
internal data class LogEntry(val seq: Long, val timeMillis: Long, val level: String, val message: String) {
fun format(): String = "${formatLogTimestamp(timeMillis)} $level: $message"
}
/**
* Single sink for every log line produced by [AppLogger], `ExtensionLogger`,
* and the HTTP-request logger. Secrets matching [CrashReportStore.redact] are masked first.
*
* Behavior:
* - Always println to stdout, so logs are visible in the platform console
* (terminal on desktop, `adb logcat -s System.out` on Android, Xcode
* console on iOS).
* - Keeps the last [MaxRecentEntries] lines, plus the last [MaxProblemEntries] warnings and
* errors, in memory for the Developer settings screen.
* - Once [attach]ed and while the file-logging setting is on (off by default),
* also appends to `LocalFileService.cacheRoot/logs/yokan.log`. When that file passes
* [MaxLogFileBytes] it becomes `yokan.log.1` (replacing the previous one), so logs on disk
* never exceed about twice that size.
*/
internal object LogSink {
private const val LOG_RELATIVE_PATH = "logs/yokan.log"
const val MaxLogFileBytes = 1024L * 1024
const val MaxRecentEntries = 500
const val MaxProblemEntries = 200
private const val MaxLogMessageChars = 16 * 1024
private const val TruncatedMessageMarker = "…[truncated]"
private val fileLock = PlatformLock()
private val memoryLock = PlatformLock()
private val recent = ArrayDeque<LogEntry>(MaxRecentEntries)
private val problems = ArrayDeque<LogEntry>(MaxProblemEntries)
private var nextSeq = 0L
private class FileTarget(val files: LocalFileService, val path: String, val enabled: () -> Boolean) {
/** Unknown until the first append in this process; then tracked without touching the disk. */
var sizeBytes = -1L
}
// Set once by the composition root; until then lines only reach stdout and memory.
@Volatile
private var target: FileTarget? = null
/** [fileLoggingEnabled] runs for every line, so it must be cheap and must not take locks. */
fun attach(files: LocalFileService, fileLoggingEnabled: () -> Boolean): Any? {
val path = runCatching { "${files.cacheRoot.trimEnd('/')}/$LOG_RELATIVE_PATH" }.getOrNull() ?: return null
return fileLock.withLock { FileTarget(files, path, fileLoggingEnabled).also { target = it } }
}
/** Retiring an old owner cannot detach a later session's file target. */
fun detach(token: Any?) = fileLock.withLock {
if (target === token) target = null
}
fun write(level: String, message: String) {
val redacted = CrashReportStore.redact(message)
val boundedMessage = if (redacted.length > MaxLogMessageChars) {
redacted.take(MaxLogMessageChars - TruncatedMessageMarker.length) + TruncatedMessageMarker
} else {
redacted
}
val entry = memoryLock.withLock {
LogEntry(nextSeq++, nowMillis(), level.take(32), boundedMessage).also {
recent.addBounded(it, MaxRecentEntries)
if (level != "INFO") problems.addBounded(it, MaxProblemEntries)
}
}
val line = entry.format()
println("[yokan] $line")
val sink = target ?: return
if (runCatching(sink.enabled).getOrDefault(false)) {
fileLock.withLock {
if (target !== sink) return@withLock
runCatching { sink.sizeBytes = appendRotatingLog(sink.files, sink.path, sink.sizeBytes, (line + "\n").encodeToByteArray()) }
}
}
}
fun recentEntries(): List<LogEntry> = memoryLock.withLock { recent.toList() }
fun problemEntries(): List<LogEntry> = memoryLock.withLock { problems.toList() }
fun clearMemory() {
memoryLock.withLock {
recent.clear()
problems.clear()
}
}
/** Returns the path of the on-disk log file, regardless of whether logging is on. */
fun logFilePath(): String? = target?.path
/** Bytes currently on disk for the log and its rotated predecessor. */
fun logFileBytes(): Long {
val sink = target ?: return 0L
return fileLock.withLock {
runCatching { sink.files.directorySize(sink.path) + sink.files.directorySize(rotatedLogPath(sink.path)) }.getOrDefault(0L)
}
}
private fun <T> ArrayDeque<T>.addBounded(value: T, max: Int) {
if (size == max) removeFirst()
addLast(value)
}
}
@OptIn(ExperimentalTime::class)
internal fun formatLogTimestamp(timeMillis: Long): String {
val local = Instant.fromEpochMilliseconds(timeMillis).toLocalDateTime(TimeZone.currentSystemDefault())
return buildString {
append(local.year.toString().padStart(4, '0'))
append('-')
append((local.month.ordinal + 1).toString().padStart(2, '0'))
append('-')
append(local.day.toString().padStart(2, '0'))
append(' ')
append(local.hour.toString().padStart(2, '0'))
append(':')
append(local.minute.toString().padStart(2, '0'))
append(':')
append(local.second.toString().padStart(2, '0'))
}
}
internal fun rotatedLogPath(path: String) = "$path.1"
/**
* Appends [bytes] to [path] (streaming; the history is never read), first moving the file to
* [rotatedLogPath] when the append would pass [maxBytes]. [knownSize] < 0 means "stat the file";
* returns the size after the append so callers can track it without touching the disk.
*/
internal fun appendRotatingLog(files: LocalFileService, path: String, knownSize: Long, bytes: ByteArray, maxBytes: Long = LogSink.MaxLogFileBytes): Long {
val size = if (knownSize < 0) files.directorySize(path) else knownSize
if (bytes.size.toLong() > maxBytes) return size
val exceedsCap = size > 0 && size > maxBytes - bytes.size
if (exceedsCap && !files.promote(path, rotatedLogPath(path))) return size
val base = if (exceedsCap) 0L else size
files.appendBytes(path, bytes)
return base + bytes.size
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/logging/Logging.kt
- Source · implementation · 36 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: object AppLogger {
12: fun info(message: String) = LogSink.write("INFO", message)
13: fun warn(message: String) = LogSink.write("WARN", message)
14: fun error(message: String) = LogSink.write("ERROR", message)
17: internal fun redactUrlForLog(url: String, maxLength: Int = 180): String {
Exact file bytes / download · SHA-256 a6d5155c061e2d05c82146d16795c36f5b31e33cade1e8acdd31334225caa751.
Complete file
package eu.friedcutlet.yokan.services.logging
import eu.friedcutlet.yokan.services.files.LocalFileService
import kotlinx.datetime.plus
/**
* Public logging surface for the app. Delegates to [LogSink]: stdout always, a bounded in-memory
* buffer for Settings → Developer, and an opt-in, size-capped log file under
* [LocalFileService.cacheRoot] (the About screen's `Logs on` setting).
*/
object AppLogger {
fun info(message: String) = LogSink.write("INFO", message)
fun warn(message: String) = LogSink.write("WARN", message)
fun error(message: String) = LogSink.write("ERROR", message)
}
internal fun redactUrlForLog(url: String, maxLength: Int = 180): String {
val cleaned = url.trim().substringBefore("#")
val withoutQuery = cleaned.substringBefore("?")
val redactedPath = withoutQuery.indexOf("://")
.takeIf { it >= 0 }
?.let { schemeIndex ->
val pathStart = withoutQuery.indexOf('/', startIndex = schemeIndex + 3)
if (pathStart < 0) {
withoutQuery
} else {
val origin = withoutQuery.take(pathStart)
val path = withoutQuery.drop(pathStart)
val fileName = path.substringAfterLast('/').takeIf { it.isNotBlank() }
if (path.count { it == '/' } > 1 && fileName != null) "$origin/.../$fileName" else withoutQuery
}
}
?: withoutQuery
val redacted = redactedPath + if ("?" in cleaned) "?..." else ""
return if (redacted.length <= maxLength) redacted else redacted.take((maxLength - 3).coerceAtLeast(0)) + "..."
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/notifications/InAppNotifications.kt
- Source · implementation · 44 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
9: data class InAppMessage(
15: fun visibleTo(id: ProfileId): Boolean = profileId == null || profileId == id
27: object InAppNotifications {
33: fun post(message: InAppMessage) {
37: fun post(title: String, message: String = "", channel: NotificationChannel? = null) {
41: fun post(payload: NotificationPayload) {
Exact file bytes / download · SHA-256 8d80095551665eb98d6ef65cc7ad87848c3e7422c3de645a0eeae3517a2ccb13.
Complete file
package eu.friedcutlet.yokan.services.notifications
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import eu.friedcutlet.yokan.domain.ProfileId
/** A message surfaced as an in-app snackbar/toast. */
data class InAppMessage(
val title: String,
val message: String,
val channel: NotificationChannel? = null,
val profileId: ProfileId? = null,
) {
fun visibleTo(id: ProfileId): Boolean = profileId == null || profileId == id
}
/**
* App-wide bus for transient in-app messages. The root composable collects
* [messages] and shows them through a Material 3 SnackbarHost, so toasts render
* inside the app instead of relying on OS-level popups (which on Linux showed
* stale/duplicate system-tray balloons).
*
* It lives in the service layer so background, non-UI code (notification
* services, download/update workers) can post without depending on Compose.
*/
object InAppNotifications {
// A small replay-less buffer so emits from background threads aren't dropped
// before the UI starts collecting.
private val _messages = MutableSharedFlow<InAppMessage>(extraBufferCapacity = 32)
val messages: SharedFlow<InAppMessage> = _messages.asSharedFlow()
fun post(message: InAppMessage) {
_messages.tryEmit(message)
}
fun post(title: String, message: String = "", channel: NotificationChannel? = null) {
_messages.tryEmit(InAppMessage(title, message, channel))
}
fun post(payload: NotificationPayload) {
_messages.tryEmit(InAppMessage(payload.title, payload.message, payload.channel, payload.profileId))
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/notifications/NotificationService.kt
- Source · implementation · 26 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
4: enum class NotificationChannel {
11: data class NotificationPayload(
19: interface NotificationService {
20: fun supported(): Boolean
21: fun requestPermission() = Unit
22: fun notify(payload: NotificationPayload)
23: fun cancel(channel: NotificationChannel, tag: String? = null)
26: expect fun createPlatformNotificationService(profileId: ProfileId = ProfileId.Default): NotificationService
Exact file bytes / download · SHA-256 f45d1a5801437a9e121c18967c4095b644c6acf995588121c7e22e5d403feb83.
Complete file
package eu.friedcutlet.yokan.services.notifications
import eu.friedcutlet.yokan.domain.ProfileId
enum class NotificationChannel {
Downloads,
LibraryUpdates,
Backup,
Sync,
}
data class NotificationPayload(
val channel: NotificationChannel,
val title: String,
val message: String,
val tag: String? = null,
val profileId: ProfileId? = null,
)
interface NotificationService {
fun supported(): Boolean
fun requestPermission() = Unit
fun notify(payload: NotificationPayload)
fun cancel(channel: NotificationChannel, tag: String? = null)
}
expect fun createPlatformNotificationService(profileId: ProfileId = ProfileId.Default): NotificationService
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/notifications/ProfileNotifications.kt
- Source · implementation · 51 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: internal data class ProfileNotificationNamespace(val id: ProfileId) {
7: private fun owned(channel: NotificationChannel, tag: String?): String =
10: fun androidTag(channel: NotificationChannel, tag: String?): String? =
13: fun androidId(legacyChannelId: String, tag: String?): Int =
16: fun iosIdentifier(channel: NotificationChannel, tag: String?): String =
24: internal class ProfileNotificationService(
30: override fun supported(): Boolean = isOpen() && delegate.supported()
31: override fun requestPermission() { if (isOpen()) delegate.requestPermission() }
32: override fun notify(payload: NotificationPayload) {
37: override fun cancel(channel: NotificationChannel, tag: String?) {
43: internal fun NotificationPayload.redacted(): NotificationPayload = copy(
Exact file bytes / download · SHA-256 ab2d0ef2485cf5bea7938fb749121ed95ace78c726580b068fc32b605f0cf6ae.
Complete file
package eu.friedcutlet.yokan.services.notifications
import eu.friedcutlet.yokan.domain.ProfileId
/** Default adopts existing OS notifications. Extra owners use full string identities, not hashes. */
internal data class ProfileNotificationNamespace(val id: ProfileId) {
private fun owned(channel: NotificationChannel, tag: String?): String =
"yokan.profile.${id.value}.${channel.name.lowercase()}.${tag.orEmpty().length}:${tag.orEmpty()}"
fun androidTag(channel: NotificationChannel, tag: String?): String? =
if (id == ProfileId.Default) null else owned(channel, tag)
fun androidId(legacyChannelId: String, tag: String?): Int =
if (id == ProfileId.Default) (legacyChannelId + tag.orEmpty()).hashCode() else 0
fun iosIdentifier(channel: NotificationChannel, tag: String?): String =
if (id == ProfileId.Default) "yokan.${channel.name.lowercase()}.${tag.orEmpty()}" else owned(channel, tag)
}
/**
* Captured stale references cannot post, cancel or request permissions after owner retirement.
* [hideContent] (Security → hide notification content) swaps titles for generic text on every platform.
*/
internal class ProfileNotificationService(
private val id: ProfileId,
private val delegate: NotificationService,
private val hideContent: () -> Boolean = { false },
private val isOpen: () -> Boolean,
) : NotificationService {
override fun supported(): Boolean = isOpen() && delegate.supported()
override fun requestPermission() { if (isOpen()) delegate.requestPermission() }
override fun notify(payload: NotificationPayload) {
if (!isOpen()) return
val shown = if (hideContent()) payload.redacted() else payload
delegate.notify(shown.copy(profileId = id))
}
override fun cancel(channel: NotificationChannel, tag: String?) {
if (isOpen()) delegate.cancel(channel, tag)
}
}
/** Keeps the channel and tag (so updates/cancels still match) but drops titles and details. */
internal fun NotificationPayload.redacted(): NotificationPayload = copy(
title = "Yokan",
message = when (channel) {
NotificationChannel.Downloads -> "Download activity"
NotificationChannel.LibraryUpdates -> "Library update"
NotificationChannel.Backup -> "Backup activity"
NotificationChannel.Sync -> "Sync activity"
},
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/scheduling/AutomaticUpdateGate.kt
- Source · implementation · 114 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
16: data class UpdateDeviceConditions(
23: enum class UpdateDeferral {
28: data class UpdateAdmission(val reasons: Set<UpdateDeferral> = emptySet(), val checkedAt: Long = 0) {
32: internal fun evaluateUpdateConstraints(
75: class AutomaticUpdateGate(
90: suspend fun check(settings: DbSettings, force: Boolean = false): UpdateAdmission = mutex.withLock {
114: expect suspend fun readUpdateDeviceConditions(needPower: Boolean = true): UpdateDeviceConditions
Exact file bytes / download · SHA-256 4d94fa93c60117cbbb3144e73aaa6f133b8fc98120595df0a82d635cceb17cee.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.system.isOnUnmeteredNetwork
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.Serializable
/** Nullable readings explicitly represent unavailable, denied or timed-out device APIs. */
@Serializable
data class UpdateDeviceConditions(
val connected: Boolean? = null,
val wifi: Boolean? = null,
val unmetered: Boolean? = null,
val externalPower: Boolean? = null,
)
enum class UpdateDeferral {
NetworkUnavailable, NetworkUnknown, WifiRequired, WifiUnknown,
UnmeteredRequired, NetworkCostUnknown, PowerRequired, PowerUnknown,
}
data class UpdateAdmission(val reasons: Set<UpdateDeferral> = emptySet(), val checkedAt: Long = 0) {
val allowed: Boolean get() = reasons.isEmpty()
}
internal fun evaluateUpdateConstraints(
constraints: DbAutomaticUpdateConstraints,
readings: UpdateDeviceConditions,
legacyAllowed: Boolean,
): UpdateAdmission {
val reasons = mutableSetOf<UpdateDeferral>()
if (constraints.network == DbUpdateNetwork.Legacy) {
if (!legacyAllowed) reasons += UpdateDeferral.UnmeteredRequired
} else {
when (readings.connected) {
false -> reasons += UpdateDeferral.NetworkUnavailable
null -> reasons += UpdateDeferral.NetworkUnknown
true -> when (constraints.network) {
DbUpdateNetwork.Wifi -> when (readings.wifi) {
false -> reasons += UpdateDeferral.WifiRequired
null -> reasons += UpdateDeferral.WifiUnknown
true -> Unit
}
DbUpdateNetwork.Unmetered -> {
val cost = readings.unmetered ?: when (constraints.unknownNetworkCost) {
DbUnknownNetworkCost.Wait -> null
DbUnknownNetworkCost.Metered -> false
DbUnknownNetworkCost.Unmetered -> true
}
when (cost) {
false -> reasons += UpdateDeferral.UnmeteredRequired
null -> reasons += UpdateDeferral.NetworkCostUnknown
true -> Unit
}
}
else -> Unit
}
}
}
if (constraints.requireExternalPower) when (readings.externalPower) {
false -> reasons += UpdateDeferral.PowerRequired
null -> reasons += UpdateDeferral.PowerUnknown
true -> Unit
}
return UpdateAdmission(reasons)
}
/** Profile-owned, serialized, short-lived cache. Construction makes no platform calls. */
class AutomaticUpdateGate(
private val read: suspend (needPower: Boolean) -> UpdateDeviceConditions = ::readUpdateDeviceConditions,
private val legacyNetwork: () -> Boolean = ::isOnUnmeteredNetwork,
private val clock: () -> Long = ::nowMillis,
private val cacheMillis: Long = 5_000,
) {
private val mutex = Mutex()
private var readings = UpdateDeviceConditions()
private var sampledAt: Long? = null
private var sampledPower = false
private var legacySampledAt: Long? = null
private var legacyUnmetered = false
private val _status = MutableStateFlow<UpdateAdmission?>(null)
val status: StateFlow<UpdateAdmission?> = _status.asStateFlow()
suspend fun check(settings: DbSettings, force: Boolean = false): UpdateAdmission = mutex.withLock {
val constraints = settings.features.library.deviceConstraints
val needsReadings = constraints.network != DbUpdateNetwork.Legacy || constraints.requireExternalPower
val now = clock()
val age = sampledAt?.let { now - it }
if (needsReadings && (force || age == null || age < 0 || age >= cacheMillis || (constraints.requireExternalPower && !sampledPower))) {
readings = catchingNonCancellation { read(constraints.requireExternalPower) }.getOrElse { UpdateDeviceConditions() }
sampledAt = clock()
sampledPower = constraints.requireExternalPower
}
if (constraints.network == DbUpdateNetwork.Legacy && settings.downloadOnlyOnWifi) {
val legacyAge = legacySampledAt?.let { now - it }
if (force || legacyAge == null || legacyAge < 0 || legacyAge >= cacheMillis) {
legacyUnmetered = catchingNonCancellation { legacyNetwork() }.getOrDefault(false)
legacySampledAt = clock()
}
}
val legacyAllowed = constraints.network != DbUpdateNetwork.Legacy || !settings.downloadOnlyOnWifi || legacyUnmetered
val checkedAt = if (needsReadings) sampledAt ?: 0 else if (settings.downloadOnlyOnWifi) legacySampledAt ?: 0 else 0
evaluateUpdateConstraints(constraints, readings, legacyAllowed).copy(checkedAt = checkedAt).also { _status.value = it }
}
}
/** Each target returns real available readings; unsupported readings remain null. */
expect suspend fun readUpdateDeviceConditions(needPower: Boolean = true): UpdateDeviceConditions
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundScheduler.kt
- Source · implementation · 85 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: internal fun periodicMinutes(seconds: Int): Long =
20: internal fun latestDailySlotMillis(
36: internal fun nextDailySlotDelayMillis(
46: internal fun backupFrequencyHours(value: Int?): Long = when (value) {
59: interface BackgroundScheduler {
61: fun schedule(
71: fun cancelAll()
74: expect fun createPlatformBackgroundScheduler(
Exact file bytes / download · SHA-256 475aa7f2d38861c109c7145b96d1bc540be64e78d5b9827af6310a87bc34435c.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.util.nowMillis
import kotlin.time.Instant
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atTime
import kotlinx.datetime.minus
import kotlinx.datetime.plus
import kotlinx.datetime.toInstant
import kotlinx.datetime.toLocalDateTime
internal fun periodicMinutes(seconds: Int): Long =
if (seconds <= 0) 0L else ((seconds + 59L) / 60L).coerceAtLeast(15L)
/** Epoch millis of the most recent occurrence of [dailyAtMinutes] (local time) at or before [now]. */
@OptIn(kotlin.time.ExperimentalTime::class)
internal fun latestDailySlotMillis(
dailyAtMinutes: Int,
now: Long = nowMillis(),
zone: TimeZone = TimeZone.currentSystemDefault(),
): Long {
val today = Instant.fromEpochMilliseconds(now).toLocalDateTime(zone).date
val slotToday = today.atTime(dailyAtMinutes / 60, dailyAtMinutes % 60).toInstant(zone).toEpochMilliseconds()
return if (slotToday <= now) {
slotToday
} else {
today.minus(1, DateTimeUnit.DAY).atTime(dailyAtMinutes / 60, dailyAtMinutes % 60).toInstant(zone).toEpochMilliseconds()
}
}
/** Millis until the next occurrence of [dailyAtMinutes] strictly after [now]. */
@OptIn(kotlin.time.ExperimentalTime::class)
internal fun nextDailySlotDelayMillis(
dailyAtMinutes: Int,
now: Long = nowMillis(),
zone: TimeZone = TimeZone.currentSystemDefault(),
): Long {
val last = Instant.fromEpochMilliseconds(latestDailySlotMillis(dailyAtMinutes, now, zone)).toLocalDateTime(zone)
return last.date.plus(1, DateTimeUnit.DAY).atTime(last.hour, last.minute).toInstant(zone).toEpochMilliseconds() - now
}
/** UI values 1..5 mean 6h / 12h / daily / 2 days / weekly. */
internal fun backupFrequencyHours(value: Int?): Long = when (value) {
1 -> 6L
2 -> 12L
3 -> 24L
4 -> 48L
5 -> 168L
else -> 0L
}
/**
* Periodic OS-level background workers. Android uses WorkManager, iOS uses
* BGTaskScheduler, and desktop/web rely on [ForegroundScheduler] while open.
*/
interface BackgroundScheduler {
/** [libraryUpdateDailyAtMinutes] >= 0 anchors the library update to that local time of day; else repeat every [libraryUpdateMinutes]. */
fun schedule(
metadataRefreshMinutes: Long,
libraryUpdateMinutes: Long,
libraryUpdateDailyAtMinutes: Int,
autoSyncMinutes: Long,
autoBackupHours: Long,
requireUnmetered: Boolean,
libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints = eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints(),
)
fun cancelAll()
}
expect fun createPlatformBackgroundScheduler(
database: YokanDatabase,
profileId: ProfileId = ProfileId.Default,
): BackgroundScheduler
/** Stale owners are terminal no-ops; unreadable registry metadata is recoverable. */
val ProfileWorkResult<PeriodicTaskOutcome>.shouldRetry: Boolean
get() = when (this) {
is ProfileWorkResult.Completed -> value.shouldRetry
ProfileWorkResult.Skipped -> false
ProfileWorkResult.Retry -> true
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundTaskCompletion.kt
- Source · implementation · 23 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: internal fun launchCompletingBackgroundTask(
Exact file bytes / download · SHA-256 65959df24aaec820661877953d4df0288b4e7c76c9f2f307dc3b66ee8f50f28c.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.services.catchingNonCancellation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/** Completes even when expiry cancels a callback before dispatch, and only after its cleanup joins. */
internal fun launchCompletingBackgroundTask(
scope: CoroutineScope,
run: suspend () -> ProfileWorkResult<PeriodicTaskOutcome>,
complete: (Boolean) -> Unit,
): Job {
val succeeded = MutableStateFlow(false)
val job = scope.launch {
val outcome = catchingNonCancellation { run() }.getOrNull()
succeeded.update { outcome?.shouldRetry == false }
}
job.invokeOnCompletion { cause -> complete(cause == null && succeeded.value) }
return job
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/scheduling/ForegroundScheduler.kt
- Source · implementation · 109 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: class ForegroundScheduler(
28: fun start() {
40: fun stop() {
45: private suspend fun tick(lastRun: LastRun) {
81: private suspend fun attempt(label: String, task: suspend () -> PeriodicTaskOutcome): Boolean =
87: private fun shouldRun(seconds: Int, last: Long): Boolean =
91: private fun shouldRunLibraryUpdate(settings: DbSettings, last: Long, startedAt: Long): Boolean {
97: private fun shouldRunBackup(settings: DbSettings, last: Long): Boolean {
103: private class LastRun(val startedAt: Long) {
Exact file bytes / download · SHA-256 c729a6d66f816b8983b6729a54a1b7764a2193c8920a07394268822aa2a4f749.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.system.isOnUnmeteredNetwork
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* Process-local fallback for desktop/web and an immediate in-app companion to
* OS background schedulers. Every completed task uses [PeriodicTaskRunner], so
* foreground and background executions produce the same result notification.
*
* The ticker runs in the owner's [scope]; cancelling it stops the scheduler.
*/
class ForegroundScheduler(
private val database: YokanDatabase,
private val periodicTasks: PeriodicTaskRunner,
private val scope: CoroutineScope,
) {
private var job: Job? = null
fun start() {
if (job?.isActive == true) return
job = scope.launch {
val lastRun = LastRun(startedAt = nowMillis())
while (true) {
catchingNonCancellation { tick(lastRun) }
.onFailure { AppLogger.warn("ForegroundScheduler tick failed: ${it.message.orEmpty()}") }
delay(60_000)
}
}
}
fun stop() {
job?.cancel()
job = null
}
private suspend fun tick(lastRun: LastRun) {
val settings = database.settings()
val networkAllowed = !settings.downloadOnlyOnWifi || isOnUnmeteredNetwork()
if (
networkAllowed &&
settings.metadataServerEnabled &&
shouldRun(settings.metadataRefreshFrequencySeconds, lastRun.metadataRefresh)
) {
if (attempt("Metadata refresh") { periodicTasks.refreshMetadata() }) lastRun.metadataRefresh = nowMillis()
}
// Library-specific admission belongs to the shared runner, including explicit overrides.
if (shouldRunLibraryUpdate(settings, lastRun.libraryUpdate, lastRun.startedAt)) {
if (attempt("Library update") { periodicTasks.updateLibrary() }) lastRun.libraryUpdate = nowMillis()
}
if (shouldRunBackup(settings, lastRun.backup)) {
if (attempt("Automatic backup") { periodicTasks.backup() }) lastRun.backup = nowMillis()
}
val syncPreference = database.syncPreferences().firstOrNull()
if (
networkAllowed &&
syncPreference?.syncOn == true &&
!syncPreference.authToken.isNullOrBlank() &&
shouldRun(syncPreference.autoSyncFrequency, lastRun.sync)
) {
if (attempt("Automatic sync") { periodicTasks.sync() }) lastRun.sync = nowMillis()
}
if (!networkAllowed) {
AppLogger.info("ForegroundScheduler skipped network work: metered connection while downloadOnlyOnWifi is on.")
}
}
/**
* Runs one task in isolation so its failure neither skips the others nor resets their
* timestamps. A task that throws still counts as attempted and waits for its next slot
* instead of re-running every tick.
*/
private suspend fun attempt(label: String, task: suspend () -> PeriodicTaskOutcome): Boolean =
catchingNonCancellation { task().attempted }.getOrElse { error ->
AppLogger.warn("$label failed: ${error.message.orEmpty()}")
true
}
private fun shouldRun(seconds: Int, last: Long): Boolean =
seconds > 0 && nowMillis() - last >= seconds.toLong() * 1000L
/** Daily mode fires once per slot, and only for slots after this scheduler started. */
private fun shouldRunLibraryUpdate(settings: DbSettings, last: Long, startedAt: Long): Boolean {
if (settings.libraryUpdateFrequencySeconds <= 0) return false
if (settings.libraryUpdateDailyAtMinutes < 0) return shouldRun(settings.libraryUpdateFrequencySeconds, last)
return latestDailySlotMillis(settings.libraryUpdateDailyAtMinutes) > maxOf(last, startedAt)
}
private fun shouldRunBackup(settings: DbSettings, last: Long): Boolean {
val frequencyHours = backupFrequencyHours(settings.backupFrequency)
return frequencyHours > 0 && nowMillis() - last >= frequencyHours * 60L * 60L * 1000L
}
/** Last-run timestamps, confined to the ticker coroutine. */
private class LastRun(val startedAt: Long) {
var metadataRefresh = 0L
var libraryUpdate = 0L
var backup = 0L
var sync = 0L
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/scheduling/PeriodicTaskRunner.kt
- Source · implementation · 175 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
19: enum class PeriodicTaskStatus { Completed, Failed, Skipped, Deferred }
21: data class PeriodicTaskOutcome(
30: class PeriodicTaskRunner(
40: suspend fun refreshMetadata(): PeriodicTaskOutcome = execute(PeriodicTask.Metadata) {
75: suspend fun updateLibrary(): PeriodicTaskOutcome = execute(PeriodicTask.Library) {
105: suspend fun sync(): PeriodicTaskOutcome = execute(PeriodicTask.Sync) {
126: suspend fun backup(): PeriodicTaskOutcome = execute(PeriodicTask.Backup) {
135: private suspend fun execute(
162: private enum class PeriodicTask(
Exact file bytes / download · SHA-256 6c6684c72e2fd2e498b3e491afd25c7f8599bb108c73c47694198d0368371d1c.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.backup.BackupService
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.library.LibraryUpdaterService
import eu.friedcutlet.yokan.services.metadata.MetadataService
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.notifications.NotificationPayload
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.sync.SyncService
enum class PeriodicTaskStatus { Completed, Failed, Skipped, Deferred }
data class PeriodicTaskOutcome(
val status: PeriodicTaskStatus,
val message: String,
) {
val shouldRetry: Boolean get() = status == PeriodicTaskStatus.Failed || status == PeriodicTaskStatus.Deferred
val attempted: Boolean get() = status != PeriodicTaskStatus.Skipped && status != PeriodicTaskStatus.Deferred
}
/** Shared execution path for foreground timers and OS background workers. */
class PeriodicTaskRunner(
private val database: YokanDatabase,
private val repository: YokanRepository,
private val metadata: MetadataService,
private val libraryUpdater: LibraryUpdaterService,
private val sync: SyncService,
private val notifications: NotificationService,
private val backup: BackupService? = null,
private val updateGate: AutomaticUpdateGate = AutomaticUpdateGate(),
) {
suspend fun refreshMetadata(): PeriodicTaskOutcome = execute(PeriodicTask.Metadata) {
val settings = database.settings()
if (!settings.metadataServerEnabled) {
return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Metadata refresh is disabled.")
}
val baseUrl = settings.metadataServerUrl.trim()
if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
return@execute PeriodicTaskOutcome(
PeriodicTaskStatus.Failed,
"Metadata server URL must start with http:// or https://.",
)
}
val titles = ItemType.entries.flatMap(repository::library)
var updated = 0
var unmatched = 0
var failed = 0
titles.forEach { title ->
catchingNonCancellation { metadata.bestMatch(baseUrl, title.name, title.itemType.toDb()) }
.onSuccess { match ->
if (match == null) {
unmatched++
} else if (repository.applyMetadata(title.id, match) != null) {
updated++
} else {
failed++
}
}
.onFailure { failed++ }
}
PeriodicTaskOutcome(
PeriodicTaskStatus.Completed,
"Updated metadata for $updated of ${titles.size} titles; $unmatched unmatched, $failed failed.",
)
}
suspend fun updateLibrary(): PeriodicTaskOutcome = execute(PeriodicTask.Library) {
if (!updateGate.check(database.settings()).allowed) {
return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Deferred, "Automatic library update is waiting for device/network conditions.")
}
var checked = 0
var updated = 0
var failed = 0
var crashedTypes = 0
for (type in DbItemType.entries) {
var deferred = false
catchingNonCancellation { libraryUpdater.updateLibrary(type,
mayStartTitle = { updateGate.check(database.settings()).allowed }) }
.onSuccess { result ->
checked += result.checked
updated += result.updated
failed += result.failed
deferred = result.deferred
}
.onFailure { crashedTypes++ }
if (deferred) return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Deferred,
"Automatic library update paused after $checked titles; $updated updated, $failed failed. Waiting for device/network conditions.")
}
val message = "Checked $checked titles; $updated updated, $failed failed" +
if (crashedTypes > 0) ", $crashedTypes libraries could not run." else "."
PeriodicTaskOutcome(
if (crashedTypes == DbItemType.entries.size) PeriodicTaskStatus.Failed else PeriodicTaskStatus.Completed,
message,
)
}
suspend fun sync(): PeriodicTaskOutcome = execute(PeriodicTask.Sync) {
val preference = database.syncPreferences().firstOrNull()
if (preference?.syncOn != true || preference.authToken.isNullOrBlank()) {
return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Automatic sync is not configured.")
}
val result = sync.sync(preference.syncId ?: 1L, database.settings())
val details = buildList {
add("${result.uploadedChanges} uploaded")
add("${result.downloadedChanges} downloaded")
if (result.settingsSynced) add("settings synced")
}.joinToString(", ")
PeriodicTaskOutcome(
if (result.errors.isEmpty()) PeriodicTaskStatus.Completed else PeriodicTaskStatus.Failed,
if (result.errors.isEmpty()) {
"Sync complete: $details."
} else {
"Sync finished with ${result.errors.size} errors: $details."
},
)
}
suspend fun backup(): PeriodicTaskOutcome = execute(PeriodicTask.Backup) {
val settings = database.settings()
if (backup == null || backupFrequencyHours(settings.backupFrequency) <= 0) {
return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Automatic backup is disabled.")
}
val result = backup.createBackup(BackupOptions(compressionLevel = settings.backupCompressionLevel ?: 6))
PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Saved ${result.itemCount} items to ${result.fileName}.")
}
private suspend fun execute(
task: PeriodicTask,
block: suspend () -> PeriodicTaskOutcome,
): PeriodicTaskOutcome {
val outcome = catchingNonCancellation { block() }.getOrElse { error ->
PeriodicTaskOutcome(
PeriodicTaskStatus.Failed,
error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty().ifBlank { "Unknown error" } },
)
}
if (outcome.status == PeriodicTaskStatus.Skipped || outcome.status == PeriodicTaskStatus.Deferred) return outcome
val title = "${task.label} ${if (outcome.status == PeriodicTaskStatus.Completed) "complete" else "failed"}"
if (outcome.status == PeriodicTaskStatus.Failed || task.notifiesSuccess) {
notifications.notify(
NotificationPayload(
channel = task.channel,
title = title,
message = outcome.message.take(240),
tag = task.tag,
),
)
}
val log = "$title: ${outcome.message}"
if (outcome.status == PeriodicTaskStatus.Completed) AppLogger.info(log) else AppLogger.warn(log)
return outcome
}
private enum class PeriodicTask(
val label: String,
val channel: NotificationChannel,
val tag: String,
val notifiesSuccess: Boolean = true,
) {
Metadata("Metadata refresh", NotificationChannel.LibraryUpdates, "periodic.metadata"),
Library("Library update", NotificationChannel.LibraryUpdates, "periodic.library"),
Sync("Automatic sync", NotificationChannel.Sync, "periodic.sync"),
// BackupService already posts "Backup created" for every successful backup.
Backup("Automatic backup", NotificationChannel.Backup, "periodic.backup", notifiesSuccess = false),
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/scheduling/ProfileWork.kt
- Source · implementation · 17 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: sealed interface ProfileWorkResult<out T> {
6: data class Completed<T>(val value: T) : ProfileWorkResult<T>
7: data object Skipped : ProfileWorkResult<Nothing>
8: data object Retry : ProfileWorkResult<Nothing>
12: data class ProfileWorkNamespace(val id: ProfileId) {
13: fun uniqueName(legacyName: String): String =
Exact file bytes / download · SHA-256 22fa01d18fb5a9d8b4488d778fd69f05224f35da56275296b926e9f5e004497c.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.domain.ProfileId
sealed interface ProfileWorkResult<out T> {
data class Completed<T>(val value: T) : ProfileWorkResult<T>
data object Skipped : ProfileWorkResult<Nothing>
data object Retry : ProfileWorkResult<Nothing>
}
/** Persisted work names stay stable across rename; Default adopts existing WorkManager jobs. */
data class ProfileWorkNamespace(val id: ProfileId) {
fun uniqueName(legacyName: String): String =
if (id == ProfileId.Default) legacyName else "$legacyName.${id.value}"
companion object { const val OwnerKey = "yokan.profile_id" }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/system/AppDeepLinks.kt
- Source · implementation · 42 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: object AppDeepLinks {
10: fun register(handler: (String) -> Unit): () -> Unit {
23: fun registerPrefix(prefix: String, handler: (String) -> Unit): () -> Unit {
32: fun dispatch(link: String?) {
Exact file bytes / download · SHA-256 aa44715deb84e198420b274c82c0173dbcfd831fbbc0ccd23f7f7aca8ca7fe45.
Complete file
package eu.friedcutlet.yokan.services.system
import eu.friedcutlet.yokan.services.logging.AppLogger
object AppDeepLinks {
private var fallbackHandler: ((String) -> Unit)? = null
private val prefixHandlers = mutableMapOf<String, (String) -> Unit>()
private var pendingLink: String? = null
fun register(handler: (String) -> Unit): () -> Unit {
this.fallbackHandler = handler
pendingLink?.let {
pendingLink = null
handler(it)
}
return {
if (this.fallbackHandler === handler) {
this.fallbackHandler = null
}
}
}
fun registerPrefix(prefix: String, handler: (String) -> Unit): () -> Unit {
prefixHandlers[prefix] = handler
pendingLink?.takeIf { it.startsWith(prefix) }?.let {
pendingLink = null
handler(it)
}
return { if (prefixHandlers[prefix] === handler) prefixHandlers.remove(prefix) }
}
fun dispatch(link: String?) {
if (link.isNullOrBlank()) return
AppLogger.info("Deep link received: $link")
val prefixMatch = prefixHandlers.entries.firstOrNull { link.startsWith(it.key) }
if (prefixMatch != null) {
prefixMatch.value(link)
return
}
fallbackHandler?.invoke(link) ?: run { pendingLink = link }
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/system/DeviceCapabilities.kt
- Source · implementation · 17 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
4: expect fun isTvDevice(): Boolean
6: internal expect fun isLocalLibraryManagerSupported(): Boolean
9: internal data class ProcessMemoryUsage(val usedBytes: Long, val maxBytes: Long)
12: internal expect fun processMemoryUsage(): ProcessMemoryUsage?
14: internal fun useRailNavigation(isTv: Boolean, compact: Boolean): Boolean = isTv || !compact
16: internal fun showBottomNavigation(isTv: Boolean, compact: Boolean, showRootNav: Boolean): Boolean =
Exact file bytes / download · SHA-256 491a08ca37186e8edbc4c24e6e67e15920d842b2881c6dab7d585fccaaac7f0e.
Complete file
package eu.friedcutlet.yokan.services.system
/** Platform capability seam; Android is the only target that currently reports TV. */
expect fun isTvDevice(): Boolean
internal expect fun isLocalLibraryManagerSupported(): Boolean
/** Managed-heap use of this process; [maxBytes] is the ceiling the runtime will grow to. */
internal data class ProcessMemoryUsage(val usedBytes: Long, val maxBytes: Long)
/** Null where the runtime exposes no cheap heap numbers (iOS, the browser). */
internal expect fun processMemoryUsage(): ProcessMemoryUsage?
internal fun useRailNavigation(isTv: Boolean, compact: Boolean): Boolean = isTv || !compact
internal fun showBottomNavigation(isTv: Boolean, compact: Boolean, showRootNav: Boolean): Boolean =
compact && !isTv && showRootNav
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/system/SystemIntegration.kt
- Source · implementation · 34 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: expect fun isOnUnmeteredNetwork(): Boolean
10: interface NetworkMonitor {
16: expect fun createNetworkMonitor(): NetworkMonitor
19: internal object UnmeteredNetwork : NetworkMonitor {
23: expect fun openSystemBrowser(url: String): Boolean
34: expect fun applyAppLanguage(languageCode: String?)
Exact file bytes / download · SHA-256 be9c6e696ad59f1b1465f8d639542ccfcb939d09efe05b025f464e5713d13269.
Complete file
package eu.friedcutlet.yokan.services.system
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** A one-off check; [NetworkMonitor] follows network changes. */
expect fun isOnUnmeteredNetwork(): Boolean
/** Whether the device's current network is unmetered, updated as it changes networks. */
interface NetworkMonitor {
/** False on a metered or Low Data Mode network, and without a network. */
val unmetered: StateFlow<Boolean>
}
/** Registers a monitor with the platform for the process lifetime; create one per process. */
expect fun createNetworkMonitor(): NetworkMonitor
/** Platforms that don't expose metering (desktop, browser) are always unmetered. */
internal object UnmeteredNetwork : NetworkMonitor {
override val unmetered: StateFlow<Boolean> = MutableStateFlow(true)
}
expect fun openSystemBrowser(url: String): Boolean
/**
* Apply the user-chosen UI language to the underlying platform so Compose
* Multiplatform Resources picks up the matching translation on the next
* recomposition. Pass `null` (or blank) to restore the system default.
*
* - JVM (Android + Desktop): updates `java.util.Locale.getDefault()`.
* - iOS: sets `NSUserDefaults.AppleLanguages` — change takes effect on
* next app launch (iOS caches the bundle locale).
*/
expect fun applyAppLanguage(languageCode: String?)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/translation/TranslatorService.kt
- Source · implementation · 186 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: class TranslationException(message: String) : RuntimeException(message)
20: class LibreTranslateTranslatorService(
43: override fun supportedLanguages(): List<TranslationLanguage> = languages
45: override fun supports(source: TranslationLanguage, target: TranslationLanguage): Boolean =
48: override suspend fun translate(request: TranslationRequest): TranslationResult {
103: private fun encodeRequest(request: TranslationRequest): String {
114: private fun detectedSource(body: JsonObject): TranslationLanguage? {
123: private fun JsonObject.stringValue(key: String): String? =
126: private fun JsonElement.jsonObjectOrNull(): JsonObject? =
134: interface TranslatorService {
137: fun supportedLanguages(): List<TranslationLanguage>
138: fun supports(source: TranslationLanguage, target: TranslationLanguage): Boolean
139: suspend fun translate(request: TranslationRequest): TranslationResult
140: suspend fun translateBatch(requests: List<TranslationRequest>): List<TranslationResult> =
144: enum class TranslationLanguage(
155: fun fromCode(code: String?): TranslationLanguage? {
165: data class TranslationRequest(
175: data class TranslationResult(
183: data class TranslationPair(
Exact file bytes / download · SHA-256 e2107a90113159e18d8b94fa5724287f528a8a0bd3820cb0d8def6f74c005910.
Complete file
package eu.friedcutlet.yokan.services.translation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
class TranslationException(message: String) : RuntimeException(message)
/**
* LibreTranslate-compatible translator. The implementation intentionally stays behind
* [TranslatorService] so OCR/image translation can depend on the app service boundary instead of
* a concrete HTTP provider.
*/
class LibreTranslateTranslatorService(
private val http: HttpService,
private val endpoint: String = DefaultEndpoint,
private val apiKey: String? = null,
) : TranslatorService {
override val providerName: String = "LibreTranslate"
private val json = Json {
ignoreUnknownKeys = true
isLenient = true
}
private val languages = listOf(
TranslationLanguage.English,
TranslationLanguage.German,
TranslationLanguage.Japanese,
)
private val supportedPairs: Set<TranslationPair> =
(languages + TranslationLanguage.Auto)
.flatMap { source -> languages.map { target -> TranslationPair(source, target) } }
.toSet()
override fun supportedLanguages(): List<TranslationLanguage> = languages
override fun supports(source: TranslationLanguage, target: TranslationLanguage): Boolean =
TranslationPair(source, target) in supportedPairs
override suspend fun translate(request: TranslationRequest): TranslationResult {
val text = request.text
if (text.isBlank()) {
return TranslationResult(
originalText = request.text,
translatedText = "",
source = request.source.takeUnless { it == TranslationLanguage.Auto },
target = request.target,
providerName = providerName,
)
}
if (request.source == request.target) {
return TranslationResult(
originalText = request.text,
translatedText = request.text,
source = request.source,
target = request.target,
providerName = providerName,
)
}
if (!supports(request.source, request.target)) {
throw TranslationException("Unsupported translation pair: ${request.source.code} -> ${request.target.code}")
}
val response = http.request(
HttpRequest(
url = endpoint,
method = "POST",
headers = mapOf(
"Accept" to "application/json",
"Content-Type" to "application/json",
),
body = encodeRequest(request),
),
)
if (response.statusCode !in 200..299) {
throw TranslationException("Translator request failed with HTTP ${response.statusCode}: ${response.body.take(160)}")
}
val body = runCatching { json.parseToJsonElement(response.body).jsonObject }
.getOrElse { error -> throw TranslationException("Translator returned invalid JSON: ${error.message}") }
val translated = body.stringValue("translatedText")
?: body.stringValue("translated_text")
?: throw TranslationException("Translator response did not include translated text.")
val detectedSource = detectedSource(body) ?: request.source.takeUnless { it == TranslationLanguage.Auto }
return TranslationResult(
originalText = request.text,
translatedText = translated,
source = detectedSource,
target = request.target,
providerName = providerName,
)
}
private fun encodeRequest(request: TranslationRequest): String {
val entries = mutableMapOf<String, JsonElement>(
"q" to JsonPrimitive(request.text),
"source" to JsonPrimitive(request.source.code),
"target" to JsonPrimitive(request.target.code),
"format" to JsonPrimitive("text"),
)
apiKey?.takeIf { it.isNotBlank() }?.let { entries["api_key"] = JsonPrimitive(it) }
return JsonObject(entries).toString()
}
private fun detectedSource(body: JsonObject): TranslationLanguage? {
body.stringValue("detectedSourceLanguage")?.let { return TranslationLanguage.fromCode(it) }
body.stringValue("detected_source_language")?.let { return TranslationLanguage.fromCode(it) }
val detected = body["detectedLanguage"]?.jsonObjectOrNull()
?: body["detected_language"]?.jsonObjectOrNull()
?: return null
return TranslationLanguage.fromCode(detected.stringValue("language"))
}
private fun JsonObject.stringValue(key: String): String? =
this[key]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }
private fun JsonElement.jsonObjectOrNull(): JsonObject? =
runCatching { jsonObject }.getOrNull()
companion object {
const val DefaultEndpoint = "https://translate.argosopentech.com/translate"
}
}
interface TranslatorService {
val providerName: String
fun supportedLanguages(): List<TranslationLanguage>
fun supports(source: TranslationLanguage, target: TranslationLanguage): Boolean
suspend fun translate(request: TranslationRequest): TranslationResult
suspend fun translateBatch(requests: List<TranslationRequest>): List<TranslationResult> =
requests.map { translate(it) }
}
enum class TranslationLanguage(
val code: String,
val displayName: String,
) {
Auto("auto", "Auto-detect"),
English("en", "English"),
German("de", "German"),
Japanese("ja", "Japanese"),
;
companion object {
fun fromCode(code: String?): TranslationLanguage? {
val normalized = code?.trim()?.lowercase().orEmpty()
if (normalized.isBlank()) return null
return entries.firstOrNull { language ->
language.code == normalized || normalized.startsWith("${language.code}-")
}
}
}
}
data class TranslationRequest(
val text: String,
val source: TranslationLanguage = TranslationLanguage.Auto,
val target: TranslationLanguage,
) {
init {
require(target != TranslationLanguage.Auto) { "Translation target language cannot be auto-detect." }
}
}
data class TranslationResult(
val originalText: String,
val translatedText: String,
val source: TranslationLanguage?,
val target: TranslationLanguage,
val providerName: String,
)
data class TranslationPair(
val source: TranslationLanguage,
val target: TranslationLanguage,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tts/ProfileSpeechService.kt
- Source · implementation · 141 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
20: class ProfileSpeechService internal constructor(
38: private fun ensureOpen() {
44: internal fun reader(): Reader {
51: override suspend fun voices(language: String?): List<String> = direct.voices(language)
52: override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) =
55: override suspend fun stop() = stopCalls(null)
57: private suspend fun stopCalls(reader: Reader?) {
70: private suspend fun releaseUtterance() {
77: internal fun retire() { job.cancel() }
79: override suspend fun closeAndJoin() = withContext(NonCancellable) {
96: fun ensureOpen() { readerJob.ensureActive(); this@ProfileSpeechService.ensureOpen() }
97: fun retire() { readerJob.cancel() }
98: override suspend fun closeAndJoin() {
103: private suspend fun <T> runOwned(action: suspend (Job, Job) -> T): T {
127: override suspend fun voices(language: String?): List<String> = runOwned { _, _ -> delegate.voices(language) }
129: override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) =
139: override suspend fun stop() = stopCalls(this)
Exact file bytes / download · SHA-256 8561b5483db40da204e91833f6ba1dab44a3ca88573bd9a78b40fdfe0faf75e3.
Complete file
package eu.friedcutlet.yokan.services.tts
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
/** Captures one native service; reader handles cannot stop another reader's utterance. */
class ProfileSpeechService internal constructor(
private val delegate: TextToSpeechService,
ownerScope: CoroutineScope,
private val isOwnerOpen: () -> Boolean = { true },
) : TextToSpeechService {
private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job])
private val job = SupervisorJob(ownerJob)
private val scope = CoroutineScope(ownerScope.coroutineContext + job)
private val callsLock = PlatformLock()
private val calls = mutableMapOf<Job, Reader>()
private val nativeLock = Mutex()
private val closeLock = Mutex()
private var needsStop = false // guarded by nativeLock; failed cleanup retries before reuse
private var released = false
private val direct = Reader()
internal val isAvailable: Boolean get() = ownerJob.isActive && job.isActive && isOwnerOpen()
private fun ensureOpen() {
ownerJob.ensureActive()
job.ensureActive()
if (!isOwnerOpen()) throw CancellationException("Speech owner is retiring.")
}
internal fun reader(): Reader {
ensureOpen()
return Reader().also {
if (!isAvailable) { it.retire(); ensureOpen() }
}
}
override suspend fun voices(language: String?): List<String> = direct.voices(language)
override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) =
direct.speak(text, request, onProgress)
override suspend fun stop() = stopCalls(null)
private suspend fun stopCalls(reader: Reader?) {
val caller = requireNotNull(currentCoroutineContext()[Job])
caller.ensureActive()
ensureOpen()
reader?.ensureOpen()
val stopping = callsLock.withLock { calls.filterValues { reader == null || it === reader }.keys.toList() }
stopping.forEach { it.cancel() }
withContext(NonCancellable) { stopping.forEach { it.join() } }
caller.ensureActive()
ensureOpen()
reader?.ensureOpen()
}
private suspend fun releaseUtterance() {
if (needsStop) {
delegate.stop()
needsStop = false
}
}
internal fun retire() { job.cancel() }
override suspend fun closeAndJoin() = withContext(NonCancellable) {
closeLock.withLock {
retire()
job.join()
if (!released) nativeLock.withLock {
releaseUtterance()
delegate.closeAndJoin()
released = true
}
}
}
internal inner class Reader : TextToSpeechService {
private val readerJob = SupervisorJob(job)
private val readerScope = CoroutineScope(scope.coroutineContext + readerJob)
val isAvailable: Boolean get() = readerJob.isActive && this@ProfileSpeechService.isAvailable
fun ensureOpen() { readerJob.ensureActive(); this@ProfileSpeechService.ensureOpen() }
fun retire() { readerJob.cancel() }
override suspend fun closeAndJoin() {
retire()
withContext(NonCancellable) { readerJob.join() }
}
private suspend fun <T> runOwned(action: suspend (Job, Job) -> T): T {
val caller = requireNotNull(currentCoroutineContext()[Job])
caller.ensureActive()
ensureOpen()
val work: Deferred<T> = readerScope.async(start = CoroutineStart.LAZY) {
val call = requireNotNull(currentCoroutineContext()[Job])
call.ensureActive(); caller.ensureActive(); ensureOpen()
nativeLock.withLock {
call.ensureActive(); caller.ensureActive(); ensureOpen()
withContext(NonCancellable) { releaseUtterance() }
call.ensureActive(); caller.ensureActive(); ensureOpen()
action(call, caller).also { call.ensureActive(); caller.ensureActive(); ensureOpen() }
}
}
callsLock.withLock { calls[work] = this }
work.invokeOnCompletion { callsLock.withLock { calls.remove(work) } }
work.start()
return try { work.await() }
finally {
withContext(NonCancellable) { work.cancelAndJoin() }
caller.ensureActive(); ensureOpen()
}
}
override suspend fun voices(language: String?): List<String> = runOwned { _, _ -> delegate.voices(language) }
override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) =
runOwned { call, caller ->
needsStop = true
try {
delegate.speak(text, request) { start, end ->
if (call.isActive && caller.isActive && isAvailable) onProgress(start, end)
}
} finally { withContext(NonCancellable) { releaseUtterance() } }
}
override suspend fun stop() = stopCalls(this)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tts/TextToSpeechService.kt
- Source · implementation · 22 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: data class TextToSpeechRequest(
10: interface TextToSpeechService {
11: suspend fun voices(language: String? = null): List<String>
12: suspend fun speak(
17: suspend fun stop()
19: suspend fun closeAndJoin() = stop()
22: expect fun createPlatformTextToSpeechService(): TextToSpeechService
Exact file bytes / download · SHA-256 1dec6532dc3cba81f383ba0793ecbea7f0b12166906434e6b9f1094ae1cba79c.
Complete file
package eu.friedcutlet.yokan.services.tts
data class TextToSpeechRequest(
val language: String? = null,
val voice: String? = null,
val speechRate: Double = 0.5,
val pitch: Double = 1.0,
)
interface TextToSpeechService {
suspend fun voices(language: String? = null): List<String>
suspend fun speak(
text: String,
request: TextToSpeechRequest = TextToSpeechRequest(),
onProgress: (startOffset: Int, endOffset: Int) -> Unit = { _, _ -> },
)
suspend fun stop()
/** Release native resources after joined calls; implementations may retry a failed release. */
suspend fun closeAndJoin() = stop()
}
expect fun createPlatformTextToSpeechService(): TextToSpeechService
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/updates/AppUpdates.kt
- Source · implementation · 109 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
17: enum class ReleaseChannel {
21: fun accepts(channel: ReleaseChannel): Boolean = channel.ordinal >= ordinal
25: fun releaseChannel(version: String): ReleaseChannel? {
38: private fun versionParts(version: String): List<Int>? {
45: data class ReleaseAsset(val name: String, val url: String, val sizeBytes: Long)
47: data class ReleaseInfo(val tag: String, val assets: List<ReleaseAsset>)
49: suspend fun fetchLatestRelease(http: HttpService, channel: ReleaseChannel = YOKAN_RELEASE_CHANNEL): ReleaseInfo? {
68: internal fun selectLatestRelease(body: String, channel: ReleaseChannel): ReleaseInfo? {
94: fun isNewerVersion(tag: String, current: String = YOKAN_VERSION): Boolean {
106: suspend fun checkForAppUpdate(http: HttpService): ReleaseInfo? =
Exact file bytes / download · SHA-256 a17d157dd1b9f8152a3c950c8333a62111ff829b31d597142da82ccfde8e60af.
Complete file
package eu.friedcutlet.yokan.services.updates
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
const val YOKAN_GITHUB_URL = "https://github.com/Schnitzel5/yokan"
enum class ReleaseChannel {
Alpha, Beta, Stable;
/** Preview builds can advance to a more stable channel; stable builds stay stable. */
fun accepts(channel: ReleaseChannel): Boolean = channel.ordinal >= ordinal
}
/** Numeric release channels: 0.0.x alpha, other 0.x.x beta, and 1.x.x+ stable. */
fun releaseChannel(version: String): ReleaseChannel? {
if ('-' in version || '+' in version) return null
val parts = versionParts(version) ?: return null
if (parts.size != 3) return null
return when {
parts[0] > 0 -> ReleaseChannel.Stable
parts.getOrElse(1) { 0 } > 0 -> ReleaseChannel.Beta
else -> ReleaseChannel.Alpha
}
}
val YOKAN_RELEASE_CHANNEL: ReleaseChannel = requireNotNull(releaseChannel(YOKAN_VERSION))
private fun versionParts(version: String): List<Int>? {
val numeric = version.trim().removePrefix("v").removePrefix("V")
.substringBefore('-').substringBefore('+')
if (!Regex("(0|[1-9][0-9]*)(\\.(0|[1-9][0-9]*)){0,2}").matches(numeric)) return null
return numeric.split('.').map { it.toIntOrNull() ?: return null }
}
data class ReleaseAsset(val name: String, val url: String, val sizeBytes: Long)
data class ReleaseInfo(val tag: String, val assets: List<ReleaseAsset>)
suspend fun fetchLatestRelease(http: HttpService, channel: ReleaseChannel = YOKAN_RELEASE_CHANNEL): ReleaseInfo? {
val response = catchingNonCancellation {
http.request(
HttpRequest(
url = "https://api.github.com/repos/Schnitzel5/yokan/releases?per_page=100",
headers = mapOf("Accept" to "application/vnd.github+json"),
),
)
}.onFailure { AppLogger.warn("[update] release check failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
.getOrNull() ?: return null
if (response.statusCode !in 200..299) {
AppLogger.warn("[update] release check returned HTTP ${response.statusCode}")
return null
}
return catchingNonCancellation { selectLatestRelease(response.body, channel) }
.onFailure { AppLogger.warn("[update] invalid release response: ${it.message}") }
.getOrNull()
}
internal fun selectLatestRelease(body: String, channel: ReleaseChannel): ReleaseInfo? {
val releases = Json.parseToJsonElement(body) as? JsonArray ?: return null
return releases.mapNotNull { element ->
val release = element as? JsonObject ?: return@mapNotNull null
if (release["draft"]?.jsonPrimitive?.booleanOrNull == true) return@mapNotNull null
val tag = release["tag_name"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null
val candidateChannel = releaseChannel(tag) ?: return@mapNotNull null
if (!channel.accepts(candidateChannel)) return@mapNotNull null
if (channel == ReleaseChannel.Stable && release["prerelease"]?.jsonPrimitive?.booleanOrNull == true) {
return@mapNotNull null
}
val assets = (release["assets"] as? JsonArray).orEmpty().mapNotNull assetLoop@ { assetElement ->
val asset = assetElement as? JsonObject ?: return@assetLoop null
val name = asset["name"]?.jsonPrimitive?.contentOrNull ?: return@assetLoop null
val url = asset["browser_download_url"]?.jsonPrimitive?.contentOrNull ?: return@assetLoop null
ReleaseAsset(name, url, asset["size"]?.jsonPrimitive?.longOrNull ?: 0L)
}
ReleaseInfo(tag, assets)
}.reduceOrNull { newest, candidate -> if (isNewerVersion(candidate.tag, newest.tag)) candidate else newest }
}
/**
* True when [tag] denotes a strictly newer numeric version than [current].
* Leading `v` and pre-release/build suffixes (`-beta`, `+42`) are ignored;
* missing components count as zero (`1.2` == `1.2.0`).
*/
fun isNewerVersion(tag: String, current: String = YOKAN_VERSION): Boolean {
val latest = versionParts(tag) ?: return false
val installed = versionParts(current) ?: return false
repeat(maxOf(latest.size, installed.size)) { index ->
val a = latest.getOrElse(index) { 0 }
val b = installed.getOrElse(index) { 0 }
if (a != b) return a > b
}
return false
}
/** Latest release only when it is newer than the installed build. */
suspend fun checkForAppUpdate(http: HttpService): ReleaseInfo? =
fetchLatestRelease(http)
?.also { AppLogger.info("[update] latest release ${it.tag}, installed $YOKAN_VERSION") }
?.takeIf { isNewerVersion(it.tag) }
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/updates/PackageInstaller.kt
- Source · implementation · 4 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
4: expect fun installPackageFromFile(path: String): Boolean
Exact file bytes / download · SHA-256 ac0388abc2fe332c5f5f93c7a6997908c5b0f67406867df5f774d48b5f60201d.
Complete file
package eu.friedcutlet.yokan.services.updates
/** Hands a downloaded update package to the platform installer; false when unsupported or it failed. */
expect fun installPackageFromFile(path: String): Boolean
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/ActivityChrome.kt
- Source · implementation · 123 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
33: internal fun visibleItemTypes(hidden: Set<NavSection>): List<ItemType> =
40: internal fun DateGroupHeader(label: String) {
51: internal fun ItemTypePagerTabRow(
101: internal fun <T> groupByDayBucket(entries: List<T>, updatedAt: (T) -> Long): List<Pair<String, List<T>>> {
117: private fun dayBucketOrder(label: String): Int = when (label) {
Exact file bytes / download · SHA-256 be6ba852a96a25d5cee290ad798eba70b4709d902bfbe8ceef4bb1d54ec6aa9c.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.PagerState
import androidx.compose.material3.Badge
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SecondaryTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.util.nowMillis
import eu.friedcutlet.yokan.ui.navigation.NavSection
import eu.friedcutlet.yokan.ui.navigation.librarySection
// ─────────────────────────────────────────────────────────────────────────────
// HistoryScreen + UpdatesScreen
//
// Both screens follow the same chrome from the Dart source (BaseLibraryTabScreen):
// a TopAppBar whose title swaps into an inline search field, a ScrollableTabRow
// of visible ItemTypes (filtered by dbSettings.hideItems), and a LazyColumn of
// rows grouped by date with sticky headers.
internal fun visibleItemTypes(hidden: Set<NavSection>): List<ItemType> =
ItemType.entries.filterNot { it.librarySection() in hidden }
// ─────────────────────────────────────────────────────────────────────────────
// Rows + helpers
@Composable
internal fun DateGroupHeader(label: String) {
Text(
text = label,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier
.fillMaxWidth()
.padding(start = 12.dp, bottom = 8.dp),
)
}
@Composable
internal fun ItemTypePagerTabRow(
types: List<ItemType>,
pagerState: PagerState,
unreadCounts: Map<ItemType, Int> = emptyMap(),
onSelect: (Int) -> Unit,
) {
val selectedIndex = pagerState.currentPage.coerceIn(types.indices)
SecondaryTabRow(
selectedTabIndex = selectedIndex,
modifier = Modifier.fillMaxWidth(),
containerColor = Color.Transparent,
indicator = {
TabRowDefaults.SecondaryIndicator(
modifier = Modifier
.tabIndicatorOffset(
selectedTabIndex = selectedIndex,
matchContentSize = false,
)
.offset(y = 1.dp),
height = 4.dp,
)
},
) {
types.forEachIndexed { index, type ->
val count = unreadCounts[type] ?: 0
Tab(
selected = index == selectedIndex,
onClick = { onSelect(index) },
text = {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(type.label)
if (count > 0) {
Badge(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurface,
) {
Text(count.toString())
}
}
}
},
)
}
}
}
/** Groups entries into Today / Yesterday / Earlier this week / Earlier this month / Older, in that order. */
internal fun <T> groupByDayBucket(entries: List<T>, updatedAt: (T) -> Long): List<Pair<String, List<T>>> {
if (entries.isEmpty()) return emptyList()
val now = nowMillis()
val dayMillis = 24L * 60L * 60L * 1000L
return entries.groupBy { entry ->
val deltaDays = ((now / dayMillis) - (updatedAt(entry) / dayMillis)).toInt()
when {
deltaDays <= 0 -> "Today"
deltaDays == 1 -> "Yesterday"
deltaDays in 2..6 -> "Earlier this week"
deltaDays in 7..29 -> "Earlier this month"
else -> "Older"
}
}.toList().sortedBy { (label, _) -> dayBucketOrder(label) }
}
private fun dayBucketOrder(label: String): Int = when (label) {
"Today" -> 0
"Yesterday" -> 1
"Earlier this week" -> 2
"Earlier this month" -> 3
else -> 4
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/ActivityFilterDialog.kt
- Source · implementation · 90 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
20: internal fun ActivityFilterDialog(
78: private fun ActivityTriStateRow(label: String, value: Int, onClick: () -> Unit) {
Exact file bytes / download · SHA-256 7ee1425df9bc0f172109925c4076eef707dc98c1c5bb002693ef110a4c0e0205.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.Category
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
/** Shared controls; Upcoming supplies only category filtering, Updates also supplies row filters. */
@Composable
internal fun ActivityFilterDialog(
categories: List<Category>,
categoryFilter: DbActivityCategoryFilter,
onCategoryFilter: ((DbActivityCategoryFilter) -> DbActivityCategoryFilter) -> Unit,
onDismiss: () -> Unit,
updatesFilter: DbUpdatesFilter? = null,
onUpdatesFilter: ((DbUpdatesFilter) -> DbUpdatesFilter) -> Unit = {},
) {
AlertDialog(onDismissRequest = onDismiss, title = { Text(stringResource(Res.string.activity_filters)) },
text = {
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 420.dp)) {
item(key = "help", contentType = "help") {
Text(stringResource(Res.string.activity_filter_help), style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(bottom = 12.dp))
}
if (updatesFilter != null) {
items(UpdatesFilterKind.entries, key = { "filter:$it" }, contentType = { "filter" }) { kind ->
val label = when (kind) {
UpdatesFilterKind.Downloaded -> Res.string.activity_filter_downloaded
UpdatesFilterKind.Unread -> Res.string.activity_filter_unread
UpdatesFilterKind.Started -> Res.string.activity_filter_started
UpdatesFilterKind.Bookmarked -> Res.string.activity_filter_bookmarked
}
ActivityTriStateRow(stringResource(label), updatesFilter.value(kind)) { onUpdatesFilter { it.cycled(kind) } }
}
item(key = "scanlators", contentType = "switch") {
Row(Modifier.fillMaxWidth().clickable { onUpdatesFilter { it.copy(hideExcludedScanlators = !it.hideExcludedScanlators) } },
verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(Res.string.activity_filter_scanlators), Modifier.weight(1f))
Switch(checked = updatesFilter.hideExcludedScanlators,
onCheckedChange = { value -> onUpdatesFilter { it.copy(hideExcludedScanlators = value) } })
}
}
}
item(key = "categories", contentType = "heading") {
Text(stringResource(Res.string.activity_filter_categories), style = MaterialTheme.typography.titleSmall,
modifier = Modifier.padding(top = 12.dp, bottom = 8.dp))
}
item(key = "uncategorized", contentType = "filter") {
ActivityTriStateRow(stringResource(Res.string.activity_filter_uncategorized), categoryFilter.value(UncategorizedActivityCategoryId)) {
onCategoryFilter { it.cycled(UncategorizedActivityCategoryId) }
}
}
items(categories, key = { "category:${it.id}" }, contentType = { "filter" }) { category ->
ActivityTriStateRow(category.name, categoryFilter.value(category.id)) { onCategoryFilter { it.cycled(category.id) } }
}
}
},
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.activity_filter_done)) } },
dismissButton = {
TextButton(onClick = {
if (updatesFilter != null) onUpdatesFilter { DbUpdatesFilter() }
else onCategoryFilter { DbActivityCategoryFilter() }
}) { Text(stringResource(Res.string.activity_filter_reset)) }
})
}
@Composable
private fun ActivityTriStateRow(label: String, value: Int, onClick: () -> Unit) {
Row(Modifier.fillMaxWidth().clickable(onClick = onClick).padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(label)
Text(stringResource(when (value) {
1 -> Res.string.activity_filter_include
2 -> Res.string.activity_filter_exclude
else -> Res.string.activity_filter_off
}), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
TriStateCheckbox(state = when (value) { 1 -> ToggleableState.On; 2 -> ToggleableState.Indeterminate; else -> ToggleableState.Off }, onClick = null)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/HistoryScreen.kt
- Source · implementation · 362 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
69: internal fun HistoryRoute(nav: Navigator, nested: Boolean) {
89: fun HistoryScreen(
240: private fun historyRows(
250: private fun HistoryPage(
287: private fun HistoryRow(
Exact file bytes / download · SHA-256 d1f24fbdbacbb957b422e67517aa17f46ea040dee09d022b4e9cc686a1598c2a.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.outlined.Delete as DeleteOutlined
import androidx.compose.material.icons.outlined.DeleteSweep as DeleteSweepOutlined
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import kotlinx.coroutines.launch
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import eu.friedcutlet.yokan.ui.components.AppBarSearchField
import eu.friedcutlet.yokan.ui.components.CoverImage
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.action_remove
/** Root History section (`nested = false`, no back) or the pushed [Route.History]. */
@Composable
internal fun HistoryRoute(nav: Navigator, nested: Boolean) {
val viewModel = viewModel { HistoryViewModel(YokanRuntime.repository, YokanRuntime.libraryIndex) }
val state by viewModel.state.collectAsStateWithLifecycle()
val hidden by nav.hiddenSections.collectAsStateWithLifecycle()
val itemType by nav.itemType.collectAsStateWithLifecycle()
HistoryScreen(
state = state,
visibleTypes = remember(hidden) { visibleItemTypes(hidden) },
initialItemType = itemType,
onItemTypeSettled = nav::selectItemType,
onOpenChapter = { manga, chapter -> nav.navigate(Route.Reader(manga.id, chapter.id)) },
onOpenDetail = { manga -> nav.navigate(Route.Detail(manga.id)) },
onRemoveHistory = viewModel::removeHistory,
onClearHistory = viewModel::clearHistory,
onBack = if (nested) nav::back else null,
)
}
@OptIn(ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
fun HistoryScreen(
state: HistoryState,
visibleTypes: List<ItemType>,
initialItemType: ItemType,
onItemTypeSettled: (ItemType) -> Unit,
onOpenChapter: (Manga, Chapter) -> Unit,
onOpenDetail: (Manga) -> Unit,
onRemoveHistory: (historyId: Long) -> Unit,
onClearHistory: (ItemType) -> Unit,
onBack: (() -> Unit)? = null,
) {
if (visibleTypes.isEmpty()) {
Scaffold(topBar = { eu.friedcutlet.yokan.ui.components.YokanTopBar(title = "History", onBack = onBack) }) { padding ->
EmptyState(
modifier = Modifier.fillMaxSize().padding(padding),
icon = Icons.Filled.History,
title = "No history yet",
)
}
return
}
val initialPage = remember(visibleTypes, initialItemType) {
visibleTypes.indexOf(initialItemType).takeIf { it >= 0 } ?: 0
}
val pagerState = rememberPagerState(initialPage = initialPage, pageCount = { visibleTypes.size })
val scope = rememberCoroutineScope()
val selectedPage = pagerState.currentPage.coerceIn(visibleTypes.indices)
val selectedTab = visibleTypes[selectedPage]
var searching by remember { mutableStateOf(false) }
var query by remember { mutableStateOf("") }
var clearAllOpen by remember { mutableStateOf(false) }
var pendingDelete by remember { mutableStateOf<History?>(null) }
LaunchedEffect(visibleTypes.size) {
if (pagerState.currentPage > visibleTypes.lastIndex) {
pagerState.scrollToPage(visibleTypes.lastIndex)
}
}
LaunchedEffect(pagerState, visibleTypes) {
snapshotFlow { pagerState.settledPage }.collect { page ->
val type = visibleTypes.getOrNull(page) ?: return@collect
onItemTypeSettled(type)
query = ""
searching = false
}
}
val entries = remember(state.rowsByType, selectedTab, query) { historyRows(state.rowsByType, selectedTab, query) }
Scaffold(
topBar = {
TopAppBar(
expandedHeight = 56.dp,
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent),
navigationIcon = {
onBack?.let {
IconButton(onClick = it) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back))
}
}
},
title = {
if (searching) {
AppBarSearchField(
query = query,
placeholder = "Search history",
onQueryChange = { query = it },
onClose = {
searching = false
query = ""
},
)
} else {
Text("History")
}
},
actions = {
if (!searching) {
IconButton(modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp), onClick = { searching = true }) {
Icon(Icons.Filled.Search, contentDescription = "Search history")
}
}
IconButton(
modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp),
onClick = { clearAllOpen = true },
enabled = entries.isNotEmpty(),
) {
Icon(Icons.Outlined.DeleteSweepOutlined, contentDescription = "Clear all history")
}
},
)
},
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding),
) {
ItemTypePagerTabRow(
types = visibleTypes,
pagerState = pagerState,
onSelect = { index ->
if (index != pagerState.currentPage) query = ""
scope.launch { pagerState.animateScrollToPage(index) }
},
)
HorizontalPager(
state = pagerState,
beyondViewportPageCount = 1,
modifier = Modifier.fillMaxSize(),
) { page ->
val type = visibleTypes[page]
val pageEntries = remember(state.rowsByType, type, query) {
historyRows(state.rowsByType, type, query)
}
HistoryPage(
entries = pageEntries,
query = query,
onOpenChapter = onOpenChapter,
onOpenDetail = onOpenDetail,
onDeleteRequest = { pendingDelete = it },
)
}
}
}
if (clearAllOpen) {
eu.friedcutlet.yokan.ui.components.ConfirmDialog(
title = "Remove everything",
message = "Remove all history entries for ${selectedTab.label}?",
confirmLabel = stringResource(Res.string.action_remove),
danger = true,
onConfirm = { onClearHistory(selectedTab) },
onDismiss = { clearAllOpen = false },
)
}
pendingDelete?.let { history ->
eu.friedcutlet.yokan.ui.components.ConfirmDialog(
title = stringResource(Res.string.action_remove),
message = "Remove this history entry?",
confirmLabel = stringResource(Res.string.action_remove),
danger = true,
onConfirm = { onRemoveHistory(history.id) },
onDismiss = { pendingDelete = null },
)
}
}
private fun historyRows(
rowsByType: Map<ItemType, List<HistoryRowModel>>,
type: ItemType,
query: String,
): List<HistoryRowModel> {
val rows = rowsByType[type].orEmpty()
return if (query.isBlank()) rows else rows.filter { it.history.title.contains(query, ignoreCase = true) }
}
@Composable
private fun HistoryPage(
entries: List<HistoryRowModel>,
query: String,
onOpenChapter: (Manga, Chapter) -> Unit,
onOpenDetail: (Manga) -> Unit,
onDeleteRequest: (History) -> Unit,
) {
if (entries.isEmpty()) {
EmptyState(
modifier = Modifier.fillMaxSize(),
icon = Icons.Filled.History,
title = if (query.isNotEmpty()) "No matches" else "No history yet",
)
return
}
val grouped = remember(entries) { groupByDayBucket(entries) { it.history.updatedAt } }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(top = 1.dp),
) {
grouped.forEach { (bucket, items) ->
item(key = "h-$bucket") {
DateGroupHeader(bucket)
}
items(items, key = { it.history.id }) { row ->
HistoryRow(
row = row,
onOpenChapter = onOpenChapter,
onOpenDetail = onOpenDetail,
onDeleteRequest = { onDeleteRequest(row.history) },
)
}
}
}
}
@Composable
private fun HistoryRow(
row: HistoryRowModel,
onOpenChapter: (Manga, Chapter) -> Unit,
onOpenDetail: (Manga) -> Unit,
onDeleteRequest: () -> Unit,
) {
val history = row.history
val manga = row.manga
val chapter = row.chapter
val title = row.title
val chapterName = row.chapterName
Row(
modifier = Modifier
.fillMaxWidth()
.height(105.dp)
.hoverHighlight(onClick = {
if (manga != null && chapter != null) onOpenChapter(manga, chapter)
})
.padding(horizontal = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
CoverImage(
model = manga?.let { it.customCoverImage ?: it.customCoverFromTracker ?: it.imageUrl },
contentDescription = "$title cover",
modifier = Modifier
.size(width = 60.dp, height = 90.dp)
.clip(RoundedCornerShape(5.dp))
.then(
if (manga != null) {
Modifier.hoverHighlight(onClick = { onOpenDetail(manga) })
} else {
Modifier
},
),
shape = RoundedCornerShape(7.dp),
fallbackInitials = title.split(" ").take(2)
.joinToString("") { it.firstOrNull()?.uppercase() ?: "" },
)
Column(
modifier = Modifier
.weight(1f)
.padding(8.dp),
verticalArrangement = Arrangement.Center,
) {
Text(
text = title,
fontSize = 14.sp,
lineHeight = 20.sp,
fontWeight = FontWeight.Bold,
letterSpacing = 0.1.sp,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
text = "$chapterName - ${eu.friedcutlet.yokan.ui.formatClockTime(history.updatedAt)}",
fontSize = 11.sp,
lineHeight = 17.sp,
letterSpacing = 0.1.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.onSurface,
)
}
IconButton(
modifier = Modifier.offset(x = 3.5.dp, y = 0.125.dp),
onClick = onDeleteRequest,
) {
Icon(
imageVector = Icons.Outlined.DeleteOutlined,
contentDescription = "Remove from history",
modifier = Modifier.size(25.dp),
)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/HistoryViewModel.kt
- Source · implementation · 97 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
24: data class HistoryRowModel(
33: data class HistoryState(
38: private class HistorySource(val history: List<History>, val titles: Map<Long, Manga>)
40: class HistoryViewModel(
65: fun removeHistory(historyId: Long) {
69: fun clearHistory(itemType: ItemType) {
78: internal fun buildHistoryRows(
Exact file bytes / download · SHA-256 01a6ab2ce10f8a3fc39ad8d362852cf224eee2bebbceab4f3a4c2976294f05e9.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/** One History row with its title and chapter resolved once per data change. */
data class HistoryRowModel(
val history: History,
val manga: Manga?,
val chapter: Chapter?,
) {
val title: String = manga?.name?.takeIf { it.isNotBlank() } ?: history.title
val chapterName: String = chapter?.name?.takeIf { it.isNotBlank() } ?: history.chapterName
}
data class HistoryState(
/** The latest entry of each title per item type, newest first. */
val rowsByType: Map<ItemType, List<HistoryRowModel>> = emptyMap(),
)
private class HistorySource(val history: List<History>, val titles: Map<Long, Manga>)
class HistoryViewModel(
private val repository: YokanRepository,
libraryIndex: LibraryIndexStore,
workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(HistoryState())
val state: StateFlow<HistoryState> = _state.asStateFlow()
init {
// Titles depend on the settings snapshot too (toDomain), so key the read on all three parts.
val source = repository.observe({ Triple(it.histories, it.mangas, it.settings) }, workDispatcher) {
val history = history()
val titles = HashMap<Long, Manga>()
for (entry in history) {
if (entry.mangaId !in titles) manga(entry.mangaId)?.let { titles[entry.mangaId] = it }
}
HistorySource(history, titles)
}
viewModelScope.launch {
combine(source, libraryIndex.index) { data, index -> buildHistoryRows(data.history, data.titles, index) }
.flowOn(workDispatcher)
.collect { rows -> _state.update { it.copy(rowsByType = rows) } }
}
}
fun removeHistory(historyId: Long) {
repository.removeHistory(historyId)
}
fun clearHistory(itemType: ItemType) {
repository.clearHistory(itemType)
}
}
/**
* Keeps the newest entry of each title, grouped by item type and sorted newest first, with the
* title and chapter resolved. The chapter is looked up only when the title still exists.
*/
internal fun buildHistoryRows(
history: List<History>,
titles: Map<Long, Manga>,
index: LibraryIndex,
): Map<ItemType, List<HistoryRowModel>> =
history.groupBy { it.itemType }
.mapValues { (_, entries) ->
entries.groupBy { it.mangaId }
.values
.mapNotNull { rows -> rows.maxByOrNull { it.updatedAt } }
.sortedByDescending { it.updatedAt }
.map { entry ->
val manga = titles[entry.mangaId]
HistoryRowModel(
history = entry,
manga = manga,
chapter = manga?.let { title -> index.chapters(title.id).firstOrNull { it.id == entry.chapterId } },
)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/TrackerLibraryScreen.kt
- Source · implementation · 677 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
83: internal fun TrackerLibraryRoute(nav: Navigator) {
130: fun TrackerLibraryScreen(
153: fun closeSearch() {
257: private fun TrackerLibraryTopBar(
369: private fun TrackerSections(
379: data class Section(
461: private fun TrackerSectionHeader(label: String, count: Int) {
488: private fun TrackerItemCard(
571: private fun TrackerItemDialog(
Exact file bytes / download · SHA-256 e24482c1b68907e89bcfda772a4c93e56e4ceb4d38ec0d80b834488219f92dde.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.BookmarkAdded
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Badge
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.services.tracking.TrackerService
import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.accountLabel
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.components.CoverImage
import eu.friedcutlet.yokan.ui.components.AppBarSearchField
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.ui_close
import yokan.composeapp.generated.resources.action_close_search
import yokan.composeapp.generated.resources.ui_search_tracker
@Composable
internal fun TrackerLibraryRoute(nav: Navigator) {
val viewModel = viewModel {
TrackerLibraryViewModel(
allTrackers = YokanRuntime.services.trackers.filter { it.hasTrackerLibrary },
repository = YokanRuntime.repository,
settings = YokanRuntime.settings,
initialItemType = nav.itemType.value,
)
}
val state by viewModel.state.collectAsStateWithLifecycle()
TrackerLibraryScreen(
state = state,
onSelectTracker = viewModel::selectTracker,
onSelectItemType = viewModel::selectItemType,
onRefresh = viewModel::load,
onSearch = viewModel::search,
onClearSearch = viewModel::clearSearch,
onOpenInLibrary = { manga -> nav.navigate(Route.Detail(manga.id)) },
onBindToLibrary = viewModel::bindToLibrary,
onAddToLibrary = { trackedTitle ->
nav.navigate(Route.GlobalSearch(state.itemType, trackedTitle.takeIf(String::isNotBlank).orEmpty()))
},
onOpenInBrowser = { url -> openSystemBrowser(url) },
)
}
/**
* Tracker library — modelled after Aniyomi/Mihon "Browse tracker" screens.
*
* Layout follows screens/wireframes/tracker-library.txt:
* - TopAppBar with a tracker avatar (initial inside a circular Surface), an
* animated title showing "<Tracker> | <ItemType>", a Search toggle, a
* Refresh action, and an overflow with "Switch tracker" / "Switch type".
* - Body is a LazyColumn of section blocks. Each block = a sticky header row
* ("Continue reading", "Popular Manga", …) followed by a horizontal LazyRow
* of CoverImage cards. Cards with a title that already exists in the local
* library get a translucent BookmarkAdded scrim overlay.
* - Tap a card → AlertDialog with cover, title, summary, score badge, and
* "Open in library" / "Bind to library" / "Open in browser" actions.
* - Tap the tracker avatar (or use the overflow) → tracker provider picker.
* - Tap the overflow → ItemType picker.
*
* The tracker library keeps its own item-type cursor ([TrackerLibraryState.itemType]):
* switching the global type would flip the user out of this section.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TrackerLibraryScreen(
state: TrackerLibraryState,
onSelectTracker: (TrackerService) -> Unit,
onSelectItemType: (ItemType) -> Unit,
onRefresh: () -> Unit,
onSearch: (String) -> Unit,
onClearSearch: () -> Unit,
onOpenInLibrary: (Manga) -> Unit,
onBindToLibrary: (Manga, DbTrackSearch) -> Unit,
onAddToLibrary: (trackedTitle: String) -> Unit,
onOpenInBrowser: (url: String) -> Unit,
) {
val trackers = state.trackers
val selectedTracker = state.selectedTracker
val currentItemType = state.itemType
var searching by remember { mutableStateOf(false) }
var query by remember { mutableStateOf("") }
var trackerPickerOpen by remember { mutableStateOf(false) }
var itemTypePickerOpen by remember { mutableStateOf(false) }
var selectedCard by remember { mutableStateOf<DbTrackSearch?>(null) }
fun closeSearch() {
searching = false
query = ""
onClearSearch()
}
val itemTypeLabel = when (currentItemType) {
ItemType.Manga -> "Manga"
ItemType.Anime -> "Anime"
ItemType.Novel -> "Novel"
}
val trackerName = selectedTracker?.name ?: "Tracker"
// Simkl/Trakt browse movies/series regardless of the manga/anime cursor.
val animatedTitle = if (selectedTracker?.syncId in setOf(SimklTrackerSyncId, TraktTrackerSyncId)) {
trackerName
} else {
"$trackerName | $itemTypeLabel"
}
Scaffold(
topBar = {
TrackerLibraryTopBar(
title = animatedTitle,
trackerName = trackerName,
account = state.account,
canSwitchTracker = trackers.size > 1,
searching = searching,
query = query,
refreshEnabled = !state.loading && selectedTracker != null,
onQueryChange = { query = it },
onSearch = { onSearch(query) },
onToggleSearch = { if (searching) closeSearch() else searching = true },
onCloseSearch = ::closeSearch,
onRefresh = onRefresh,
onPickTracker = { trackerPickerOpen = true },
onPickItemType = { itemTypePickerOpen = true },
)
},
) { padding ->
TrackerSections(
state = state,
trackerName = trackerName,
onSelectCard = { selectedCard = it },
modifier = Modifier.fillMaxSize().padding(padding),
)
}
if (trackerPickerOpen && trackers.isNotEmpty()) {
ChoiceDialog(
title = "Switch tracker",
options = trackers,
selected = selectedTracker,
label = { it.name },
onSelect = onSelectTracker,
onDismiss = { trackerPickerOpen = false },
)
}
if (itemTypePickerOpen) {
val itemTypes = remember { listOf(ItemType.Manga, ItemType.Anime, ItemType.Novel) }
ChoiceDialog(
title = "Switch type",
options = itemTypes,
selected = currentItemType,
label = {
when (it) {
ItemType.Manga -> "Manga"
ItemType.Anime -> "Anime"
ItemType.Novel -> "Novel"
}
},
onSelect = onSelectItemType,
onDismiss = { itemTypePickerOpen = false },
)
}
selectedCard?.let { search ->
TrackerItemDialog(
search = search,
matchedManga = state.matchInLibrary(search),
trackerSyncId = selectedTracker?.syncId,
onOpenInLibrary = { manga ->
selectedCard = null
onOpenInLibrary(manga)
},
onBindToLibrary = { manga ->
onBindToLibrary(manga, search)
selectedCard = null
},
onAddToLibrary = { trackedTitle ->
selectedCard = null
onAddToLibrary(trackedTitle)
},
onOpenInBrowser = { url ->
onOpenInBrowser(url)
selectedCard = null
},
onDismiss = { selectedCard = null },
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TrackerLibraryTopBar(
title: String,
trackerName: String,
account: DbTrackPreference?,
canSwitchTracker: Boolean,
searching: Boolean,
query: String,
refreshEnabled: Boolean,
onQueryChange: (String) -> Unit,
onSearch: () -> Unit,
onToggleSearch: () -> Unit,
onCloseSearch: () -> Unit,
onRefresh: () -> Unit,
onPickTracker: () -> Unit,
onPickItemType: () -> Unit,
) {
var overflowOpen by remember { mutableStateOf(false) }
val accountLabel = account?.accountLabel
val pickTrackerModifier = if (canSwitchTracker) Modifier.hoverHighlight(onClick = onPickTracker) else Modifier
TopAppBar(
navigationIcon = {
val initial = (accountLabel ?: trackerName).firstOrNull()?.uppercaseChar()?.toString() ?: "?"
CoverImage(
model = account?.accountAvatarUrl,
contentDescription = accountLabel ?: trackerName,
modifier = Modifier
.padding(start = 8.dp)
.size(32.dp)
.clip(RoundedCornerShape(50))
.then(pickTrackerModifier),
shape = RoundedCornerShape(50),
fallbackInitials = initial,
)
},
title = {
if (searching) {
AppBarSearchField(
query = query,
placeholder = "Search $trackerName",
onQueryChange = onQueryChange,
onClose = onCloseSearch,
onSearch = onSearch,
)
} else {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier
.clip(MaterialTheme.shapes.medium)
.then(pickTrackerModifier)
.padding(horizontal = 6.dp, vertical = 4.dp),
) {
Column {
Text(title, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (accountLabel != null) {
Text(
accountLabel,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
},
actions = {
IconButton(onClick = onToggleSearch) {
Icon(
imageVector = if (searching) Icons.Filled.Close else Icons.Filled.Search,
contentDescription = if (searching) {
stringResource(Res.string.action_close_search)
} else {
stringResource(Res.string.ui_search_tracker)
},
)
}
IconButton(onClick = onRefresh, enabled = refreshEnabled) {
Icon(Icons.Filled.Refresh, contentDescription = "Refresh tracker")
}
Box {
IconButton(onClick = { overflowOpen = true }) {
Icon(Icons.Filled.MoreVert, contentDescription = "More options")
}
DropdownMenu(
expanded = overflowOpen,
onDismissRequest = { overflowOpen = false },
) {
DropdownMenuItem(
text = { Text("Switch tracker") },
onClick = {
overflowOpen = false
onPickTracker()
},
)
DropdownMenuItem(
text = { Text("Switch type (manga/anime)") },
onClick = {
overflowOpen = false
onPickItemType()
},
)
}
}
},
)
}
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
private fun TrackerSections(
state: TrackerLibraryState,
trackerName: String,
onSelectCard: (DbTrackSearch) -> Unit,
modifier: Modifier = Modifier,
) {
// Compose the section list in provider order (Mangayomi's
// _sectionsMAL/_sectionsAL/... quartet); a search section leads
// when a query was submitted, and empty sections are skipped so
// the LazyColumn isn't padded with empty sticky headers.
data class Section(
val key: String,
val label: String,
val items: List<DbTrackSearch>,
)
val sections = buildList {
if (state.submittedQuery.isNotBlank()) {
add(Section("search", "Search results: \"${state.submittedQuery}\"", state.searchResults))
}
state.sections.forEach { spec ->
val items = state.sectionResults[spec.label].orEmpty()
if (items.isNotEmpty()) {
add(Section(spec.label, spec.label, items))
}
}
}
val error = state.error
Box(modifier = modifier) {
if (state.trackers.isEmpty()) {
EmptyState(
modifier = Modifier.fillMaxSize(),
icon = Icons.Filled.AccountTree,
title = "No trackers configured",
)
} else if (state.loading && sections.isEmpty()) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
} else if (sections.isEmpty()) {
EmptyState(
modifier = Modifier.fillMaxSize(),
icon = Icons.Filled.AccountTree,
title = error ?: "Nothing to show. Connect $trackerName or refresh.",
)
} else {
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
error?.let { msg ->
item(key = "err") {
Text(
msg,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),
)
}
}
sections.forEach { section ->
stickyHeader(key = "h-${section.key}") {
TrackerSectionHeader(label = section.label, count = section.items.size)
}
item(key = "row-${section.key}") {
LazyRow(
contentPadding = PaddingValues(horizontal = 12.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp),
) {
items(
section.items,
key = { it.title.orEmpty() + ":" + (it.mediaId ?: 0) + ":" + section.key },
) { search ->
TrackerItemCard(
search = search,
inLibrary = state.matchInLibrary(search) != null,
onClick = { onSelectCard(search) },
)
}
}
}
}
}
}
}
}
@Composable
private fun TrackerSectionHeader(label: String, count: Int) {
Surface(
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 1.dp,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
label,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.weight(1f),
)
if (count > 0) {
Badge { Text(count.toString()) }
}
}
}
}
@Composable
private fun TrackerItemCard(
search: DbTrackSearch,
inLibrary: Boolean,
onClick: () -> Unit,
) {
val title = search.title.orEmpty()
Card(
modifier = Modifier
.width(132.dp)
.clip(MaterialTheme.shapes.medium)
.hoverHighlight(onClick = onClick),
) {
Column {
Box {
CoverImage(
model = search.coverUrl.takeIf { it.isNotBlank() },
contentDescription = title,
fallbackInitials = title.firstOrNull()?.toString()?.uppercase(),
modifier = Modifier
.fillMaxWidth()
.aspectRatio(2f / 3f)
.clip(RoundedCornerShape(topStart = 8.dp, topEnd = 8.dp)),
)
// Score badge — top-right corner.
val score = search.score
if (score != null && score > 0.0) {
Surface(
modifier = Modifier
.align(Alignment.TopEnd)
.padding(6.dp),
color = Color.Black.copy(alpha = 0.55f),
shape = RoundedCornerShape(50),
) {
Row(
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(2.dp),
) {
Icon(
Icons.Filled.Star,
contentDescription = null,
tint = Color.Yellow,
modifier = Modifier.size(12.dp),
)
Text(
text = ((score * 10).toInt() / 10.0).toString(),
color = Color.White,
style = MaterialTheme.typography.labelSmall,
)
}
}
}
// "Already in library" scrim overlay.
if (inLibrary) {
Box(
modifier = Modifier
.matchParentSize()
.clip(RoundedCornerShape(topStart = 8.dp, topEnd = 8.dp))
.background(Color.Black.copy(alpha = 0.45f)),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.BookmarkAdded,
contentDescription = "Already in library",
tint = Color.White,
modifier = Modifier.size(32.dp),
)
}
}
}
Text(
text = title.ifBlank { "Unknown" },
style = MaterialTheme.typography.bodySmall,
fontWeight = FontWeight.Medium,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
)
}
}
}
@Composable
private fun TrackerItemDialog(
search: DbTrackSearch,
matchedManga: Manga?,
trackerSyncId: Int?,
onOpenInLibrary: (Manga) -> Unit,
onBindToLibrary: (Manga) -> Unit,
onAddToLibrary: (String) -> Unit,
onOpenInBrowser: (String) -> Unit,
onDismiss: () -> Unit,
) {
val title = search.title.orEmpty().ifBlank { "Unknown" }
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
title = { Text(title, maxLines = 2, overflow = TextOverflow.Ellipsis) },
text = {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
CoverImage(
model = search.coverUrl.takeIf { it.isNotBlank() },
contentDescription = title,
fallbackInitials = title.firstOrNull()?.toString()?.uppercase(),
modifier = Modifier
.width(96.dp)
.aspectRatio(2f / 3f)
.clip(RoundedCornerShape(8.dp)),
)
Column(
modifier = Modifier
.weight(1f)
.heightIn(max = 240.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
if (search.status.isNotBlank()) {
Text(
search.status,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
search.score?.takeIf { it > 0.0 }?.let { sc ->
Badge {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Filled.Star, contentDescription = null, modifier = Modifier.size(12.dp))
Spacer(Modifier.width(2.dp))
Text(((sc * 10).toInt() / 10.0).toString())
}
}
}
search.totalChapter?.let { count ->
Text(
"$count ch",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (matchedManga != null) {
Text(
"Already in your library",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
if (search.summary.isNotBlank()) {
Text(
search.summary,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 8,
overflow = TextOverflow.Ellipsis,
)
}
}
}
},
confirmButton = {
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
if (matchedManga != null) {
TextButton(onClick = { onOpenInLibrary(matchedManga) }) { Text("Open in library") }
TextButton(onClick = { onBindToLibrary(matchedManga) }) { Text("Bind / migrate") }
} else {
// Mangayomi's track_library_add: unmatched tracker titles jump to a
// cross-source search so the entry can be added to the library.
TextButton(onClick = { onAddToLibrary(title) }) { Text("Add to library") }
}
val url = search.trackingUrl
if (!url.isNullOrBlank()) {
TextButton(onClick = { onOpenInBrowser(url) }) { Text("Open in browser") }
}
}
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(Res.string.ui_close)) }
},
)
// trackerSyncId reserved for future per-tracker actions (e.g. unbind on a
// matched entry). Kept on the signature so callers don't need to re-look it up.
@Suppress("UNUSED_PARAMETER") fun ignore(id: Int?) = Unit
ignore(trackerSyncId)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/TrackerLibraryViewModel.kt
- Source · implementation · 275 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
34: data class TrackerLibraryState(
57: internal fun TrackerLibraryState.matchInLibrary(search: DbTrackSearch): Manga? =
60: class TrackerLibraryViewModel(
104: fun selectTracker(tracker: TrackerService?) {
111: fun selectItemType(itemType: ItemType) {
119: fun load() {
147: fun search(text: String) {
164: fun clearSearch() {
170: fun bindToLibrary(manga: Manga, search: DbTrackSearch) {
184: data class TrackerLibrarySectionSpec(
196: internal fun trackerLibrarySections(syncId: Int, itemType: ItemType): List<TrackerLibrarySectionSpec> {
Exact file bytes / download · SHA-256 ef2451eabba31e2a0c0864ad81048ab7f2669343a896ac057a51b91b43659358.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KitsuTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TrackerService
import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.orderedTrackers
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
data class TrackerLibraryState(
val trackers: List<TrackerService> = emptyList(),
val selectedTracker: TrackerService? = null,
/** The tracker library's own item-type cursor, seeded from the root one. */
val itemType: ItemType = ItemType.Manga,
/** Signed-in account of [selectedTracker], if any. */
val account: DbTrackPreference? = null,
val sections: List<TrackerLibrarySectionSpec> = emptyList(),
/** Section label → loaded entries. */
val sectionResults: Map<String, List<DbTrackSearch>> = emptyMap(),
/** Non-blank while a search result section is shown. */
val submittedQuery: String = "",
val searchResults: List<DbTrackSearch> = emptyList(),
val loading: Boolean = false,
val error: String? = null,
/** Library titles of [itemType] keyed by trimmed, lower-cased name. */
val libraryByTitle: Map<String, Manga> = emptyMap(),
)
/**
* Tracker entries don't carry a library id, so a case-insensitive title match is the closest
* approximation of "already in the library".
*/
internal fun TrackerLibraryState.matchInLibrary(search: DbTrackSearch): Manga? =
search.title?.trim()?.lowercase()?.let(libraryByTitle::get)
class TrackerLibraryViewModel(
allTrackers: List<TrackerService>,
private val repository: YokanRepository,
settings: SettingsStore,
initialItemType: ItemType,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(
TrackerLibraryState(itemType = initialItemType, sections = trackerLibrarySections(-1, initialItemType)),
)
val state: StateFlow<TrackerLibraryState> = _state.asStateFlow()
private var loadJob: Job? = null
private var searchJob: Job? = null
init {
viewModelScope.launch {
settings.db.map { orderedTrackers(allTrackers, it) }.distinctUntilChanged().collect { trackers ->
val current = state.value
// A changed tracker count resets the selection to the first tracker; a reorder keeps it.
val keep = current.selectedTracker != null && trackers.size == current.trackers.size
val selected = if (keep) current.selectedTracker else trackers.firstOrNull()
_state.update { it.copy(trackers = trackers) }
selectTracker(selected)
}
}
viewModelScope.launch {
combine(
_state.map { it.selectedTracker?.syncId }.distinctUntilChanged(),
repository.snapshots.map { it.trackPreferences }.distinctUntilChanged(),
) { syncId, preferences -> syncId?.let { id -> preferences.firstOrNull { it.syncId == id.toLong() } } }
.collect { account -> _state.update { it.copy(account = account) } }
}
viewModelScope.launch {
combine(
_state.map { it.itemType }.distinctUntilChanged(),
repository.observe({ it.mangas to it.settings }, workDispatcher) { },
) { type, _ -> type }
.map { type -> repository.allTitles(type).associateBy { it.name.trim().lowercase() } }
.flowOn(workDispatcher)
.collect { titles -> _state.update { it.copy(libraryByTitle = titles) } }
}
}
fun selectTracker(tracker: TrackerService?) {
if (tracker === state.value.selectedTracker) return
_state.update { it.copy(selectedTracker = tracker) }
clearSearch()
load()
}
fun selectItemType(itemType: ItemType) {
if (itemType == state.value.itemType) return
_state.update { it.copy(itemType = itemType) }
clearSearch()
load()
}
/** Reloads every section of the selected tracker, one after another. */
fun load() {
val current = state.value
val sections = trackerLibrarySections(current.selectedTracker?.syncId ?: -1, current.itemType)
_state.update { it.copy(sections = sections) }
val tracker = current.selectedTracker ?: return
loadJob?.cancel()
_state.update { it.copy(loading = true, error = null, sectionResults = emptyMap()) }
loadJob = viewModelScope.launch {
sections.forEach { spec ->
catchingNonCancellation {
withContext(workDispatcher) {
if (spec.rankingType == null) {
tracker.fetchUserData(spec.isMangaFlag)
} else {
tracker.fetchGeneralData(spec.isMangaFlag, spec.rankingType)
}
}
}.onSuccess { entries ->
_state.update { it.copy(sectionResults = it.sectionResults + (spec.label to entries)) }
}.onFailure { failure ->
// User lists often require auth; only surface errors from public sections.
if (spec.rankingType != null) _state.update { it.copy(error = it.error ?: failure.message) }
}
}
_state.update { it.copy(loading = false) }
}
}
fun search(text: String) {
val current = state.value
val tracker = current.selectedTracker ?: return
if (text.isBlank()) {
clearSearch()
return
}
val isManga = current.itemType != ItemType.Anime
_state.update { it.copy(submittedQuery = text) }
searchJob?.cancel()
searchJob = viewModelScope.launch {
catchingNonCancellation { withContext(workDispatcher) { tracker.search(text, isManga) } }
.onSuccess { results -> _state.update { it.copy(searchResults = results) } }
.onFailure { failure -> _state.update { it.copy(error = failure.message ?: "Search failed") } }
}
}
fun clearSearch() {
searchJob?.cancel()
_state.update { it.copy(submittedQuery = "", searchResults = emptyList()) }
}
/** Binds [manga] to [search], tagged with the selected tracker. */
fun bindToLibrary(manga: Manga, search: DbTrackSearch) {
val syncId = state.value.selectedTracker?.syncId
val payload = if (syncId != null) search.copy(syncId = syncId) else search
repository.bindTrack(manga.id, payload, manga.itemType)
}
}
/**
* One horizontally-scrolling row in the tracker library. `rankingType == null`
* loads the user's own list (Continue reading/watching); otherwise the key is
* handed to [TrackerService.fetchGeneralData].
* `isMangaFlag` mirrors Mangayomi's parameter reuse — for Simkl/Trakt it means
* "movies" instead of "manga".
*/
data class TrackerLibrarySectionSpec(
val label: String,
val rankingType: String?,
val isMangaFlag: Boolean,
)
/** Ranking/browse sections exist for the Mangayomi providers and the metadata source only ([trackerLibrarySections]). */
internal val TrackerService.hasTrackerLibrary: Boolean
get() = isMetadataSource ||
syncId in setOf(MalTrackerSyncId, AnilistTrackerSyncId, KitsuTrackerSyncId, SimklTrackerSyncId, TraktTrackerSyncId)
/** Provider-specific section lists mirroring Mangayomi's tracker_library_screen.dart. */
internal fun trackerLibrarySections(syncId: Int, itemType: ItemType): List<TrackerLibrarySectionSpec> {
val isAnime = itemType == ItemType.Anime
return when (syncId) {
MalTrackerSyncId -> if (isAnime) {
listOf(
TrackerLibrarySectionSpec("Continue watching", null, false),
TrackerLibrarySectionSpec("Airing Anime", "airing", false),
TrackerLibrarySectionSpec("Popular Anime", "bypopularity", false),
TrackerLibrarySectionSpec("Upcoming Anime", "upcoming", false),
)
} else {
listOf(
TrackerLibrarySectionSpec("Continue reading", null, true),
TrackerLibrarySectionSpec("Popular Manga", "bypopularity", true),
TrackerLibrarySectionSpec("Top Manga", "manga", true),
TrackerLibrarySectionSpec("Top Manhwa", "manhwa", true),
TrackerLibrarySectionSpec("Top Manhua", "manhua", true),
)
}
AnilistTrackerSyncId -> if (isAnime) {
listOf(
TrackerLibrarySectionSpec("Continue watching", null, false),
TrackerLibrarySectionSpec("Upcoming Anime", "upcoming", false),
TrackerLibrarySectionSpec("Popular Anime", "popular", false),
TrackerLibrarySectionSpec("Trending Anime", "trending", false),
TrackerLibrarySectionSpec("Latest Anime", "latest", false),
)
} else {
listOf(
TrackerLibrarySectionSpec("Continue reading", null, true),
TrackerLibrarySectionSpec("Upcoming Manga", "upcoming", true),
TrackerLibrarySectionSpec("Popular Manga", "popular", true),
TrackerLibrarySectionSpec("Trending Manga", "trending", true),
TrackerLibrarySectionSpec("Latest Manga", "latest", true),
)
}
KitsuTrackerSyncId -> if (isAnime) {
listOf(
TrackerLibrarySectionSpec("Continue watching", null, false),
TrackerLibrarySectionSpec("Popular Anime", "popular", false),
TrackerLibrarySectionSpec("Latest Anime", "latest", false),
TrackerLibrarySectionSpec("Best Rated Anime", "best", false),
)
} else {
listOf(
TrackerLibrarySectionSpec("Continue reading", null, true),
TrackerLibrarySectionSpec("Popular Manga", "popular", true),
TrackerLibrarySectionSpec("Latest Manga", "latest", true),
TrackerLibrarySectionSpec("Best Rated Manga", "best", true),
)
}
SimklTrackerSyncId -> listOf(
TrackerLibrarySectionSpec("Continue watching movies", null, true),
TrackerLibrarySectionSpec("Continue watching series", null, false),
TrackerLibrarySectionSpec("Trending Movies", "trending", true),
TrackerLibrarySectionSpec("Trending Series", "trending", false),
TrackerLibrarySectionSpec("Airing Series", "airing", false),
TrackerLibrarySectionSpec("Top Series (All Time)", "best", false),
)
TraktTrackerSyncId -> listOf(
TrackerLibrarySectionSpec("Continue watching movies", null, true),
TrackerLibrarySectionSpec("Continue watching series", null, false),
TrackerLibrarySectionSpec("Trending Movies", "trending", true),
TrackerLibrarySectionSpec("Trending Series", "trending", false),
TrackerLibrarySectionSpec("Popular Movies", "popular", true),
TrackerLibrarySectionSpec("Popular Series", "popular", false),
TrackerLibrarySectionSpec("Top Movies (All Time)", "favorited/all", true),
TrackerLibrarySectionSpec("Top Series (All Time)", "favorited/all", false),
)
else -> {
val isManga = !isAnime
listOf(
TrackerLibrarySectionSpec(if (isAnime) "Continue watching" else "Continue reading", null, isManga),
TrackerLibrarySectionSpec("Trending", "trending", isManga),
TrackerLibrarySectionSpec("Popular", "popular", isManga),
TrackerLibrarySectionSpec("Top", "top", isManga),
)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/UpdateErrorsScreen.kt
- Source · implementation · 186 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
50: internal fun UpdateErrorsRoute(nav: Navigator) {
73: internal fun UpdateErrorsScreen(
Exact file bytes / download · SHA-256 70ad0fae3475766befae5033949837e2c50adc03f3c57331c16d3c9c0797135d.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.SwapHoriz
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbUpdateError
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.library.withoutUpdateError
import eu.friedcutlet.yokan.ui.components.CoverImage
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
@Composable
internal fun UpdateErrorsRoute(nav: Navigator) {
val settings = YokanRuntime.settings
val repository = YokanRuntime.repository
val db by settings.db.collectAsStateWithLifecycle()
val errors = db.updateErrors.orEmpty()
val titles by produceState(emptyMap<Long, Manga>(), errors) {
value = withContext(Dispatchers.Default) {
errors.mapNotNull { error -> repository.manga(error.mangaId)?.let { error.mangaId to it } }.toMap()
}
}
UpdateErrorsScreen(
errors = errors,
titles = titles,
title = "Update errors",
onBack = nav::back,
onMigrate = { mangaId -> nav.navigate(Route.Migrate(mangaId)) },
onDismissError = { mangaId -> settings.updateDb { it.withoutUpdateError(mangaId) } },
onClearErrors = { settings.updateDb { it.copy(updateErrors = emptyList()) } },
)
}
@Composable
@OptIn(ExperimentalMaterial3Api::class)
internal fun UpdateErrorsScreen(
errors: List<DbUpdateError>,
titles: Map<Long, Manga>,
title: String,
onBack: () -> Unit,
onMigrate: (mangaId: Long) -> Unit,
onDismissError: (mangaId: Long) -> Unit,
onClearErrors: () -> Unit,
) {
Scaffold(
topBar = {
TopAppBar(
title = { Text(title) },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back))
}
},
actions = {
if (errors.isNotEmpty()) {
IconButton(
onClick = onClearErrors,
) {
Icon(Icons.Filled.Delete, contentDescription = "Clear all")
}
}
},
)
},
) { padding ->
if (errors.isEmpty()) {
Box(
modifier = Modifier.fillMaxSize().padding(padding),
contentAlignment = Alignment.Center,
) {
Text(
text = "No update errors",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
LazyColumn(
modifier = Modifier.fillMaxSize().padding(padding),
contentPadding = PaddingValues(vertical = 8.dp),
) {
items(errors, key = { it.mangaId }) { err ->
val manga = titles[err.mangaId]
ListItem(
leadingContent = {
Box(
modifier = Modifier
.size(width = 40.dp, height = 56.dp)
.clip(RoundedCornerShape(4.dp)),
) {
CoverImage(
model = manga?.let { it.customCoverImage ?: it.customCoverFromTracker ?: it.imageUrl },
contentDescription = "${err.name} cover",
modifier = Modifier.fillMaxSize(),
shape = RoundedCornerShape(4.dp),
fallbackInitials = err.name.split(" ").take(2)
.joinToString("") { it.firstOrNull()?.uppercase() ?: "" },
)
}
},
headlineContent = {
Text(
text = err.name,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.SemiBold,
)
},
supportingContent = {
Text(
text = err.error,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
},
trailingContent = {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
if (manga != null) {
IconButton(
onClick = { onMigrate(manga.id) },
) {
Icon(
Icons.Filled.SwapHoriz,
contentDescription = "Migrate",
tint = MaterialTheme.colorScheme.primary,
)
}
}
IconButton(
onClick = { onDismissError(err.mangaId) },
) {
Icon(
Icons.Filled.Close,
contentDescription = "Dismiss",
)
}
}
},
)
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/UpdatesFilters.kt
- Source · implementation · 33 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: internal fun filterUpdateRows(
33: private fun matches(state: Int, value: Boolean): Boolean = when (state) { 1 -> value; 2 -> !value; else -> true }
Exact file bytes / download · SHA-256 ab9bfcf751f1dbc02f0189bf0bef6984189e89b1e1691575cc5013b29efd452e.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import eu.friedcutlet.yokan.database.DbUpdatesFilter
import eu.friedcutlet.yokan.database.UpdatesFilterKind
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.normalizeScanlator
import eu.friedcutlet.yokan.services.library.ActivityCategoryMatcher
/** No database or per-row chapter scans. Inputs are the already observed activity projection. */
internal fun filterUpdateRows(
rows: List<UpdateRowModel>,
filter: DbUpdatesFilter,
categories: List<Category>,
downloadedChapterIds: Set<Long>,
excludedScanlators: Map<Long, Set<String>>,
): List<UpdateRowModel> {
if (!filter.active) return rows
val categoryMatcher = ActivityCategoryMatcher(filter.categories, categories.mapTo(mutableSetOf()) { it.id })
return rows.filter { row ->
val chapter = row.chapter
val progress = chapter?.lastPageRead?.toDoubleOrNull()?.takeIf { it.isFinite() } ?: 0.0
matches(filter.value(UpdatesFilterKind.Downloaded), row.update.chapterId in downloadedChapterIds) &&
matches(filter.value(UpdatesFilterKind.Unread), !row.isRead) &&
// Started means unfinished progress; the inverse means untouched, also unfinished.
(filter.value(UpdatesFilterKind.Started) == 0 || (!row.isRead && matches(filter.value(UpdatesFilterKind.Started), progress > 0))) &&
matches(filter.value(UpdatesFilterKind.Bookmarked), chapter?.isBookmarked == true) &&
(!filter.hideExcludedScanlators || chapter == null ||
normalizeScanlator(chapter.scanlator) !in excludedScanlators[row.update.mangaId].orEmpty()) &&
categoryMatcher.matches(row.manga?.categories)
}
}
private fun matches(state: Int, value: Boolean): Boolean = when (state) { 1 -> value; 2 -> !value; else -> true }
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/UpdatesScreen.kt
- Source · implementation · 606 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
86: internal fun UpdatesRoute(nav: Navigator) {
119: private class UpdateRowActions(
130: fun UpdatesScreen(
348: private fun updateRows(
358: private fun UpdatesPage(
406: private fun UpdateRow(row: UpdateRowModel, actions: UpdateRowActions) {
477: private fun DownloadStatusIcon(
Exact file bytes / download · SHA-256 c89c2b31976159ce2760f1656325b329e7bb4945b2a0e8f9a85e81effae4fe89.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDownward
import androidx.compose.material.icons.filled.DownloadDone
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.NewReleases
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.FilterList
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.DbUpdatesFilter
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_remove
import yokan.composeapp.generated.resources.activity_filters
import yokan.composeapp.generated.resources.delete
import yokan.composeapp.generated.resources.ok
import androidx.compose.material.icons.outlined.DeleteSweep as DeleteSweepOutlined
import androidx.compose.material.icons.outlined.Refresh as RefreshOutlined
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import kotlinx.coroutines.launch
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import eu.friedcutlet.yokan.ui.formatTimestamp
import eu.friedcutlet.yokan.ui.components.AppBarSearchField
import eu.friedcutlet.yokan.ui.components.CoverImage
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
@Composable
internal fun UpdatesRoute(nav: Navigator) {
val viewModel = viewModel {
UpdatesViewModel(
repository = YokanRuntime.repository,
settings = YokanRuntime.settings,
libraryIndex = YokanRuntime.libraryIndex,
libraryUpdates = YokanRuntime.libraryUpdates,
downloads = YokanRuntime.chapterDownloads,
)
}
val state by viewModel.state.collectAsStateWithLifecycle()
val hidden by nav.hiddenSections.collectAsStateWithLifecycle()
val itemType by nav.itemType.collectAsStateWithLifecycle()
UpdatesScreen(
state = state,
visibleTypes = remember(hidden) { visibleItemTypes(hidden) },
initialItemType = itemType,
onItemTypeSettled = nav::selectItemType,
onOpenUpdateErrors = { nav.navigate(Route.UpdateErrors) },
onRefresh = viewModel::refresh,
onDismissFailedUpdates = viewModel::dismissFailedUpdates,
onClearUpdates = viewModel::clearUpdates,
onOpenChapter = { manga, chapter -> nav.navigate(Route.Reader(manga.id, chapter.id)) },
onOpenDetail = { manga -> nav.navigate(Route.Detail(manga.id)) },
onDownload = viewModel::download,
onCancelDownload = viewModel::cancelDownload,
onRemoveDownload = viewModel::removeDownload,
onOpenDownloadLocation = viewModel::openDownloadLocation,
onUpdateFilters = viewModel::updateFilters,
)
}
/** Callbacks of one Updates row, bundled so pages and rows take a single parameter. */
private class UpdateRowActions(
val onOpenChapter: (Manga, Chapter) -> Unit,
val onOpenDetail: (Manga) -> Unit,
val onDownload: (UpdateRowModel) -> Unit,
val onCancelDownload: (downloadId: Long) -> Unit,
val onRemoveDownload: (downloadId: Long) -> Unit,
val onOpenDownloadLocation: (downloadId: Long) -> Unit,
)
@OptIn(ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
fun UpdatesScreen(
state: UpdatesState,
visibleTypes: List<ItemType>,
initialItemType: ItemType,
onItemTypeSettled: (ItemType) -> Unit,
onOpenUpdateErrors: () -> Unit,
onRefresh: (ItemType) -> Unit,
onDismissFailedUpdates: () -> Unit,
onClearUpdates: (ItemType) -> Unit,
onOpenChapter: (Manga, Chapter) -> Unit,
onOpenDetail: (Manga) -> Unit,
onDownload: (UpdateRowModel) -> Unit,
onCancelDownload: (downloadId: Long) -> Unit,
onRemoveDownload: (downloadId: Long) -> Unit,
onOpenDownloadLocation: (downloadId: Long) -> Unit,
onUpdateFilters: (ItemType, (DbUpdatesFilter) -> DbUpdatesFilter) -> Unit = { _, _ -> },
) {
if (visibleTypes.isEmpty()) {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Updates") },
expandedHeight = 56.dp,
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent),
)
},
) { padding ->
EmptyState(
modifier = Modifier.fillMaxSize().padding(padding),
icon = Icons.Filled.NewReleases,
title = "No updates yet",
)
}
return
}
val initialPage = remember(visibleTypes, initialItemType) {
visibleTypes.indexOf(initialItemType).takeIf { it >= 0 } ?: 0
}
val pagerState = rememberPagerState(initialPage = initialPage, pageCount = { visibleTypes.size })
val selectedPage = pagerState.currentPage.coerceIn(visibleTypes.indices)
val selectedTab = visibleTypes[selectedPage]
var searching by remember { mutableStateOf(false) }
var query by remember { mutableStateOf("") }
var clearAllOpen by remember { mutableStateOf(false) }
var filtersOpen by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val rowActions = remember(onOpenChapter, onOpenDetail, onDownload, onCancelDownload, onRemoveDownload, onOpenDownloadLocation) {
UpdateRowActions(onOpenChapter, onOpenDetail, onDownload, onCancelDownload, onRemoveDownload, onOpenDownloadLocation)
}
LaunchedEffect(visibleTypes.size) {
if (pagerState.currentPage > visibleTypes.lastIndex) {
pagerState.scrollToPage(visibleTypes.lastIndex)
}
}
LaunchedEffect(pagerState, visibleTypes) {
snapshotFlow { pagerState.settledPage }.collect { page ->
val type = visibleTypes.getOrNull(page) ?: return@collect
onItemTypeSettled(type)
query = ""
searching = false
}
}
val entries = remember(state.rowsByType, selectedTab, query) {
updateRows(state.rowsByType, selectedTab, query)
}
val refreshing = state.refreshing
val triggerRefresh: () -> Unit = { onRefresh(selectedTab) }
Scaffold(
topBar = {
TopAppBar(
expandedHeight = 56.dp,
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent),
title = {
if (searching) {
AppBarSearchField(
query = query,
placeholder = "Search updates",
onQueryChange = { query = it },
onClose = {
searching = false
query = ""
},
)
} else {
Text("Updates")
}
},
actions = {
IconButton(onClick = { filtersOpen = true }) {
Icon(Icons.Filled.FilterList, stringResource(Res.string.activity_filters),
tint = if (state.filters.updates(selectedTab.toDb()).active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant)
}
if (!searching) {
if (state.hasUpdateErrors) {
IconButton(
modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp),
onClick = onOpenUpdateErrors,
) {
Icon(
imageVector = Icons.Filled.ErrorOutline,
contentDescription = "Update errors",
tint = MaterialTheme.colorScheme.error,
)
}
}
IconButton(modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp), onClick = { searching = true }) {
Icon(Icons.Filled.Search, contentDescription = "Search updates")
}
}
IconButton(modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp), onClick = triggerRefresh, enabled = !refreshing) {
Icon(Icons.Outlined.RefreshOutlined, contentDescription = "Refresh library")
}
IconButton(
modifier = Modifier.size(40.dp).offset(x = 4.dp, y = 0.375.dp),
onClick = { clearAllOpen = true },
enabled = entries.isNotEmpty(),
) {
Icon(Icons.Outlined.DeleteSweepOutlined, contentDescription = "Clear all updates")
}
},
)
},
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding),
) {
ItemTypePagerTabRow(
types = visibleTypes,
pagerState = pagerState,
unreadCounts = remember(state.rowsByType) {
state.rowsByType.mapValues { (_, rows) -> rows.size }
},
onSelect = { index ->
if (index != pagerState.currentPage) query = ""
scope.launch { pagerState.animateScrollToPage(index) }
},
)
PullToRefreshBox(
modifier = Modifier.fillMaxSize(),
isRefreshing = refreshing,
onRefresh = triggerRefresh,
) {
HorizontalPager(
state = pagerState,
beyondViewportPageCount = 1,
modifier = Modifier.fillMaxSize(),
) { page ->
val type = visibleTypes[page]
val pageEntries = remember(state.rowsByType, type, query) {
updateRows(state.rowsByType, type, query)
}
UpdatesPage(
entries = pageEntries,
query = query,
lastUpdatedAt = state.lastUpdatedAt[type],
formatTimestamp = { millis -> formatTimestamp(millis, state.dateFormat, state.relativeTimestamps) },
actions = rowActions,
)
}
}
}
}
if (filtersOpen) {
val filter = state.filters.updates(selectedTab.toDb())
ActivityFilterDialog(state.categoriesByType[selectedTab].orEmpty(), filter.categories,
onCategoryFilter = { change -> onUpdateFilters(selectedTab) { it.copy(categories = change(it.categories)) } },
onDismiss = { filtersOpen = false }, updatesFilter = filter,
onUpdatesFilter = { change -> onUpdateFilters(selectedTab, change) })
}
if (clearAllOpen) {
eu.friedcutlet.yokan.ui.components.ConfirmDialog(
title = "Remove everything",
message = "Remove all updates for ${selectedTab.label}?",
confirmLabel = stringResource(Res.string.action_remove),
danger = true,
onConfirm = { onClearUpdates(selectedTab) },
onDismiss = { clearAllOpen = false },
)
}
state.failedUpdates?.let { errors ->
if (errors.isNotEmpty()) {
val plural = if (errors.size == 1) selectedTab.label.lowercase() else "${selectedTab.label.lowercase()}s"
androidx.compose.material3.AlertDialog(
onDismissRequest = onDismissFailedUpdates,
title = { Text("Failed to update ${errors.size} $plural") },
text = {
Box(modifier = Modifier.fillMaxWidth().heightIn(max = 240.dp)) {
LazyColumn(modifier = Modifier.fillMaxWidth()) {
items(errors, key = { it.mangaId }) { err ->
Text(
text = "• ${err.name}",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(vertical = 2.dp),
)
}
}
}
},
confirmButton = {
androidx.compose.material3.TextButton(onClick = onDismissFailedUpdates) {
Text(stringResource(Res.string.ok))
}
},
)
}
}
}
private fun updateRows(
rowsByType: Map<ItemType, List<UpdateRowModel>>,
type: ItemType,
query: String,
): List<UpdateRowModel> {
val rows = rowsByType[type].orEmpty()
return if (query.isBlank()) rows else rows.filter { it.update.title.contains(query, ignoreCase = true) }
}
@Composable
private fun UpdatesPage(
entries: List<UpdateRowModel>,
query: String,
lastUpdatedAt: Long?,
formatTimestamp: (Long) -> String,
actions: UpdateRowActions,
) {
if (entries.isEmpty()) {
EmptyState(
modifier = Modifier.fillMaxSize(),
icon = Icons.Filled.NewReleases,
title = if (query.isNotEmpty()) "No matches" else "No recent updates",
)
return
}
val grouped = remember(entries) { groupByDayBucket(entries) { it.update.updatedAt } }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(top = 11.dp),
) {
lastUpdatedAt?.let { updatedAt ->
item(key = "last-updated") {
Text(
text = "Library last updated: ${formatTimestamp(updatedAt)}",
style = MaterialTheme.typography.bodyMedium,
fontStyle = FontStyle.Italic,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier.padding(
start = 10.dp,
end = 10.dp,
top = 10.dp,
bottom = 20.dp,
),
)
}
}
grouped.forEach { (bucket, items) ->
item(key = "u-$bucket") {
DateGroupHeader(bucket)
}
items(items, key = { it.update.id }) { row ->
UpdateRow(row, actions)
}
}
}
}
@Composable
private fun UpdateRow(row: UpdateRowModel, actions: UpdateRowActions) {
val manga = row.manga
val chapter = row.chapter
val title = row.title
val chapterName = row.chapterName
val isRead = row.isRead
Row(
modifier = Modifier
.fillMaxWidth()
.height(55.dp)
.hoverHighlight(onClick = {
if (manga != null && chapter != null) actions.onOpenChapter(manga, chapter)
})
.padding(horizontal = 13.dp, vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically,
) {
CoverImage(
model = manga?.let { it.customCoverImage ?: it.customCoverFromTracker ?: it.imageUrl },
contentDescription = "$title cover",
modifier = Modifier
.size(width = 40.dp, height = 45.dp)
.clip(RoundedCornerShape(5.dp))
.then(
if (manga != null) {
Modifier.hoverHighlight(onClick = { actions.onOpenDetail(manga) })
} else {
Modifier
},
),
shape = RoundedCornerShape(5.dp),
fallbackInitials = title.split(" ").take(2)
.joinToString("") { it.firstOrNull()?.uppercase() ?: "" },
)
Column(
modifier = Modifier
.weight(1f)
.padding(horizontal = 10.dp),
verticalArrangement = Arrangement.Center,
) {
Text(
text = title,
fontSize = 14.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = chapterName,
fontSize = 11.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
color = if (isRead) {
Color.Gray
} else {
MaterialTheme.colorScheme.onSurface
},
)
}
if (manga != null && chapter != null) {
DownloadStatusIcon(
download = row.download,
actions = actions,
onDownload = { actions.onDownload(row) },
)
} else {
Spacer(Modifier.width(35.dp))
}
}
}
@Composable
private fun DownloadStatusIcon(
download: DbDownload?,
actions: UpdateRowActions,
onDownload: () -> Unit,
) {
var menuExpanded by remember(download?.id) { mutableStateOf(false) }
val indicatorColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
Box(
modifier = Modifier
.width(35.dp)
.height(41.dp)
.padding(vertical = 3.dp),
contentAlignment = Alignment.Center,
) {
if (download == null) {
IconButton(
modifier = Modifier.size(35.dp),
onClick = onDownload,
) {
Icon(
imageVector = Icons.Filled.ArrowDownward,
contentDescription = "Download",
modifier = Modifier.size(18.dp),
tint = indicatorColor,
)
}
CircularProgressIndicator(
progress = { 1f },
modifier = Modifier.size(20.dp),
color = indicatorColor,
strokeWidth = 2.dp,
)
} else {
val completed = download.isDownload == true
val succeeded = download.succeeded ?: 0
val total = download.total ?: 0
val progress = if (total > 0) {
(succeeded.toFloat() / total.coerceAtLeast(1)).coerceIn(0f, 1f)
} else {
0f
}
val running = download.isStartDownload == true
IconButton(
modifier = Modifier.size(35.dp),
onClick = { menuExpanded = true },
) {
when {
completed -> Icon(
imageVector = Icons.Filled.DownloadDone,
contentDescription = "Downloaded",
modifier = Modifier.size(25.dp),
tint = indicatorColor,
)
succeeded > 0 -> {
Icon(
imageVector = Icons.Filled.ArrowDownward,
contentDescription = "Download in progress",
modifier = Modifier.size(18.dp),
tint = indicatorColor,
)
CircularProgressIndicator(
progress = { progress },
modifier = Modifier.size(20.dp),
color = indicatorColor,
strokeWidth = 2.dp,
)
}
running -> {
Icon(
imageVector = Icons.Filled.ArrowDownward,
contentDescription = "Download queued",
modifier = Modifier.size(18.dp),
tint = indicatorColor,
)
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
color = indicatorColor,
strokeWidth = 2.dp,
)
}
else -> Icon(
imageVector = Icons.Filled.Refresh,
contentDescription = "Download stopped",
modifier = Modifier.size(22.dp),
tint = MaterialTheme.colorScheme.error,
)
}
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = { menuExpanded = false },
) {
if (completed) {
DropdownMenuItem(
text = { Text("Send") },
onClick = {
menuExpanded = false
actions.onOpenDownloadLocation(download.id)
},
)
DropdownMenuItem(
text = { Text(stringResource(Res.string.delete)) },
onClick = {
menuExpanded = false
actions.onRemoveDownload(download.id)
},
)
} else {
DropdownMenuItem(
text = { Text("Start downloading") },
onClick = {
menuExpanded = false
actions.onCancelDownload(download.id)
onDownload()
},
)
DropdownMenuItem(
text = { Text(stringResource(Res.string.action_cancel)) },
onClick = {
menuExpanded = false
actions.onCancelDownload(download.id)
},
)
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/UpdatesViewModel.kt
- Source · implementation · 220 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
40: data class UpdateRowModel(
51: data class UpdatesState(
66: private class UpdatesSource(
73: private data class UpdatesPreferences(
78: class UpdatesViewModel(
140: fun updateFilters(type: ItemType, transform: (DbUpdatesFilter) -> DbUpdatesFilter) {
146: fun refresh(itemType: ItemType) {
155: fun dismissFailedUpdates() {
159: fun clearUpdates(itemType: ItemType) {
163: fun download(row: UpdateRowModel) {
169: fun cancelDownload(downloadId: Long) {
173: fun removeDownload(downloadId: Long) {
177: fun openDownloadLocation(downloadId: Long) {
182: private fun lastLibraryUpdate(titles: List<Manga>): Long? =
192: internal fun buildUpdateRows(
Exact file bytes / download · SHA-256 a6afd3829ec9f37965ceac82e6b0c6ec2712deeb66ca5b251b03b9402292e3c7.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observeSnapshot
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.data.toDomainMangas
import eu.friedcutlet.yokan.database.DbUpdatesFilter
import eu.friedcutlet.yokan.database.DbActivityPreferences
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.normalizeScanlator
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbUpdateError
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.UpdateEntry
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.download.ChapterDownloads
import eu.friedcutlet.yokan.services.library.LibraryUpdateController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/** One Updates row with its title, chapter and download resolved once per data change. */
data class UpdateRowModel(
val update: UpdateEntry,
val manga: Manga?,
val chapter: Chapter?,
val download: DbDownload?,
) {
val title: String = manga?.name?.takeIf { it.isNotBlank() } ?: update.title
val chapterName: String = chapter?.name?.takeIf { it.isNotBlank() } ?: update.chapterName
val isRead: Boolean = chapter?.isRead ?: update.isRead
}
data class UpdatesState(
/** Rows per item type, newest first. */
val rowsByType: Map<ItemType, List<UpdateRowModel>> = emptyMap(),
/** Latest update time of a favourite, non-local title per item type; absent when never updated. */
val lastUpdatedAt: Map<ItemType, Long> = emptyMap(),
val dateFormat: String = "",
val relativeTimestamps: Int = 0,
val hasUpdateErrors: Boolean = false,
val refreshing: Boolean = false,
/** Errors of the last manual refresh; non-null shows the failure dialog. */
val failedUpdates: List<DbUpdateError>? = null,
val categoriesByType: Map<ItemType, List<Category>> = emptyMap(),
val filters: DbActivityPreferences = DbActivityPreferences(),
)
private class UpdatesSource(
val updates: List<UpdateEntry>,
val titles: Map<Long, Manga>,
val lastUpdatedAt: Map<ItemType, Long>,
val categories: Map<ItemType, List<Category>>,
)
private data class UpdatesPreferences(
val filters: DbActivityPreferences,
val scanlators: Map<Long, Set<String>>,
)
class UpdatesViewModel(
private val repository: YokanRepository,
private val settings: SettingsStore,
libraryIndex: LibraryIndexStore,
private val libraryUpdates: LibraryUpdateController,
private val downloads: ChapterDownloads,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(UpdatesState())
val state: StateFlow<UpdatesState> = _state.asStateFlow()
init {
val source = repository.observeSnapshot({ listOf(it.updates, it.mangas, it.settings.titleMetadata, it.categories) }, workDispatcher) { snapshot ->
val titles = snapshot.mangas.toDomainMangas(snapshot.settings).associateBy { it.id }
UpdatesSource(
updates = snapshot.updates.mapNotNull { update ->
val id = update.mangaId ?: return@mapNotNull null
val manga = titles[id]
UpdateEntry(update.id, id, update.chapterId ?: 0L, manga?.itemType ?: ItemType.Manga,
manga?.name.orEmpty(), update.chapterName.orEmpty(), manga?.source.orEmpty(),
update.date.orEmpty(), false, update.updatedAt)
},
titles = titles,
lastUpdatedAt = titles.values.groupBy { it.itemType }.mapNotNull { (type, list) ->
lastLibraryUpdate(list)?.let { type to it }
}.toMap(),
categories = snapshot.categories.map { it.toDomain() }.groupBy { it.forItemType }
.mapValues { (_, values) -> values.sortedBy { it.position } },
)
}
val downloadRecords = repository.observeSnapshot({ it.downloads }, workDispatcher) { it.downloads }
viewModelScope.launch {
val rows = combine(source, libraryIndex.index.filter { it !== LibraryIndex.Empty }, downloadRecords) { data, index, records ->
Triple(data, buildUpdateRows(data.updates, data.titles, index, records), index.downloadedChapterIds)
}
val preferences = settings.db.map { db -> UpdatesPreferences(DbActivityPreferences(updates = db.features.activity.updates),
db.filterScanlatorList.orEmpty().mapNotNull { entry -> entry.mangaId?.let { id ->
id to entry.scanlators.orEmpty().map(::normalizeScanlator).toSet()
} }.distinctBy { it.first }.toMap())
}.distinctUntilChanged()
combine(rows, preferences) { (data, built, downloaded), prefs ->
Triple(data, built.mapValues { (type, values) -> filterUpdateRows(values, prefs.filters.updates(type.toDb()),
data.categories[type].orEmpty(), downloaded, prefs.scanlators) }, prefs.filters)
}.flowOn(workDispatcher)
.collect { (data, filtered, filters) ->
_state.update { it.copy(rowsByType = filtered, lastUpdatedAt = data.lastUpdatedAt,
categoriesByType = data.categories, filters = filters) }
}
}
viewModelScope.launch {
settings.db.collect { db ->
_state.update {
it.copy(
dateFormat = db.dateFormat,
relativeTimestamps = db.relativeTimesTamps,
hasUpdateErrors = db.updateErrors.orEmpty().isNotEmpty(),
)
}
}
}
}
fun updateFilters(type: ItemType, transform: (DbUpdatesFilter) -> DbUpdatesFilter) {
settings.updateDb { db -> db.copy(features = db.features.copy(activity = db.features.activity.let { prefs ->
prefs.withUpdates(type.toDb(), transform(prefs.updates(type.toDb())))
})) }
}
fun refresh(itemType: ItemType) {
if (state.value.refreshing) return
_state.update { it.copy(refreshing = true) }
viewModelScope.launch {
val errors = catchingNonCancellation { libraryUpdates.run(itemType) }.getOrNull()?.errors.orEmpty()
_state.update { it.copy(refreshing = false, failedUpdates = errors.ifEmpty { it.failedUpdates }) }
}
}
fun dismissFailedUpdates() {
_state.update { it.copy(failedUpdates = null) }
}
fun clearUpdates(itemType: ItemType) {
repository.clearUpdates(itemType)
}
fun download(row: UpdateRowModel) {
val manga = row.manga ?: return
val chapter = row.chapter ?: return
downloads.enqueue(manga, chapter, destinationRoot = null)
}
fun cancelDownload(downloadId: Long) {
downloads.cancel(downloadId)
}
fun removeDownload(downloadId: Long) {
downloads.remove(downloadId)
}
fun openDownloadLocation(downloadId: Long) {
downloads.openLocation(downloadId)
}
}
private fun lastLibraryUpdate(titles: List<Manga>): Long? =
titles.asSequence()
.filter { it.favorite && !it.isLocalArchive }
.maxOfOrNull { it.lastUpdateMillis }
?.takeIf { it > 0L }
/**
* Resolves every update's title, chapter and first download record once, grouped by item type and
* sorted newest first. The chapter is looked up only when the title still exists.
*/
internal fun buildUpdateRows(
updates: List<UpdateEntry>,
titles: Map<Long, Manga>,
index: LibraryIndex,
downloads: List<DbDownload>,
): Map<ItemType, List<UpdateRowModel>> {
val downloadByChapter = HashMap<Long, DbDownload>()
for (download in downloads) {
val chapterId = download.chapterId ?: continue
if (chapterId !in downloadByChapter) downloadByChapter[chapterId] = download
}
// Resolve each chapter once, including long-running titles with thousands of update records.
val chaptersByTitle = HashMap<Long, Map<Long, Chapter>>()
return updates.sortedByDescending { it.updatedAt }
.groupBy { it.itemType }
.mapValues { (_, entries) ->
entries.map { update ->
val manga = titles[update.mangaId]
UpdateRowModel(
update = update,
manga = manga,
chapter = manga?.let { title -> chaptersByTitle.getOrPut(title.id) {
index.chapters(title.id).associateBy { it.id }
}[update.chapterId] },
download = downloadByChapter[update.chapterId],
)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/applock/AppLockLifecycleEffect.kt
- Source · implementation · 31 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
17: fun AppLockLifecycleEffect(settings: SettingsStore, appLock: AppLockController) {
Exact file bytes / download · SHA-256 85b9cf4bbd5ff4359a14d277c3c652f54964ff357269fe8ca157c51f6c7f90fa.
Complete file
package eu.friedcutlet.yokan.ui.screens.applock
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.appLockDue
import eu.friedcutlet.yokan.services.applock.AppLockController
import eu.friedcutlet.yokan.util.nowMillis
/**
* Leaving the foreground locks the app when the Security setting is on. Timeout 0 locks as soon as
* the app leaves the foreground; longer timeouts are measured from ON_STOP and checked on ON_START.
*/
@Composable
fun AppLockLifecycleEffect(settings: SettingsStore, appLock: AppLockController) {
val backgroundedAt = remember { longArrayOf(-1L) }
LifecycleEventEffect(Lifecycle.Event.ON_STOP) {
val current = settings.db.value
if (!current.appLockEnabled) return@LifecycleEventEffect
if (current.features.privacy.appLockTimeoutMinutes == 0) appLock.reset() else backgroundedAt[0] = nowMillis()
}
LifecycleEventEffect(Lifecycle.Event.ON_START) {
val since = backgroundedAt[0].also { backgroundedAt[0] = -1L }
val current = settings.db.value
if (since >= 0 && current.appLockEnabled &&
appLockDue(current.features.privacy.appLockTimeoutMinutes, since, nowMillis())
) appLock.reset()
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/applock/AppLockOverlay.kt
- Source · implementation · 117 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
37: fun AppLockOverlay(
44: fun unlock() {
Exact file bytes / download · SHA-256 3c9612cb6139d9357f3f474cadc3488329e71855d5c9d3d2a34971fcd50dd6d9.
Complete file
package eu.friedcutlet.yokan.ui.screens.applock
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
/**
* Full-screen lock surface the app root stacks above everything while locked
* (Mangayomi's AppLockScreen over the router). [onUnlock] starts an authentication
* and reports whether it succeeded.
*/
@Composable
fun AppLockOverlay(
unlocked: Boolean,
supported: Boolean,
onUnlock: (onResult: (Boolean) -> Unit) -> Unit,
) {
var authenticating by remember { mutableStateOf(false) }
var failed by remember { mutableStateOf(false) }
fun unlock() {
authenticating = true
failed = false
onUnlock { ok ->
authenticating = false
failed = !ok
}
}
LaunchedEffect(Unit) {
if (!unlocked && !authenticating) unlock()
}
// No AppBar — full-screen overlay. Back press is intentionally ignored
// (PopScope(canPop:false) parity): the user must authenticate via the Unlock
// button. We do not register a BackHandler, so the surrounding host can
// decide whether back closes the screen; the screen itself takes no action.
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.surface),
contentAlignment = Alignment.Center,
) {
Column(
modifier = Modifier.padding(32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(20.dp),
) {
Box(
modifier = Modifier
.size(96.dp)
.background(
MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.6f),
RoundedCornerShape(24.dp),
),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.Lock,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(56.dp),
)
}
Text(
if (unlocked) "Unlocked" else "App is locked",
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.SemiBold,
)
Text(
when {
unlocked -> "You can now use the app."
!supported -> "Biometric authentication is unavailable on this device."
failed -> "Authentication failed. Tap Unlock to try again."
authenticating -> "Authenticating…"
else -> "Authenticate to unlock and continue using the application."
},
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
)
if (!unlocked) {
Button(
onClick = { if (!authenticating) unlock() },
enabled = !authenticating,
) {
Icon(Icons.Filled.Lock, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(if (authenticating) "Authenticating…" else "Unlock")
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/more/MoreScreen.kt
- Source · implementation · 165 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
51: internal fun MoreRoute(nav: Navigator) {
68: fun MoreScreen(
137: private fun MoreToggleRow(
159: private fun MoreNavigationRow(
Exact file bytes / download · SHA-256 d7e94d7fb55a0a63c81db7641b9609106ebea4e239112384c05b1152e99dddb1.
Complete file
package eu.friedcutlet.yokan.ui.screens.more
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Label
import androidx.compose.material.icons.outlined.CalendarMonth
import androidx.compose.material.icons.outlined.CloudOff
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.Groups
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.QueryStats
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Storage
import androidx.compose.material.icons.outlined.VisibilityOff
import androidx.compose.material3.Switch
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider as HorizontalDivider
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import org.jetbrains.compose.resources.painterResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.mangayomi_icon
import eu.friedcutlet.yokan.ui.navigation.NavSection
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.YokanListRow
import eu.friedcutlet.yokan.ui.status.LocalGlobalStatusOpener
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.global_status
@Composable
internal fun MoreRoute(nav: Navigator) {
val settings = YokanRuntime.settings
val user by settings.user.collectAsStateWithLifecycle()
val hiddenSections by nav.hiddenSections.collectAsStateWithLifecycle()
MoreScreen(
downloadedOnly = user.downloadedOnly,
incognitoMode = user.incognitoMode,
historyHidden = NavSection.History in hiddenSections,
onToggleDownloadedOnly = { settings.update { it.copy(downloadedOnly = !it.downloadedOnly) } },
onToggleIncognito = { settings.update { it.copy(incognitoMode = !it.incognitoMode) } },
onOpenGlobalStatus = LocalGlobalStatusOpener.current,
onNavigate = nav::navigate,
)
}
/** Mangayomi's edge-to-edge More hub, preserving its order and visual density. */
@Composable
fun MoreScreen(
downloadedOnly: Boolean,
incognitoMode: Boolean,
historyHidden: Boolean,
onToggleDownloadedOnly: () -> Unit,
onToggleIncognito: () -> Unit,
onOpenGlobalStatus: () -> Unit,
onNavigate: (Route) -> Unit,
) {
val scrollState = rememberScrollState()
Scaffold { innerPadding ->
ScrollbarBox(
state = scrollState,
modifier = Modifier.fillMaxSize().padding(innerPadding),
) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(scrollState),
) {
Spacer(Modifier.height(56.dp))
Image(
painter = painterResource(Res.drawable.mangayomi_icon),
contentDescription = null,
colorFilter = ColorFilter.tint(
if (eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor.current.luminance() < 0.5f) Color.White else Color.Black,
),
modifier = Modifier
.fillMaxWidth()
.height(180.dp)
.padding(vertical = 40.dp),
)
HorizontalDivider()
MoreToggleRow(
icon = Icons.Outlined.CloudOff,
title = "Downloaded only",
description = "Filters all entries in your library",
checked = downloadedOnly,
onCheckedChange = { onToggleDownloadedOnly() },
)
MoreToggleRow(
icon = Icons.Outlined.VisibilityOff,
title = "Incognito mode",
description = "Pauses reading and watching history",
checked = incognitoMode,
onCheckedChange = { onToggleIncognito() },
)
HorizontalDivider()
MoreNavigationRow(stringResource(Res.string.global_status), Icons.Outlined.Info, onOpenGlobalStatus)
if (historyHidden) {
MoreNavigationRow("History", Icons.Outlined.History) { onNavigate(Route.History) }
}
MoreNavigationRow("Download queue", Icons.Outlined.Download) { onNavigate(Route.Settings(SettingsPage.DownloadQueue)) }
MoreNavigationRow("Local media", Icons.Outlined.Storage) { onNavigate(Route.LocalLibraryOverview) }
MoreNavigationRow("Categories", Icons.AutoMirrored.Outlined.Label) { onNavigate(Route.Settings(SettingsPage.Categories)) }
MoreNavigationRow("Statistics", Icons.Outlined.QueryStats) { onNavigate(Route.Settings(SettingsPage.Statistics)) }
MoreNavigationRow("Calendar", Icons.Outlined.CalendarMonth) { onNavigate(Route.Settings(SettingsPage.Calendar)) }
MoreNavigationRow("Together", Icons.Outlined.Groups) { onNavigate(Route.Settings(SettingsPage.Together)) }
MoreNavigationRow("Data and storage", Icons.Outlined.Storage) { onNavigate(Route.Settings(SettingsPage.DataAndStorage)) }
HorizontalDivider()
MoreNavigationRow("Settings", Icons.Outlined.Settings) { onNavigate(Route.Settings()) }
MoreNavigationRow("About", Icons.Outlined.Info) { onNavigate(Route.Settings(SettingsPage.About)) }
}
}
}
}
@Composable
private fun MoreToggleRow(
icon: ImageVector,
title: String,
description: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
) {
YokanListRow(
title = title,
subtitle = description,
icon = icon,
onClick = { onCheckedChange(!checked) },
trailingContent = {
Switch(
checked = checked,
onCheckedChange = onCheckedChange,
)
},
)
}
@Composable
private fun MoreNavigationRow(
title: String,
icon: ImageVector,
onClick: () -> Unit,
) {
YokanListRow(title = title, icon = icon, onClick = onClick)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/SettingsIndexScreen.kt
- Source · implementation · 125 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
49: internal fun SettingsIndexScreen(
Exact file bytes / download · SHA-256 c03320a6f6660ac63d022a4b04cf6c2fb8ec0248552a3c5b123d0069d538f3f5.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.screens.settings.profiles.ProfileQuickSwitch
import eu.friedcutlet.yokan.ui.components.YokanListRow
import eu.friedcutlet.yokan.ui.components.YokanTopBar
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.settings_index_accounts
import yokan.composeapp.generated.resources.settings_index_app
import yokan.composeapp.generated.resources.settings_index_content
import yokan.composeapp.generated.resources.settings_index_media
import yokan.composeapp.generated.resources.settings_index_privacy
import yokan.composeapp.generated.resources.settings_search_label
import yokan.composeapp.generated.resources.settings_search_no_results
import yokan.composeapp.generated.resources.ui_clear
import eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider as HorizontalDivider
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
@Composable
internal fun SettingsIndexScreen(
title: String,
settings: DbSettings,
onBack: () -> Unit,
onNavigate: (Route.Settings) -> Unit,
) {
val scrollState = rememberScrollState()
var query by rememberSaveable { mutableStateOf("") }
val options = settingsSearchOptions(settings)
val results = remember(options, query) { searchSettingsOptions(options, query) }
val sections = listOf(
Res.string.settings_index_app to listOf(SettingsPage.Profiles, SettingsPage.General, SettingsPage.Appearance),
Res.string.settings_index_media to listOf(SettingsPage.Reader, SettingsPage.NovelReader, SettingsPage.PlayerOverview),
Res.string.settings_index_content to listOf(SettingsPage.Library, SettingsPage.Downloads, SettingsPage.Browse),
Res.string.settings_index_accounts to listOf(SettingsPage.Tracking, SettingsPage.Sync, SettingsPage.Discord),
Res.string.settings_index_privacy to listOf(SettingsPage.Security, SettingsPage.About, SettingsPage.Developer),
)
Scaffold(
topBar = {
YokanTopBar(
title = title,
onBack = onBack,
)
},
) { padding ->
ScrollbarBox(
state = scrollState,
modifier = Modifier.fillMaxSize().padding(padding),
) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(scrollState),
) {
ProfileQuickSwitch()
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text(stringResource(Res.string.settings_search_label)) },
singleLine = true,
modifier = Modifier.fillMaxWidth().padding(16.dp),
trailingIcon = {
if (query.isNotEmpty()) IconButton(onClick = { query = "" }) {
Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.ui_clear))
}
},
)
if (query.isNotBlank()) {
if (results.isEmpty()) Text(stringResource(Res.string.settings_search_no_results),
modifier = Modifier.padding(16.dp).semantics { liveRegion = LiveRegionMode.Polite })
results.forEach { option ->
YokanListRow(
title = option.title,
subtitle = listOf(stringResource(option.page.title), option.currentValue, option.description).filter { it.isNotBlank() }.joinToString(" · "),
onClick = { onNavigate(Route.Settings(option.page, highlight = option.id)) },
)
}
} else {
sections.forEach { (label, pages) ->
Text(stringResource(label), style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(start = 16.dp, top = 24.dp, bottom = 8.dp).semantics { heading() })
pages.forEach { page ->
YokanListRow(
title = stringResource(page.title),
icon = page.icon,
onClick = { onNavigate(Route.Settings(page)) },
)
}
HorizontalDivider(Modifier.padding(horizontal = 16.dp))
}
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/SettingsRoute.kt
- Source · implementation · 129 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
61: internal fun SettingsRoute(route: Route.Settings, nav: Navigator) {
Exact file bytes / download · SHA-256 4ce309acdde84828b3fdcd8f8c00fc4ad75c0e67d86a67d2edc58781c6a99ff5.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.normalizeScanlator
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.screens.downloads.DownloadQueueRoute
import eu.friedcutlet.yokan.ui.screens.novel.NovelReaderSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.about.AboutSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.appearance.AppearanceSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.browse.BrowseSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.browse.CookiesSettingsScreen
import eu.friedcutlet.yokan.ui.screens.settings.browse.SourceRepositoriesRoute
import eu.friedcutlet.yokan.ui.screens.settings.calendar.CalendarSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.data.CreateBackupRoute
import eu.friedcutlet.yokan.ui.screens.settings.data.DataAndStorageRoute
import eu.friedcutlet.yokan.ui.screens.settings.developer.DeveloperSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.discord.DiscordSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.downloads.DownloadsSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.extensionserver.ExtensionServerSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.general.GeneralSettingsScreen
import eu.friedcutlet.yokan.ui.screens.settings.library.CategoriesSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.library.LibrarySettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.metadata.MetadataServerSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.navigation.CustomNavigationSettingsScreen
import eu.friedcutlet.yokan.ui.screens.settings.player.CustomButtonsRoute
import eu.friedcutlet.yokan.ui.screens.settings.player.InternalPlayerSettingsScreen
import eu.friedcutlet.yokan.ui.screens.settings.player.PlayerAdvancedSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.player.PlayerAudioSettingsScreen
import eu.friedcutlet.yokan.ui.screens.settings.player.PlayerDecoderSettingsScreen
import eu.friedcutlet.yokan.ui.screens.settings.player.PlayerOverviewScreen
import eu.friedcutlet.yokan.ui.screens.settings.player.TorrentSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.profiles.ProfileBackupScreen
import eu.friedcutlet.yokan.ui.screens.settings.profiles.ProfilesScreen
import eu.friedcutlet.yokan.ui.screens.settings.reader.ReaderSettingsScreen
import eu.friedcutlet.yokan.ui.screens.settings.security.SecuritySettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.statistics.StatisticsSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.sync.SyncSettingsRoute
import eu.friedcutlet.yokan.ui.screens.settings.tracking.ManageTrackersRoute
import eu.friedcutlet.yokan.ui.screens.settings.tracking.TrackingDetailRoute
import eu.friedcutlet.yokan.ui.screens.settings.tracking.TrackingSettingsRoute
import eu.friedcutlet.yokan.ui.screens.together.TogetherRoute
import org.jetbrains.compose.resources.stringResource
internal val LocalSettingsSearchTarget = staticCompositionLocalOf<SettingsSearchOption?> { null }
@Composable
internal fun SettingsRoute(route: Route.Settings, nav: Navigator) {
val owner = remember(nav) { YokanRuntime.activeSession }
val settingsStore = owner.settings
val settings by settingsStore.db.collectAsStateWithLifecycle()
val highlighted = route.highlight?.let { id -> settingsSearchOptions(settings).firstOrNull { it.id == id } }
// One-shot like the old hand-off: frozen for the first visit (a value change must not re-scroll), and
// gone when the page comes back after a sub-page was pushed on top of it.
var highlightConsumed by rememberSaveable(route) { mutableStateOf(false) }
val target = remember(route) { highlighted.takeUnless { highlightConsumed } }
LaunchedEffect(route) { highlightConsumed = true }
val title = stringResource(route.page.title)
val onUpdate: ((DbSettings) -> DbSettings) -> Unit = settingsStore::updateDb
val onBack: () -> Unit = nav::back
val onOpen: (SettingsPage) -> Unit = { nav.navigate(Route.Settings(it)) }
// Pushed pages seed their type switcher from the root cursor, as they did from the store's selection.
val itemType = nav.itemType.value
CompositionLocalProvider(LocalSettingsSearchTarget provides target) {
when (route.page) {
SettingsPage.RestoreBackup -> ProfileBackupScreen(export = false, onBack = onBack)
SettingsPage.Profiles -> ProfilesScreen(onBack)
SettingsPage.Index -> SettingsIndexScreen(title, settings, onBack) { nav.navigate(it) }
SettingsPage.General -> GeneralSettingsScreen(title, settings, onUpdate, onBack)
SettingsPage.Appearance -> AppearanceSettingsRoute(title, settings, onUpdate, onBack, onOpen)
SettingsPage.Reader -> {
val index by owner.libraryIndex.index.collectAsStateWithLifecycle()
val groups = remember(index) { index.chaptersByManga.values.flatten().map { it.scanlator }
.distinctBy { normalizeScanlator(it) } }
ReaderSettingsScreen(title, settings, onUpdate, onBack, groups)
}
SettingsPage.NovelReader -> NovelReaderSettingsRoute(title, nav)
SettingsPage.PlayerOverview -> PlayerOverviewScreen(title, onBack, onOpen)
SettingsPage.Player -> InternalPlayerSettingsScreen(title, settings, onUpdate, onBack)
SettingsPage.PlayerDecoder -> PlayerDecoderSettingsScreen(title, settings, onUpdate, onBack)
SettingsPage.PlayerAudio -> PlayerAudioSettingsScreen(title, settings, onUpdate, onBack)
SettingsPage.CustomButtons -> CustomButtonsRoute(title, onBack)
SettingsPage.PlayerAdvanced -> PlayerAdvancedSettingsRoute(title, settings, onUpdate, onBack)
SettingsPage.Downloads -> DownloadsSettingsRoute(title, settings, onUpdate, onBack)
SettingsPage.Tracking -> TrackingSettingsRoute(title, settings, onUpdate, onBack, onOpen)
SettingsPage.ManageTrackers -> ManageTrackersRoute(title, settings, onBack)
SettingsPage.TrackingDetail -> TrackingDetailRoute(title, onBack)
SettingsPage.Sync -> {
val sync by settingsStore.sync.collectAsStateWithLifecycle()
SyncSettingsRoute(title, settings, sync, settingsStore::updateSync, onBack)
}
SettingsPage.Browse -> BrowseSettingsRoute(title, settings, onUpdate, onBack, onOpen)
SettingsPage.Cookies -> CookiesSettingsScreen(title, settings, onUpdate, onBack)
SettingsPage.ExtensionServer -> ExtensionServerSettingsRoute(title, settings, onUpdate, onBack)
SettingsPage.MetadataServer -> MetadataServerSettingsRoute(title, settings, onUpdate, onBack)
SettingsPage.Repositories -> SourceRepositoriesRoute(title, itemType, pinnedType = null, onBack)
SettingsPage.MangaRepositories -> SourceRepositoriesRoute(title, itemType, ItemType.Manga, onBack)
SettingsPage.AnimeRepositories -> SourceRepositoriesRoute(title, itemType, ItemType.Anime, onBack)
SettingsPage.NovelRepositories -> SourceRepositoriesRoute(title, itemType, ItemType.Novel, onBack)
SettingsPage.Security -> SecuritySettingsRoute(title, settings, onUpdate, onBack)
SettingsPage.About -> AboutSettingsRoute(title, settings, onUpdate, onBack)
SettingsPage.DataAndStorage -> DataAndStorageRoute(title, settings, onUpdate, onBack, onOpen)
SettingsPage.Discord -> DiscordSettingsRoute(title, settings, onUpdate, onBack)
SettingsPage.Torrent -> TorrentSettingsRoute(title, settings, onBack)
SettingsPage.CreateBackup -> CreateBackupRoute(title, settings, onUpdate, onBack)
SettingsPage.Library -> LibrarySettingsRoute(title, settings, onUpdate, onBack, onOpen, itemType)
SettingsPage.Categories -> CategoriesSettingsRoute(title, itemType, onBack)
SettingsPage.Statistics -> StatisticsSettingsRoute(title, itemType, onBack)
SettingsPage.Calendar -> CalendarSettingsRoute(title, itemType, onBack) { nav.navigate(Route.Detail(it.id)) }
SettingsPage.DownloadQueue -> DownloadQueueRoute(onBack)
SettingsPage.CustomNavigation -> CustomNavigationSettingsScreen(title, settings, onUpdate, onBack)
SettingsPage.Together -> TogetherRoute(title, nav)
SettingsPage.Developer -> DeveloperSettingsRoute(title, settings, onUpdate, onBack)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/SettingsSearch.kt
- Source · implementation · 186 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: internal data class SettingsSearchOption(
20: private fun normalizeSettingsQuery(value: String): String = value.lowercase()
24: internal fun searchSettingsOptions(options: List<SettingsSearchOption>, query: String): List<SettingsSearchOption> {
46: internal fun settingsSearchOptions(settings: DbSettings): List<SettingsSearchOption> = listOfNotNull(
Exact file bytes / download · SHA-256 46731e7283089d8dfc59d1c7bcb7cf79b7cd4f3332a1968dcc9278410cd7af86.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings
import androidx.compose.runtime.Composable
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.http.platformSupportsCustomDns
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
internal data class SettingsSearchOption(
val id: String,
val title: String,
val page: SettingsPage,
val aliases: String = "",
val description: String = "",
val currentValue: String = "",
val anchored: Boolean = false,
)
private fun normalizeSettingsQuery(value: String): String = value.lowercase()
.replace("wi-fi", "wifi").replace("wi fi", "wifi")
.replace('-', ' ').trim().split(Regex("\\s+")).joinToString(" ")
internal fun searchSettingsOptions(options: List<SettingsSearchOption>, query: String): List<SettingsSearchOption> {
val normalized = normalizeSettingsQuery(query)
if (normalized.isEmpty()) return emptyList()
val words = normalized.split(' ')
return options.mapNotNull { option ->
val title = normalizeSettingsQuery(option.title)
val aliases = normalizeSettingsQuery(option.aliases)
val details = normalizeSettingsQuery("${option.description} ${option.currentValue}")
if (!words.all { it in "$title $aliases $details" }) return@mapNotNull null
val score = when {
title == normalized -> 0
title.startsWith(normalized) -> 1
words.all { it in title } -> 2
words.all { it in "$title $aliases" } -> 3
else -> 4
}
option to score
}.sortedWith(compareBy({ it.second }, { it.first.title }, { it.first.id })).map { it.first }
}
/** Only explicitly safe values are indexed: never tokens, cookies, paths, accounts, or server URLs. */
@Composable
internal fun settingsSearchOptions(settings: DbSettings): List<SettingsSearchOption> = listOfNotNull(
SettingsSearchOption("profiles", stringResource(Res.string.profiles_title), SettingsPage.Profiles, "account library create rename switch delete backup"),
SettingsSearchOption("doh", stringResource(Res.string.tile_dns_over_https), SettingsPage.General, "dns encrypted resolver", anchored = true)
.takeIf { platformSupportsCustomDns },
SettingsSearchOption("dns-provider", "DNS provider", SettingsPage.General, "cloudflare google quad9 custom doh", "Available when DNS over HTTPS is enabled")
.takeIf { platformSupportsCustomDns },
SettingsSearchOption("user-agent", stringResource(Res.string.default_user_agent), SettingsPage.General, "browser http header", anchored = true),
SettingsSearchOption("cloudflare", "Cloudflare bypass proxy", SettingsPage.General, "flaresolverr byparr"),
SettingsSearchOption("weights", "Recommendations weights", SettingsPage.General, "genre setting synopsis theme reset"),
SettingsSearchOption("discord", stringResource(Res.string.tile_discord_rpc), SettingsPage.Discord, "discord presence activity rpc", anchored = true),
SettingsSearchOption("discord-account-add", "Discord accounts", SettingsPage.Discord, "discord login account switch token", anchored = true),
SettingsSearchOption("discord-message", "Discord custom message", SettingsPage.Discord, "discord status buttons timestamp", anchored = true),
SettingsSearchOption("discord-private", stringResource(Res.string.tile_hide_rpc_in_incognito), SettingsPage.Discord, "discord privacy", anchored = true),
SettingsSearchOption("discord-categories", "Discord private categories", SettingsPage.Discord, "discord privacy hide category", anchored = true),
SettingsSearchOption("discord-progress", stringResource(Res.string.tile_show_rpc_progress), SettingsPage.Discord, "discord progress", anchored = true),
SettingsSearchOption("discord-title", stringResource(Res.string.tile_show_rpc_title), SettingsPage.Discord, "discord title", anchored = true),
SettingsSearchOption("discord-cover", stringResource(Res.string.tile_show_rpc_cover), SettingsPage.Discord, "discord cover", anchored = true),
SettingsSearchOption("system-theme", stringResource(Res.string.settings_follow_system_theme), SettingsPage.Appearance, "automatic dark light", anchored = true),
SettingsSearchOption("app-icons", stringResource(Res.string.app_icon_title), SettingsPage.Appearance, "launcher icon torii light dark reset home screen", anchored = true),
SettingsSearchOption("eink-mode", stringResource(Res.string.eink_mode), SettingsPage.Appearance, "eink e-ink epaper e-reader kindle kobo boox ghosting refresh grayscale", currentValue = if (settings.einkMode) settings.einkPreset.label else "", anchored = true),
SettingsSearchOption("dark", stringResource(Res.string.settings_dark_mode), SettingsPage.Appearance, "night", "Turn off Follow system theme to change manually"),
SettingsSearchOption("black", stringResource(Res.string.settings_pure_black_dark_mode), SettingsPage.Appearance, "oled amoled", "Available in dark mode"),
SettingsSearchOption("theme", stringResource(Res.string.settings_theme), SettingsPage.Appearance, "palette color scheme"),
SettingsSearchOption("blend", stringResource(Res.string.settings_blend_level), SettingsPage.Appearance, "color"),
SettingsSearchOption("auto-scale", "Automatic UI scale", SettingsPage.Appearance, "system text size"),
SettingsSearchOption("scale", stringResource(Res.string.ui_ui_scale), SettingsPage.Appearance, "size zoom accessibility", currentValue = "${(settings.uiScale * 100).toInt()}%"),
SettingsSearchOption("language", stringResource(Res.string.settings_app_language), SettingsPage.Appearance, "locale translation", anchored = true),
SettingsSearchOption("font", stringResource(Res.string.settings_font), SettingsPage.Appearance, "typeface typography", currentValue = settings.appFontFamily ?: "Default"),
SettingsSearchOption("relative-time", stringResource(Res.string.settings_relative_timestamps), SettingsPage.Appearance, "dates time ago"),
SettingsSearchOption("date-format", stringResource(Res.string.settings_date_format), SettingsPage.Appearance, "dates"),
SettingsSearchOption("navigation-order", stringResource(Res.string.settings_reorder_navigation), SettingsPage.CustomNavigation, "hide tabs reorder navigation"),
SettingsSearchOption("merge-library", stringResource(Res.string.merge_library_nav_mobile), SettingsPage.CustomNavigation, "navigation mobile tabs"),
SettingsSearchOption("reader-mode", stringResource(Res.string.default_reading_mode), SettingsPage.Reader, "rtl ltr webtoon vertical horizontal", currentValue = settings.defaultReaderMode.name, anchored = true),
SettingsSearchOption("hold-to-scroll", stringResource(Res.string.reader_hold_to_scroll), SettingsPage.Reader, "hold press scroll speed gesture continuous webtoon", anchored = true),
SettingsSearchOption("automatic-layout", stringResource(Res.string.reader_layout_automatic), SettingsPage.Reader, "automatic layout detection pairing spread webtoon", anchored = true),
SettingsSearchOption("reader-animation", stringResource(Res.string.double_tap_animation_speed), SettingsPage.Reader, "zoom motion"),
SettingsSearchOption("reader-background", stringResource(Res.string.background_color), SettingsPage.Reader, "page color"),
SettingsSearchOption("preload", stringResource(Res.string.page_preload_amount), SettingsPage.Reader, "prefetch cache pages", currentValue = "${settings.pagePreloadAmount} pages", anchored = true),
SettingsSearchOption("reader-scale", stringResource(Res.string.scale_type), SettingsPage.Reader, "fit width height stretch"),
SettingsSearchOption("reader-fullscreen", stringResource(Res.string.tile_full_screen_reader), SettingsPage.Reader, "fullscreen"),
SettingsSearchOption("page-animation", stringResource(Res.string.animate_page_transitions), SettingsPage.Reader, "motion"),
SettingsSearchOption("paged-crop", stringResource(Res.string.crop_borders), SettingsPage.Reader, "trim margins", anchored = true),
SettingsSearchOption("gaps", stringResource(Res.string.show_page_gaps), SettingsPage.Reader, "spacing"),
SettingsSearchOption("page-number", stringResource(Res.string.show_page_number), SettingsPage.Reader, "counter"),
SettingsSearchOption("webtoon-padding", stringResource(Res.string.webtoon_side_padding), SettingsPage.Reader, "margins"),
SettingsSearchOption("invert", stringResource(Res.string.invert_colors), SettingsPage.Reader, "negative"),
SettingsSearchOption("grayscale", stringResource(Res.string.grayscale), SettingsPage.Reader, "monochrome"),
SettingsSearchOption("tap-zones", stringResource(Res.string.use_page_tap_zones), SettingsPage.Reader, "gestures navigation"),
SettingsSearchOption("keep-screen", stringResource(Res.string.keep_screen_on), SettingsPage.Reader, "awake sleep"),
SettingsSearchOption("duplicates", stringResource(Res.string.tile_auto_read_duplicate_chapters), SettingsPage.Reader, "mark read"),
SettingsSearchOption("release-defaults", stringResource(Res.string.releases_default_section), SettingsPage.Reader, "scanlator priority skip duplicate chapter releases", anchored = true),
SettingsSearchOption("split-wide-pages", stringResource(Res.string.reader_split_wide_pages), SettingsPage.Reader, "double spread landscape halves paged webtoon"),
SettingsSearchOption("rotate-wide-pages", stringResource(Res.string.reader_rotate_wide_pages), SettingsPage.Reader, "landscape spread orientation turn"),
SettingsSearchOption("skip-read", stringResource(Res.string.reader_skip_read), SettingsPage.Reader, "chapter navigation next previous"),
SettingsSearchOption("skip-filtered", stringResource(Res.string.reader_skip_filtered), SettingsPage.Reader, "chapter navigation filters"),
SettingsSearchOption("chapter-transition", stringResource(Res.string.reader_always_show_transition), SettingsPage.Reader, "chapter end card"),
SettingsSearchOption("save-title-folder", stringResource(Res.string.reader_save_title_folder), SettingsPage.Reader, "save image album directory"),
SettingsSearchOption("volume-keys", stringResource(Res.string.reader_volume_keys), SettingsPage.Reader, "hardware buttons page turn"),
SettingsSearchOption("subtitle-language", stringResource(Res.string.default_subtitle_language), SettingsPage.Player, "captions", anchored = true),
SettingsSearchOption("mark-seen", stringResource(Res.string.tile_mark_episode_as_seen), SettingsPage.Player, "progress watched threshold"),
SettingsSearchOption("skip-intro", stringResource(Res.string.tile_default_skip_intro_length), SettingsPage.Player, "seconds"),
SettingsSearchOption("double-skip", stringResource(Res.string.tile_double_tap_skip_length), SettingsPage.Player, "seek seconds"),
SettingsSearchOption("playback-speed", stringResource(Res.string.tile_default_playback_speed), SettingsPage.Player, "video speed", currentValue = "${settings.defaultPlaybackSpeed}x", anchored = true),
SettingsSearchOption("libass", stringResource(Res.string.tile_use_libass), SettingsPage.Player, "subtitles rendering"),
SettingsSearchOption("aniskip", stringResource(Res.string.tile_aniskip), SettingsPage.Player, "skip intro outro", anchored = true),
SettingsSearchOption("auto-skip", stringResource(Res.string.tile_auto_skip), SettingsPage.Player, "aniskip", "Available when AniSkip is enabled"),
SettingsSearchOption("aniskip-timeout", stringResource(Res.string.tile_aniskip_timeout), SettingsPage.Player, "skip timeout", "Available when AniSkip is enabled"),
SettingsSearchOption("player-fullscreen", stringResource(Res.string.tile_fullscreen_player), SettingsPage.Player, "fullscreen video"),
SettingsSearchOption("landscape", stringResource(Res.string.tile_force_landscape), SettingsPage.Player, "orientation rotate"),
SettingsSearchOption("hardware", stringResource(Res.string.tile_enable_hardware_acceleration), SettingsPage.PlayerDecoder, "gpu performance", anchored = true),
SettingsSearchOption("hwdec", stringResource(Res.string.tile_hardware_decoder), SettingsPage.PlayerDecoder, "hwdec codec", anchored = true),
SettingsSearchOption("gpu-next", stringResource(Res.string.tile_gpu_next), SettingsPage.PlayerDecoder, "rendering"),
SettingsSearchOption("debanding", stringResource(Res.string.debanding), SettingsPage.PlayerDecoder, "banding video"),
SettingsSearchOption("yuv", stringResource(Res.string.tile_force_yuv420p), SettingsPage.PlayerDecoder, "black screen pixel format"),
SettingsSearchOption("audio-language", "Preferred audio languages", SettingsPage.PlayerAudio, "jpn eng dub"),
SettingsSearchOption("pitch", stringResource(Res.string.tile_audio_pitch_correction), SettingsPage.PlayerAudio, "audio speed"),
SettingsSearchOption("channels", stringResource(Res.string.tile_audio_channel), SettingsPage.PlayerAudio, "stereo surround mono"),
SettingsSearchOption("volume", "Volume boost cap", SettingsPage.PlayerAudio, "loudness amplification"),
SettingsSearchOption("custom-button", "Add custom player button", SettingsPage.CustomButtons, "javascript command press long press startup favourite reorder"),
SettingsSearchOption("mpv", stringResource(Res.string.tile_use_mpv_config), SettingsPage.PlayerAdvanced, "mpv.conf input.conf scripts shaders"),
SettingsSearchOption("mpv-reset", "Redownload mpv config files", SettingsPage.PlayerAdvanced, "reset defaults replace"),
SettingsSearchOption("torrent", "Torrent streaming", SettingsPage.Torrent, "torrserver magnet torrent port trackers proxy"),
SettingsSearchOption("wifi", stringResource(Res.string.tile_only_on_wi_fi), SettingsPage.Downloads, "wifi wireless downloads", anchored = true),
SettingsSearchOption("cbz", stringResource(Res.string.save_as_cbz_archive), SettingsPage.Downloads, "zip archive"),
SettingsSearchOption("delete-read", stringResource(Res.string.delete_download_after_reading), SettingsPage.Downloads, "cleanup"),
SettingsSearchOption("concurrent", stringResource(Res.string.allow_concurrent_downloads), SettingsPage.Downloads, "parallel simultaneous", anchored = true),
SettingsSearchOption("concurrent-count", stringResource(Res.string.concurrent_downloads), SettingsPage.Downloads, "parallel limit", "Available when concurrent downloads are enabled"),
SettingsSearchOption("delay", stringResource(Res.string.download_delay), SettingsPage.Downloads, "throttle jitter"),
SettingsSearchOption("download-speed", "Download speed limit", SettingsPage.Downloads, "bandwidth throttle"),
SettingsSearchOption("upload-speed", "Upload speed limit", SettingsPage.Downloads, "bandwidth throttle"),
SettingsSearchOption("download-location", stringResource(Res.string.download_location), SettingsPage.Downloads, "folder path storage"),
SettingsSearchOption("rescan", "Rescan local folders", SettingsPage.Downloads, "reindex scan"),
SettingsSearchOption("add-folder", stringResource(Res.string.add_local_folder), SettingsPage.Downloads, "virtual folder usb local media"),
SettingsSearchOption("destination", "Download destination", SettingsPage.Downloads, "virtual folder", "Choose a folder when Ask download destination is off"),
SettingsSearchOption("ask-destination", "Ask download destination", SettingsPage.Downloads, "prompt folder"),
SettingsSearchOption("update-progress", "Update progress after reading", SettingsPage.Tracking, "tracking chapter episode", anchored = true),
SettingsSearchOption("connect-tracker", "Connect tracker", SettingsPage.Tracking, "anilist kitsu myanimelist mal simkl trakt oauth login logout"),
SettingsSearchOption("tracking-edit", "Save tracking progress", SettingsPage.ManageTrackers, "score status unbind", "Select a connected tracker and a bound title"),
SettingsSearchOption("sync-on", stringResource(Res.string.tile_sync_on), SettingsPage.Sync, "enable cloud hub", anchored = true),
SettingsSearchOption("auto-sync", stringResource(Res.string.tile_auto_sync), SettingsPage.Sync, "frequency schedule", "Available when sync is enabled"),
SettingsSearchOption("sync-history", stringResource(Res.string.tile_sync_histories), SettingsPage.Sync, "history"),
SettingsSearchOption("sync-updates", stringResource(Res.string.tile_sync_updates), SettingsPage.Sync, "updates"),
SettingsSearchOption("sync-settings", stringResource(Res.string.sync_enable_settings), SettingsPage.Sync, "preferences"),
SettingsSearchOption("hub-login", "Sign in to sync server", SettingsPage.Sync, "yokan hub account"),
SettingsSearchOption("sync-upload", "Upload only", SettingsPage.Sync, "push changes", "Requires a connected account and enabled sync"),
SettingsSearchOption("sync-download", "Download only", SettingsPage.Sync, "pull changes", "Requires a connected account and enabled sync"),
SettingsSearchOption("cloud-backup", "Upload backup", SettingsPage.Sync, "cloud snapshot", "Requires a connected cloud provider"),
SettingsSearchOption("cloud-restore", "Restore latest", SettingsPage.Sync, "cloud backup", "Requires a connected cloud provider"),
SettingsSearchOption("extension-updates", stringResource(Res.string.check_for_extension_updates), SettingsPage.Browse, "sources updates"),
SettingsSearchOption("extension-auto", stringResource(Res.string.auto_extensions_updates), SettingsPage.Browse, "install updates", "Enable extension update checks first"),
SettingsSearchOption("pinned", stringResource(Res.string.only_include_pinned_sources), SettingsPage.Browse, "global search"),
SettingsSearchOption("nsfw", stringResource(Res.string.tile_show_nsfw_sources), SettingsPage.Browse, "adult explicit"),
SettingsSearchOption("cookies", "Cookies", SettingsPage.Cookies, "delete clear web login privacy reveal hide values", anchored = true),
SettingsSearchOption("clean-db", stringResource(Res.string.clean_database), SettingsPage.Browse, "cleanup cached entries"),
SettingsSearchOption("clear-sources", "Clear installed sources", SettingsPage.Browse, "remove extensions", "Applies to the selected media type"),
SettingsSearchOption("clear-library", "Clear library", SettingsPage.Browse, "delete favourites progress", "Applies to the selected media type"),
SettingsSearchOption("clear-local", "Clear local library", SettingsPage.Browse, "remove indexed archives"),
SettingsSearchOption("manga-repo", "Add manga repository", SettingsPage.MangaRepositories, "repo url extensions"),
SettingsSearchOption("anime-repo", "Add anime repository", SettingsPage.AnimeRepositories, "repo url extensions"),
SettingsSearchOption("novel-repo", "Add novel repository", SettingsPage.NovelRepositories, "repo url extensions"),
SettingsSearchOption("server-install", "Install extension server", SettingsPage.ExtensionServer, "mihon apk jre bridge proxy", "Available actions depend on platform"),
SettingsSearchOption("metadata-url", "Metadata server URL", SettingsPage.MetadataServer, "api lookup tags alternative titles"),
SettingsSearchOption("lock", stringResource(Res.string.app_lock), SettingsPage.Security, "biometric device credential privacy", anchored = true),
SettingsSearchOption("version", "Version", SettingsPage.About, "app version beta", anchored = true),
SettingsSearchOption("app-update", stringResource(Res.string.tile_check_for_app_updates), SettingsPage.About, "upgrade release"),
SettingsSearchOption("logs", stringResource(Res.string.tile_enable_logs), SettingsPage.About, "debug diagnostics logging"),
SettingsSearchOption("developer-mode", "Developer mode", SettingsPage.Developer, "local recipe catalog loopback http testing"),
SettingsSearchOption("developer-diagnostics", "Diagnostics and logs", SettingsPage.Developer, "memory heap graph errors warnings image cache hits network requests"),
SettingsSearchOption("backup-create", "Create backup", SettingsPage.CreateBackup, "export data compression encryption"),
SettingsSearchOption("backup-restore", "Restore backup", SettingsPage.DataAndStorage, "import merge replace recovery"),
SettingsSearchOption("backup-frequency", stringResource(Res.string.backup_frequency), SettingsPage.DataAndStorage, "automatic schedule"),
SettingsSearchOption("compression", stringResource(Res.string.compression_level), SettingsPage.DataAndStorage, "backup size"),
SettingsSearchOption("cache", "Clear cache", SettingsPage.DataAndStorage, "storage free space"),
SettingsSearchOption("library-updates", "Automatic library updates", SettingsPage.Library, "refresh schedule background"),
SettingsSearchOption("category-tabs", "Display category tabs", SettingsPage.Library, "library layout"),
SettingsSearchOption("counts", "Show number of items", SettingsPage.Library, "library count"),
SettingsSearchOption("download-badges", "Show download badges", SettingsPage.Library, "library downloaded chapters"),
SettingsSearchOption("language-badge", "Show source language", SettingsPage.Library, "library badge"),
SettingsSearchOption("source-badge", "Show source badge", SettingsPage.Library, "library source"),
SettingsSearchOption("category-create", "Add category", SettingsPage.Categories, "organise group titles rename reorder hidden update"),
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/SettingsTiles.kt
- Source · implementation · 303 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
59: internal fun SettingsScaffold(
89: private fun SearchableSettingsList(
114: override fun item(
136: internal fun YokanMenuTile(
174: internal fun RouteTile(
189: internal fun SettingTile(
204: internal fun <T> ChoiceTile(
228: internal fun SwitchTile(
250: internal fun SettingsSection(title: String) {
264: internal fun InfoRow(text: String) {
297: internal fun ButtonRow(text: String, danger: Boolean = false, onClick: () -> Unit = {}) {
Exact file bytes / download · SHA-256 7256d240c893300664c31483d979d12c222c63880d3a6b79b660679dee6ca3fb.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.components.YokanTopBar
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.settings_search_open_option
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
@Composable
internal fun SettingsScaffold(
title: String,
onBack: () -> Unit,
listState: LazyListState = rememberLazyListState(),
content: LazyListScope.() -> Unit,
) {
Scaffold(
topBar = {
YokanTopBar(
title = title,
onBack = onBack,
)
},
) { padding ->
ScrollbarBox(
state = listState,
modifier = Modifier
.fillMaxSize()
.padding(padding),
) {
SearchableSettingsList(
state = listState,
modifier = Modifier.fillMaxSize(),
content = content,
)
}
}
}
@Composable
private fun SearchableSettingsList(
state: LazyListState,
modifier: Modifier,
content: LazyListScope.() -> Unit,
) {
val target = LocalSettingsSearchTarget.current
var targetIndex by remember(target) { mutableStateOf<Int?>(null) }
LaunchedEffect(targetIndex, target) {
targetIndex?.let { state.scrollToItem(it) }
}
Column(modifier) {
if (target != null) {
Text(target.title, style = MaterialTheme.typography.titleSmall,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp).semantics { heading() })
if (!target.anchored) Text(
listOf(stringResource(Res.string.settings_search_open_option), target.description)
.filter { it.isNotBlank() }.joinToString(". "),
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
)
}
LazyColumn(state = state, modifier = Modifier.weight(1f).fillMaxWidth()) {
val delegate = this
var index = 0
content(object : LazyListScope by delegate {
override fun item(
key: Any?,
contentType: Any?,
content: @Composable LazyItemScope.() -> Unit,
) {
val selected = target != null && key == target.id
if (selected) targetIndex = index
index++
delegate.item(key, contentType) {
if (selected) {
Box(Modifier.border(2.dp, MaterialTheme.colorScheme.primary, MaterialTheme.shapes.small)) {
content()
}
} else content()
}
}
})
}
}
}
@Composable
internal fun YokanMenuTile(
title: String,
modifier: Modifier = Modifier,
subtitle: String? = null,
trailing: @Composable (() -> Unit)? = null,
enabled: Boolean = true,
onClick: () -> Unit = {},
) {
val rowModifier = modifier
.fillMaxWidth()
.let { if (enabled) it.hoverHighlight(onClick = onClick) else it }
ListItem(
modifier = rowModifier,
headlineContent = {
Text(
text = title,
color = if (enabled) {
MaterialTheme.colorScheme.onSurface
} else {
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
},
)
},
supportingContent = subtitle?.let {
{
Text(
text = it,
fontSize = 11.sp,
color = MaterialTheme.colorScheme.secondary,
)
}
},
trailingContent = trailing,
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
)
}
@Composable
internal fun RouteTile(
page: SettingsPage,
title: String,
subtitle: String? = null,
onOpen: (SettingsPage) -> Unit,
) {
YokanMenuTile(
title = title,
subtitle = subtitle,
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = { onOpen(page) },
)
}
@Composable
internal fun SettingTile(
title: String,
subtitle: String?,
enabled: Boolean = true,
onClick: (() -> Unit)? = null,
) {
YokanMenuTile(title = title, subtitle = subtitle, enabled = enabled, onClick = onClick ?: {})
}
/**
* Tile that opens a modal single-choice picker instead of cycling on tap. Replaces the
* "tap to rotate" pattern across reader/player/sync settings so the user sees every option at once
* (matching how Aniyomi exposes enum settings).
*/
@Composable
internal fun <T> ChoiceTile(
title: String,
options: List<T>,
selected: T?,
label: (T) -> String,
enabled: Boolean = true,
onSelect: (T) -> Unit,
) {
var open by remember { mutableStateOf(false) }
if (open) {
ChoiceDialog(
title = title,
options = options,
selected = selected,
label = label,
onSelect = onSelect,
onDismiss = { open = false },
)
}
val subtitle = selected?.let(label) ?: "—"
YokanMenuTile(title = title, subtitle = subtitle, enabled = enabled, onClick = { open = true })
}
@Composable
internal fun SwitchTile(
title: String,
subtitle: String?,
value: Boolean,
onValueChange: (Boolean) -> Unit,
enabled: Boolean = true,
) {
YokanMenuTile(
modifier = Modifier.semantics(mergeDescendants = true) {
role = Role.Switch
stateDescription = if (value) "On" else "Off"
contentDescription = subtitle?.let { "$title. $it" } ?: title
},
title = title,
subtitle = subtitle,
enabled = enabled,
onClick = { if (enabled) onValueChange(!value) },
trailing = { Switch(checked = value, onCheckedChange = onValueChange, enabled = enabled) },
)
}
@Composable
internal fun SettingsSection(title: String) {
Text(
// Uppercase + slight tracking gives section headers the "label" feel
// used in MUI's `<Typography variant="overline">` rows.
text = title.uppercase(),
modifier = Modifier.padding(start = 24.dp, top = 24.dp, bottom = 6.dp),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold,
letterSpacing = 1.sp,
)
}
@Composable
internal fun InfoRow(text: String) {
// MUI `<Alert severity="info">` shape — soft tonal surface, leading icon
// tinted with the primary container palette, no chevron. Replaces the
// previous "row that looks like a navigation item" rendering, which made
// every information banner read as something the user should tap.
Surface(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 4.dp),
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
) {
Row(
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
verticalAlignment = Alignment.Top,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Icon(
Icons.Filled.Info,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(20.dp),
)
Text(
text,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
internal fun ButtonRow(text: String, danger: Boolean = false, onClick: () -> Unit = {}) {
Box(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {
Button(onClick = onClick, modifier = Modifier.fillMaxWidth().height(48.dp), shape = RoundedCornerShape(50)) {
Text(text, color = if (danger) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onPrimary)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/TextInputDialog.kt
- Source · implementation · 85 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
31: internal fun TextInputDialog(
41: fun submit() {
Exact file bytes / download · SHA-256 7017705f8d21bff88bf651c18107709910e378bd7b885884285578333820f33a.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_save
@Composable
internal fun TextInputDialog(
title: String,
initialValue: String,
placeholder: String,
helperText: String? = null,
singleLine: Boolean = true,
onConfirm: (String) -> Unit,
onDismiss: () -> Unit,
) {
var value by remember { mutableStateOf(initialValue) }
fun submit() {
onConfirm(value)
onDismiss()
}
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = {
Text(
title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
OutlinedTextField(
value = value,
onValueChange = { value = it },
placeholder = { Text(placeholder, maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingText = helperText?.let { text -> { Text(text) } },
singleLine = singleLine,
shape = MaterialTheme.shapes.large,
modifier = Modifier.fillMaxWidth(),
// Pressing Enter on a single-line field submits the dialog.
keyboardOptions = if (singleLine) {
KeyboardOptions(imeAction = ImeAction.Done)
} else {
KeyboardOptions.Default
},
keyboardActions = KeyboardActions(onDone = { submit() }),
)
},
confirmButton = {
Button(
onClick = { submit() },
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 8.dp),
) { Text(stringResource(Res.string.action_save), style = MaterialTheme.typography.labelLarge) }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) }
},
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/about/AboutSettingsScreen.kt
- Source · implementation · 216 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
57: internal fun AboutSettingsRoute(
80: private fun AboutSettingsScreen(
Exact file bytes / download · SHA-256 c25d6197ccb5e790c7bd07d5d62fbe7edbafb3482783312b25452dbf9093f025.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.about
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.logging.LogSink
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.services.updates.ReleaseAsset
import eu.friedcutlet.yokan.services.updates.ReleaseChannel
import eu.friedcutlet.yokan.services.updates.YOKAN_GITHUB_URL
import eu.friedcutlet.yokan.services.updates.YOKAN_RELEASE_CHANNEL
import eu.friedcutlet.yokan.services.updates.YOKAN_VERSION
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.data.formatBytes
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.delete
import yokan.composeapp.generated.resources.tile_check_for_app_updates
import yokan.composeapp.generated.resources.ui_close
import yokan.composeapp.generated.resources.version_title
import yokan.composeapp.generated.resources.version_channel_alpha
import yokan.composeapp.generated.resources.version_channel_beta
import yokan.composeapp.generated.resources.version_channel_stable
import yokan.composeapp.generated.resources.version_channel_label
import eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider as HorizontalDivider
@Composable
internal fun AboutSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val model = viewModel { AboutSettingsViewModel(YokanRuntime.services.http, YokanRuntime.localFiles) }
val state by model.state.collectAsStateWithLifecycle()
AboutSettingsScreen(
title = title,
settings = settings,
state = state,
onUpdate = onUpdate,
onCheckForUpdate = model::checkForUpdate,
onDownloadAsset = model::downloadAsset,
onShareLog = model::shareLog,
onShareCrashReport = model::shareCrashReport,
onDeleteCrashReport = model::deleteCrashReport,
onBack = onBack,
)
}
@Composable
private fun AboutSettingsScreen(
title: String,
settings: DbSettings,
state: AboutSettingsState,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onCheckForUpdate: () -> Unit,
onDownloadAsset: (ReleaseAsset) -> Unit,
onShareLog: (String) -> Unit,
onShareCrashReport: () -> Unit,
onDeleteCrashReport: () -> Unit,
onBack: () -> Unit,
) {
val crashReport = state.crashReport
var crashReportOpen by remember { mutableStateOf(false) }
if (crashReportOpen) {
AlertDialog(
onDismissRequest = { crashReportOpen = false },
title = { Text("Last crash report") },
text = { Text(crashReport.orEmpty(), modifier = Modifier.heightIn(max = 360.dp).verticalScroll(rememberScrollState())) },
confirmButton = { TextButton(onClick = { crashReportOpen = false }) { Text(stringResource(Res.string.ui_close)) } },
)
}
SettingsScaffold(title, onBack) {
item {
// App banner — centered icon + name + version, matching the Flutter "logo" tile.
Column(
modifier = Modifier.fillMaxWidth().padding(vertical = 24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Icon(
Icons.AutoMirrored.Filled.MenuBook,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(72.dp),
)
Text("Yokan", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.SemiBold)
}
}
item { HorizontalDivider() }
item(key = "version") {
val channelLabel = stringResource(when (YOKAN_RELEASE_CHANNEL) {
ReleaseChannel.Alpha -> Res.string.version_channel_alpha
ReleaseChannel.Beta -> Res.string.version_channel_beta
ReleaseChannel.Stable -> Res.string.version_channel_stable
})
SettingTile(
stringResource(Res.string.version_title),
stringResource(Res.string.version_channel_label, channelLabel, YOKAN_VERSION),
)
}
item {
SwitchTile(
title = stringResource(Res.string.tile_check_for_app_updates),
subtitle = null,
value = settings.checkForAppUpdates,
onValueChange = { v -> onUpdate { it.copy(checkForAppUpdates = v) } },
)
}
item {
SettingTile(
title = "Check for update",
subtitle = state.updateMessage ?: "Query GitHub Releases for the latest build",
onClick = onCheckForUpdate,
)
}
// Show downloadable assets right under the check-for-update row when a release was fetched.
state.release?.let { info ->
info.assets.take(ShownAssets).forEach { asset ->
item(key = "asset:${asset.name}") {
val isDownloaded = asset.name in state.downloadedAssets
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(asset.name, fontWeight = FontWeight.SemiBold)
Text(formatBytes(asset.sizeBytes), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
}
OutlinedButton(onClick = { onDownloadAsset(asset) }) { Text(if (isDownloaded) "Re-download" else "Download") }
}
}
}
}
item {
SwitchTile(
title = "Logs on",
subtitle = "Append app logs to a file",
value = settings.enableFileLogging,
onValueChange = { v -> onUpdate { it.copy(enableFileLogging = v) } },
)
}
if (settings.enableFileLogging) {
val logPath = LogSink.logFilePath()
item {
SettingTile(
title = "Share app logs",
subtitle = logPath ?: "No log file yet",
enabled = logPath != null,
onClick = { logPath?.let(onShareLog) },
)
}
}
crashReport?.let { report ->
item {
SettingTile(
title = "Last crash report",
subtitle = "Stored locally; ${formatBytes(report.encodeToByteArray().size.toLong())}",
onClick = { crashReportOpen = true },
)
}
item {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.End,
) {
TextButton(onClick = onShareCrashReport) { Text("Share") }
TextButton(onClick = onDeleteCrashReport) { Text(stringResource(Res.string.delete)) }
}
}
}
item {
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
OutlinedButton(onClick = {
openSystemBrowser(YOKAN_GITHUB_URL)
}) { Text("GitHub") }
OutlinedButton(onClick = {
openSystemBrowser("https://discord.gg/yokan")
}) { Text("Discord") }
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/about/AboutSettingsViewModel.kt
- Source · implementation · 124 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
27: internal data class AboutSettingsState(
36: internal class AboutSettingsViewModel(
51: fun checkForUpdate() {
73: fun downloadAsset(asset: ReleaseAsset) {
98: fun shareLog(path: String) {
104: fun shareCrashReport() {
110: fun deleteCrashReport() {
115: private fun assetPath(asset: ReleaseAsset) = "${files.cacheRoot}/updates/${asset.name}"
117: private suspend fun refreshDownloaded(assets: List<ReleaseAsset>) {
Exact file bytes / download · SHA-256 97977a78d11a0ed0886f49c47f4ddb939f9309490ca36973639a5ad183ef490c.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.about
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.logging.CrashReportStore
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
import eu.friedcutlet.yokan.services.updates.ReleaseAsset
import eu.friedcutlet.yokan.services.updates.ReleaseInfo
import eu.friedcutlet.yokan.services.updates.YOKAN_VERSION
import eu.friedcutlet.yokan.services.updates.fetchLatestRelease
import eu.friedcutlet.yokan.services.updates.installPackageFromFile
import eu.friedcutlet.yokan.services.updates.isNewerVersion
import eu.friedcutlet.yokan.ui.screens.reader.shareImage
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
internal data class AboutSettingsState(
val checkingUpdate: Boolean = false,
val release: ReleaseInfo? = null,
val updateMessage: String? = null,
/** Names of shown release assets already present in the update cache. */
val downloadedAssets: Set<String> = emptySet(),
val crashReport: String? = null,
)
internal class AboutSettingsViewModel(
private val http: HttpService,
private val files: LocalFileService,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(AboutSettingsState())
val state: StateFlow<AboutSettingsState> = _state.asStateFlow()
init {
viewModelScope.launch {
val report = withContext(workDispatcher) { CrashReportStore.read(files) }
_state.update { it.copy(crashReport = report) }
}
}
fun checkForUpdate() {
if (_state.value.checkingUpdate) return
_state.update { it.copy(checkingUpdate = true, updateMessage = "Searching…") }
viewModelScope.launch {
val info = fetchLatestRelease(http)
val newer = info?.takeIf { isNewerVersion(it.tag) }
_state.update {
it.copy(
release = newer,
downloadedAssets = emptySet(),
updateMessage = when {
info == null -> "Network error"
newer != null -> "Update available: ${info.tag} • ${info.assets.size} assets"
else -> "You're up to date ($YOKAN_VERSION)"
},
checkingUpdate = false,
)
}
newer?.let { refreshDownloaded(it.assets.take(ShownAssets)) }
}
}
fun downloadAsset(asset: ReleaseAsset) {
viewModelScope.launch {
val downloadedPath = assetPath(asset)
val installed = catchingNonCancellation {
val response = http.request(HttpRequest(asset.url))
if (response.statusCode in 200..299 && response.bodyBytes.isNotEmpty()) {
withContext(workDispatcher) { files.writeBytes(downloadedPath, response.bodyBytes) }
// Android launches the package installer; other
// platforms reveal the artifact for manual install.
if (!installPackageFromFile(downloadedPath)) {
files.openLocation(downloadedPath.substringBeforeLast('/'))
}
true
} else {
false
}
}.getOrDefault(false)
if (!installed) {
InAppNotifications.post("Update download failed", asset.name)
}
refreshDownloaded(listOf(asset))
}
}
/** Hands the log to the platform share sheet (Mangayomi's Share.shareXFiles); falls back to revealing the folder. */
fun shareLog(path: String) {
val bytes = runCatching { files.readBytes(path) }.getOrDefault(ByteArray(0))
val shared = bytes.isNotEmpty() && shareImage(bytes, "yokan.log", "text/plain")
if (!shared) files.openLocation(path.substringBeforeLast('/'))
}
fun shareCrashReport() {
val report = _state.value.crashReport ?: return
val shared = shareImage(report.encodeToByteArray(), "yokan-crash-report.txt", "text/plain")
if (!shared) files.openLocation(files.cacheRoot)
}
fun deleteCrashReport() {
CrashReportStore.delete(files)
_state.update { it.copy(crashReport = null) }
}
private fun assetPath(asset: ReleaseAsset) = "${files.cacheRoot}/updates/${asset.name}"
private suspend fun refreshDownloaded(assets: List<ReleaseAsset>) {
val present = withContext(workDispatcher) { assets.associate { it.name to files.exists(assetPath(it)) } }
_state.update { s -> s.copy(downloadedAssets = s.downloadedAssets - present.keys + present.filterValues { it }.keys) }
}
}
/** Release assets listed under the check-for-update row. */
internal const val ShownAssets = 5
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/appearance/AppIconPicker.kt
- Source · implementation · 171 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
38: private fun iconDesignLabel(design: AppIconDesign) = stringResource(when (design) {
44: private fun iconAppearanceLabel(appearance: AppIconAppearance) = stringResource(when (appearance) {
51: private fun iconLabel(selection: AppIconSelection) = if (selection.design == AppIconDesign.Default) {
56: private fun IconPreview(selection: AppIconSelection, modifier: Modifier = Modifier) {
75: internal fun AppIconTile(state: AppIconState, onOpen: () -> Unit) {
90: internal fun AppIconPicker(
Exact file bytes / download · SHA-256 04c369260b4898d206faec98be2173ce393c18186f279ec27974546fc3a986cd.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.appearance
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.services.appicons.AppIconAppearance
import eu.friedcutlet.yokan.services.appicons.AppIconDesign
import eu.friedcutlet.yokan.services.appicons.AppIconPlatform
import eu.friedcutlet.yokan.services.appicons.AppIconSelection
import eu.friedcutlet.yokan.ui.screens.settings.YokanMenuTile
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
@Composable
private fun iconDesignLabel(design: AppIconDesign) = stringResource(when (design) {
AppIconDesign.Default -> Res.string.app_icon_default
AppIconDesign.Torii -> Res.string.app_icon_torii
})
@Composable
private fun iconAppearanceLabel(appearance: AppIconAppearance) = stringResource(when (appearance) {
AppIconAppearance.Light -> Res.string.app_icon_light
AppIconAppearance.Dark -> Res.string.app_icon_dark
AppIconAppearance.System -> Res.string.app_icon_system
})
@Composable
private fun iconLabel(selection: AppIconSelection) = if (selection.design == AppIconDesign.Default) {
iconDesignLabel(selection.design)
} else "${iconDesignLabel(selection.design)} · ${iconAppearanceLabel(selection.appearance)}"
@Composable
private fun IconPreview(selection: AppIconSelection, modifier: Modifier = Modifier) {
// Both supplied appearances are shown for Follow system, rather than pretending the app's
// explicit dark theme can tell us what the Home Screen is currently displaying.
Row(modifier, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val appearances = if (selection.appearance == AppIconAppearance.System) {
listOf(AppIconAppearance.Light, AppIconAppearance.Dark)
} else listOf(selection.appearance)
appearances.forEach { appearance ->
val resource = when {
selection.design == AppIconDesign.Default -> Res.drawable.icon_red
appearance == AppIconAppearance.Dark -> Res.drawable.icon_torii_dark
else -> Res.drawable.icon_torii_light
}
Image(painterResource(resource), contentDescription = null, modifier = Modifier.size(56.dp))
}
}
}
@Composable
internal fun AppIconTile(state: AppIconState, onOpen: () -> Unit) {
YokanMenuTile(
title = stringResource(Res.string.app_icon_title),
subtitle = when {
state.busy -> stringResource(Res.string.app_icon_busy)
!state.capabilities.canChange -> stringResource(Res.string.app_icon_static)
state.failed -> stringResource(Res.string.app_icon_error)
else -> state.selection?.let { iconLabel(it) } ?: stringResource(Res.string.app_icon_unknown)
},
trailing = { state.selection?.let { IconPreview(it) } },
onClick = { if (!state.busy) onOpen() },
)
}
@Composable
internal fun AppIconPicker(
state: AppIconState,
onDesign: (AppIconDesign) -> Unit,
onAppearance: (AppIconSelection) -> Unit,
onApply: () -> Unit,
onReset: () -> Unit,
onRefresh: () -> Unit,
onDismiss: () -> Unit,
) {
val resetLabel = stringResource(Res.string.app_icon_reset)
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(Res.string.app_icon_title)) },
text = {
Column(Modifier.heightIn(max = 480.dp).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(Res.string.app_icon_device), style = MaterialTheme.typography.bodySmall)
Text(stringResource(when {
!state.capabilities.canChange -> Res.string.app_icon_static
state.capabilities.platform == AppIconPlatform.Android -> Res.string.app_icon_android
else -> Res.string.app_icon_ios
}), style = MaterialTheme.typography.bodySmall)
if (state.capabilities.canChange) {
Text(stringResource(Res.string.app_icon_design), style = MaterialTheme.typography.titleSmall)
Column(Modifier.selectableGroup()) {
state.capabilities.choices.map { it.design }.distinct().forEach { design ->
val preview = state.capabilities.choices.firstOrNull { it.design == design && it.appearance == state.draft.appearance }
?: state.capabilities.choices.first { it.design == design }
Row(Modifier.fillMaxWidth().selectable(
selected = state.draft.design == design,
enabled = !state.busy, role = Role.RadioButton,
onClick = { onDesign(design) },
).padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
RadioButton(selected = state.draft.design == design, onClick = null, enabled = !state.busy)
IconPreview(preview)
Text(iconDesignLabel(design))
}
}
}
if (state.draft.design != AppIconDesign.Default) {
Text(stringResource(Res.string.app_icon_appearance), style = MaterialTheme.typography.titleSmall)
Column(Modifier.selectableGroup()) {
state.capabilities.choices.filter { it.design == state.draft.design }.forEach { selection ->
Row(Modifier.fillMaxWidth().selectable(
selected = state.draft == selection,
enabled = !state.busy, role = Role.RadioButton,
onClick = { onAppearance(selection) },
).padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
RadioButton(selected = state.draft == selection, onClick = null, enabled = !state.busy)
Text(iconAppearanceLabel(selection.appearance))
}
}
}
}
}
if (state.busy) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
CircularProgressIndicator(Modifier.size(24.dp))
Text(stringResource(Res.string.app_icon_busy))
}
if (state.failed) {
Text(stringResource(Res.string.app_icon_error), color = MaterialTheme.colorScheme.error)
TextButton(onClick = onRefresh, enabled = !state.busy) { Text(stringResource(Res.string.app_icon_refresh)) }
}
}
},
confirmButton = {
if (state.capabilities.canChange) TextButton(onClick = onApply, enabled = !state.busy) {
Text(stringResource(Res.string.app_icon_apply))
}
},
dismissButton = {
Row {
if (state.capabilities.canChange) TextButton(onClick = onReset, enabled = !state.busy,
modifier = Modifier.semantics { contentDescription = resetLabel }) {
Text(stringResource(Res.string.app_icon_reset_short))
}
TextButton(onClick = onDismiss) { Text(stringResource(Res.string.app_icon_close)) }
}
},
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/appearance/AppIconViewModel.kt
- Source · implementation · 82 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
17: internal data class AppIconState(
26: internal class AppIconViewModel(private val service: AppIconService) : ViewModel() {
32: fun refresh() {
49: fun openPicker() {
53: fun dismissPicker() { _state.update { it.copy(pickerOpen = false) } }
54: fun chooseDesign(design: AppIconDesign) {
62: fun chooseAppearance(selection: AppIconSelection) {
66: fun applyDraft() { select(_state.value.draft) }
68: fun select(selection: AppIconSelection) {
Exact file bytes / download · SHA-256 96dbbdb513e94043410e0c8000cf0fe0cd581bccc0769f3dc1d04d0ddd5103ad.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.appearance
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.services.appicons.AppIconDesign
import eu.friedcutlet.yokan.services.appicons.AppIconCapabilities
import eu.friedcutlet.yokan.services.appicons.AppIconSelection
import eu.friedcutlet.yokan.services.appicons.AppIconService
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
internal data class AppIconState(
val capabilities: AppIconCapabilities,
val selection: AppIconSelection? = null,
val busy: Boolean = false,
val pickerOpen: Boolean = false,
val draft: AppIconSelection = AppIconSelection.Default,
val failed: Boolean = false,
)
internal class AppIconViewModel(private val service: AppIconService) : ViewModel() {
private val _state = MutableStateFlow(AppIconState(service.capabilities))
val state = _state.asStateFlow()
init { refresh() }
fun refresh() {
if (_state.value.busy) return
_state.update { it.copy(busy = true, failed = false) }
viewModelScope.launch {
try {
val current = service.current()
_state.update { it.copy(selection = current, failed = current == null) }
} catch (error: CancellationException) {
throw error
} catch (_: Exception) {
_state.update { it.copy(selection = null, failed = true) }
} finally {
_state.update { it.copy(busy = false) }
}
}
}
fun openPicker() {
if (_state.value.busy) return
_state.update { it.copy(pickerOpen = true, draft = it.selection ?: AppIconSelection.Default) }
}
fun dismissPicker() { _state.update { it.copy(pickerOpen = false) } }
fun chooseDesign(design: AppIconDesign) {
if (_state.value.busy) return
_state.update { state ->
val choices = state.capabilities.choices.filter { it.design == design }
val next = choices.firstOrNull { it.appearance == state.draft.appearance } ?: choices.firstOrNull()
if (next == null) state else state.copy(draft = next)
}
}
fun chooseAppearance(selection: AppIconSelection) {
if (_state.value.busy || selection !in _state.value.capabilities.choices) return
_state.update { if (selection.design == it.draft.design) it.copy(draft = selection) else it }
}
fun applyDraft() { select(_state.value.draft) }
fun select(selection: AppIconSelection) {
if (_state.value.busy || selection !in service.capabilities.choices) return
_state.update { it.copy(busy = true, failed = false) }
viewModelScope.launch {
// OS operations cannot be withdrawn when this settings route closes. Join completion
// and read the installation's real state rather than leaving a stale optimistic choice.
withContext(NonCancellable) {
var failed = false
try { service.apply(selection) } catch (_: Exception) { failed = true }
val actual = try { service.current() } catch (_: Exception) { null }
_state.update { it.copy(selection = actual, busy = false, pickerOpen = it.pickerOpen && (failed || actual != selection), failed = failed || actual != selection) }
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/appearance/AppearanceSettingsScreen.kt
- Source · implementation · 444 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
81: internal fun AppearanceSettingsRoute(
105: internal fun AppearanceSettingsScreen(
416: internal fun DbL10nLocale?.languageLabel(): String = when {
440: private fun relativeTimestampLabel(value: Int): String = when (value) {
Exact file bytes / download · SHA-256 d9eab28b48d7856c1abd9b10ee38d1f0fa3da700001adf71c90269a925ae102f.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.appearance
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.AspectRatio
import androidx.compose.material.icons.filled.ColorLens
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbL10nLocale
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.appicons.AppIconDesign
import eu.friedcutlet.yokan.services.appicons.AppIconSelection
import eu.friedcutlet.yokan.services.system.isTvDevice
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.CustomNavigation
import eu.friedcutlet.yokan.ui.screens.settings.RouteTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.YokanMenuTile
import eu.friedcutlet.yokan.ui.theme.AppFontFamilyChoices
import eu.friedcutlet.yokan.ui.theme.FlexSchemes
import eu.friedcutlet.yokan.ui.theme.rememberSystemDark
import eu.friedcutlet.yokan.ui.theme.resolveDarkMode
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.eink_device
import yokan.composeapp.generated.resources.eink_mode
import yokan.composeapp.generated.resources.eink_mode_help
import yokan.composeapp.generated.resources.eink_optimize_downloads
import yokan.composeapp.generated.resources.eink_optimize_downloads_help
import yokan.composeapp.generated.resources.eink_refresh
import yokan.composeapp.generated.resources.eink_refresh_every
import yokan.composeapp.generated.resources.eink_refresh_every_page
import yokan.composeapp.generated.resources.eink_refresh_off
import yokan.composeapp.generated.resources.eink_section
import eu.friedcutlet.yokan.database.DbEinkPreset
import eu.friedcutlet.yokan.database.EinkRefreshIntervals
import eu.friedcutlet.yokan.ui.screens.settings.ChoiceTile
import yokan.composeapp.generated.resources.settings_app_language
import yokan.composeapp.generated.resources.settings_blend_level
import yokan.composeapp.generated.resources.settings_dark_mode
import yokan.composeapp.generated.resources.settings_date_format
import yokan.composeapp.generated.resources.settings_follow_system_theme
import yokan.composeapp.generated.resources.settings_font
import yokan.composeapp.generated.resources.settings_pure_black_dark_mode
import yokan.composeapp.generated.resources.settings_relative_timestamps
import yokan.composeapp.generated.resources.settings_reorder_navigation
import yokan.composeapp.generated.resources.settings_reorder_navigation_subtitle
import yokan.composeapp.generated.resources.settings_section_appearance
import yokan.composeapp.generated.resources.settings_section_theme
import yokan.composeapp.generated.resources.settings_section_timestamp
import yokan.composeapp.generated.resources.settings_theme
import yokan.composeapp.generated.resources.ui_ui_scale
@Composable
internal fun AppearanceSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
onOpen: (SettingsPage) -> Unit,
) {
val model = viewModel { AppIconViewModel(YokanRuntime.appIcons) }
val iconState by model.state.collectAsStateWithLifecycle()
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { model.refresh() }
AppearanceSettingsScreen(
title, settings, onUpdate, onBack, onOpen,
iconState = iconState,
onIconPickerOpen = model::openPicker,
onIconPickerDismiss = model::dismissPicker,
onIconDesign = model::chooseDesign,
onIconAppearance = model::chooseAppearance,
onIconApply = model::applyDraft,
onIconReset = { model.select(AppIconSelection.Default) },
onIconRefresh = model::refresh,
)
}
@Composable
internal fun AppearanceSettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
onOpen: (SettingsPage) -> Unit,
iconState: AppIconState,
onIconPickerOpen: () -> Unit,
onIconPickerDismiss: () -> Unit,
onIconDesign: (AppIconDesign) -> Unit,
onIconAppearance: (AppIconSelection) -> Unit,
onIconApply: () -> Unit,
onIconReset: () -> Unit,
onIconRefresh: () -> Unit,
) {
val blend = (settings.flexColorSchemeBlendLevel / 100.0).toFloat().coerceIn(0f, 1f)
val systemDark = rememberSystemDark()
val previewDarkTheme = resolveDarkMode(
followSystem = settings.followSystemTheme,
themeIsDark = settings.themeIsDark,
systemDark = systemDark,
)
var themePickerOpen by remember { mutableStateOf(false) }
var languagePickerOpen by remember { mutableStateOf(false) }
var fontPickerOpen by remember { mutableStateOf(false) }
var relativeTimestampPickerOpen by remember { mutableStateOf(false) }
var dateFormatPickerOpen by remember { mutableStateOf(false) }
if (themePickerOpen) {
ThemePreviewDialog(
settings = settings,
darkTheme = previewDarkTheme,
blend = blend,
onApply = { idx -> onUpdate { it.copy(flexSchemeColorIndex = idx) } },
onDismiss = { themePickerOpen = false },
)
}
if (languagePickerOpen) {
// Mangayomi's 17 supported locales (app_localizations.dart).
val choices = listOf(
null,
DbL10nLocale("ar"),
DbL10nLocale("as"),
DbL10nLocale("de"),
DbL10nLocale("en"),
DbL10nLocale("es"),
DbL10nLocale("es", "419"),
DbL10nLocale("fr"),
DbL10nLocale("hi"),
DbL10nLocale("id"),
DbL10nLocale("it"),
DbL10nLocale("ja"),
DbL10nLocale("pt"),
DbL10nLocale("pt", "BR"),
DbL10nLocale("ru"),
DbL10nLocale("th"),
DbL10nLocale("tr"),
DbL10nLocale("zh"),
)
ChoiceDialog(
title = stringResource(Res.string.settings_app_language),
options = choices,
selected = choices.firstOrNull {
it?.languageCode == settings.locale?.languageCode && it?.countryCode == settings.locale?.countryCode
} ?: choices.firstOrNull { it?.languageCode == settings.locale?.languageCode } ?: choices[0],
label = { it.languageLabel() },
onSelect = { locale -> onUpdate { it.copy(locale = locale) } },
onDismiss = { languagePickerOpen = false },
)
}
if (fontPickerOpen) {
val choices = AppFontFamilyChoices
ChoiceDialog(
title = stringResource(Res.string.settings_font),
options = choices,
selected = settings.appFontFamily ?: "Default",
label = { it },
onSelect = { font -> onUpdate { it.copy(appFontFamily = font.takeIf { it != "Default" }) } },
onDismiss = { fontPickerOpen = false },
)
}
if (relativeTimestampPickerOpen) {
ChoiceDialog(
title = stringResource(Res.string.settings_relative_timestamps),
options = listOf(0, 1, 2),
selected = settings.relativeTimesTamps.coerceIn(0, 2),
label = ::relativeTimestampLabel,
onSelect = { value -> onUpdate { it.copy(relativeTimesTamps = value) } },
onDismiss = { relativeTimestampPickerOpen = false },
)
}
if (dateFormatPickerOpen) {
ChoiceDialog(
title = stringResource(Res.string.settings_date_format),
options = DateFormats,
selected = settings.dateFormat,
label = { it },
onSelect = { format -> onUpdate { it.copy(dateFormat = format) } },
onDismiss = { dateFormatPickerOpen = false },
)
}
if (iconState.pickerOpen) {
AppIconPicker(iconState, onIconDesign, onIconAppearance, onIconApply, onIconReset, onIconRefresh, onIconPickerDismiss)
}
SettingsScaffold(title, onBack) {
item { SettingsSection(stringResource(Res.string.settings_section_theme)) }
item(key = "system-theme") {
SwitchTile(
stringResource(Res.string.settings_follow_system_theme),
if (settings.followSystemTheme) "Currently following system" else null,
settings.followSystemTheme,
{ value -> onUpdate { it.copy(followSystemTheme = value) } },
)
}
if (!settings.followSystemTheme) {
item { SwitchTile(stringResource(Res.string.settings_dark_mode), null, settings.themeIsDark, { onUpdate { it.copy(followSystemTheme = false, themeIsDark = !it.themeIsDark) } }) }
}
if (previewDarkTheme) {
item { SwitchTile(stringResource(Res.string.settings_pure_black_dark_mode), null, settings.pureBlackDarkMode, { value -> onUpdate { it.copy(pureBlackDarkMode = value) } }) }
}
item {
val schemeIndex = settings.flexSchemeColorIndex.coerceIn(0, FlexSchemes.lastIndex)
val schemeName = FlexSchemes[schemeIndex].displayName
YokanMenuTile(
title = stringResource(Res.string.settings_theme),
subtitle = schemeName,
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = { themePickerOpen = true },
)
}
item {
ElevatedCard(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp)) {
Column(Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.Filled.ColorLens, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
Text(stringResource(Res.string.settings_blend_level), fontWeight = FontWeight.Medium, modifier = Modifier.weight(1f))
Text("${(blend * 100).toInt()}%", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.labelMedium)
}
Slider(value = blend, onValueChange = { value -> onUpdate { it.copy(flexColorSchemeBlendLevel = value * 100.0) } })
}
}
}
item { MaterialKolorBlock(settings, onUpdate) }
item { SettingsSection(stringResource(Res.string.eink_section)) }
item(key = "eink-mode") {
SwitchTile(
stringResource(Res.string.eink_mode),
stringResource(Res.string.eink_mode_help),
settings.einkMode,
{ value -> onUpdate { it.copy(einkMode = value) } },
)
}
if (settings.einkMode) {
item(key = "eink-device") {
ChoiceTile(stringResource(Res.string.eink_device), DbEinkPreset.entries, settings.einkPreset, { it.label }) { preset ->
onUpdate { it.copy(einkPreset = preset) }
}
}
item(key = "eink-refresh") {
val labels = EinkRefreshIntervals.associateWith { pages ->
when (pages) {
0 -> stringResource(Res.string.eink_refresh_off)
1 -> stringResource(Res.string.eink_refresh_every_page)
else -> stringResource(Res.string.eink_refresh_every, pages)
}
}
ChoiceTile(stringResource(Res.string.eink_refresh), EinkRefreshIntervals, settings.einkRefreshEveryPages, { labels.getValue(it) }) { pages ->
onUpdate { it.copy(einkRefreshEveryPages = pages) }
}
}
item(key = "eink-downloads") {
val preset = settings.einkPreset
SwitchTile(
stringResource(Res.string.eink_optimize_downloads),
stringResource(Res.string.eink_optimize_downloads_help, preset.label, preset.width, preset.height),
settings.einkOptimizeDownloads,
{ value -> onUpdate { it.copy(einkOptimizeDownloads = value) } },
)
}
}
item { SettingsSection(stringResource(Res.string.settings_section_appearance)) }
item(key = "app-icons") {
AppIconTile(iconState, onIconPickerOpen)
}
item {
SwitchTile(
"Automatic UI scale",
"Adjust scale from the platform text-size setting",
settings.autoUiScale,
{ value -> onUpdate { it.copy(autoUiScale = value) } },
)
}
item {
ElevatedCard(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp)) {
Column(Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
val currentScale = settings.uiScale.toFloat().coerceIn(0.75f, 2.0f)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.Filled.Tune, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
Text(stringResource(Res.string.ui_ui_scale), fontWeight = FontWeight.Medium, modifier = Modifier.weight(1f))
Text("${(currentScale * 100).toInt()}%", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.labelMedium)
}
Slider(
value = currentScale,
onValueChange = { value ->
// Snap to 5% steps so the persisted number stays readable.
val snapped = ((value * 20).toInt() / 20f).coerceIn(0.75f, 2.0f)
onUpdate { it.copy(uiScale = snapped.toDouble()) }
},
enabled = !settings.autoUiScale,
valueRange = 0.75f..2.0f,
steps = 24,
)
Text(
if (settings.autoUiScale) "Using automatic scaling" else "System default 100%",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
if (isTvDevice()) {
item {
val currentTvScale = (settings.tvUiScale ?: 1.0).toFloat().coerceIn(0.85f, 1.25f)
ElevatedCard(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp)) {
Column(Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.Filled.AspectRatio, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
Text("TV interface scale", fontWeight = FontWeight.Medium, modifier = Modifier.weight(1f))
Text("${(currentTvScale * 100).toInt()}%", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.labelMedium)
}
Slider(
value = currentTvScale,
onValueChange = { value ->
val snapped = ((value * 20).toInt() / 20f).coerceIn(0.85f, 1.25f)
onUpdate { it.copy(tvUiScale = snapped.toDouble()) }
},
valueRange = 0.85f..1.25f,
steps = 7,
)
Text(
"Fine-tune sizing for TV screens and viewing distances",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
item {
SwitchTile(
"Anime-only TV mode",
"Hide manga and novel library tabs on TV layout",
settings.animeOnlyTvMode ?: true,
{ value -> onUpdate { it.copy(animeOnlyTvMode = value) } },
)
}
}
item(key = "language") {
YokanMenuTile(
title = stringResource(Res.string.settings_app_language),
subtitle = settings.locale.languageLabel(),
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = { languagePickerOpen = true },
)
}
item {
YokanMenuTile(
title = stringResource(Res.string.settings_font),
subtitle = settings.appFontFamily ?: "Default",
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = { fontPickerOpen = true },
)
}
item { RouteTile(CustomNavigation, stringResource(Res.string.settings_reorder_navigation), stringResource(Res.string.settings_reorder_navigation_subtitle), onOpen = onOpen) }
item { SettingsSection(stringResource(Res.string.settings_section_timestamp)) }
item {
YokanMenuTile(
title = stringResource(Res.string.settings_relative_timestamps),
subtitle = relativeTimestampLabel(settings.relativeTimesTamps),
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = { relativeTimestampPickerOpen = true },
)
}
item {
YokanMenuTile(
title = stringResource(Res.string.settings_date_format),
subtitle = settings.dateFormat,
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = { dateFormatPickerOpen = true },
)
}
}
}
private val DateFormats = listOf(
"M/d/y",
"MM/dd/yy",
"dd/MM/yy",
"yyyy-MM-dd",
"dd MMM yyyy",
"MMM dd, yyyy",
"MM/dd/yyyy",
"dd/MM/yyyy",
"d/M/y",
"y/M/d",
"yyyy/MM/dd",
"MMM d, y",
"MMM d, yyyy",
"MMMM d, yyyy",
)
internal fun DbL10nLocale?.languageLabel(): String = when {
this?.languageCode == null -> "Default"
languageCode == "es" && countryCode == "419" -> "Español (Latinoamérica)"
languageCode == "pt" && countryCode == "BR" -> "Português (Brasil)"
else -> when (languageCode) {
"ar" -> "العربية"
"as" -> "অসমীয়া"
"de" -> "Deutsch"
"en" -> "English"
"es" -> "Español"
"fr" -> "Français"
"hi" -> "हिन्दी"
"id" -> "Bahasa Indonesia"
"it" -> "Italiano"
"ja" -> "日本語"
"pt" -> "Português"
"ru" -> "Русский"
"th" -> "ไทย"
"tr" -> "Türkçe"
"zh" -> "中文"
else -> languageCode.orEmpty()
}
}
private fun relativeTimestampLabel(value: Int): String = when (value) {
0 -> "Off"
1 -> "Short"
else -> "Long"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/appearance/MaterialKolorBlock.kt
- Source · implementation · 279 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
68: internal fun MaterialKolorBlock(settings: DbSettings, onUpdate: ((DbSettings) -> DbSettings) -> Unit) {
188: private fun SeedColorPresets(current: Int?, onPick: (Int) -> Unit) {
221: private fun SeedColorHexDialog(current: Int?, onDismiss: () -> Unit, onSave: (Int?) -> Unit) {
262: private fun argbHex(argb: Int): String {
271: private fun parseArgbHex(raw: String): Int? {
Exact file bytes / download · SHA-256 181735e76cb8f4c228a08246ce7d83d0d6bb3025f032ec26a78b48b5e8ab9c42.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.appearance
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.ColorLens
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.files.pickFile
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.YokanMenuTile
import eu.friedcutlet.yokan.ui.theme.PaletteStyleChoices
import eu.friedcutlet.yokan.ui.theme.materialYouAvailable
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.ui_clear
/**
* MaterialKolor section in Appearance: seed color (presets + hex), seed image
* picker, palette style, Material You toggle, Material Expressive toggle.
*
* The seed image takes precedence over the explicit seed color; clearing the
* image falls back to the hex seed (and clearing both falls back to the legacy
* FlexSchemes palette so the theme always renders something usable).
*/
@Composable
internal fun MaterialKolorBlock(settings: DbSettings, onUpdate: ((DbSettings) -> DbSettings) -> Unit) {
val scope = rememberCoroutineScope()
var stylePickerOpen by remember { mutableStateOf(false) }
var hexDialogOpen by remember { mutableStateOf(false) }
if (stylePickerOpen) {
ChoiceDialog(
title = "Palette style",
options = PaletteStyleChoices,
selected = settings.themePaletteStyle,
label = { it },
onSelect = { value -> onUpdate { it.copy(themePaletteStyle = value) } },
onDismiss = { stylePickerOpen = false },
)
}
if (hexDialogOpen) {
SeedColorHexDialog(
current = settings.themeSeedColor,
onDismiss = { hexDialogOpen = false },
onSave = { value ->
onUpdate { it.copy(themeSeedColor = value) }
hexDialogOpen = false
},
)
}
ElevatedCard(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp)) {
Column(Modifier.padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.Filled.ColorLens, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
Text("MaterialKolor", fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f))
Text(
"Tonal Spot • Spec 2025",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.labelMedium,
)
}
// Material You: only meaningful where the OS exposes a wallpaper palette.
if (materialYouAvailable) {
SwitchTile(
title = "Material You",
subtitle = "Use the device wallpaper palette",
value = settings.materialYou,
onValueChange = { value -> onUpdate { it.copy(materialYou = value) } },
)
} else {
Text(
"Material You uses the device wallpaper palette on Android 12+; not available on this platform.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
}
SwitchTile(
title = "Material Expressive",
subtitle = "Expressive palette + Spec 2025 tonal mapping",
value = settings.materialExpressive,
onValueChange = { value -> onUpdate { it.copy(materialExpressive = value) } },
)
YokanMenuTile(
title = "Palette style",
subtitle = if (settings.materialExpressive) "Expressive (locked by Material Expressive)" else settings.themePaletteStyle,
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = { if (!settings.materialExpressive) stylePickerOpen = true },
)
Text("Seed color", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Medium)
SeedColorPresets(
current = settings.themeSeedColor,
onPick = { argb -> onUpdate { it.copy(themeSeedColor = argb, themeSeedImagePath = null) } },
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
OutlinedButton(onClick = { hexDialogOpen = true }, modifier = Modifier.weight(1f)) {
Icon(Icons.Filled.Edit, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(settings.themeSeedColor?.let { "Edit hex (${argbHex(it)})" } ?: "Set hex…")
}
if (settings.themeSeedColor != null) {
TextButton(onClick = { onUpdate { it.copy(themeSeedColor = null) } }) {
Text(stringResource(Res.string.ui_clear))
}
}
}
Text("Seed from image", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Medium)
Text(
settings.themeSeedImagePath ?: "Pick an image to derive the palette from its dominant color.",
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(
onClick = {
scope.launch {
pickFile(
extensions = listOf("png", "jpg", "jpeg", "webp", "bmp", "gif"),
)?.let { path ->
onUpdate { it.copy(themeSeedImagePath = path) }
}
}
},
modifier = Modifier.weight(1f),
) {
Icon(Icons.Filled.Folder, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Pick image")
}
if (settings.themeSeedImagePath != null) {
TextButton(onClick = { onUpdate { it.copy(themeSeedImagePath = null) } }) {
Text(stringResource(Res.string.ui_clear))
}
}
}
}
}
}
@Composable
private fun SeedColorPresets(current: Int?, onPick: (Int) -> Unit) {
// A small set of Material-You-ish seeds plus a few familiar app accents.
val presets = listOf(
0xFF6750A4.toInt(), // Material default purple
0xFFE91E63.toInt(), // Pink
0xFFEF6C00.toInt(), // Orange
0xFFFFC107.toInt(), // Amber
0xFF2E7D32.toInt(), // Green
0xFF00897B.toInt(), // Teal
0xFF1976D2.toInt(), // Blue
0xFF5E35B1.toInt(), // Deep Purple
0xFF607D8B.toInt(), // Blue Grey
)
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
presets.forEach { argb ->
val color = Color(argb.toLong() and 0xFFFFFFFFL)
val selected = current == argb
Box(
modifier = Modifier
.size(36.dp)
.background(color, CircleShape)
.border(
width = if (selected) 3.dp else 1.dp,
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
shape = CircleShape,
)
.clickable { onPick(argb) },
)
}
}
}
@Composable
private fun SeedColorHexDialog(current: Int?, onDismiss: () -> Unit, onSave: (Int?) -> Unit) {
var text by remember { mutableStateOf(current?.let { argbHex(it) } ?: "") }
val parsed = parseArgbHex(text)
val error = if (text.isNotEmpty() && parsed == null) "Use #RRGGBB or #AARRGGBB" else null
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = {
Text(
"Seed color (hex)",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
Column {
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("#RRGGBB or #AARRGGBB") },
singleLine = true,
isError = error != null,
shape = MaterialTheme.shapes.large,
modifier = Modifier.fillMaxWidth(),
)
error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
}
},
confirmButton = {
Button(
enabled = parsed != null || text.isBlank(),
onClick = { onSave(parsed) },
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 8.dp),
) { Text(stringResource(Res.string.action_save), style = MaterialTheme.typography.labelLarge) }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
)
}
private fun argbHex(argb: Int): String {
val a = (argb ushr 24) and 0xFF
val r = (argb ushr 16) and 0xFF
val g = (argb ushr 8) and 0xFF
val b = argb and 0xFF
val hex = listOf(a, r, g, b).joinToString("") { it.toString(16).padStart(2, '0').uppercase() }
return "#$hex"
}
private fun parseArgbHex(raw: String): Int? {
val trimmed = raw.trim().removePrefix("#")
val full = when (trimmed.length) {
6 -> "FF$trimmed"
8 -> trimmed
else -> return null
}
return runCatching { full.toLong(16).toInt() }.getOrNull()
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/appearance/ThemePreview.kt
- Source · implementation · 248 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
58: internal fun ThemePreviewDialog(
124: private fun ThemePreviewCard(
204: private fun ThemeOptionRow(
241: private fun ThemeSwatch(color: Color, size: Int = 18) {
Exact file bytes / download · SHA-256 094015c419c8ed70acccf052b5e63b768fdbd29a285f906671f0b80800666418.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.appearance
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import eu.friedcutlet.yokan.ui.theme.FlexScheme
import eu.friedcutlet.yokan.ui.theme.FlexSchemes
import eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import eu.friedcutlet.yokan.ui.theme.asColor
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.settings_theme
@Composable
internal fun ThemePreviewDialog(
settings: DbSettings,
darkTheme: Boolean,
blend: Float,
onApply: (Int) -> Unit,
onDismiss: () -> Unit,
) {
val currentIndex = settings.flexSchemeColorIndex.coerceIn(0, FlexSchemes.lastIndex)
var previewIndex by remember(currentIndex) { mutableStateOf(currentIndex) }
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = {
Text(
stringResource(Res.string.settings_theme),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
ThemePreviewCard(
scheme = FlexSchemes[previewIndex],
schemeIndex = previewIndex,
darkTheme = darkTheme,
pureBlack = settings.pureBlackDarkMode,
blend = blend,
)
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 360.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
FlexSchemes.forEachIndexed { index, scheme ->
ThemeOptionRow(
scheme = scheme,
selected = index == previewIndex,
current = index == currentIndex,
onClick = { previewIndex = index },
)
}
}
}
},
confirmButton = {
Button(
onClick = {
onApply(previewIndex)
onDismiss()
},
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 8.dp),
) {
Text(stringResource(Res.string.action_save), style = MaterialTheme.typography.labelLarge)
}
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) }
},
)
}
@Composable
private fun ThemePreviewCard(
scheme: FlexScheme,
schemeIndex: Int,
darkTheme: Boolean,
pureBlack: Boolean,
blend: Float,
) {
YokanTheme(
darkTheme = darkTheme,
schemeIndex = schemeIndex,
pureBlackDark = pureBlack,
blendLevel = blend,
uiScale = 1f,
) {
Surface(
modifier = Modifier.fillMaxWidth(),
color = LocalYokanScaffoldColor.current,
shape = MaterialTheme.shapes.large,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
) {
Column(
modifier = Modifier.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Surface(
modifier = Modifier.size(38.dp),
shape = MaterialTheme.shapes.medium,
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
) {
Box(contentAlignment = Alignment.Center) {
Icon(Icons.Filled.Palette, contentDescription = null)
}
}
Column(modifier = Modifier.weight(1f)) {
Text(scheme.displayName, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text("Preview", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val palette = if (darkTheme) scheme.dark else scheme.light
ThemeSwatch(palette.primary.asColor())
ThemeSwatch(palette.secondary.asColor())
ThemeSwatch(palette.tertiary.asColor())
ThemeSwatch(MaterialTheme.colorScheme.surfaceVariant)
}
Surface(
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
shape = MaterialTheme.shapes.medium,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f)),
) {
Column(
modifier = Modifier.fillMaxWidth().padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.AutoMirrored.Filled.MenuBook, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
Text("Library row", modifier = Modifier.weight(1f), fontWeight = FontWeight.Medium)
Surface(
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
shape = MaterialTheme.shapes.small,
) {
Text("New", modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp), style = MaterialTheme.typography.labelSmall)
}
}
LinearProgressIndicator(
progress = { 0.68f },
modifier = Modifier.fillMaxWidth(),
)
}
}
}
}
}
}
@Composable
private fun ThemeOptionRow(
scheme: FlexScheme,
selected: Boolean,
current: Boolean,
onClick: () -> Unit,
) {
Surface(
modifier = Modifier.fillMaxWidth().clip(MaterialTheme.shapes.medium).clickable(onClick = onClick),
color = if (selected) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.42f) else MaterialTheme.colorScheme.surface,
shape = MaterialTheme.shapes.medium,
border = BorderStroke(
width = if (selected) 2.dp else 1.dp,
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant,
),
) {
Row(
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
ThemeSwatch(scheme.dark.primary.asColor(), size = 14)
ThemeSwatch(scheme.dark.secondary.asColor(), size = 14)
ThemeSwatch(scheme.dark.tertiary.asColor(), size = 14)
}
Column(modifier = Modifier.weight(1f)) {
Text(scheme.displayName, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (current) {
Text("Current", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
RadioButton(selected = selected, onClick = onClick)
}
}
}
@Composable
private fun ThemeSwatch(color: Color, size: Int = 18) {
Box(
modifier = Modifier
.size(size.dp)
.background(color, CircleShape)
.border(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f), CircleShape),
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/browse/BrowseClearViewModel.kt
- Source · implementation · 80 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
18: internal data class BrowseClearState(
24: private data class ClearOutcome(val result: ClearResult, val hubConfigured: Boolean, val sources: Boolean)
27: internal class BrowseClearViewModel(
35: fun clearLibrary(types: Set<ItemType>) = clear {
42: fun clearSources(types: Set<ItemType>) = clear {
46: fun clearFeedback() = _state.update { it.copy(error = null, success = null) }
48: private fun clear(operation: suspend () -> ClearOutcome) {
Exact file bytes / download · SHA-256 d80f855459c285d9c9f131dcd82f798246b3bd76cdde4230b590aa42ddb291b6.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.browse
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.library.ClearResult
import eu.friedcutlet.yokan.services.library.SelectiveDataClearService
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
internal data class BrowseClearState(
val busy: Boolean = false,
val error: String? = null,
val success: String? = null,
)
private data class ClearOutcome(val result: ClearResult, val hubConfigured: Boolean, val sources: Boolean)
/** Runs the selective database clear away from the UI thread and reports only committed results. */
internal class BrowseClearViewModel(
private val service: SelectiveDataClearService,
private val hasConfiguredHub: () -> Boolean,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(BrowseClearState())
val state: StateFlow<BrowseClearState> = _state.asStateFlow()
fun clearLibrary(types: Set<ItemType>) = clear {
val (result, hubConfigured) = withContext(workDispatcher) {
service.clearLibrary(types) to hasConfiguredHub()
}
ClearOutcome(result, hubConfigured, sources = false)
}
fun clearSources(types: Set<ItemType>) = clear {
withContext(workDispatcher) { ClearOutcome(service.clearSources(types), hubConfigured = false, sources = true) }
}
fun clearFeedback() = _state.update { it.copy(error = null, success = null) }
private fun clear(operation: suspend () -> ClearOutcome) {
if (_state.value.busy) return
_state.update { it.copy(busy = true, error = null, success = null) }
viewModelScope.launch {
try {
val outcome = operation()
val result = outcome.result
_state.update {
if (!result.cleared) {
it.copy(busy = false, error = result.error ?: "Nothing was cleared. Check the selected types and try again.")
} else {
it.copy(
busy = false,
success = when {
result.deliveryPending -> "Saved locally; hub delivery pending."
outcome.sources -> "${result.sourcesRemoved} source definitions removed locally. Library entries and media files were kept."
outcome.hubConfigured -> "Library records cleared; hub delivery is up to date."
else -> "Library records cleared locally; no hub is configured."
},
)
}
}
} catch (error: CancellationException) {
_state.update { it.copy(busy = false) }
throw error
} catch (error: Throwable) {
_state.update {
it.copy(busy = false, error = error.message ?: "Could not clear the selected data. Nothing was confirmed as cleared.")
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/browse/BrowseSettingsScreen.kt
- Source · implementation · 298 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
58: internal data class DestructiveAction(
64: internal fun parseClearItemTypes(input: String): Set<ItemType>? {
75: private enum class ClearTarget { Library, Sources }
78: internal fun BrowseSettingsRoute(
122: internal fun BrowseSettingsScreen(
Exact file bytes / download · SHA-256 7ddab50663aa2f92dfdcf75fbd5be1d9392e0c6be59e966711571ecd84ceea59.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.browse
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeMode
import eu.friedcutlet.yokan.services.library.SelectiveDataClearService
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
import eu.friedcutlet.yokan.ui.components.ConfirmDialog
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.CreateBackup
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.AnimeRepositories
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.Cookies
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.ExtensionServer
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.MangaRepositories
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.MetadataServer
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.NovelRepositories
import eu.friedcutlet.yokan.ui.screens.settings.ButtonRow
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.RouteTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.auto_extensions_updates
import yokan.composeapp.generated.resources.check_for_extension_updates
import yokan.composeapp.generated.resources.clean_database
import yokan.composeapp.generated.resources.only_include_pinned_sources
import yokan.composeapp.generated.resources.tile_show_nsfw_sources
import yokan.composeapp.generated.resources.hide_library_section
import yokan.composeapp.generated.resources.hide_library_summary
internal data class DestructiveAction(
val title: String,
val message: String,
val onConfirm: () -> Unit,
)
internal fun parseClearItemTypes(input: String): Set<ItemType>? {
val parts = input.split(',')
if (parts.isEmpty() || parts.any { it.isBlank() }) return null
val selected = linkedSetOf<ItemType>()
for (part in parts) {
val type = ItemType.entries.firstOrNull { it.name.equals(part.trim(), ignoreCase = true) } ?: return null
selected += type
}
return selected.takeIf { it.isNotEmpty() }
}
private enum class ClearTarget { Library, Sources }
@Composable
internal fun BrowseSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
onOpen: (SettingsPage) -> Unit,
) {
val owner = remember { YokanRuntime.activeSession }
val clearViewModel = viewModel {
val service = SelectiveDataClearService(
database = owner.database,
downloader = owner.services.downloader,
onSourcesCommitted = { ids ->
ids.forEach { sourceId ->
owner.services.extensionRuntimeFactory.evict(sourceId)
owner.chapterPages.invalidateSource(sourceId)
}
},
)
BrowseClearViewModel(
service = service,
hasConfiguredHub = {
owner.database.snapshot().syncPreferences.any {
!it.server.isNullOrBlank() && !it.server.startsWith("cloud://")
}
},
)
}
val clearState by clearViewModel.state.collectAsStateWithLifecycle()
BrowseSettingsScreen(
title, settings, onUpdate, onBack, onOpen,
extensionServerIsRemoteOnly = owner.services.extensionServer.mode == ExtensionServerRuntimeMode.Unsupported,
onClearSources = clearViewModel::clearSources,
onCleanDatabase = { owner.repository.cleanDatabase() },
onClearLibrary = clearViewModel::clearLibrary,
onClearLocalLibrary = owner.localLibrary::clear,
clearBusy = clearState.busy,
clearError = clearState.error,
clearSuccess = clearState.success,
onClearFeedback = clearViewModel::clearFeedback,
)
}
@Composable
internal fun BrowseSettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
onOpen: (SettingsPage) -> Unit,
extensionServerIsRemoteOnly: Boolean,
onClearSources: (Set<ItemType>) -> Unit,
onCleanDatabase: () -> Unit,
onClearLibrary: (Set<ItemType>) -> Unit,
onClearLocalLibrary: () -> Int,
clearBusy: Boolean = false,
clearError: String? = null,
clearSuccess: String? = null,
onClearFeedback: () -> Unit = {},
) {
var pendingDestructive by remember { mutableStateOf<DestructiveAction?>(null) }
var pendingClear by remember { mutableStateOf<ClearTarget?>(null) }
var clearTypesText by remember { mutableStateOf("") }
val selectedClearTypes = parseClearItemTypes(clearTypesText)
LaunchedEffect(clearSuccess) {
if (clearSuccess != null) {
pendingClear = null
clearTypesText = ""
}
}
val dismissClear = {
pendingClear = null
clearTypesText = ""
onClearFeedback()
}
pendingClear?.let { target ->
val selectedLabels = selectedClearTypes?.joinToString { it.label } ?: ""
val library = target == ClearTarget.Library
AlertDialog(
onDismissRequest = { if (!clearBusy) dismissClear() },
title = { Text(if (library) "Clear library records" else "Clear source definitions") },
text = {
Column {
Text(if (library) {
"This deletes all selected titles, including favorites and cached entries, plus their chapters, progress, tracking, and download records. With a connected yokan-hub, deletions propagate to your other devices; without a configured hub, this clear is local-only. Sources stay in place. Downloaded and local media files are not deleted."
} else {
"This deletes only the selected local source definitions and preferences from the database. Library entries stay in place. A later repository refresh may rediscover some sources. Downloaded and local media files are not deleted."
})
OutlinedTextField(
value = clearTypesText,
onValueChange = { clearTypesText = it },
modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
label = { Text("Types to clear") },
placeholder = { Text("manga,anime,novel") },
supportingText = {
Text(if (selectedClearTypes == null) "Enter one or more types separated by commas: manga, anime, novel." else "Selected: $selectedLabels")
},
isError = selectedClearTypes == null && clearTypesText.isNotEmpty(),
singleLine = true,
enabled = !clearBusy,
)
if (clearError != null) {
Text(clearError, color = MaterialTheme.colorScheme.error,
modifier = Modifier.semantics { liveRegion = LiveRegionMode.Assertive })
}
}
},
confirmButton = {
TextButton(
onClick = { selectedClearTypes?.let { types -> if (library) onClearLibrary(types) else onClearSources(types) } },
enabled = selectedClearTypes != null && !clearBusy,
) { Text(if (clearBusy) "Clearing…" else if (library) "Clear library records" else "Clear source definitions") }
},
dismissButton = {
Row {
TextButton(onClick = { onOpen(CreateBackup) }, enabled = !clearBusy) { Text("Create backup") }
TextButton(onClick = dismissClear, enabled = !clearBusy) { Text(stringResource(Res.string.action_cancel)) }
}
},
)
}
pendingDestructive?.let { action ->
ConfirmDialog(
title = action.title,
message = action.message,
confirmLabel = "Yes, clear",
danger = true,
onConfirm = action.onConfirm,
onDismiss = { pendingDestructive = null },
)
}
SettingsScaffold(title, onBack) {
item { SettingsSection("Extensions") }
item {
RouteTile(
ExtensionServer,
if (extensionServerIsRemoteOnly) "Remote APK extension server" else "Android proxy server (Mihon)",
if (extensionServerIsRemoteOnly) "Connect to a hosted server URL" else "Install and run the local bridge",
onOpen = onOpen,
)
}
item { RouteTile(MetadataServer, "Metadata server", "Alternative titles, tags, and tracker sync", onOpen = onOpen) }
item { RouteTile(MangaRepositories, "Manga extensions repo", "Manage manga repo URLs", onOpen = onOpen) }
item { RouteTile(AnimeRepositories, "Anime extensions repo", "Manage anime repo URLs", onOpen = onOpen) }
item { RouteTile(NovelRepositories, "Novel extensions repo", "Manage novel repo URLs", onOpen = onOpen) }
item { SwitchTile(stringResource(Res.string.check_for_extension_updates), null, settings.checkForExtensionUpdates, { value -> onUpdate { it.copy(checkForExtensionUpdates = value) } }) }
item {
ButtonRow("Clear source definitions", danger = true) {
onClearFeedback()
clearTypesText = ""
pendingClear = ClearTarget.Sources
}
}
item {
val cleanDatabaseTitle = stringResource(Res.string.clean_database)
SettingTile(
cleanDatabaseTitle,
"Delete non-favorited entries and their chapter data",
onClick = {
pendingDestructive = DestructiveAction(
title = cleanDatabaseTitle,
message = "Delete every entry that isn't in your library (cached browsing results) and its chapter data? Favorited entries are kept.",
) { onCleanDatabase() }
},
)
}
item {
SettingTile("Clear library records", "Remove selected media types from the library database", onClick = {
onClearFeedback()
clearTypesText = ""
pendingClear = ClearTarget.Library
})
}
if (clearSuccess != null) {
item {
Text(
clearSuccess,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp).semantics { liveRegion = LiveRegionMode.Polite },
color = MaterialTheme.colorScheme.primary,
)
}
}
item {
SettingTile(
"Clear local library",
"Remove indexed local and archive titles",
onClick = {
pendingDestructive = DestructiveAction(
title = "Clear local library",
message = "All local and archive titles, chapters, history, updates, and download records will be removed. Remote library entries are kept. This cannot be undone.",
) {
val removed = onClearLocalLibrary()
InAppNotifications.post(
"Local library cleared",
"$removed ${if (removed == 1) "title" else "titles"} removed",
)
}
},
)
}
if (settings.checkForExtensionUpdates) {
item { SwitchTile(stringResource(Res.string.auto_extensions_updates), "Auto-install updates when available", settings.autoExtensionsUpdates, { value -> onUpdate { it.copy(autoExtensionsUpdates = value) } }) }
}
item { SettingsSection(stringResource(Res.string.hide_library_section)) }
item { InfoRow(stringResource(Res.string.hide_library_summary)) }
ItemType.entries.forEach { type ->
item(key = "hide-library-${type.name}") {
SwitchTile(type.label, null, settings.features.browse.hidesLibrary(type), { value ->
onUpdate { it.copy(features = it.features.copy(browse = it.features.browse.withHideLibrary(type, value))) }
})
}
}
item { SettingsSection("Global search") }
item { SwitchTile(stringResource(Res.string.only_include_pinned_sources), null, settings.onlyIncludePinnedSources, { value -> onUpdate { it.copy(onlyIncludePinnedSources = value) } }) }
item { SettingsSection("NSFW sources") }
item { SwitchTile(stringResource(Res.string.tile_show_nsfw_sources), null, settings.showNsfw, { value -> onUpdate { it.copy(showNsfw = value) } }) }
item { InfoRow("NSFW sources may contain explicit material. The app does not endorse or curate this content — use at your own discretion.") }
item { SettingsSection("Cookies") }
item { RouteTile(Cookies, "Cookies", "Manage stored source cookies", onOpen = onOpen) }
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/browse/CookiesSettingsScreen.kt
- Source · implementation · 111 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
34: internal fun CookiesSettingsScreen(
110: internal fun cookieValueText(value: String?, revealed: Boolean): String =
Exact file bytes / download · SHA-256 c0e29571404264861bbce2f454e732ff27d0252036acbbb0ed52d9ebb9707499.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.browse
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Security
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.components.ConfirmDialog
import eu.friedcutlet.yokan.ui.screens.settings.ButtonRow
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.ui_clear
@Composable
internal fun CookiesSettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val cookies = settings.cookiesList.orEmpty()
// Deliberately not saveable: revealing secrets lasts only while this screen is open.
var revealValues by remember { mutableStateOf(false) }
var pendingDestructive by remember { mutableStateOf<DestructiveAction?>(null) }
pendingDestructive?.let { action ->
ConfirmDialog(
title = action.title,
message = action.message,
confirmLabel = stringResource(Res.string.ui_clear),
danger = true,
onConfirm = {
action.onConfirm()
pendingDestructive = null
},
onDismiss = { pendingDestructive = null },
)
}
SettingsScaffold(title, onBack) {
item(key = "cookies") {
SwitchTile(
title = "Show cookie values",
subtitle = "Hidden by default. Revealing applies only while this screen is open.",
value = revealValues,
onValueChange = { revealValues = it },
)
}
if (cookies.isEmpty()) {
item(key = "empty") { InfoRow("No cookies stored yet. Cookies are captured automatically when sources set them via Set-Cookie headers.") }
} else {
cookies.distinctBy { it.host }.forEach { cookie ->
item(key = "host:${cookie.host?.let { "known:$it" } ?: "unknown"}") {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Icon(Icons.Filled.Security, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
Column(Modifier.weight(1f)) {
Text(cookie.host ?: "Unknown host", fontWeight = FontWeight.SemiBold)
Text(
text = cookieValueText(cookie.cookie, revealValues),
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
}
TextButton(onClick = {
pendingDestructive = DestructiveAction(
title = "Clear cookies for ${cookie.host ?: "Unknown host"}?",
message = "This may sign you out of this source. This cannot be undone.",
) {
onUpdate { current ->
current.copy(cookiesList = current.cookiesList.orEmpty().filterNot { it.host == cookie.host })
}
}
}) { Text(stringResource(Res.string.ui_clear)) }
}
}
}
item(key = "clear-all") {
ButtonRow("Clear all cookies", danger = true) {
pendingDestructive = DestructiveAction(
title = "Clear all cookies?",
message = "This removes cookies for every host and may sign you out of sources. This cannot be undone.",
) { onUpdate { it.copy(cookiesList = emptyList()) } }
}
}
}
}
}
internal fun cookieValueText(value: String?, revealed: Boolean): String =
if (revealed) value.orEmpty() else "•••••••• (hidden)"
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/browse/RepositoriesViewModel.kt
- Source · implementation · 81 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
20: internal data class RepositoriesState(
28: internal class RepositoriesViewModel(
42: fun selectType(type: ItemType) = _state.update { it.copy(itemType = type, repositories = repository.repositories(type)) }
44: fun upsert(repo: DbRepo) {
49: fun remove(jsonUrl: String) {
54: fun showMessage(message: String) = _state.update { it.copy(message = message) }
56: fun refresh(repo: DbRepo) {
80: private fun reload() = _state.update { it.copy(repositories = repository.repositories(it.itemType)) }
Exact file bytes / download · SHA-256 b547a2166049da70061dd7200a3c796cf17c6b8f88f2b9cdbe033c1aae2edf3d.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.browse
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.SourceInstallService
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
internal data class RepositoriesState(
val itemType: ItemType,
val repositories: List<DbRepo>,
/** JSON URL of the repository being refreshed; one refresh at a time. */
val loadingRepoUrl: String? = null,
val message: String? = null,
)
internal class RepositoriesViewModel(
initialType: ItemType,
private val repository: YokanRepository,
private val sourceInstall: SourceInstallService,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(RepositoriesState(initialType, repository.repositories(initialType)))
val state: StateFlow<RepositoriesState> = _state.asStateFlow()
init {
// Repositories live in the settings row; sync and deep links write it too.
viewModelScope.launch { repository.snapshots.distinctUntilChangedBy { it.settings }.collect { reload() } }
}
fun selectType(type: ItemType) = _state.update { it.copy(itemType = type, repositories = repository.repositories(type)) }
fun upsert(repo: DbRepo) {
repository.upsertRepository(_state.value.itemType, repo)
reload()
}
fun remove(jsonUrl: String) {
repository.removeRepository(_state.value.itemType, jsonUrl)
reload()
}
fun showMessage(message: String) = _state.update { it.copy(message = message) }
fun refresh(repo: DbRepo) {
val jsonUrl = repo.jsonUrl.orEmpty()
val current = _state.value
if (jsonUrl.isBlank() || current.loadingRepoUrl != null) return
val type = current.itemType
_state.update {
it.copy(loadingRepoUrl = jsonUrl, message = "Refreshing ${repo.name ?: jsonUrl.substringAfterLast('/')}...")
}
viewModelScope.launch {
val result = withContext(workDispatcher) {
catchingNonCancellation { sourceInstall.refreshRepository(type, repo) }
}
val message = result.fold(
onSuccess = { summary ->
"${repo.name ?: "Repository"}: ${summary.fetched} fetched, ${summary.added} added, ${summary.updateAvailable} updates, ${summary.updated} auto-updated, ${summary.obsolete} obsolete."
},
onFailure = { error ->
"${repo.name ?: "Repository"} refresh failed: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}"
},
)
_state.update { it.copy(loadingRepoUrl = null, message = message) }
}
}
private fun reload() = _state.update { it.copy(repositories = repository.repositories(it.itemType)) }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/browse/SourceRepositoriesScreen.kt
- Source · implementation · 355 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
76: internal fun SourceRepositoriesRoute(title: String, initialItemType: ItemType, pinnedType: ItemType?, onBack: () -> Unit) {
99: internal fun SourceRepositoriesScreen(
135: fun submitRepo() {
Exact file bytes / download · SHA-256 943272f76f99db8b9a702a08d79630253731d09c34f0644ed0d038e15698f739.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.browse
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.DeleteSweep
import androidx.compose.material.icons.filled.Explore
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.OpenInBrowser
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.extensions.SourceRepositoryUrls
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.ui.components.ConfirmDialog
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.TooltipIconButton
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_add
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_refresh
import yokan.composeapp.generated.resources.action_remove
@Composable
internal fun SourceRepositoriesRoute(title: String, initialItemType: ItemType, pinnedType: ItemType?, onBack: () -> Unit) {
val model = viewModel {
RepositoriesViewModel(pinnedType ?: initialItemType, YokanRuntime.repository, YokanRuntime.sourceInstall)
}
val state by model.state.collectAsStateWithLifecycle()
SourceRepositoriesScreen(
title = title,
state = state,
showTypeSwitcher = pinnedType == null,
onBack = onBack,
onSelectType = model::selectType,
onUpsert = model::upsert,
onRemove = model::remove,
onRefresh = model::refresh,
onMessage = model::showMessage,
)
}
/**
* When opened from a type-specific entry (Manga/Anime/Novel extensions repo) the type is pinned and
* the switcher hidden, so each list is a fully separate screen.
*/
@Composable
internal fun SourceRepositoriesScreen(
title: String,
state: RepositoriesState,
showTypeSwitcher: Boolean,
onBack: () -> Unit,
onSelectType: (ItemType) -> Unit,
onUpsert: (DbRepo) -> Unit,
onRemove: (jsonUrl: String) -> Unit,
onRefresh: (DbRepo) -> Unit,
onMessage: (String) -> Unit,
) {
var newRepoUrl by remember { mutableStateOf("") }
var newRepoName by remember { mutableStateOf("") }
val selectedType = state.itemType
val loadingRepoUrl = state.loadingRepoUrl
var pendingRemoval by remember { mutableStateOf<DbRepo?>(null) }
var addOpen by remember { mutableStateOf(false) }
// Compose exposes no common constructor for ClipEntry yet; retain the text-only KMP API.
@Suppress("DEPRECATION")
val clipboard = LocalClipboardManager.current
pendingRemoval?.let { repo ->
ConfirmDialog(
title = "Remove repository",
message = "Remove \"${repo.name ?: repo.jsonUrl ?: "repository"}\" from ${selectedType.label.lowercase()} sources? Installed extensions are kept; only the repository reference is removed.",
confirmLabel = stringResource(Res.string.action_remove),
danger = true,
onConfirm = {
repo.jsonUrl?.let(onRemove)
},
onDismiss = { pendingRemoval = null },
)
}
if (addOpen) {
val canAddRepo = newRepoUrl.startsWith("http") || newRepoUrl.startsWith("file://")
fun submitRepo() {
if (!canAddRepo) return
val normalizedUrl = SourceRepositoryUrls.normalizeUrl(newRepoUrl)
val displayName = SourceRepositoryUrls.resolveDisplayName(
newRepoName,
normalizedUrl,
"${selectedType.label} repository"
)
onUpsert(
DbRepo(
name = displayName,
jsonUrl = normalizedUrl,
website = normalizedUrl.substringBeforeLast('/').takeIf { it.startsWith("http") },
),
)
newRepoName = ""
newRepoUrl = ""
addOpen = false
}
AlertDialog(
onDismissRequest = { addOpen = false },
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = {
Text(
"Add repository",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(
value = newRepoName,
onValueChange = { newRepoName = it },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
shape = MaterialTheme.shapes.large,
label = { Text("Repository name") },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
)
OutlinedTextField(
value = newRepoUrl,
onValueChange = { newRepoUrl = it },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
shape = MaterialTheme.shapes.large,
label = { Text("Repository JSON URL") },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { submitRepo() }),
)
Text(
"URL must end in .json",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
},
confirmButton = {
Button(
enabled = canAddRepo,
onClick = { submitRepo() },
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 8.dp),
) { Text(stringResource(Res.string.action_add), style = MaterialTheme.typography.labelLarge) }
},
dismissButton = {
TextButton(onClick = { addOpen = false }) { Text(stringResource(Res.string.action_cancel)) }
},
)
}
SettingsScaffold(title, onBack) {
if (showTypeSwitcher) {
item {
FlowRow(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
ItemType.entries.forEach { type ->
FilterChip(
selected = selectedType == type,
onClick = { onSelectType(type) },
label = { Text(type.label) },
)
}
}
}
}
state.message?.let { message ->
item {
ListItem(
headlineContent = { Text(message, style = MaterialTheme.typography.bodyMedium) },
leadingContent = { Icon(Icons.Filled.Info, contentDescription = null, tint = MaterialTheme.colorScheme.primary) },
)
}
}
val repoList = state.repositories
item { SettingsSection("${selectedType.label} repositories") }
if (repoList.isEmpty()) {
item {
EmptyState(
icon = Icons.Filled.Explore,
title = "No repositories configured",
modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp, horizontal = 16.dp),
subtitle = "Tap Add to register a repository JSON URL for ${selectedType.label.lowercase()} sources.",
)
}
} else {
repoList.forEach { repo ->
val isHidden = repo.hidden == true
val isLoading = loadingRepoUrl == repo.jsonUrl
// upsertRepository keeps one entry per JSON URL, so the URL identifies the row.
item(key = "repo:${repo.jsonUrl}") {
ElevatedCard(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
) {
Column(Modifier.padding(horizontal = 12.dp, vertical = 12.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.primaryContainer,
modifier = Modifier.size(40.dp),
) {
Box(contentAlignment = Alignment.Center) {
Icon(
if (repo.jsonUrl?.startsWith("file://") == true) Icons.Filled.Folder else Icons.Filled.Explore,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
)
}
}
Column(Modifier.weight(1f)) {
Text(
repo.name ?: "Repository",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = if (isHidden) MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f) else MaterialTheme.colorScheme.onSurface,
textDecoration = if (isHidden) TextDecoration.LineThrough else null,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
repo.jsonUrl ?: repo.website.orEmpty(),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
if (isLoading) {
Spacer(Modifier.height(8.dp))
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
Spacer(Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
) {
if (!repo.website.isNullOrBlank()) {
TooltipIconButton(
tooltip = "Open website",
icon = Icons.Filled.OpenInBrowser,
onClick = { openSystemBrowser(repo.website) },
)
}
TooltipIconButton(
tooltip = "Copy URL",
icon = Icons.Filled.ContentCopy,
onClick = {
repo.jsonUrl?.let { url ->
clipboard.setText(AnnotatedString(url))
onMessage("Copied URL to clipboard.")
}
},
enabled = !repo.jsonUrl.isNullOrBlank(),
)
TooltipIconButton(
tooltip = if (isHidden) "Show" else "Hide",
icon = if (isHidden) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
onClick = {
if (!repo.jsonUrl.isNullOrBlank()) {
onUpsert(repo.copy(hidden = !isHidden))
}
},
enabled = !repo.jsonUrl.isNullOrBlank(),
)
TooltipIconButton(
tooltip = stringResource(Res.string.action_refresh),
icon = Icons.Filled.Sync,
onClick = { onRefresh(repo) },
enabled = !isLoading && !repo.jsonUrl.isNullOrBlank(),
)
TooltipIconButton(
tooltip = stringResource(Res.string.action_remove),
icon = Icons.Filled.DeleteSweep,
onClick = { pendingRemoval = repo },
tint = MaterialTheme.colorScheme.error,
)
}
}
}
}
}
}
item {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
horizontalArrangement = Arrangement.End,
) {
ExtendedFloatingActionButton(
onClick = { addOpen = true },
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
text = { Text(stringResource(Res.string.action_add)) },
)
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/calendar/CalendarSettingsScreen.kt
- Source · implementation · 318 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
65: internal fun CalendarSettingsRoute(title: String, initialItemType: ItemType, onBack: () -> Unit, onOpenTitle: (Manga) -> Unit) {
80: internal fun CalendarSettingsScreen(
Exact file bytes / download · SHA-256 fc63f71a09a004074f4d7a70e09d86bfb8a16a5713174fc91a568c3321480851.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.calendar
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.CollectionsBookmark
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material.icons.filled.Update
import androidx.compose.material3.Badge
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.database.DbActivityCategoryFilter
import eu.friedcutlet.yokan.ui.screens.activity.ActivityFilterDialog
import kotlinx.datetime.LocalDate
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_refresh
import yokan.composeapp.generated.resources.activity_filters
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import kotlinx.coroutines.launch
@Composable
internal fun CalendarSettingsRoute(title: String, initialItemType: ItemType, onBack: () -> Unit, onOpenTitle: (Manga) -> Unit) {
val model = viewModel { CalendarViewModel(initialItemType, YokanRuntime.repository, YokanRuntime.libraryUpdates) }
val state by model.state.collectAsStateWithLifecycle()
CalendarSettingsScreen(
title = title,
state = state,
onBack = onBack,
onSelectType = model::selectType,
onRefresh = model::refresh,
onOpenTitle = onOpenTitle,
onCategoryFilter = model::updateCategoryFilter,
)
}
@Composable
internal fun CalendarSettingsScreen(
title: String,
state: CalendarState,
onBack: () -> Unit,
onSelectType: (ItemType) -> Unit,
onRefresh: () -> Unit,
onOpenTitle: (Manga) -> Unit,
onCategoryFilter: ((DbActivityCategoryFilter) -> DbActivityCategoryFilter) -> Unit = {},
) {
val selectedType = state.itemType
val refreshing = state.refreshing
val today = state.today
val events = state.events
val scope = rememberCoroutineScope()
var viewYear by remember { mutableStateOf(today.year) }
var viewMonth by remember { mutableStateOf(today.month.ordinal + 1) }
var selectedDate by remember { mutableStateOf<LocalDate?>(null) }
var filtersOpen by remember { mutableStateOf(false) }
if (filtersOpen) ActivityFilterDialog(state.categories, state.categoryFilter, onCategoryFilter, { filtersOpen = false })
val upcoming: List<Pair<Manga, LocalDate>> = remember(events) {
events.flatMap { (date, mangas) -> mangas.map { it to date } }
.sortedBy { (_, date) -> date.toString() }
}
val groupedByDate = remember(upcoming) {
upcoming.groupBy { it.second }.toList().sortedBy { it.first.toString() }
}
val listState = rememberLazyListState()
SettingsScaffold(title, onBack, listState) {
item {
OutlinedButton(onClick = { filtersOpen = true }, modifier = Modifier.padding(horizontal = 16.dp)) {
Text(stringResource(Res.string.activity_filters))
}
}
item {
FlowRow(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
val pillShape = RoundedCornerShape(50)
ItemType.entries.forEach { type ->
FilterChip(
selected = selectedType == type,
onClick = { onSelectType(type); selectedDate = null },
label = { Text(type.label, style = MaterialTheme.typography.labelLarge) },
shape = pillShape,
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primary,
selectedLabelColor = MaterialTheme.colorScheme.onPrimary,
containerColor = MaterialTheme.colorScheme.surfaceContainerHighest,
labelColor = MaterialTheme.colorScheme.onSurfaceVariant,
),
border = null,
)
}
OutlinedButton(
onClick = onRefresh,
enabled = !refreshing,
shape = pillShape,
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp),
) {
Icon(Icons.Filled.Sync, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(Modifier.width(6.dp))
Text(
if (refreshing) "Refreshing…" else stringResource(Res.string.action_refresh),
style = MaterialTheme.typography.labelLarge,
)
}
}
}
item {
MonthCalendar(
year = viewYear,
month = viewMonth,
today = today,
selectedDate = selectedDate,
eventsByDate = events.mapValues { it.value.size },
onPrev = {
if (viewMonth == 1) { viewMonth = 12; viewYear-- } else viewMonth--
},
onNext = {
if (viewMonth == 12) { viewMonth = 1; viewYear++ } else viewMonth++
},
onSelectDate = { date ->
selectedDate = date
val groupIndex = groupedByDate.indexOfFirst { it.first == date }
if (groupIndex >= 0) {
val precedingItems = groupedByDate
.take(groupIndex)
.sumOf { (_, entries) -> 1 + entries.size }
scope.launch {
listState.animateScrollToItem(index = 3 + precedingItems)
}
}
},
)
}
if (upcoming.isEmpty()) {
item { EmptyState(icon = Icons.Filled.CalendarMonth, title = "Calendar", modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp, horizontal = 16.dp), subtitle = "No favorite ${selectedType.label.lowercase()} entries have update cadence data.") }
} else {
groupedByDate.forEach { (date, entries) ->
item(key = "date:$date", contentType = "date") {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp, top = 18.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = if (selectedDate != null) "On $date" else date.toString(),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Medium,
modifier = Modifier.weight(1f),
)
Badge(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
) {
Text("${entries.size}")
}
}
}
entries.forEach { (manga, _) ->
item(key = "calendar:${manga.id}", contentType = "entry") {
Surface(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 2.dp)
.clip(MaterialTheme.shapes.large)
.hoverHighlight(onClick = { onOpenTitle(manga) }),
color = MaterialTheme.colorScheme.surface,
) {
ListItem(
headlineContent = {
Text(
manga.name,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
},
supportingContent = {
Text(
manga.source,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
leadingContent = {
Box(
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f)),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.CollectionsBookmark,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(20.dp),
)
}
},
trailingContent = {
Icon(
Icons.AutoMirrored.Filled.KeyboardArrowRight,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
colors = ListItemDefaults.colors(
containerColor = Color.Transparent,
),
)
}
}
}
}
}
val updates = state.updates
if (updates.isNotEmpty()) {
item { SettingsSection("Recent update records") }
updates.forEach { update ->
item(key = "update:${update.id}", contentType = "update") {
Surface(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 2.dp),
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surface,
) {
ListItem(
headlineContent = {
Text(
update.title,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
},
supportingContent = {
Text(
"${update.chapterName} • ${update.date}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
leadingContent = {
Box(
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f)),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Filled.Update,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(20.dp),
)
}
},
colors = ListItemDefaults.colors(
containerColor = Color.Transparent,
),
)
}
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/calendar/CalendarViewModel.kt
- Source · implementation · 114 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
34: internal data class CalendarState(
45: internal class CalendarViewModel(
67: fun selectType(type: ItemType) {
71: fun updateCategoryFilter(transform: (DbActivityCategoryFilter) -> DbActivityCategoryFilter) {
79: fun refresh() {
91: private fun load(type: ItemType, refreshing: Boolean, snapshot: YokanDatabaseSnapshot): CalendarState {
107: internal fun calendarEvents(titles: List<Manga>, today: LocalDate): Map<LocalDate, List<Manga>> =
113: private fun currentDate(): LocalDate =
Exact file bytes / download · SHA-256 cc379e34f23d3d3ccb29af0ee05e4a8172f76213994b93129dffb4ad6e78d7c2.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.calendar
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.data.toDomainMangas
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.DbActivityCategoryFilter
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.services.library.ActivityCategoryMatcher
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.UpdateEntry
import eu.friedcutlet.yokan.services.library.LibraryUpdateController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.plus
import kotlinx.datetime.toLocalDateTime
internal data class CalendarState(
val itemType: ItemType,
val today: LocalDate,
/** Favorite titles of [itemType] by their expected next-update date. */
val events: Map<LocalDate, List<Manga>> = emptyMap(),
val updates: List<UpdateEntry> = emptyList(),
val refreshing: Boolean = false,
val categories: List<Category> = emptyList(),
val categoryFilter: DbActivityCategoryFilter = DbActivityCategoryFilter(),
)
internal class CalendarViewModel(
initialType: ItemType,
private val repository: YokanRepository,
private val libraryUpdates: LibraryUpdateController,
private val today: LocalDate = currentDate(),
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val itemType = MutableStateFlow(initialType)
private val refreshing = MutableStateFlow(false)
val state: StateFlow<CalendarState> = combine(
itemType,
repository.snapshots.distinctUntilChanged { old, new ->
old.mangas === new.mangas && old.updates === new.updates && old.categories === new.categories &&
old.settings.titleMetadata == new.settings.titleMetadata && old.settings.features.activity.upcoming == new.settings.features.activity.upcoming
},
refreshing,
) { type, snapshot, refreshing -> load(type, refreshing, snapshot) }
.flowOn(workDispatcher)
// Seeded synchronously so the first frame never flashes the empty state.
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), load(initialType, false, repository.snapshots.value))
fun selectType(type: ItemType) {
itemType.update { type }
}
fun updateCategoryFilter(transform: (DbActivityCategoryFilter) -> DbActivityCategoryFilter) {
val type = itemType.value.toDb()
repository.updateDbSettings { db -> db.copy(features = db.features.copy(activity = db.features.activity.let { prefs ->
prefs.withUpcoming(type, transform(prefs.upcoming(type)))
})) }
}
/** Runs a library update for the selected type; ignored while one is running. */
fun refresh() {
if (refreshing.value) return
refreshing.update { true }
viewModelScope.launch {
try {
libraryUpdates.run(itemType.value)
} finally {
refreshing.update { false }
}
}
}
private fun load(type: ItemType, refreshing: Boolean, snapshot: YokanDatabaseSnapshot): CalendarState {
val categories = snapshot.categories.filter { it.forItemType == type.toDb() }.map { it.toDomain() }.sortedBy { it.position }
val filter = snapshot.settings.features.activity.upcoming(type.toDb())
val matcher = ActivityCategoryMatcher(filter, categories.mapTo(mutableSetOf()) { it.id })
val titles = snapshot.mangas.filter { it.itemType == type.toDb() }.toDomainMangas(snapshot.settings)
val filtered = titles.filter { matcher.matches(it.categories) }
val byId = filtered.associateBy { it.id }
return CalendarState(itemType = type, today = today, events = calendarEvents(filtered, today),
updates = snapshot.updates.mapNotNull { update ->
val manga = byId[update.mangaId] ?: return@mapNotNull null
UpdateEntry(update.id, manga.id, update.chapterId ?: 0L, type, manga.name, update.chapterName.orEmpty(),
manga.source, update.date.orEmpty(), false, update.updatedAt)
}, refreshing = refreshing, categories = categories, categoryFilter = filter)
}
}
internal fun calendarEvents(titles: List<Manga>, today: LocalDate): Map<LocalDate, List<Manga>> =
titles.filter { it.favorite }.groupBy { manga ->
today.plus((manga.smartUpdateDays ?: 0).coerceAtLeast(0), DateTimeUnit.DAY)
}
@OptIn(kotlin.time.ExperimentalTime::class)
private fun currentDate(): LocalDate =
kotlin.time.Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/calendar/MonthCalendar.kt
- Source · implementation · 132 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
31: internal fun MonthCalendar(
Exact file bytes / download · SHA-256 59fcfa2f0e1d5b432d202e4f72834cb650bd2a556b99935ff4cc394569ad2fde.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.calendar
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlinx.datetime.LocalDate
import kotlinx.datetime.isoDayNumber
@Composable
internal fun MonthCalendar(
year: Int,
month: Int,
today: LocalDate,
selectedDate: LocalDate?,
eventsByDate: Map<LocalDate, Int>,
onPrev: () -> Unit,
onNext: () -> Unit,
onSelectDate: (LocalDate) -> Unit,
) {
val firstOfMonth = LocalDate(year, month, 1)
val daysInMonth = when (month) {
1, 3, 5, 7, 8, 10, 12 -> 31
4, 6, 9, 11 -> 30
2 -> if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) 29 else 28
else -> 30
}
// Monday = 1, Sunday = 7 in kotlinx-datetime DayOfWeek. Pad with empty cells to align Monday-start grid.
val leadingBlanks = (firstOfMonth.dayOfWeek.isoDayNumber - 1).coerceAtLeast(0)
val totalCells = leadingBlanks + daysInMonth
val rows = (totalCells + 6) / 7
val monthNames = listOf("January","February","March","April","May","June","July","August","September","October","November","December")
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
IconButton(onClick = onPrev) {
Icon(Icons.AutoMirrored.Filled.KeyboardArrowLeft, contentDescription = "Previous month")
}
Text(
"${monthNames[(month - 1).coerceIn(0, 11)]} $year",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
IconButton(onClick = onNext) {
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = "Next month")
}
}
Row(modifier = Modifier.fillMaxWidth()) {
listOf("Mon","Tue","Wed","Thu","Fri","Sat","Sun").forEach { name ->
Box(modifier = Modifier.weight(1f), contentAlignment = Alignment.Center) {
Text(name, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
repeat(rows) { row ->
Row(modifier = Modifier.fillMaxWidth()) {
repeat(7) { col ->
val cellIndex = row * 7 + col
val dayNumber = cellIndex - leadingBlanks + 1
if (dayNumber in 1..daysInMonth) {
val date = LocalDate(year, month, dayNumber)
val isToday = date == today
val isSelected = date == selectedDate
val eventCount = eventsByDate[date] ?: 0
val baseModifier = Modifier
.weight(1f)
.padding(2.dp)
.clip(RoundedCornerShape(8.dp))
val backgroundColor = when {
isSelected -> MaterialTheme.colorScheme.primary
isToday -> MaterialTheme.colorScheme.primaryContainer
else -> Color.Transparent
}
val textColor = when {
isSelected -> MaterialTheme.colorScheme.onPrimary
isToday -> MaterialTheme.colorScheme.onPrimaryContainer
else -> MaterialTheme.colorScheme.onSurface
}
// Trailing padding is inner content padding, kept inside the tinted, clickable cell.
Box(
modifier = baseModifier
.background(backgroundColor)
.clickable { onSelectDate(date) }
.padding(vertical = 8.dp),
contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(1.dp)) {
Text(dayNumber.toString(), color = textColor, style = MaterialTheme.typography.bodyMedium, fontWeight = if (isToday || isSelected) FontWeight.SemiBold else FontWeight.Normal)
if (eventCount > 0) {
Box(
modifier = Modifier
.size(6.dp)
.clip(RoundedCornerShape(50))
.background(if (isSelected) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.primary),
)
}
}
}
} else {
Box(modifier = Modifier.weight(1f).padding(2.dp))
}
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/developer/DeveloperSettingsScreen.kt
- Source · implementation · 203 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
48: internal fun DeveloperSettingsRoute(
60: internal fun DeveloperSettingsScreen(
132: private fun StatRow(label: String, value: String) {
149: private fun MemoryGraph(samples: List<ProcessMemoryUsage>) {
186: private fun LogLine(entry: LogEntry) {
198: private fun percent(part: Long, total: Long): String = if (total == 0L) "–" else "${part * 100 / total}%"
200: private fun formatDuration(millis: Long): String {
Exact file bytes / download · SHA-256 7489ca1187a2a18422859e7d4e57497dd70fead5bd578f98aff3b3a720be51b5.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.developer
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.FilterChip
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.logging.LogEntry
import eu.friedcutlet.yokan.services.logging.LogSink
import eu.friedcutlet.yokan.services.logging.formatLogTimestamp
import eu.friedcutlet.yokan.services.system.ProcessMemoryUsage
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.data.formatBytes
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.ui_clear
@Composable
internal fun DeveloperSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val model = viewModel { DeveloperSettingsViewModel() }
val state by model.state.collectAsStateWithLifecycle()
DeveloperSettingsScreen(title, settings, state, onUpdate, onClearLogs = model::clearLogs, onBack = onBack)
}
@Composable
internal fun DeveloperSettingsScreen(
title: String,
settings: DbSettings,
state: DeveloperDiagnosticsState,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onClearLogs: () -> Unit,
onBack: () -> Unit,
) {
var problemsOnly by rememberSaveable { mutableStateOf(false) }
SettingsScaffold(title, onBack) {
item {
SwitchTile(
"Developer mode",
"Allow recipe catalogs served from http://127.0.0.1 for local testing",
settings.developerMode,
{ value -> onUpdate { it.copy(developerMode = value) } },
)
}
item { StatRow("Uptime", formatDuration(state.uptimeMillis)) }
item { SettingsSection("Memory") }
if (state.memorySupported) {
item(key = "memory-graph") { MemoryGraph(state.memory) }
} else {
item { InfoRow("This platform does not report heap usage.") }
}
item { SettingsSection("Network") }
item { StatRow("Requests", state.network.requests.toString()) }
item { StatRow("Transport failures", state.network.failures.toString()) }
item { StatRow("HTTP errors (4xx/5xx)", state.network.httpErrors.toString()) }
item { StatRow("Received", formatBytes(state.network.bytesReceived)) }
item { SettingsSection("Image cache") }
val images = state.images
item { StatRow("Memory-cache hits", "${images.memoryHits} (${percent(images.memoryHits, images.loads)})") }
item { StatRow("Disk-cache hits", "${images.diskHits} (${percent(images.diskHits, images.loads)})") }
item { StatRow("Network loads", "${images.networkLoads} (${percent(images.networkLoads, images.loads)})") }
item { StatRow("Failed loads", images.errors.toString()) }
state.imageCache?.let { cache ->
item { StatRow("Memory cache", "${formatBytes(cache.memoryBytes)} of ${formatBytes(cache.memoryMaxBytes)}") }
cache.diskBytes?.let { disk -> item { StatRow("Disk cache", "${formatBytes(disk)} of ${formatBytes(cache.diskMaxBytes ?: 0)}") } }
}
item { SettingsSection("Logs") }
item {
StatRow(
"Log file",
if (settings.enableFileLogging) {
"${formatBytes(state.logFileBytes)} (max ${formatBytes(LogSink.MaxLogFileBytes * 2)}) · ${state.logFilePath.orEmpty()}"
} else {
"Off (enable \"Logs on\" in About)"
},
)
}
item {
FlowRow(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
FilterChip(selected = !problemsOnly, onClick = { problemsOnly = false }, label = { Text("All (${state.logs.size})") })
FilterChip(selected = problemsOnly, onClick = { problemsOnly = true }, label = { Text("Errors & warnings (${state.problems.size})") })
TextButton(onClick = onClearLogs) { Text(stringResource(Res.string.ui_clear)) }
}
}
val entries = if (problemsOnly) state.problems else state.logs
if (entries.isEmpty()) item { InfoRow("No log lines yet.") }
items(entries, key = { it.seq }) { entry -> LogLine(entry) }
}
}
@Composable
private fun StatRow(label: String, value: String) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(label, style = MaterialTheme.typography.bodyMedium)
Text(
value,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.End,
modifier = Modifier.weight(1f),
)
}
}
@Composable
private fun MemoryGraph(samples: List<ProcessMemoryUsage>) {
val latest = samples.lastOrNull()
val lineColor = MaterialTheme.colorScheme.primary
val gridColor = MaterialTheme.colorScheme.outlineVariant
val summary = latest?.let { "${formatBytes(it.usedBytes)} used of ${formatBytes(it.maxBytes)} max" } ?: "Sampling…"
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {
Text(summary, style = MaterialTheme.typography.bodyMedium)
Canvas(
Modifier
.fillMaxWidth()
.height(120.dp)
.padding(top = 8.dp)
.semantics { contentDescription = "Heap usage over the last two minutes. $summary" },
) {
drawLine(gridColor, Offset(0f, size.height), Offset(size.width, size.height))
drawLine(gridColor, Offset(0f, 0f), Offset(size.width, 0f))
val max = samples.maxOfOrNull { it.maxBytes }?.takeIf { it > 0 } ?: return@Canvas
if (samples.size < 2) return@Canvas
val step = size.width / (DeveloperSettingsViewModel.MemorySamples - 1)
val startX = size.width - step * (samples.size - 1)
val path = Path()
samples.forEachIndexed { index, sample ->
val x = startX + step * index
val y = size.height * (1f - sample.usedBytes.toFloat() / max)
if (index == 0) path.moveTo(x, y) else path.lineTo(x, y)
}
drawPath(path, lineColor, style = Stroke(width = 2.dp.toPx()))
}
Text(
"Scale: 0 – ${formatBytes(samples.maxOfOrNull { it.maxBytes } ?: 0)} · last two minutes",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun LogLine(entry: LogEntry) {
val color = when (entry.level) {
"ERROR" -> MaterialTheme.colorScheme.error
"WARN" -> MaterialTheme.colorScheme.tertiary
else -> MaterialTheme.colorScheme.onSurfaceVariant
}
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp)) {
Text("${formatLogTimestamp(entry.timeMillis)} ${entry.level}", style = MaterialTheme.typography.labelSmall, color = color)
Text(entry.message, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace)
}
}
private fun percent(part: Long, total: Long): String = if (total == 0L) "–" else "${part * 100 / total}%"
private fun formatDuration(millis: Long): String {
val seconds = millis / 1_000
return "${seconds / 3_600}h ${(seconds % 3_600) / 60}m ${seconds % 60}s"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/developer/DeveloperSettingsViewModel.kt
- Source · implementation · 80 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
27: internal data class DeveloperDiagnosticsState(
44: internal class DeveloperSettingsViewModel(
57: fun clearLogs() = LogSink.clearMemory()
59: private fun sample(previous: DeveloperDiagnosticsState): DeveloperDiagnosticsState {
Exact file bytes / download · SHA-256 2bc03fa667b1af46beb2f0f8685ecca0cecbd9f909eddd63de9f20d5bcaa9599.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.developer
import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.services.logging.Diagnostics
import eu.friedcutlet.yokan.services.logging.ImageStats
import eu.friedcutlet.yokan.services.logging.LogEntry
import eu.friedcutlet.yokan.services.logging.LogSink
import eu.friedcutlet.yokan.services.logging.NetworkStats
import eu.friedcutlet.yokan.services.system.ProcessMemoryUsage
import eu.friedcutlet.yokan.services.system.processMemoryUsage
import eu.friedcutlet.yokan.ui.image.ImageCacheUsage
import eu.friedcutlet.yokan.ui.image.imageCacheUsage
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.scan
import kotlinx.coroutines.flow.stateIn
@Immutable
internal data class DeveloperDiagnosticsState(
/** Oldest first; empty where the platform reports no heap numbers. */
val memory: List<ProcessMemoryUsage> = emptyList(),
val memorySupported: Boolean = true,
val network: NetworkStats = NetworkStats(),
val images: ImageStats = ImageStats(),
val imageCache: ImageCacheUsage? = null,
/** Newest first. */
val logs: List<LogEntry> = emptyList(),
/** Warnings and errors, newest first. */
val problems: List<LogEntry> = emptyList(),
val logFilePath: String? = null,
val logFileBytes: Long = 0,
val uptimeMillis: Long = 0,
)
/** Samples process diagnostics once a second, only while the Developer screen is collecting. */
internal class DeveloperSettingsViewModel(
workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
val state: StateFlow<DeveloperDiagnosticsState> = flow {
while (true) {
emit(Unit)
delay(SampleIntervalMillis)
}
}
.scan(DeveloperDiagnosticsState()) { previous, _ -> sample(previous) }
.flowOn(workDispatcher)
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DeveloperDiagnosticsState())
fun clearLogs() = LogSink.clearMemory()
private fun sample(previous: DeveloperDiagnosticsState): DeveloperDiagnosticsState {
val memory = processMemoryUsage()
return DeveloperDiagnosticsState(
memory = if (memory == null) emptyList() else (previous.memory + memory).takeLast(MemorySamples),
memorySupported = memory != null,
network = Diagnostics.network.value,
images = Diagnostics.images.value,
imageCache = imageCacheUsage(),
logs = LogSink.recentEntries().asReversed(),
problems = LogSink.problemEntries().asReversed(),
logFilePath = LogSink.logFilePath(),
logFileBytes = LogSink.logFileBytes(),
uptimeMillis = nowMillis() - Diagnostics.startedAtMillis,
)
}
companion object {
const val SampleIntervalMillis = 1_000L
/** Two minutes of history at one sample per second. */
const val MemorySamples = 120
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/discord/DiscordLogin.kt
- Source · implementation · 26 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: internal expect fun DiscordLoginWebView(modifier: Modifier, onToken: (String) -> Unit)
22: internal fun cleanDiscordTokenResult(raw: String?): String? {
Exact file bytes / download · SHA-256 e65f94c4d9ae10c686ae448287ce9752b32964bc0a7aed338f85224a93649510.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.discord
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
/** True where an embedded browser can host Discord's own login page (Android, iOS). */
internal expect val discordWebLoginAvailable: Boolean
/** Discord's login page; reports the session token once the user has signed in. */
@Composable
internal expect fun DiscordLoginWebView(modifier: Modifier, onToken: (String) -> Unit)
/**
* Reads the signed-in token. Discord deletes `window.localStorage` from its own window, so the
* script reads it through a fresh same-origin iframe.
*/
internal const val DiscordTokenScript =
"(function(){try{var f=document.createElement('iframe');f.style.display='none';document.body.appendChild(f);" +
"var t=f.contentWindow.localStorage.getItem('token');f.remove();return t||'';}catch(e){return '';}})()"
/** WebViews hand script results back JSON-encoded, and Discord stores the token JSON-quoted. */
internal fun cleanDiscordTokenResult(raw: String?): String? {
var value = raw?.trim() ?: return null
repeat(3) { value = value.replace("\\\"", "\"").removeSurrounding("\"") }
return value.takeIf { it.isNotBlank() && it != "null" && it.count { c -> c == '.' } == 2 }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/discord/DiscordSettingsScreen.kt
- Source · implementation · 251 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
59: internal fun DiscordSettingsRoute(
82: internal fun DiscordSettingsScreen(
96: fun update(transform: (DbDiscordPreferences) -> DbDiscordPreferences) {
Exact file bytes / download · SHA-256 521ada7a58245b19f74a5cf673fe33b86dee8ed9a9aef3c86d9453ef17a46361.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.discord
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbDiscordButton
import eu.friedcutlet.yokan.database.DbDiscordPreferences
import eu.friedcutlet.yokan.database.DbDiscordStatus
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.UncategorizedActivityCategoryId
import eu.friedcutlet.yokan.ui.components.YokanTopBar
import eu.friedcutlet.yokan.ui.screens.settings.ChoiceTile
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.TextInputDialog
import eu.friedcutlet.yokan.ui.screens.settings.YokanMenuTile
import eu.friedcutlet.yokan.ui.screens.settings.downloads.PolicyCategoryTile
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.ok
import yokan.composeapp.generated.resources.tile_discord_rpc
import yokan.composeapp.generated.resources.tile_hide_rpc_in_incognito
import yokan.composeapp.generated.resources.tile_show_rpc_cover
import yokan.composeapp.generated.resources.tile_show_rpc_progress
import yokan.composeapp.generated.resources.tile_show_rpc_title
import yokan.composeapp.generated.resources.ui_close
private val UncategorizedEntry = DbCategory(id = UncategorizedActivityCategoryId, name = "Uncategorized", forItemType = DbItemType.Manga)
@Composable
internal fun DiscordSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val model = viewModel {
val owner = YokanRuntime.activeSession
DiscordSettingsViewModel(owner.settings, YokanRuntime.discordRpc, owner.database.categories())
}
val state by model.state.collectAsStateWithLifecycle()
DiscordSettingsScreen(
title, settings, state, onUpdate,
onToggleRpc = model::toggleRpc,
onAddAccount = model::addAccount,
onSwitchAccount = model::switchAccount,
onRemoveAccount = model::removeAccount,
onDismissError = model::dismissError,
onBack = onBack,
)
}
@Composable
internal fun DiscordSettingsScreen(
title: String,
settings: DbSettings,
state: DiscordSettingsState,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onToggleRpc: (Boolean) -> Unit,
onAddAccount: (String) -> Unit,
onSwitchAccount: (String) -> Unit,
onRemoveAccount: (String) -> Unit,
onDismissError: () -> Unit,
onBack: () -> Unit,
) {
val prefs = settings.features.discord
val enabled = settings.enableDiscordRpc
fun update(transform: (DbDiscordPreferences) -> DbDiscordPreferences) {
onUpdate { it.copy(features = it.features.copy(discord = transform(it.features.discord))) }
}
var addDialog by remember { mutableStateOf(false) }
var tokenDialog by remember { mutableStateOf(false) }
var webLogin by remember { mutableStateOf(false) }
var messageDialog by remember { mutableStateOf(false) }
var editButton by remember { mutableStateOf<Int?>(null) }
if (addDialog) {
AlertDialog(
onDismissRequest = { addDialog = false },
title = { Text("Add Discord account") },
text = { Text("Presence is published with your own Discord login. Discord does not officially allow automating user accounts; use at your own risk.") },
confirmButton = {
TextButton(onClick = {
addDialog = false
if (discordWebLoginAvailable) webLogin = true else tokenDialog = true
}) { Text(if (discordWebLoginAvailable) "Log in" else "Enter token") }
},
dismissButton = {
if (discordWebLoginAvailable) TextButton(onClick = { addDialog = false; tokenDialog = true }) { Text("Enter token") }
else TextButton(onClick = { addDialog = false }) { Text(stringResource(Res.string.action_cancel)) }
},
)
}
if (tokenDialog) {
TextInputDialog(
title = "Discord token",
initialValue = "",
placeholder = "Token",
helperText = "Your own account token from the Discord web client's local storage.",
onConfirm = { token -> if (token.isNotBlank()) onAddAccount(token) },
onDismiss = { tokenDialog = false },
)
}
if (webLogin) {
Dialog(onDismissRequest = { webLogin = false }, properties = DialogProperties(usePlatformDefaultWidth = false)) {
Scaffold(topBar = {
YokanTopBar(title = "Log in to Discord", actions = {
IconButton(onClick = { webLogin = false }) { Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.ui_close)) }
})
}) { padding ->
Box(Modifier.fillMaxSize().padding(padding)) {
DiscordLoginWebView(Modifier.fillMaxSize()) { token ->
webLogin = false
onAddAccount(token)
}
}
}
}
}
if (messageDialog) {
TextInputDialog(
title = "Custom message",
initialValue = prefs.customMessage,
placeholder = "Replaces \"Reading/Watching <title>\"",
onConfirm = { value -> update { it.copy(customMessage = value.trim()) } },
onDismiss = { messageDialog = false },
)
}
editButton?.let { index ->
val existing = prefs.buttons.getOrNull(index)
TextInputDialog(
title = "Button ${index + 1}",
initialValue = existing?.let { "${it.label} | ${it.url}" }.orEmpty(),
placeholder = "Label | https://example.com",
helperText = "Leave empty to remove the button.",
onConfirm = { raw ->
val label = raw.substringBefore('|').trim()
val url = raw.substringAfter('|', "").trim()
update { current ->
val buttons = current.buttons.toMutableList()
val next = DbDiscordButton(label, url).takeIf { label.isNotEmpty() && url.startsWith("http") }
when {
next == null -> if (index < buttons.size) buttons.removeAt(index)
index < buttons.size -> buttons[index] = next
else -> buttons += next
}
current.copy(buttons = buttons)
}
},
onDismiss = { editButton = null },
)
}
state.error?.let { error ->
AlertDialog(
onDismissRequest = onDismissError,
title = { Text("Discord") },
text = { Text(error) },
confirmButton = { TextButton(onClick = onDismissError) { Text(stringResource(Res.string.ok)) } },
)
}
SettingsScaffold(title, onBack) {
item(key = "discord") {
SwitchTile(stringResource(Res.string.tile_discord_rpc), state.rpcStatus, enabled, onToggleRpc)
}
item(key = "accounts-section") { SettingsSection("Accounts") }
item(key = "accounts-info") { InfoRow("Android, iOS and web publish presence through the active account. Desktop uses the running Discord app unless an account is active here.") }
prefs.accounts.forEach { account ->
item(key = "account-${account.id}") {
YokanMenuTile(
title = account.displayName,
subtitle = if (account.displayName != account.username) "@${account.username}" else null,
onClick = { onSwitchAccount(account.id) },
trailing = {
Row {
RadioButton(selected = account.id == prefs.activeAccountId, onClick = { onSwitchAccount(account.id) })
IconButton(onClick = { onRemoveAccount(account.id) }) { Icon(Icons.Filled.Delete, contentDescription = "Remove ${account.displayName}") }
}
},
)
}
}
item(key = "discord-account-add") { SettingTile(if (state.busy) "Checking account…" else "Add account", null, enabled = !state.busy) { addDialog = true } }
item(key = "display-section") { SettingsSection("Display") }
item(key = "discord-status") {
ChoiceTile("Online status", DbDiscordStatus.entries, prefs.status, { it.label }, enabled = enabled) { value -> update { it.copy(status = value) } }
}
item(key = "discord-message") { SettingTile("Custom message", prefs.customMessage.ifBlank { "Not set" }, enabled = enabled) { messageDialog = true } }
item(key = "discord-progress") { SwitchTile(stringResource(Res.string.tile_show_rpc_progress), null, settings.rpcShowReadingWatchingProgress, { value -> onUpdate { it.copy(rpcShowReadingWatchingProgress = value) } }, enabled = enabled) }
item(key = "discord-title") { SwitchTile(stringResource(Res.string.tile_show_rpc_title), null, settings.rpcShowTitle, { value -> onUpdate { it.copy(rpcShowTitle = value) } }, enabled = enabled) }
item(key = "discord-cover") { SwitchTile(stringResource(Res.string.tile_show_rpc_cover), null, settings.rpcShowCoverImage, { value -> onUpdate { it.copy(rpcShowCoverImage = value) } }, enabled = enabled) }
item(key = "discord-timestamp") { SwitchTile("Show elapsed time", null, prefs.showTimestamp, { value -> update { it.copy(showTimestamp = value) } }, enabled = enabled) }
item(key = "discord-buttons") { SwitchTile("Show buttons", null, prefs.showButtons, { value -> update { it.copy(showButtons = value) } }, enabled = enabled) }
if (prefs.showButtons) {
(0 until 2).forEach { index ->
item(key = "discord-button-$index") {
SettingTile("Button ${index + 1}", prefs.buttons.getOrNull(index)?.let { "${it.label} · ${it.url}" } ?: "Not set", enabled = enabled) { editButton = index }
}
}
}
item(key = "privacy-section") { SettingsSection("Privacy") }
item(key = "discord-private") { SwitchTile(stringResource(Res.string.tile_hide_rpc_in_incognito), null, settings.hideDiscordRpcInIncognito, { value -> onUpdate { it.copy(hideDiscordRpcInIncognito = value) } }, enabled = enabled) }
item(key = "discord-always-private") { SwitchTile("Never show titles", "Show only that Yokan is open", prefs.alwaysPrivate, { value -> update { it.copy(alwaysPrivate = value) } }, enabled = enabled) }
item(key = "discord-categories") {
PolicyCategoryTile(
title = "Private categories",
categories = listOf(UncategorizedEntry) + state.categories,
selected = prefs.privateCategoryIds,
allWhenEmpty = false,
label = { if (it.id == UncategorizedActivityCategoryId) it.name else "${it.forItemType.name}: ${it.name}" },
) { ids -> update { it.copy(privateCategoryIds = ids) } }
}
}
}
private val DbDiscordStatus.label: String
get() = when (this) {
DbDiscordStatus.Online -> "Online"
DbDiscordStatus.Idle -> "Idle"
DbDiscordStatus.DoNotDisturb -> "Do not disturb"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/discord/DiscordSettingsViewModel.kt
- Source · implementation · 63 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
18: internal data class DiscordSettingsState(
27: internal class DiscordSettingsViewModel(
35: fun toggleRpc(enabled: Boolean) {
41: fun addAccount(token: String) {
52: fun switchAccount(id: String) = updateDiscord { it.withActive(id) }
54: fun removeAccount(id: String) = updateDiscord { it.withoutAccount(id) }
56: fun dismissError() = _state.update { it.copy(error = null) }
58: private fun updateDiscord(transform: (DbDiscordPreferences) -> DbDiscordPreferences) {
Exact file bytes / download · SHA-256 bc61cd356f267bed941253934c8cd6cfbd72a73befd657f692c3bb98c4542dbc.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.discord
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbDiscordPreferences
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.discord.DiscordRpcService
import eu.friedcutlet.yokan.services.discord.resolveDiscordAccount
import eu.friedcutlet.yokan.services.http.createDefaultPlatformHttpClientEngine
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
internal data class DiscordSettingsState(
val categories: List<DbCategory> = emptyList(),
val busy: Boolean = false,
val error: String? = null,
/** The presence service's status line, refreshed after every change made here. */
val rpcStatus: String = "",
)
/** Discord account login/switching and the presence toggle; every change re-publishes presence. */
internal class DiscordSettingsViewModel(
private val settings: SettingsStore,
private val rpc: DiscordRpcService,
categories: List<DbCategory>,
) : ViewModel() {
private val _state = MutableStateFlow(DiscordSettingsState(categories = categories, rpcStatus = rpc.status().message))
val state: StateFlow<DiscordSettingsState> = _state.asStateFlow()
fun toggleRpc(enabled: Boolean) {
settings.updateDb { it.copy(enableDiscordRpc = enabled) }
val status = if (enabled) rpc.initialize(settings.db.value) else rpc.shutdown().let { rpc.status() }
_state.update { it.copy(rpcStatus = status.message) }
}
fun addAccount(token: String) {
if (_state.value.busy) return
_state.update { it.copy(busy = true, error = null) }
viewModelScope.launch {
catchingNonCancellation { resolveDiscordAccount(token, createDefaultPlatformHttpClientEngine()) }
.onSuccess { account -> updateDiscord { it.withAccount(account) } }
.onFailure { error -> _state.update { it.copy(error = error.message ?: "Discord login failed") } }
_state.update { it.copy(busy = false) }
}
}
fun switchAccount(id: String) = updateDiscord { it.withActive(id) }
fun removeAccount(id: String) = updateDiscord { it.withoutAccount(id) }
fun dismissError() = _state.update { it.copy(error = null) }
private fun updateDiscord(transform: (DbDiscordPreferences) -> DbDiscordPreferences) {
settings.updateDb { it.copy(features = it.features.copy(discord = transform(it.features.discord))) }
val status = rpc.initialize(settings.db.value)
_state.update { it.copy(rpcStatus = status.message) }
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/downloads/DownloadPolicySettings.kt
- Source · implementation · 117 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
19: internal fun LazyListScope.downloadPolicyItems(
27: fun update(transform: (DbDownloadPolicy) -> DbDownloadPolicy) = onUpdate { current ->
62: private fun PolicyCountTile(title: String, count: Int, maximum: Int = 100, onChange: (Int) -> Unit) {
68: internal fun PolicyCategoryTile(
101: internal fun DownloadCleanupDialog(state: DownloadPolicyUiState, onDismiss: () -> Unit, onConfirm: () -> Unit) {
Exact file bytes / download · SHA-256 39461abb475fcf45ab2c9349b7d2afb9cb68a7f98f5002c5012c9c6459271e0e.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.downloads
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.ui.screens.settings.*
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
internal fun LazyListScope.downloadPolicyItems(
settings: DbSettings,
state: DownloadPolicyUiState,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onPreview: () -> Unit,
) {
val policy = settings.features.downloads
imageDataSaverItems(settings.features.imageDataSaver, state.sources, onUpdate)
fun update(transform: (DbDownloadPolicy) -> DbDownloadPolicy) = onUpdate { current ->
current.copy(features = current.features.copy(downloads = transform(current.features.downloads)))
}
item("policy-images") { SettingsSection(stringResource(Res.string.download_image_processing)) }
item("policy-split") { SwitchTile(stringResource(Res.string.download_split_images), stringResource(Res.string.download_split_images_hint), policy.splitTallImages, { value -> update { it.copy(splitTallImages = value) } }) }
if (policy.splitTallImages) item("policy-split-height") {
val heights = listOf(1024, 2048, 3072, 4096, 6144, 8192)
val labels = heights.associateWith { stringResource(Res.string.download_image_pixels, it) }
ChoiceTile(stringResource(Res.string.download_split_height), heights, policy.splitImageHeight.coerceIn(1024, 8192), { labels[it].orEmpty() }) { value -> update { it.copy(splitImageHeight = value) } }
}
item("policy-automatic") { SettingsSection(stringResource(Res.string.download_policy_automation)) }
item("policy-new") { SwitchTile(stringResource(Res.string.download_policy_new), stringResource(Res.string.download_policy_new_hint), policy.autoDownloadNew, { value -> update { it.copy(autoDownloadNew = value) } }) }
item("policy-unread") { SwitchTile(stringResource(Res.string.download_policy_unread), null, policy.unreadOnly, { value -> update { it.copy(unreadOnly = value) } }) }
item("policy-filler") { SwitchTile(stringResource(Res.string.download_policy_filler), null, policy.includeFiller, { value -> update { it.copy(includeFiller = value) } }) }
item("policy-include") { PolicyCategoryTile(stringResource(Res.string.download_policy_include), state.categories, policy.includeCategoryIds, true) { ids -> update { it.copy(includeCategoryIds = ids) } } }
item("policy-exclude") { PolicyCategoryTile(stringResource(Res.string.download_policy_exclude), state.categories, policy.excludeCategoryIds, false) { ids -> update { it.copy(excludeCategoryIds = ids) } } }
item("policy-ahead") { SettingsSection(stringResource(Res.string.download_policy_ahead)) }
item("policy-ahead-hint") { InfoRow(stringResource(Res.string.download_policy_ahead_hint)) }
item("policy-ahead-manga") { PolicyCountTile(stringResource(Res.string.download_policy_ahead_manga), policy.ahead(DbItemType.Manga)) { value -> update { it.copy(aheadManga = value) } } }
item("policy-ahead-anime") { PolicyCountTile(stringResource(Res.string.download_policy_ahead_anime), policy.ahead(DbItemType.Anime)) { value -> update { it.copy(aheadAnime = value) } } }
item("policy-ahead-novel") { PolicyCountTile(stringResource(Res.string.download_policy_ahead_novel), policy.ahead(DbItemType.Novel)) { value -> update { it.copy(aheadNovel = value) } } }
item("policy-cleanup") { SettingsSection(stringResource(Res.string.download_policy_cleanup)) }
item("policy-consumed") { SwitchTile(stringResource(Res.string.download_policy_consumed), stringResource(Res.string.download_policy_consumed_hint), policy.cleanupAfterConsumption || settings.deleteDownloadAfterReading, { value ->
onUpdate { current -> current.copy(deleteDownloadAfterReading = value, features = current.features.copy(downloads = current.features.downloads.copy(cleanupAfterConsumption = value))) }
}) }
item("policy-manual") { SwitchTile(stringResource(Res.string.download_policy_manual), null, policy.cleanupAfterManualMark, { value -> update { it.copy(cleanupAfterManualMark = value) } }) }
item("policy-keep") { PolicyCountTile(stringResource(Res.string.download_policy_keep), policy.keepLastConsumed.coerceIn(0, 1000), 1000) { value -> update { it.copy(keepLastConsumed = value) } } }
item("policy-bookmarks") { SwitchTile(stringResource(Res.string.download_policy_bookmarks), null, policy.protectBookmarks, { value -> update { it.copy(protectBookmarks = value) } }) }
item("policy-cleanup-exclude") { PolicyCategoryTile(stringResource(Res.string.download_policy_cleanup_exclude), state.categories, policy.cleanupExcludedCategoryIds, false) { ids -> update { it.copy(cleanupExcludedCategoryIds = ids) } } }
item("policy-preview") { YokanMenuTile(title = stringResource(Res.string.download_policy_preview), subtitle = stringResource(if (state.busy) Res.string.download_policy_busy else Res.string.download_policy_preview_hint), onClick = { if (!state.busy) onPreview() }) }
if (state.failed) item("policy-error") { InfoRow(stringResource(Res.string.download_policy_failed)) }
state.deletedCount?.let { count -> item("policy-result") { InfoRow(stringResource(Res.string.download_policy_deleted, count)) } }
}
@Composable
private fun PolicyCountTile(title: String, count: Int, maximum: Int = 100, onChange: (Int) -> Unit) {
val off = stringResource(Res.string.download_policy_off)
ChoiceTile(title, (listOf(0, 1, 2, 3, 5, 10, 20, 50, 100, maximum, count)).distinct().sorted(), count, { if (it == 0) off else it.toString() }, onSelect = onChange)
}
@Composable
internal fun PolicyCategoryTile(
title: String,
categories: List<DbCategory>,
selected: Set<Long>,
allWhenEmpty: Boolean,
label: (DbCategory) -> String = { "${it.forItemType.name}: ${it.name}" },
onChange: (Set<Long>) -> Unit,
) {
var open by remember { mutableStateOf(false) }
val empty = stringResource(if (allWhenEmpty) Res.string.download_policy_all_categories else Res.string.download_policy_no_categories)
YokanMenuTile(title = title, subtitle = if (selected.isEmpty()) empty else categories.filter { it.id in selected }.joinToString(transform = label).ifEmpty { empty }, onClick = { open = true })
if (open) AlertDialog(
onDismissRequest = { open = false },
title = { Text(title) },
text = {
if (categories.isEmpty()) Text(stringResource(Res.string.download_policy_no_categories_hint))
else LazyColumn(Modifier.fillMaxWidth().heightIn(max = 360.dp)) {
items(categories, key = { it.id }) { category ->
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).toggleable(category.id in selected, role = Role.Checkbox) {
onChange(if (it) selected + category.id else selected - category.id)
}.padding(horizontal = 8.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Checkbox(category.id in selected, onCheckedChange = null)
Spacer(Modifier.width(12.dp))
Text(label(category), style = MaterialTheme.typography.bodyLarge)
}
}
}
},
confirmButton = { TextButton(onClick = { open = false }) { Text(stringResource(Res.string.download_policy_done)) } },
)
}
@Composable
internal fun DownloadCleanupDialog(state: DownloadPolicyUiState, onDismiss: () -> Unit, onConfirm: () -> Unit) {
val preview = state.preview ?: return
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(Res.string.download_policy_preview_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(if (preview.isEmpty()) Res.string.download_policy_preview_empty else Res.string.download_policy_preview_count, preview.size))
if (preview.isNotEmpty()) LazyColumn(Modifier.fillMaxWidth().heightIn(max = 300.dp)) {
items(preview, key = { it.chapterId }) { item -> ListItem(headlineContent = { Text(item.title) }, supportingContent = { Text(item.chapter) }) }
}
}
},
confirmButton = { TextButton(onClick = if (preview.isEmpty()) onDismiss else onConfirm) { Text(stringResource(if (preview.isEmpty()) Res.string.download_policy_done else Res.string.download_policy_delete)) } },
dismissButton = { if (preview.isNotEmpty()) TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/downloads/DownloadsSettingsScreen.kt
- Source · implementation · 378 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
58: internal fun DownloadsSettingsRoute(
88: private fun DownloadsSettingsScreen(
337: private fun FolderTile(
366: private fun normalizedNetworkSpeedLimit(value: Int): Int =
373: private fun networkSpeedLimitLabel(value: Int): String = when {
Exact file bytes / download · SHA-256 464549f3227f5e6d2b29756d15e318fad12d16d5177ff1133641f0c81b9ebe48.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.downloads
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.DeleteSweep
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.configuredLocalFolders
import eu.friedcutlet.yokan.database.nameFromPath
import eu.friedcutlet.yokan.database.normalizeLocalFolders
import eu.friedcutlet.yokan.database.resolveDownloadFolderName
import eu.friedcutlet.yokan.services.files.pickFolder
import eu.friedcutlet.yokan.services.library.LocalLibraryScanResult
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.screens.settings.ChoiceTile
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.YokanMenuTile
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.add_local_folder
import yokan.composeapp.generated.resources.allow_concurrent_downloads
import yokan.composeapp.generated.resources.allow_concurrent_downloads_subtitle
import yokan.composeapp.generated.resources.concurrent_downloads
import yokan.composeapp.generated.resources.delete_download_after_reading
import yokan.composeapp.generated.resources.download_delay
import yokan.composeapp.generated.resources.save_as_cbz_archive
import yokan.composeapp.generated.resources.tile_only_on_wi_fi
import eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider as HorizontalDivider
@Composable
internal fun DownloadsSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val vm = viewModel { DownloadsSettingsViewModel(YokanRuntime.localLibrary, YokanRuntime.localFiles.downloadRoot, YokanRuntime.repository, YokanRuntime.services.downloadAutomation) }
val scan by vm.scan.collectAsStateWithLifecycle()
val policy by vm.policy.collectAsStateWithLifecycle()
val externalVm = viewModel { ExternalDownloadsViewModel(YokanRuntime.services.externalDownloads) }
val external by externalVm.state.collectAsStateWithLifecycle()
DownloadCleanupDialog(policy, vm::dismissPreview, vm::confirmCleanup)
DownloadsSettingsScreen(
title = title,
settings = settings,
defaultDownloadRoot = vm.defaultDownloadRoot,
lastScan = scan.lastScan,
onUpdate = onUpdate,
onBack = onBack,
onRescanLocalLibrary = vm::rescan,
policy = policy,
onPreviewCleanup = vm::previewCleanup,
external = external,
onExternalTest = externalVm::testConnection,
onExternalUpdate = { change -> externalVm.clearConnection(); onUpdate(change) },
onExternalAction = externalVm::act,
)
}
@Composable
private fun DownloadsSettingsScreen(
title: String,
settings: DbSettings,
defaultDownloadRoot: String,
lastScan: LocalLibraryScanResult?,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
onRescanLocalLibrary: () -> Unit,
policy: DownloadPolicyUiState,
onPreviewCleanup: () -> Unit,
external: RemoteDownloadsUiState,
onExternalTest: () -> Unit,
onExternalUpdate: ((DbSettings) -> DbSettings) -> Unit,
onExternalAction: (String, RemoteDownloadAction) -> Unit,
) {
val scope = rememberCoroutineScope()
var structureHelpOpen by remember { mutableStateOf(false) }
var folderEditState by remember { mutableStateOf<LocalFolderEditState?>(null) }
var downloadPickerOpen by remember { mutableStateOf(false) }
val configuredFolders = settings.configuredLocalFolders()
folderEditState?.let { state ->
LocalFolderNameDialog(
initialName = state.initialName,
path = state.path,
existingNames = configuredFolders.map { it.name }.toSet() - setOfNotNull(state.editing?.name),
onDismiss = { folderEditState = null },
onConfirm = { name ->
onUpdate { current ->
val existing = current.configuredLocalFolders().toMutableList()
if (state.editing != null) {
val index = existing.indexOfFirst { it.name == state.editing.name && it.path == state.editing.path }
if (index >= 0) existing[index] = DbLocalFolder(name = name, path = state.editing.path)
} else {
existing += DbLocalFolder(name = name, path = state.path)
}
val normalized = normalizeLocalFolders(existing)
current.copy(
namedLocalFolders = normalized,
localFolders = normalized.map { it.path },
downloadLocalFolderName = resolveDownloadFolderName(current.downloadLocalFolderName, normalized),
)
}
folderEditState = null
},
)
}
if (downloadPickerOpen) {
val folders = configuredFolders.ifEmpty { emptyList() }
ChoiceDialog(
title = "Download destination",
options = listOf<String?>(null) + folders.map { it.name },
selected = settings.downloadLocalFolderName,
label = { name -> name ?: "Default (app folder)" },
onSelect = { value -> onUpdate { it.copy(downloadLocalFolderName = value) } },
onDismiss = { downloadPickerOpen = false },
)
}
if (structureHelpOpen) {
LocalFolderStructureDialog(onDismiss = { structureHelpOpen = false })
}
SettingsScaffold(title, onBack) {
item { SettingsSection("Network and storage") }
item(key = "wifi") { SwitchTile(stringResource(Res.string.tile_only_on_wi_fi), null, settings.downloadOnlyOnWifi, { value -> onUpdate { it.copy(downloadOnlyOnWifi = value) } }) }
item { SwitchTile(stringResource(Res.string.save_as_cbz_archive), null, settings.saveAsCBZArchive, { value -> onUpdate { it.copy(saveAsCBZArchive = value) } }) }
item(key = "concurrent") {
SwitchTile(
stringResource(Res.string.allow_concurrent_downloads),
stringResource(Res.string.allow_concurrent_downloads_subtitle),
settings.allowConcurrentDownloads,
{ value -> onUpdate { it.copy(allowConcurrentDownloads = value) } },
)
}
if (settings.allowConcurrentDownloads) {
item {
ChoiceTile(
title = stringResource(Res.string.concurrent_downloads),
options = (1..255).toList(),
selected = settings.concurrentDownloads.coerceIn(1, 255),
label = { it.toString() },
) { value -> onUpdate { it.copy(concurrentDownloads = value) } }
}
}
item {
ChoiceTile(
title = stringResource(Res.string.download_delay),
options = listOf(0, 1, 2, 3, 5, 10, 15, 30, 60),
selected = settings.downloadDelaySeconds.coerceIn(0, 120),
label = { if (it == 0) "Off" else "$it s (+ jitter)" },
) { value -> onUpdate { it.copy(downloadDelaySeconds = value) } }
}
item {
ChoiceTile(
title = "Download speed limit",
options = NetworkSpeedLimitOptions,
selected = normalizedNetworkSpeedLimit(settings.networkDownloadSpeedLimitKib),
label = ::networkSpeedLimitLabel,
) { value -> onUpdate { it.copy(networkDownloadSpeedLimitKib = value) } }
}
item {
ChoiceTile(
title = "Upload speed limit",
options = NetworkSpeedLimitOptions,
selected = normalizedNetworkSpeedLimit(settings.networkUploadSpeedLimitKib),
label = ::networkSpeedLimitLabel,
) { value -> onUpdate { it.copy(networkUploadSpeedLimitKib = value) } }
}
downloadPolicyItems(settings, policy, onUpdate, onPreviewCleanup)
externalDownloadSettings(settings.features.externalDownloads, external, onExternalUpdate, onExternalTest)
remoteDownloadItems(external, onExternalAction)
item { SettingsSection("Local library") }
item {
YokanMenuTile(
title = "Download location",
subtitle = settings.downloadLocation.ifBlank { defaultDownloadRoot },
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = {
scope.launch {
pickFolder(settings.downloadLocation)?.let { picked ->
onUpdate { it.copy(downloadLocation = picked) }
}
}
},
)
}
item {
YokanMenuTile(
title = "Rescan local folders",
subtitle = lastScan?.let { "Last scan: ${it.total} items (added ${it.added}, updated ${it.updated})" } ?: "Reindex configured local folders",
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = onRescanLocalLibrary,
)
}
item {
YokanMenuTile(
title = stringResource(Res.string.add_local_folder),
subtitle = "Pick a folder to add to the local library",
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = {
scope.launch {
pickFolder()?.let { picked ->
if (configuredFolders.none { it.path == picked }) {
folderEditState = LocalFolderEditState(
path = picked,
initialName = nameFromPath(picked),
editing = null,
)
}
}
}
},
)
}
item {
YokanMenuTile(
title = "Download destination",
subtitle = when {
configuredFolders.isEmpty() -> "App default folder (no virtual folders configured)"
settings.askDownloadDestination -> "Ask each time"
else -> settings.downloadLocalFolderName ?: "App default folder"
},
trailing = { Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null) },
onClick = {
if (configuredFolders.isNotEmpty() && !settings.askDownloadDestination) {
downloadPickerOpen = true
}
},
)
}
item {
SwitchTile(
title = "Ask download destination",
subtitle = "Prompt for the target virtual folder when downloading",
value = settings.askDownloadDestination,
onValueChange = { value -> onUpdate { it.copy(askDownloadDestination = value) } },
)
}
item { HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) }
item {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"Virtual folders",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Medium,
modifier = Modifier.weight(1f),
)
IconButton(onClick = { structureHelpOpen = true }) {
Icon(Icons.Filled.Info, contentDescription = "Local folder structure help")
}
}
}
item {
InfoRow(
"Each virtual folder has a user-chosen name and a current path. Library entries are stored under the name, so moving a USB drive to a different mount point only requires updating the path here.",
)
}
if (configuredFolders.isEmpty()) {
item {
ListItem(
headlineContent = {
Text(
"No local folders configured. Tap \"Add local folder\" above to add one.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
leadingContent = { Icon(Icons.Filled.Info, contentDescription = null, tint = MaterialTheme.colorScheme.primary) },
)
}
} else {
configuredFolders.forEach { folder ->
item(key = "folder:${folder.name}") {
FolderTile(
name = folder.name,
path = folder.path,
default = false,
onRename = {
folderEditState = LocalFolderEditState(
path = folder.path,
initialName = folder.name,
editing = folder,
)
},
onRemove = {
onUpdate { current ->
val remaining = current.configuredLocalFolders().filterNot { it.name == folder.name && it.path == folder.path }
val normalized = normalizeLocalFolders(remaining)
current.copy(
namedLocalFolders = normalized,
localFolders = normalized.map { it.path },
downloadLocalFolderName = resolveDownloadFolderName(current.downloadLocalFolderName, normalized),
)
}
},
)
}
}
}
}
}
@Composable
private fun FolderTile(
name: String,
path: String,
default: Boolean,
onRename: (() -> Unit)? = null,
onRemove: (() -> Unit)? = null,
) {
YokanMenuTile(
title = name,
subtitle = if (default) "$path • Default" else path,
trailing = {
Row {
onRename?.let {
IconButton(onClick = it) {
Icon(Icons.Filled.Edit, contentDescription = "Rename folder")
}
}
onRemove?.let {
IconButton(onClick = it) {
Icon(Icons.Filled.DeleteSweep, contentDescription = "Remove folder", tint = MaterialTheme.colorScheme.error)
}
}
}
},
)
}
private val NetworkSpeedLimitOptions = listOf(0, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384)
private fun normalizedNetworkSpeedLimit(value: Int): Int =
if (value in NetworkSpeedLimitOptions) {
value
} else {
NetworkSpeedLimitOptions.minBy { kotlin.math.abs(it - value) }
}
private fun networkSpeedLimitLabel(value: Int): String = when {
value <= 0 -> "No limit"
value < 1024 -> "$value KiB/s"
value % 1024 == 0 -> "${value / 1024} MiB/s"
else -> "${value / 1024.0} MiB/s"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/downloads/DownloadsSettingsViewModel.kt
- Source · implementation · 87 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
26: internal class DownloadsSettingsViewModel(
45: fun previewCleanup() {
58: fun dismissPreview() { _policy.update { it.copy(preview = null) } }
60: fun confirmCleanup() {
75: fun rescan() {
80: internal data class DownloadPolicyUiState(
Exact file bytes / download · SHA-256 ae95d426c72d0a4a23cebbf0e33947ba2e48689ff0780b3f54d55dcfb7a7427f.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.downloads
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.services.download.DownloadAutomation
import eu.friedcutlet.yokan.services.download.DownloadCleanupItem
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.library.LocalLibraryController
import eu.friedcutlet.yokan.services.library.LocalLibraryScanState
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
/** Local-folder rescans for the Downloads page; the scan state is app-wide, owned by [LocalLibraryController]. */
internal class DownloadsSettingsViewModel(
private val localLibrary: LocalLibraryController,
val defaultDownloadRoot: String,
repository: YokanRepository,
private val automation: DownloadAutomation,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
val scan: StateFlow<LocalLibraryScanState> = localLibrary.scan
private val _policy = MutableStateFlow(DownloadPolicyUiState())
val policy = _policy.asStateFlow()
init {
viewModelScope.launch {
repository.snapshots.map { it.categories to it.sources }.distinctUntilChanged().collect { (categories, sources) ->
_policy.update { it.copy(categories = categories.sortedWith(compareBy({ it.forItemType.ordinal }, { it.position ?: 0 }, { it.name })), sources = sources.sortedBy { source -> source.name }) }
}
}
}
fun previewCleanup() {
if (_policy.value.busy) return
_policy.update { it.copy(busy = true, deletedCount = null, failed = false) }
viewModelScope.launch {
try {
val preview = withContext(workDispatcher) { automation.previewReadCleanup() }
_policy.update { it.copy(preview = preview) }
} catch (cancel: CancellationException) { throw cancel }
catch (_: Exception) { _policy.update { it.copy(failed = true) } }
finally { _policy.update { it.copy(busy = false) } }
}
}
fun dismissPreview() { _policy.update { it.copy(preview = null) } }
fun confirmCleanup() {
val ids = _policy.value.preview?.mapTo(mutableSetOf()) { it.chapterId } ?: return
if (_policy.value.busy) return
_policy.update { it.copy(busy = true, preview = null, failed = false) }
viewModelScope.launch {
try {
val count = withContext(workDispatcher) { automation.cleanupReadDownloads(ids) }
_policy.update { it.copy(deletedCount = count) }
} catch (cancel: CancellationException) { throw cancel }
catch (_: Exception) { _policy.update { it.copy(failed = true) } }
finally { _policy.update { it.copy(busy = false) } }
}
}
// A failed scan is recorded in [scan] by the controller.
fun rescan() {
viewModelScope.launch { catchingNonCancellation { localLibrary.rescan() } }
}
}
internal data class DownloadPolicyUiState(
val categories: List<DbCategory> = emptyList(),
val sources: List<DbSource> = emptyList(),
val preview: List<DownloadCleanupItem>? = null,
val busy: Boolean = false,
val deletedCount: Int? = null,
val failed: Boolean = false,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/downloads/ExternalDownloadSettings.kt
- Source · implementation · 103 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: internal fun LazyListScope.externalDownloadSettings(
27: fun update(change: (DbExternalDownloads) -> DbExternalDownloads) = onUpdate { current -> current.copy(features = current.features.copy(externalDownloads = change(current.features.externalDownloads))) }
43: private fun ExternalTextTile(title: String, value: String, secret: Boolean = false, valid: (String) -> Boolean = { true }, onChange: (String) -> Unit) {
57: internal fun LazyListScope.remoteDownloadItems(state: RemoteDownloadsUiState, onAction: (String, RemoteDownloadAction) -> Unit) {
66: private fun RemoteDownloadRow(job: DbRemoteDownloadJob, busy: Boolean, onAction: (String, RemoteDownloadAction) -> Unit) {
Exact file bytes / download · SHA-256 14a82feaec34d849557e68db38e6ad417f5df8594615d5270ae9d61f8dc20427.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.downloads
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.download.ExternalDownloads
import eu.friedcutlet.yokan.ui.screens.settings.*
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
internal fun LazyListScope.externalDownloadSettings(
prefs: DbExternalDownloads,
state: RemoteDownloadsUiState,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onTest: () -> Unit,
) {
fun update(change: (DbExternalDownloads) -> DbExternalDownloads) = onUpdate { current -> current.copy(features = current.features.copy(externalDownloads = change(current.features.externalDownloads))) }
item("external-settings") { SettingsSection(stringResource(Res.string.external_downloader_title)) }
item("external-preference") {
val builtIn = stringResource(Res.string.external_downloader_builtin)
ChoiceTile(stringResource(Res.string.external_downloader_preferred), PreferredDownloader.entries, prefs.preferred,
{ if (it == PreferredDownloader.BuiltIn) builtIn else "aria2" }) { value -> update { it.copy(preferred = value) } }
}
item("external-hint") { InfoRow(stringResource(Res.string.external_downloader_hint)) }
item("external-endpoint") { ExternalTextTile(stringResource(Res.string.external_downloader_url), prefs.endpoint, valid = { it.isBlank() || ExternalDownloads.validEndpoint(it.trim()) }) { value -> update { it.copy(endpoint = value.trim()) } } }
item("external-token") { ExternalTextTile(stringResource(Res.string.external_downloader_token), prefs.secret, secret = true) { value -> update { it.copy(secret = value) } } }
item("external-directory") { ExternalTextTile(stringResource(Res.string.external_downloader_directory), prefs.directory, valid = { it.isBlank() || ExternalDownloads.validDirectory(it.trim()) }) { value -> update { it.copy(directory = value.trim()) } } }
item("external-test") { YokanMenuTile(title = stringResource(Res.string.external_downloader_test), subtitle = stringResource(if (state.testing) Res.string.external_downloader_testing else Res.string.external_downloader_test_hint), enabled = !state.testing && ExternalDownloads.validConfiguration(prefs), onClick = onTest) }
state.version?.let { version -> item("external-version") { InfoRow(stringResource(Res.string.external_downloader_connected, version)) } }
}
@Composable
private fun ExternalTextTile(title: String, value: String, secret: Boolean = false, valid: (String) -> Boolean = { true }, onChange: (String) -> Unit) {
var open by remember { mutableStateOf(false) }
YokanMenuTile(title = title, subtitle = if (secret && value.isNotEmpty()) "••••••••" else value.ifEmpty { stringResource(Res.string.external_downloader_unset) }, onClick = { open = true })
if (open) {
var draft by remember(value) { mutableStateOf(value) }
AlertDialog(onDismissRequest = { open = false }, title = { Text(title) }, text = {
OutlinedTextField(draft, { if (it.length <= 4096) draft = it }, singleLine = true, label = { Text(title) }, isError = !valid(draft),
supportingText = { if (!valid(draft)) Text(stringResource(Res.string.external_downloader_invalid)) },
keyboardOptions = KeyboardOptions(autoCorrectEnabled = false, keyboardType = if (secret) KeyboardType.Password else KeyboardType.Text),
visualTransformation = if (secret) PasswordVisualTransformation() else VisualTransformation.None)
}, confirmButton = { TextButton(enabled = valid(draft), onClick = { onChange(draft); open = false }) { Text(stringResource(Res.string.download_policy_done)) } }, dismissButton = { TextButton(onClick = { open = false }) { Text(stringResource(Res.string.action_cancel)) } })
}
}
internal fun LazyListScope.remoteDownloadItems(state: RemoteDownloadsUiState, onAction: (String, RemoteDownloadAction) -> Unit) {
if (state.failed) item("external-action-error") { InfoRow(stringResource(Res.string.external_downloader_failed)) }
if (state.jobs.isEmpty()) return
item("external-queue-heading") { SettingsSection(stringResource(Res.string.external_downloader_queue)) }
item("external-queue-hint") { InfoRow(stringResource(Res.string.external_downloader_remote_hint)) }
items(state.jobs.asReversed(), key = { "remote-${it.id}" }, contentType = { "remote-download" }) { job -> RemoteDownloadRow(job, job.id in state.busyIds, onAction) }
}
@Composable
private fun RemoteDownloadRow(job: DbRemoteDownloadJob, busy: Boolean, onAction: (String, RemoteDownloadAction) -> Unit) {
var forget by remember(job.id) { mutableStateOf(false) }
val completed = job.files.count { it.state == RemoteDownloadState.Complete }
val bytes = job.files.sumOf { it.completedBytes } / (1024 * 1024)
val fraction = if (job.files.isEmpty()) 0f else (job.files.sumOf { file -> if (file.state == RemoteDownloadState.Complete) 1.0 else if (file.totalBytes > 0) (file.completedBytes.toDouble() / file.totalBytes).coerceIn(0.0, 1.0) else 0.0 } / job.files.size).toFloat()
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(job.mangaName, style = MaterialTheme.typography.titleMedium)
Text(job.chapterName, style = MaterialTheme.typography.bodyMedium)
SelectionContainer { Text(job.directory, style = MaterialTheme.typography.bodySmall) }
Text(stringResource(when {
job.problem == RemoteDownloadProblem.ServerChanged -> Res.string.external_downloader_server_changed
job.problem == RemoteDownloadProblem.Connection -> Res.string.external_downloader_offline
job.problem == RemoteDownloadProblem.MissingOrRejected -> Res.string.external_downloader_unverified
job.complete -> Res.string.external_downloader_complete
job.terminal -> Res.string.external_downloader_cancelled
job.intent == RemoteDownloadIntent.Cancel -> Res.string.external_downloader_cancelling
job.intent == RemoteDownloadIntent.Pause && job.files.all { it.state in setOf(RemoteDownloadState.Pending, RemoteDownloadState.Paused, RemoteDownloadState.Complete, RemoteDownloadState.Removed) } -> Res.string.external_downloader_pause_confirmed
job.intent == RemoteDownloadIntent.Pause -> Res.string.external_downloader_paused
job.files.any { it.state == RemoteDownloadState.Error } -> Res.string.external_downloader_error
else -> Res.string.external_downloader_running
}), style = MaterialTheme.typography.bodySmall)
Text(stringResource(Res.string.external_downloader_progress, completed, job.files.size, bytes), style = MaterialTheme.typography.bodySmall)
LinearProgressIndicator(progress = { fraction }, modifier = Modifier.fillMaxWidth())
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (!job.terminal) {
TextButton(enabled = !busy, onClick = { onAction(job.id, if (job.intent == RemoteDownloadIntent.Pause) RemoteDownloadAction.Resume else RemoteDownloadAction.Pause) }) { Text(stringResource(if (job.intent == RemoteDownloadIntent.Pause) Res.string.external_downloader_resume else Res.string.external_downloader_pause)) }
TextButton(enabled = !busy, onClick = { onAction(job.id, RemoteDownloadAction.Cancel) }) { Text(stringResource(Res.string.action_cancel)) }
TextButton(enabled = !busy, onClick = { onAction(job.id, RemoteDownloadAction.Refresh) }) { Text(stringResource(Res.string.external_downloader_refresh)) }
}
if (job.files.any { it.state in setOf(RemoteDownloadState.Error, RemoteDownloadState.Removed, RemoteDownloadState.Attention, RemoteDownloadState.Submitting) }) TextButton(enabled = !busy, onClick = { onAction(job.id, RemoteDownloadAction.Retry) }) { Text(stringResource(Res.string.external_downloader_retry)) }
TextButton(enabled = !busy, onClick = { forget = true }) { Text(stringResource(Res.string.external_downloader_forget)) }
}
}
if (forget) AlertDialog(onDismissRequest = { forget = false }, title = { Text(stringResource(Res.string.external_downloader_forget)) },
text = { Text(stringResource(Res.string.external_downloader_forget_hint)) },
confirmButton = { TextButton(onClick = { forget = false; onAction(job.id, RemoteDownloadAction.Forget) }) { Text(stringResource(Res.string.external_downloader_forget)) } },
dismissButton = { TextButton(onClick = { forget = false }) { Text(stringResource(Res.string.action_cancel)) } })
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/downloads/ExternalDownloadsViewModel.kt
- Source · implementation · 68 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
17: internal enum class RemoteDownloadAction { Pause, Resume, Cancel, Retry, Refresh, Forget }
18: internal data class RemoteDownloadsUiState(
26: internal class ExternalDownloadsViewModel(private val downloads: ExternalDownloads) : ViewModel() {
37: fun clearConnection() { _state.update { it.copy(version = null, failed = false) } }
38: fun testConnection() {
49: fun act(id: String, action: RemoteDownloadAction) {
Exact file bytes / download · SHA-256 60f9030de7e55c705800c3803857c3aa51ad471e4f8a4482b71b6336063eb416.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.downloads
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.database.DbRemoteDownloadJob
import eu.friedcutlet.yokan.database.RemoteDownloadIntent
import eu.friedcutlet.yokan.services.download.ExternalDownloads
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
internal enum class RemoteDownloadAction { Pause, Resume, Cancel, Retry, Refresh, Forget }
internal data class RemoteDownloadsUiState(
val jobs: List<DbRemoteDownloadJob> = emptyList(),
val busyIds: Set<String> = emptySet(),
val testing: Boolean = false,
val version: String? = null,
val failed: Boolean = false,
)
internal class ExternalDownloadsViewModel(private val downloads: ExternalDownloads) : ViewModel() {
private val _state = MutableStateFlow(RemoteDownloadsUiState(downloads.jobs.value))
val state = _state.asStateFlow()
init {
viewModelScope.launch {
_state.subscriptionCount.map { it > 0 }.distinctUntilChanged().collectLatest { visible ->
if (visible) downloads.jobs.collect { jobs -> _state.update { it.copy(jobs = jobs) } }
}
}
}
fun clearConnection() { _state.update { it.copy(version = null, failed = false) } }
fun testConnection() {
if (_state.value.testing) return
_state.update { it.copy(testing = true, failed = false, version = null) }
viewModelScope.launch {
try { val version = downloads.testConnection(); _state.update { it.copy(version = version) } }
catch (cancel: CancellationException) { throw cancel }
catch (_: Exception) { _state.update { it.copy(failed = true) } }
finally { _state.update { it.copy(testing = false) } }
}
}
fun act(id: String, action: RemoteDownloadAction) {
if (id in _state.value.busyIds) return
_state.update { it.copy(busyIds = it.busyIds + id, failed = false) }
viewModelScope.launch {
try {
when (action) {
RemoteDownloadAction.Pause -> downloads.setIntent(id, RemoteDownloadIntent.Pause)
RemoteDownloadAction.Resume -> downloads.setIntent(id, RemoteDownloadIntent.Run)
RemoteDownloadAction.Cancel -> downloads.setIntent(id, RemoteDownloadIntent.Cancel)
RemoteDownloadAction.Retry -> downloads.retry(id)
RemoteDownloadAction.Forget -> downloads.remove(id, forgetUnverified = true)
RemoteDownloadAction.Refresh -> Unit
}
if (action != RemoteDownloadAction.Forget) downloads.reconcile(id)
} catch (cancel: CancellationException) { throw cancel }
catch (_: Exception) { _state.update { it.copy(failed = true) } }
finally { _state.update { it.copy(busyIds = it.busyIds - id) } }
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/downloads/ImageDataSaverSettings.kt
- Source · implementation · 92 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
20: internal fun LazyListScope.imageDataSaverItems(settings: DbImageDataSaver, sources: List<DbSource>, onUpdate: ((DbSettings) -> DbSettings) -> Unit) {
21: fun update(transform: (DbImageDataSaver) -> DbImageDataSaver) = onUpdate { current -> current.copy(features = current.features.copy(imageDataSaver = transform(current.features.imageDataSaver))) }
57: private fun ImageSaverEndpointTile(endpoint: String, onChange: (String) -> Unit) {
74: private fun ImageSaverSourceTile(sources: List<DbSource>, selected: Set<Long>, onChange: (Set<Long>) -> Unit) {
Exact file bytes / download · SHA-256 cfb626a0d45f321b29a63de2e03af028baa090c012f28029a89a3edc87d7b149.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.downloads
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.download.ImageDataSaver
import eu.friedcutlet.yokan.ui.screens.settings.*
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
internal fun LazyListScope.imageDataSaverItems(settings: DbImageDataSaver, sources: List<DbSource>, onUpdate: ((DbSettings) -> DbSettings) -> Unit) {
fun update(transform: (DbImageDataSaver) -> DbImageDataSaver) = onUpdate { current -> current.copy(features = current.features.copy(imageDataSaver = transform(current.features.imageDataSaver))) }
item("image-saver-section") { SettingsSection(stringResource(Res.string.image_saver_title)) }
item("image-saver-provider") {
val off = stringResource(Res.string.download_policy_off)
ChoiceTile(stringResource(Res.string.image_saver_provider), ImageSaverProvider.entries, settings.provider, { provider ->
when (provider) { ImageSaverProvider.Off -> off; ImageSaverProvider.Wsrv -> "wsrv.nl"; ImageSaverProvider.Resmush -> "reSmush.it"; ImageSaverProvider.BandwidthHero -> "Bandwidth Hero" }
}) { provider -> update { current ->
when (provider) {
ImageSaverProvider.Resmush -> current.copy(provider = provider, format = ImageSaverFormat.Original, grayscale = false, quality = 95)
ImageSaverProvider.BandwidthHero -> current.copy(provider = provider, format = current.format.takeUnless { it == ImageSaverFormat.Original } ?: ImageSaverFormat.Webp)
else -> current.copy(provider = provider)
}
} }
}
if (settings.provider == ImageSaverProvider.Off) return
item("image-saver-info") { InfoRow(stringResource(Res.string.image_saver_privacy)) }
if (settings.provider == ImageSaverProvider.BandwidthHero) item("image-saver-endpoint") {
ImageSaverEndpointTile(settings.bandwidthHeroUrl) { value -> update { it.copy(bandwidthHeroUrl = value) } }
}
item("image-saver-reader") { SwitchTile(stringResource(Res.string.image_saver_reader), null, settings.forReader, { value -> update { it.copy(forReader = value) } }) }
item("image-saver-downloads") { SwitchTile(stringResource(Res.string.image_saver_downloads), null, settings.forDownloads, { value -> update { it.copy(forDownloads = value) } }) }
item("image-saver-quality") { ChoiceTile(stringResource(Res.string.image_saver_quality), (listOf(10, 25, 40, 60, 75, 80, 90, 92, 95, 100) + settings.quality.coerceIn(1, 100)).distinct().sorted(), settings.quality.coerceIn(1, 100), Int::toString) { value -> update { it.copy(quality = value) } } }
if (settings.provider != ImageSaverProvider.Resmush) {
item("image-saver-format") {
val original = stringResource(Res.string.image_saver_original)
val options = if (settings.provider == ImageSaverProvider.BandwidthHero) listOf(ImageSaverFormat.Jpeg, ImageSaverFormat.Webp) else ImageSaverFormat.entries
ChoiceTile(stringResource(Res.string.image_saver_format), options, settings.format, { format -> when (format) { ImageSaverFormat.Original -> original; ImageSaverFormat.Jpeg -> "JPEG"; ImageSaverFormat.Webp -> "WebP" } }) { value -> update { it.copy(format = value) } }
}
item("image-saver-gray") { SwitchTile(stringResource(Res.string.image_saver_grayscale), null, settings.grayscale, { value -> update { it.copy(grayscale = value) } }) }
} else item("image-saver-resmush") { InfoRow(stringResource(Res.string.image_saver_resmush_hint)) }
item("image-saver-jpeg") { SwitchTile(stringResource(Res.string.image_saver_skip_jpeg), null, settings.skipJpeg, { value -> update { it.copy(skipJpeg = value) } }) }
item("image-saver-gif") { SwitchTile(stringResource(Res.string.image_saver_skip_gif), null, settings.skipGif, { value -> update { it.copy(skipGif = value) } }) }
item("image-saver-sources") { ImageSaverSourceTile(sources, settings.excludedSourceIds) { ids -> update { it.copy(excludedSourceIds = ids) } } }
}
@Composable
private fun ImageSaverEndpointTile(endpoint: String, onChange: (String) -> Unit) {
var open by remember { mutableStateOf(false) }
val title = stringResource(Res.string.image_saver_endpoint)
YokanMenuTile(title = title, subtitle = endpoint.ifBlank { stringResource(Res.string.image_saver_endpoint_hint) }, onClick = { open = true })
if (open) {
var value by remember(endpoint) { mutableStateOf(endpoint) }
val valid = value.isBlank() || ImageDataSaver.validEndpoint(value.trim())
AlertDialog(onDismissRequest = { open = false }, title = { Text(title) }, text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(Res.string.image_saver_endpoint_hint))
OutlinedTextField(value, { value = it }, singleLine = true, isError = !valid, label = { Text(title) })
}
}, confirmButton = { TextButton(enabled = valid, onClick = { onChange(value.trim()); open = false }) { Text(stringResource(Res.string.download_policy_done)) } }, dismissButton = { TextButton(onClick = { open = false }) { Text(stringResource(Res.string.action_cancel)) } })
}
}
@Composable
private fun ImageSaverSourceTile(sources: List<DbSource>, selected: Set<Long>, onChange: (Set<Long>) -> Unit) {
var open by remember { mutableStateOf(false) }
val title = stringResource(Res.string.image_saver_excluded_sources)
YokanMenuTile(title = title, subtitle = stringResource(Res.string.image_saver_source_count, selected.size), onClick = { open = true })
if (open) AlertDialog(onDismissRequest = { open = false }, title = { Text(title) }, text = {
LazyColumn(Modifier.fillMaxWidth().heightIn(max = 360.dp)) {
item("hint") { Text(stringResource(Res.string.image_saver_sources_hint)) }
items(sources, key = { it.id }, contentType = { "source" }) { source ->
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).toggleable(source.id in selected, role = Role.Checkbox) {
onChange(if (it) selected + source.id else selected - source.id)
}.padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
Checkbox(source.id in selected, onCheckedChange = null)
Spacer(Modifier.width(12.dp))
Text("${source.name.orEmpty()} (${source.lang.orEmpty().uppercase()})")
}
}
}
}, confirmButton = { TextButton(onClick = { open = false }) { Text(stringResource(Res.string.download_policy_done)) } })
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/downloads/LocalFolderDialogs.kt
- Source · implementation · 266 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
51: internal data class LocalFolderEditState(
58: internal fun LocalFolderNameDialog(
116: internal fun LocalFolderStructureDialog(onDismiss: () -> Unit) {
214: private fun LocalFolderStructureExample(
Exact file bytes / download · SHA-256 13f2bf47370a2d36aca5291f6854b6ed50b08891cf8dca06c6ff4204e5ab24a2.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.downloads
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ChromeReaderMode
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.PlayCircle
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.ui_close
internal data class LocalFolderEditState(
val path: String,
val initialName: String,
val editing: DbLocalFolder?,
)
@Composable
internal fun LocalFolderNameDialog(
initialName: String,
path: String,
existingNames: Set<String>,
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
) {
var name by remember(initialName) { mutableStateOf(initialName) }
val trimmed = name.trim()
val collision = trimmed.isNotEmpty() && existingNames.contains(trimmed)
val empty = trimmed.isEmpty()
val isReserved = trimmed.equals("local", ignoreCase = true)
val error = when {
empty -> "Name cannot be empty"
isReserved -> "\"local\" is reserved for the default folder"
collision -> "Name already used"
else -> null
}
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = {
Text(
if (existingNames.isEmpty()) "Name folder" else "Edit folder name",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
Column {
Text(path, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text("Folder name") },
isError = error != null,
singleLine = true,
shape = MaterialTheme.shapes.large,
modifier = Modifier.fillMaxWidth(),
)
error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
}
},
confirmButton = {
Button(
onClick = { onConfirm(trimmed) },
enabled = error == null,
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 8.dp),
) { Text(stringResource(Res.string.action_save), style = MaterialTheme.typography.labelLarge) }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
)
}
@Composable
internal fun LocalFolderStructureDialog(onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = {
Text(
"Organize local files",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
Column(
modifier = Modifier
.heightIn(max = 560.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
"Use a separate root folder for each library type. Include Manga, Anime, or Novel in the root folder name so Yokan can classify it.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
LocalFolderStructureExample(
title = "Manga",
detail = "Image folders or CBZ, ZIP, CBT, and TAR archives",
icon = Icons.AutoMirrored.Filled.MenuBook,
structure = """
Manga/
└── Title name/
├── cover.jpg
├── Chapter 01/
│ ├── 001.jpg
│ └── 002.png
└── Chapter 02.cbz
""".trimIndent(),
)
LocalFolderStructureExample(
title = "Anime",
detail = "Video files with optional matching subtitles",
icon = Icons.Filled.PlayCircle,
structure = """
Anime/
└── Title name/
├── cover.jpg
├── Episode 01.mkv
└── Episode 01_subtitles/
├── en.srt
└── de.srt
""".trimIndent(),
)
LocalFolderStructureExample(
title = "Novel",
detail = "EPUB files",
icon = Icons.AutoMirrored.Filled.ChromeReaderMode,
structure = """
Novel/
└── Title name/
├── cover.jpg
└── Book.epub
""".trimIndent(),
)
Surface(
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.6f),
shape = MaterialTheme.shapes.large,
) {
Row(
modifier = Modifier.fillMaxWidth().padding(12.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
Icons.Filled.Sync,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.size(20.dp),
)
Text(
"After adding or moving files, run Rescan local folders.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer,
)
}
}
}
},
confirmButton = {
Button(
onClick = onDismiss,
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 8.dp),
) { Text(stringResource(Res.string.ui_close), style = MaterialTheme.typography.labelLarge) }
},
)
}
@Composable
private fun LocalFolderStructureExample(
title: String,
detail: String,
icon: ImageVector,
structure: String,
) {
Surface(
modifier = Modifier.fillMaxWidth(),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f),
shape = MaterialTheme.shapes.large,
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
) {
Column(
modifier = Modifier.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Surface(
color = MaterialTheme.colorScheme.primaryContainer,
shape = CircleShape,
) {
Icon(
icon,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.padding(8.dp).size(18.dp),
)
}
Column(modifier = Modifier.weight(1f)) {
Text(
title,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
)
Text(
detail,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Text(
structure,
fontFamily = FontFamily.Monospace,
style = MaterialTheme.typography.bodySmall,
lineHeight = 18.sp,
)
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/extensionserver/ExtensionServerSettingsScreen.kt
- Source · implementation · 426 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
57: internal fun ExtensionServerSettingsRoute(
89: private fun ExtensionServerSettingsScreen(
375: private fun ExtensionServerStatusTile(label: String, value: String, exists: Boolean) {
403: private fun ExtensionServerInfoTile(label: String, value: String) {
421: private fun extensionServerVersionFromPath(path: String): String =
Exact file bytes / download · SHA-256 55ef4539f2572aff55a6c9c769d7d8cf7f777778a4bc67d9308e4482b4b2d76a.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.extensionserver
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.Speed
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.Update
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ext.ExtensionServerRelease
import eu.friedcutlet.yokan.ext.ExtensionServerStatus
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerInstallPhase
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerInstallStatus
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeMode
import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.TextInputDialog
import eu.friedcutlet.yokan.ui.screens.settings.data.formatBytes
@Composable
internal fun ExtensionServerSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val model = viewModel { ExtensionServerSettingsViewModel(YokanRuntime.services.extensionServer, YokanRuntime.database) }
val state by model.state.collectAsStateWithLifecycle()
val runtimeStatus by model.runtimeStatus.collectAsStateWithLifecycle()
val installStatus by model.installStatus.collectAsStateWithLifecycle()
val latestRelease by model.latestRelease.collectAsStateWithLifecycle()
ExtensionServerSettingsScreen(
title = title,
savedServerUrl = settings.androidProxyServer,
state = state,
runtimeStatus = runtimeStatus,
installStatus = installStatus,
latestRelease = latestRelease,
onSaveServerUrl = { url ->
onUpdate { it.copy(androidProxyServer = url) }
model.serverUrlSaved()
},
onCheckFiles = model::checkFiles,
onInstallLatest = model::installLatest,
onImportExisting = model::importExisting,
onToggleServer = model::toggleServer,
onCheckServer = model::checkServer,
onBack = onBack,
)
}
@Composable
private fun ExtensionServerSettingsScreen(
title: String,
savedServerUrl: String?,
state: ExtensionServerSettingsState,
runtimeStatus: ExtensionServerStatus,
installStatus: ExtensionServerInstallStatus,
latestRelease: ExtensionServerRelease?,
onSaveServerUrl: (String) -> Unit,
onCheckFiles: () -> Unit,
onInstallLatest: () -> Unit,
onImportExisting: () -> Unit,
onToggleServer: (serverUrl: String, onServerUrl: (String) -> Unit) -> Unit,
onCheckServer: (String) -> Unit,
onBack: () -> Unit,
) {
val mode = state.mode
val configured = state.configured
val jrePath = state.jrePath
val serverPath = state.serverPath
val remoteOnly = mode == ExtensionServerRuntimeMode.Unsupported
var serverUrl by remember(savedServerUrl, remoteOnly) {
mutableStateOf(savedServerUrl ?: if (remoteOnly) "" else defaultMihonProxyUrl)
}
var proxyDialogOpen by remember { mutableStateOf(false) }
val downloading = installStatus.phase == ExtensionServerInstallPhase.Downloading
val checkingFiles = installStatus.phase == ExtensionServerInstallPhase.Checking
val busy = downloading || checkingFiles || state.checkingServer || state.importingServerJar
val installedVersion = extensionServerVersionFromPath(serverPath).ifBlank {
if (configured) state.bundledServerVersion.orEmpty() else ""
}
val latestVersion = latestRelease?.version.orEmpty()
val hasUpdate = configured && latestVersion.isNotBlank() &&
(installedVersion.isBlank() || installedVersion != latestVersion)
val installationAvailable = state.installationAvailable
val showFileSection = !remoteOnly && mode != ExtensionServerRuntimeMode.AndroidApkBridge
val canImport = mode != ExtensionServerRuntimeMode.AndroidApkBridge && installationAvailable
val actionLabel = when {
!installationAvailable -> "Runtime unavailable"
!configured -> "Download"
hasUpdate -> "Update files"
else -> "Up to date"
}
if (proxyDialogOpen) {
TextInputDialog(
title = if (remoteOnly) "Set server URL" else "Set proxy address",
initialValue = serverUrl,
placeholder = if (remoteOnly) "https://your-server.example" else defaultMihonProxyUrl,
onConfirm = { value ->
serverUrl = value.trim().ifBlank { if (remoteOnly) "" else defaultMihonProxyUrl }
onSaveServerUrl(serverUrl)
},
onDismiss = { proxyDialogOpen = false },
)
}
SettingsScaffold(title, onBack) {
if (showFileSection) {
item { SettingsSection("Mihon proxy server") }
item {
Text(
when {
state.unavailableReason != null -> state.unavailableReason
mode == ExtensionServerRuntimeMode.IosSideloadedJvm && installationAvailable ->
"This sideload build runs the extension server on its signed, interpreter-only JVM. It starts when a Mihon extension needs it, and you can also start or stop it below."
mode == ExtensionServerRuntimeMode.IosSideloadedJvm ->
"This build does not include the signed sideloaded Java runtime. Download, import, and start are unavailable."
else ->
"Download the local extension server and its JRE. Yokan verifies the release checksum, installs both files, and owns the server process."
},
modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
item {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
OutlinedButton(
modifier = Modifier.weight(1f),
enabled = !busy,
onClick = onCheckFiles,
) {
Icon(if (configured) Icons.Filled.DoneAll else Icons.Filled.Info, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(if (checkingFiles) "Checking files" else if (configured) "Files installed" else "Files missing")
}
Button(
modifier = Modifier.weight(1f),
enabled = installationAvailable && state.requiresBundleDownload && !busy &&
latestRelease != null && (!configured || hasUpdate),
onClick = onInstallLatest,
) {
Icon(
when {
!configured -> Icons.Filled.Download
hasUpdate -> Icons.Filled.Update
else -> Icons.Filled.DoneAll
},
contentDescription = null,
)
Spacer(Modifier.width(6.dp))
Text(actionLabel)
}
}
}
if (canImport) {
item {
OutlinedButton(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
enabled = !busy,
onClick = onImportExisting,
) {
Icon(Icons.Filled.Folder, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(
when {
state.importingServerJar -> "Importing"
mode == ExtensionServerRuntimeMode.IosSideloadedJvm -> "Import existing JAR"
else -> "Detect files in selected folder"
},
)
}
}
}
if (downloading) {
item {
Column(
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (installStatus.totalBytes > 0) {
LinearProgressIndicator(
progress = {
(installStatus.downloadedBytes.toFloat() / installStatus.totalBytes.toFloat())
.coerceIn(0f, 1f)
},
modifier = Modifier.fillMaxWidth(),
)
Text(
"${formatBytes(installStatus.downloadedBytes)}/${formatBytes(installStatus.totalBytes)}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
Text(
"Preparing download",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
if (mode == ExtensionServerRuntimeMode.DesktopDownloadedJvm) {
item {
ExtensionServerStatusTile(
label = "Install location",
value = serverPath.substringBeforeLast('/'),
exists = configured,
)
}
item { ExtensionServerStatusTile("JRE executable", jrePath, jrePath.isNotBlank()) }
item { ExtensionServerStatusTile("Extension server JAR", serverPath, serverPath.isNotBlank()) }
} else {
item {
ExtensionServerStatusTile(
label = "App install location",
value = when {
configured -> "Signed runtime bundled with Yokan"
installationAvailable -> ""
else -> "Sideload runtime not included"
},
exists = configured,
)
}
}
item { ExtensionServerInfoTile("Installed version", installedVersion) }
item { ExtensionServerInfoTile("Latest version", latestVersion) }
} else {
item { SettingsSection(if (remoteOnly) "Browser connection" else "Local APK bridge") }
item {
Text(
if (remoteOnly) {
"Browsers cannot run the local JVM server. Provide a remotely hosted APK Extension Server URL below; it must allow this site's origin (CORS)."
} else {
"Android runs the Mihon APK bridge inside Yokan. No 120 MB JRE or server bundle download is required."
},
modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
item { SettingsSection(if (remoteOnly) "Remote server" else "Server") }
if (!remoteOnly) {
item {
ExtensionServerStatusTile(
label = "Runtime status",
value = runtimeStatus.message.ifBlank { runtimeStatus.phase.name },
exists = runtimeStatus.isRunning,
)
}
}
item {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
if (!remoteOnly) {
Button(
modifier = Modifier.weight(1f),
enabled = !busy && configured,
onClick = { onToggleServer(serverUrl) { serverUrl = it } },
) {
Icon(if (runtimeStatus.isRunning) Icons.Filled.Remove else Icons.Filled.Terminal, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(if (runtimeStatus.isRunning) "Stop" else "Start")
}
}
OutlinedButton(
modifier = if (remoteOnly) Modifier.fillMaxWidth() else Modifier.weight(1f),
enabled = !busy && serverUrl.startsWith("http"),
onClick = { onCheckServer(serverUrl) },
) {
Icon(Icons.Filled.Speed, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(if (state.checkingServer) "Checking" else if (remoteOnly) "Check connection" else "Check")
}
}
}
item { SettingsSection(if (remoteOnly) "APK Extension Server URL" else "Android proxy server") }
item { ExtensionServerStatusTile(if (remoteOnly) "Server URL" else "Android proxy server", serverUrl, serverUrl.startsWith("http")) }
item {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
OutlinedButton(
modifier = if (remoteOnly) Modifier.fillMaxWidth() else Modifier.weight(1f),
onClick = { proxyDialogOpen = true },
) {
Icon(Icons.Filled.Edit, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(if (remoteOnly) "Set server URL" else "Set proxy address")
}
if (!remoteOnly) {
OutlinedButton(
modifier = Modifier.weight(1f),
onClick = {
openSystemBrowser(
"https://github.com/kodjodevf/M-Extension-Server/releases",
)
},
) {
Icon(Icons.Filled.Download, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Get APK bridge")
}
}
}
}
if (busy) {
item {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp))
}
}
val visibleMessage = state.statusMessage ?: installStatus.message.takeIf { it.isNotBlank() }
visibleMessage?.let { message ->
item {
ListItem(
headlineContent = { Text(message, style = MaterialTheme.typography.bodyMedium) },
leadingContent = {
Icon(Icons.Filled.Info, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
},
)
}
}
}
}
@Composable
private fun ExtensionServerStatusTile(label: String, value: String, exists: Boolean) {
Surface(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
shape = RoundedCornerShape(12.dp),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
color = Color.Transparent,
) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
if (exists) Icons.Filled.DoneAll else Icons.Filled.Info,
contentDescription = null,
modifier = Modifier.size(18.dp),
tint = if (exists) Color(0xFF43A047) else Color(0xFFFB8C00),
)
Spacer(Modifier.width(8.dp))
Text(label, style = MaterialTheme.typography.bodyMedium)
}
Text(
value.ifBlank { "Not configured" },
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
private fun ExtensionServerInfoTile(label: String, value: String) {
Surface(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
shape = RoundedCornerShape(12.dp),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
color = Color.Transparent,
) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(label, style = MaterialTheme.typography.bodyMedium)
Text(
value.ifBlank { "Unknown" },
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
private fun extensionServerVersionFromPath(path: String): String =
Regex("""(?:^|[/\\])v?(\d+\.\d+\.\d+)(?:[/\\]|$)""")
.find(path)
?.groupValues
?.getOrNull(1)
.orEmpty()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/extensionserver/ExtensionServerSettingsViewModel.kt
- Source · implementation · 196 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
22: internal data class ExtensionServerSettingsState(
37: internal class ExtensionServerSettingsViewModel(
77: fun serverUrlSaved() = showMessage(if (_state.value.mode == ExtensionServerRuntimeMode.Unsupported) "Server URL saved." else "Proxy address saved.")
79: fun checkFiles() {
98: fun installLatest() {
112: fun importExisting() {
149: fun toggleServer(serverUrl: String, onServerUrl: (String) -> Unit) {
170: fun checkServer(serverUrl: String) {
182: private fun syncPersistedPaths() {
195: private fun showMessage(message: String) = _state.update { it.copy(statusMessage = message) }
Exact file bytes / download · SHA-256 0d6f9f10142a5fc43e710af850073f02c81984c8e073319054eb7cbaca130f31.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.extensionserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.ext.ExtensionServerRelease
import eu.friedcutlet.yokan.ext.ExtensionServerStatus
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerInstallStatus
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeMode
import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeService
import eu.friedcutlet.yokan.services.extensions.mihon.extensionServerPortFromUrl
import eu.friedcutlet.yokan.services.files.pickFile
import eu.friedcutlet.yokan.services.files.pickFolder
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
internal data class ExtensionServerSettingsState(
val mode: ExtensionServerRuntimeMode,
val requiresBundleDownload: Boolean,
val installationAvailable: Boolean,
val bundledServerVersion: String?,
val unavailableReason: String? = null,
val jrePath: String,
val serverPath: String,
val configured: Boolean,
val statusMessage: String? = null,
val checkingServer: Boolean = false,
val importingServerJar: Boolean = false,
)
/** Extension-server install/runtime actions; paths mirror the persisted settings. */
internal class ExtensionServerSettingsViewModel(
private val runtime: ExtensionServerRuntimeService,
private val database: YokanDatabase,
) : ViewModel() {
private val _state = MutableStateFlow(
database.settings().let { persisted ->
ExtensionServerSettingsState(
mode = runtime.mode,
requiresBundleDownload = runtime.requiresBundleDownload,
installationAvailable = runtime.installationAvailable,
bundledServerVersion = runtime.bundledServerVersion,
unavailableReason = runtime.unavailableReason,
jrePath = persisted.jrePath,
serverPath = persisted.extensionServerPath,
configured = runtime.isConfigured(),
)
},
)
val state: StateFlow<ExtensionServerSettingsState> = _state.asStateFlow()
val runtimeStatus: StateFlow<ExtensionServerStatus> = runtime.status
val installStatus: StateFlow<ExtensionServerInstallStatus> = runtime.installation
val latestRelease: StateFlow<ExtensionServerRelease?> = runtime.latestRelease
init {
viewModelScope.launch {
if (runtime.requiresBundleDownload && runtime.installationAvailable) {
catchingNonCancellation { runtime.refreshLatestRelease() }
.onFailure { error ->
showMessage("Release check failed: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}")
}
}
}
// Path edits from elsewhere (sync, restore) re-read the persisted paths like the old keyed state did.
viewModelScope.launch {
database.snapshots()
.distinctUntilChangedBy { it.settings.jrePath to it.settings.extensionServerPath }
.collect { syncPersistedPaths() }
}
}
fun serverUrlSaved() = showMessage(if (_state.value.mode == ExtensionServerRuntimeMode.Unsupported) "Server URL saved." else "Proxy address saved.")
fun checkFiles() {
viewModelScope.launch {
_state.update { it.copy(configured = runtime.isConfigured()) }
val releaseResult = if (runtime.requiresBundleDownload && runtime.installationAvailable) {
catchingNonCancellation { runtime.refreshLatestRelease() }
} else {
Result.success(null)
}
showMessage(
releaseResult.fold(
onSuccess = {
if (_state.value.configured) "Extension server files are installed." else "Extension server files are missing."
},
onFailure = { "File check failed: ${it.message.orEmpty()}" },
),
)
}
}
fun installLatest() {
viewModelScope.launch {
showMessage(
catchingNonCancellation { runtime.installLatest() }.fold(
onSuccess = {
syncPersistedPaths()
"Extension server ${it.version} installed."
},
onFailure = { "Installation failed: ${it.message.orEmpty()}" },
),
)
}
}
fun importExisting() {
_state.update { it.copy(importingServerJar = true) }
viewModelScope.launch {
try {
val serverPath = _state.value.serverPath
val selection = catchingNonCancellation {
when (runtime.mode) {
ExtensionServerRuntimeMode.DesktopDownloadedJvm ->
pickFolder(serverPath.substringBeforeLast('/').ifBlank { null })
ExtensionServerRuntimeMode.IosSideloadedJvm ->
pickFile(listOf("jar"), serverPath.ifBlank { null })
ExtensionServerRuntimeMode.AndroidApkBridge,
ExtensionServerRuntimeMode.Unsupported,
-> null
}
}
selection.exceptionOrNull()?.let {
showMessage("Could not select extension server files: ${it.message.orEmpty()}")
}
selection.getOrNull()?.let { selected ->
showMessage(
catchingNonCancellation { runtime.useExisting(selected) }.fold(
onSuccess = {
syncPersistedPaths()
"Existing extension server files detected."
},
onFailure = { "Could not use selected files: ${it.message.orEmpty()}" },
),
)
}
} finally {
_state.update { it.copy(importingServerJar = false) }
}
}
}
/** Stops a running server, otherwise starts one on [serverUrl]'s port; [onServerUrl] receives the bound URL. */
fun toggleServer(serverUrl: String, onServerUrl: (String) -> Unit) {
viewModelScope.launch {
_state.update { it.copy(checkingServer = true) }
val message = if (runtime.status.value.isRunning) {
catchingNonCancellation { runtime.stop() }.fold(
onSuccess = { "Extension server stopped." },
onFailure = { "Stop failed: ${it.message.orEmpty()}" },
)
} else {
catchingNonCancellation { runtime.start(extensionServerPortFromUrl(serverUrl)) }.fold(
onSuccess = {
it.baseUrl?.let(onServerUrl)
"Extension server is running at ${it.baseUrl ?: serverUrl}."
},
onFailure = { "Start failed: ${it.message.orEmpty()}" },
)
}
_state.update { it.copy(statusMessage = message, checkingServer = false) }
}
}
fun checkServer(serverUrl: String) {
viewModelScope.launch {
_state.update { it.copy(checkingServer = true) }
val message = if (runtime.check(serverUrl)) {
"Proxy server is reachable at ${serverUrl.trimEnd('/')}."
} else {
"Proxy server check failed."
}
_state.update { it.copy(statusMessage = message, checkingServer = false) }
}
}
private fun syncPersistedPaths() {
val persisted = database.settings()
_state.update {
it.copy(
installationAvailable = runtime.installationAvailable,
bundledServerVersion = runtime.bundledServerVersion,
jrePath = persisted.jrePath,
serverPath = persisted.extensionServerPath,
configured = runtime.isConfigured(),
)
}
}
private fun showMessage(message: String) = _state.update { it.copy(statusMessage = message) }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/general/GeneralSettingsScreen.kt
- Source · implementation · 247 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
53: internal fun GeneralSettingsScreen(
195: private fun BorderedGroup(
224: private fun WeightSlider(title: String, value: Float, onChange: (Float) -> Unit) {
Exact file bytes / download · SHA-256 2f74d921757b498b74e7aa14284bebf89f241af6b93ea237df57470920f3811d.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.general
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Restore
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.friedcutlet.yokan.database.DbAlgorithmWeights
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DefaultUserAgent
import eu.friedcutlet.yokan.services.http.CustomDohProviderId
import eu.friedcutlet.yokan.services.http.DohProviderOption
import eu.friedcutlet.yokan.services.http.DohProviders
import eu.friedcutlet.yokan.services.http.platformSupportsCustomDns
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.formatDecimal
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.TextInputDialog
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_reset
import yokan.composeapp.generated.resources.default_user_agent
import yokan.composeapp.generated.resources.tile_dns_over_https
@Composable
internal fun GeneralSettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val weights = settings.algorithmWeights ?: DbAlgorithmWeights()
var dohProviderDialog by remember { mutableStateOf(false) }
var customDohDialog by remember { mutableStateOf(false) }
var userAgentDialog by remember { mutableStateOf(false) }
var cfProxyDialog by remember { mutableStateOf(false) }
val currentDohProvider = if (settings.dohProviderId == CustomDohProviderId) {
DohProviderOption(CustomDohProviderId, "Custom", settings.customDohUrl)
} else {
DohProviders.firstOrNull { it.id == settings.dohProviderId } ?: DohProviders[0]
}
val dohProviderSubtitle = if (settings.dohProviderId == CustomDohProviderId) {
if (settings.customDohUrl.isNotBlank()) "Custom · ${settings.customDohUrl}" else "Custom"
} else {
currentDohProvider.name
}
if (dohProviderDialog) {
val allOptions = DohProviders + DohProviderOption(CustomDohProviderId, "Custom", settings.customDohUrl)
ChoiceDialog(
title = "DNS provider",
options = allOptions,
selected = currentDohProvider,
label = { opt ->
if (opt.id == CustomDohProviderId && settings.customDohUrl.isNotBlank()) {
"Custom (${settings.customDohUrl})"
} else {
opt.name
}
},
onSelect = { provider ->
dohProviderDialog = false
if (provider.id == CustomDohProviderId) {
customDohDialog = true
} else {
onUpdate { it.copy(dohProviderId = provider.id, dohEnabled = true) }
}
},
onDismiss = { dohProviderDialog = false },
)
}
if (customDohDialog) {
TextInputDialog(
title = "Custom DoH URL",
initialValue = settings.customDohUrl,
placeholder = "https://example.com/dns-query",
helperText = "Must be an https DoH (JSON) endpoint",
onConfirm = { raw ->
val trimmed = raw.trim()
val url = if (trimmed.isNotBlank() && !trimmed.startsWith("http://") && !trimmed.startsWith("https://")) {
"https://$trimmed"
} else {
trimmed
}
onUpdate {
it.copy(
customDohUrl = url,
dohProviderId = CustomDohProviderId,
dohEnabled = true,
)
}
},
onDismiss = { customDohDialog = false },
)
}
if (userAgentDialog) {
TextInputDialog(
title = stringResource(Res.string.default_user_agent),
initialValue = settings.userAgent,
placeholder = DefaultUserAgent,
singleLine = false,
onConfirm = { value -> onUpdate { it.copy(userAgent = value.trim().ifBlank { DefaultUserAgent }) } },
onDismiss = { userAgentDialog = false },
)
}
if (cfProxyDialog) {
TextInputDialog(
title = "Cloudflare bypass proxy",
initialValue = settings.cloudflareBypassProxyUrl,
placeholder = "http://localhost:8191/v1",
helperText = "Any FlareSolverr-compatible solver (FlareSolverr, Byparr); a bare host:port gets /v1. Leave empty to disable.",
onConfirm = { value -> onUpdate { it.copy(cloudflareBypassProxyUrl = value.trim()) } },
onDismiss = { cfProxyDialog = false },
)
}
SettingsScaffold(title, onBack) {
// DoH expansion header: taps the row to toggle, and when enabled exposes a "DNS provider" sub-tile.
// Darwin and browser engines resolve hosts themselves, so those platforms hide it.
if (platformSupportsCustomDns) {
item(key = "doh") {
SwitchTile(
stringResource(Res.string.tile_dns_over_https),
if (settings.dohEnabled) dohProviderSubtitle else null,
settings.dohEnabled,
{ value -> onUpdate { it.copy(dohEnabled = value) } },
)
}
}
if (platformSupportsCustomDns && settings.dohEnabled) {
item {
SettingTile(
"DNS provider",
dohProviderSubtitle,
onClick = {
if (settings.dohProviderId == CustomDohProviderId && settings.customDohUrl.isBlank()) {
customDohDialog = true
} else {
dohProviderDialog = true
}
},
)
}
}
item(key = "user-agent") { SettingTile(stringResource(Res.string.default_user_agent), settings.userAgent.ifBlank { DefaultUserAgent }, onClick = { userAgentDialog = true }) }
item {
SettingTile(
"Cloudflare bypass proxy",
settings.cloudflareBypassProxyUrl.ifBlank { "Disabled" },
onClick = { cfProxyDialog = true },
)
}
item {
BorderedGroup(
title = "Recommendations weights",
onReset = { onUpdate { it.copy(algorithmWeights = DbAlgorithmWeights()) } },
) {
WeightSlider("Genre", weights.genre / 100f, { value -> onUpdate { it.copy(algorithmWeights = weights.copy(genre = (value * 100).toInt())) } })
WeightSlider("Setting", weights.setting / 100f, { value -> onUpdate { it.copy(algorithmWeights = weights.copy(setting = (value * 100).toInt())) } })
WeightSlider("Synopsis", weights.synopsis / 100f, { value -> onUpdate { it.copy(algorithmWeights = weights.copy(synopsis = (value * 100).toInt())) } })
WeightSlider("Theme", weights.theme / 100f, { value -> onUpdate { it.copy(algorithmWeights = weights.copy(theme = (value * 100).toInt())) } })
}
}
}
}
@Composable
private fun BorderedGroup(
title: String,
onReset: () -> Unit,
content: @Composable ColumnScope.() -> Unit,
) {
Surface(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp),
shape = RoundedCornerShape(5.dp),
border = BorderStroke(3.dp, MaterialTheme.colorScheme.primary),
) {
Column(modifier = Modifier.padding(10.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(title, fontWeight = FontWeight.Bold)
Spacer(Modifier.width(20.dp))
OutlinedButton(onClick = onReset) {
Icon(Icons.Filled.Restore, contentDescription = null)
Spacer(Modifier.width(8.dp))
Text(stringResource(Res.string.action_reset))
}
}
Spacer(Modifier.height(10.dp))
content()
}
}
}
@Composable
private fun WeightSlider(title: String, value: Float, onChange: (Float) -> Unit) {
val hapticFeedback = LocalHapticFeedback.current
Column(
modifier = Modifier.padding(8.dp),
horizontalAlignment = Alignment.Start,
) {
Text(title)
Text(
formatDecimal(value.toDouble(), 2),
fontSize = 11.sp,
color = MaterialTheme.colorScheme.secondary,
)
Spacer(Modifier.height(20.dp))
Slider(
value = value,
onValueChange = { nextValue ->
if ((nextValue * 100).toInt() != (value * 100).toInt()) {
hapticFeedback.performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)
}
onChange(nextValue)
},
)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/library/AutomaticUpdateConditionsViewModel.kt
- Source · implementation · 40 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
14: data class AutomaticUpdateConditionsState(val checking: Boolean = false, val admission: UpdateAdmission? = null)
16: class AutomaticUpdateConditionsViewModel(
39: fun refresh() { refreshes.update { it + 1 } }
Exact file bytes / download · SHA-256 69231c1e6482798a4f556309ee16bfcd65490ede2a7bdd948ab2aed47d4cffdd.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.library
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.services.scheduling.AutomaticUpdateGate
import eu.friedcutlet.yokan.services.scheduling.UpdateAdmission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
data class AutomaticUpdateConditionsState(val checking: Boolean = false, val admission: UpdateAdmission? = null)
class AutomaticUpdateConditionsViewModel(
private val settings: SettingsStore,
private val gate: AutomaticUpdateGate,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(AutomaticUpdateConditionsState())
val state: StateFlow<AutomaticUpdateConditionsState> = _state.asStateFlow()
private val refreshes = MutableStateFlow(0L)
init {
viewModelScope.launch {
gate.status.collect { admission -> _state.update { it.copy(admission = admission) } }
}
viewModelScope.launch {
combine(settings.db.map { it.features.library.deviceConstraints to it.downloadOnlyOnWifi }.distinctUntilChanged(), refreshes) { _, _ -> Unit }
.collectLatest {
_state.update { it.copy(checking = true) }
try { withContext(workDispatcher) { gate.check(settings.db.value, force = true) } }
finally { _state.update { it.copy(checking = false) } }
}
}
}
fun refresh() { refreshes.update { it + 1 } }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/library/CategoriesSettingsScreen.kt
- Source · implementation · 325 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
72: internal fun CategoriesSettingsRoute(title: String, initialItemType: ItemType, onBack: () -> Unit) {
91: internal fun CategoriesSettingsScreen(
112: fun categoryLabel(id: Long) = when (id) {
217: private fun CategoryEditorRow(
Exact file bytes / download · SHA-256 7dfa13dfba0c2699b4e3dd635782a99703bf51eca5e647ed373dd69e57863440.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.library
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Label
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.DeleteSweep
import androidx.compose.material.icons.filled.DragHandle
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material.icons.filled.Update
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.components.ConfirmDialog
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.ReorderableColumn
import eu.friedcutlet.yokan.ui.components.TooltipIconButton
import eu.friedcutlet.yokan.ui.components.YokanChipTabs
import eu.friedcutlet.yokan.ui.components.YokanDivider
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.TextInputDialog
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_add
import yokan.composeapp.generated.resources.category_move_down
import yokan.composeapp.generated.resources.category_move_up
import yokan.composeapp.generated.resources.category_reorder
import yokan.composeapp.generated.resources.delete
import yokan.composeapp.generated.resources.library_default_category
import yokan.composeapp.generated.resources.library_default_category_ask
import yokan.composeapp.generated.resources.library_default_category_none
@Composable
internal fun CategoriesSettingsRoute(title: String, initialItemType: ItemType, onBack: () -> Unit) {
val model = viewModel { CategoriesViewModel(initialItemType, YokanRuntime.repository) }
val state by model.state.collectAsStateWithLifecycle()
CategoriesSettingsScreen(
title = title,
state = state,
onBack = onBack,
onSelectType = model::selectType,
onCreate = model::create,
onRename = model::rename,
onMove = model::move,
onToggleHidden = model::toggleHidden,
onToggleShouldUpdate = model::toggleShouldUpdate,
onRemove = model::remove,
onDefaultCategory = model::setDefaultCategory,
)
}
@Composable
internal fun CategoriesSettingsScreen(
title: String,
state: CategoriesState,
onBack: () -> Unit,
onSelectType: (ItemType) -> Unit,
onCreate: (name: String) -> Unit,
onRename: (Category, name: String) -> Unit,
onMove: (Category, offset: Int) -> Unit,
onToggleHidden: (Category) -> Unit,
onToggleShouldUpdate: (Category) -> Unit,
onRemove: (Category) -> Unit,
onDefaultCategory: (Long?) -> Unit = {},
) {
val selectedType = state.itemType
var renameTarget by remember { mutableStateOf<Category?>(null) }
var addDialog by remember { mutableStateOf(false) }
var deleteTarget by remember { mutableStateOf<Category?>(null) }
var defaultDialog by remember(selectedType) { mutableStateOf(false) }
val defaultTitle = stringResource(Res.string.library_default_category)
val askLabel = stringResource(Res.string.library_default_category_ask)
val noneLabel = stringResource(Res.string.library_default_category_none)
fun categoryLabel(id: Long) = when (id) {
-1L -> askLabel
0L -> noneLabel
else -> state.categories.firstOrNull { it.id == id }?.name ?: askLabel
}
if (defaultDialog) {
ChoiceDialog(
title = defaultTitle,
options = listOf(-1L, 0L) + state.categories.map { it.id },
selected = state.defaultCategoryId ?: -1L,
label = ::categoryLabel,
onSelect = { onDefaultCategory(it.takeIf { id -> id >= 0 }); defaultDialog = false },
onDismiss = { defaultDialog = false },
)
}
renameTarget?.let { current ->
TextInputDialog(
title = "Rename category",
initialValue = current.name,
placeholder = "Category name",
onConfirm = { value -> if (value.isNotBlank()) onRename(current, value) },
onDismiss = { renameTarget = null },
)
}
if (addDialog) {
TextInputDialog(
title = "Add category",
initialValue = "",
placeholder = "Category name",
onConfirm = { value -> if (value.isNotBlank()) onCreate(value) },
onDismiss = { addDialog = false },
)
}
deleteTarget?.let { current ->
ConfirmDialog(
title = "Delete category",
message = "Delete \"${current.name}\"? Library entries in this category will be uncategorised.",
confirmLabel = stringResource(Res.string.delete),
danger = true,
onConfirm = { onRemove(current) },
onDismiss = { deleteTarget = null },
)
}
Box(modifier = Modifier.fillMaxSize()) {
SettingsScaffold(title, onBack) {
item {
YokanChipTabs(
options = ItemType.entries.map { it.label },
selectedIndex = ItemType.entries.indexOf(selectedType),
onSelect = { idx -> onSelectType(ItemType.entries[idx]) },
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
val categories = state.categories
item(key = "default-category-$selectedType") {
SettingTile(
defaultTitle,
categoryLabel(state.defaultCategoryId ?: -1L),
onClick = { defaultDialog = true },
)
}
if (categories.isEmpty()) {
item { EmptyState(icon = Icons.AutoMirrored.Filled.Label, title = "No categories", modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp, horizontal = 16.dp), subtitle = "Create categories to group ${selectedType.label.lowercase()} library entries.") }
} else {
item(key = "category-order-$selectedType") {
ReorderableColumn(
items = categories,
key = { it.id },
onMove = { from, to -> onMove(categories[from], to - from) },
modifier = Modifier.padding(horizontal = 15.dp),
) { category, dragHandle, isDragging ->
val index = categories.indexOfFirst { it.id == category.id }
CategoryEditorRow(
category = category,
dragHandle = dragHandle,
isDragging = isDragging,
canMoveUp = index > 0,
canMoveDown = index < categories.lastIndex,
onMoveUp = { onMove(category, -1) },
onMoveDown = { onMove(category, 1) },
onRename = { renameTarget = category },
onToggleShouldUpdate = { onToggleShouldUpdate(category) },
onToggleHidden = { onToggleHidden(category) },
onDelete = { deleteTarget = category },
)
}
}
}
// Bottom spacer so the floating Add button never covers the last row.
item { Spacer(Modifier.height(88.dp)) }
}
FloatingActionButton(
onClick = { addDialog = true },
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp),
) {
Icon(Icons.Filled.Add, contentDescription = stringResource(Res.string.action_add))
}
}
}
@Composable
private fun CategoryEditorRow(
category: Category,
modifier: Modifier = Modifier,
dragHandle: Modifier,
isDragging: Boolean,
canMoveUp: Boolean,
canMoveDown: Boolean,
onMoveUp: () -> Unit,
onMoveDown: () -> Unit,
onRename: () -> Unit,
onToggleShouldUpdate: () -> Unit,
onToggleHidden: () -> Unit,
onDelete: () -> Unit,
) {
var reorderMenu by remember { mutableStateOf(false) }
Surface(
modifier = modifier.fillMaxWidth(),
color = if (isDragging) MaterialTheme.colorScheme.surface else Color.Transparent,
shadowElevation = if (isDragging) 6.dp else 0.dp,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box {
IconButton(
onClick = { reorderMenu = true },
modifier = Modifier.size(48.dp).then(dragHandle),
) {
Icon(Icons.Filled.DragHandle, contentDescription = stringResource(Res.string.category_reorder, category.name))
}
DropdownMenu(expanded = reorderMenu, onDismissRequest = { reorderMenu = false }) {
DropdownMenuItem(
text = { Text(stringResource(Res.string.category_move_up)) },
enabled = canMoveUp,
onClick = { reorderMenu = false; onMoveUp() },
)
DropdownMenuItem(
text = { Text(stringResource(Res.string.category_move_down)) },
enabled = canMoveDown,
onClick = { reorderMenu = false; onMoveDown() },
)
}
}
Column(Modifier.weight(1f).padding(vertical = 6.dp)) {
// Trailing padding is inner content padding, kept inside the highlighted, clickable row.
Row(
modifier = Modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.large)
.hoverHighlight(onClick = onRename)
.padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Box(
modifier = Modifier
.size(36.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f)),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.AutoMirrored.Filled.Label,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(18.dp),
)
}
Text(
category.name,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.weight(1f),
textDecoration = if (category.hidden) TextDecoration.LineThrough else TextDecoration.None,
color = if (category.hidden) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onSurface,
)
}
YokanDivider(inset = 12.dp)
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(Modifier.weight(1f))
TooltipIconButton(
tooltip = "Rename",
icon = Icons.Filled.Tune,
onClick = onRename,
)
TooltipIconButton(
tooltip = if (category.shouldUpdate) "Auto-update on" else "Auto-update off",
icon = Icons.Filled.Update,
onClick = onToggleShouldUpdate,
tint = if (category.shouldUpdate) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
)
TooltipIconButton(
tooltip = if (category.hidden) "Show" else "Hide",
icon = if (category.hidden) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
onClick = onToggleHidden,
tint = if (category.hidden) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.primary,
)
TooltipIconButton(
tooltip = stringResource(Res.string.delete),
icon = Icons.Filled.DeleteSweep,
onClick = onDelete,
tint = MaterialTheme.colorScheme.error,
)
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/library/CategoriesViewModel.kt
- Source · implementation · 65 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
16: internal data class CategoriesState(val itemType: ItemType, val categories: List<Category>, val defaultCategoryId: Long? = null)
18: internal class CategoriesViewModel(initialType: ItemType, private val repository: YokanRepository) : ViewModel() {
29: fun selectType(type: ItemType) = _state.update { stateFor(type) }
31: fun setDefaultCategory(id: Long?) = write {
39: fun create(name: String) = write { repository.createCategory(_state.value.itemType, name) }
41: fun rename(category: Category, name: String) = write { repository.updateCategory(category.id, name = name) }
43: fun toggleHidden(category: Category) = write { repository.updateCategory(category.id, hidden = !category.hidden) }
45: fun toggleShouldUpdate(category: Category) =
48: fun move(category: Category, offset: Int) = write { repository.moveCategory(_state.value.itemType, category.id, offset) }
50: fun remove(category: Category) = write { repository.removeCategory(category.id) }
53: private inline fun write(block: () -> Unit) {
58: private fun stateFor(type: ItemType): CategoriesState {
64: private fun reload() = _state.update { stateFor(it.itemType) }
Exact file bytes / download · SHA-256 d629c0a057f039fdc328330d16a50f00197c9593e682696c9737a112ea4ee780.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.library
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.domain.Category
import eu.friedcutlet.yokan.domain.ItemType
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
internal data class CategoriesState(val itemType: ItemType, val categories: List<Category>, val defaultCategoryId: Long? = null)
internal class CategoriesViewModel(initialType: ItemType, private val repository: YokanRepository) : ViewModel() {
private val _state = MutableStateFlow(stateFor(initialType))
val state: StateFlow<CategoriesState> = _state.asStateFlow()
init {
// External writes (sync, restore, the library screen) reach this page through the snapshots.
viewModelScope.launch { repository.snapshots.distinctUntilChangedBy {
it.categories to it.settings.features.library
}.collect { reload() } }
}
fun selectType(type: ItemType) = _state.update { stateFor(type) }
fun setDefaultCategory(id: Long?) = write {
val type = _state.value.itemType
if (id != null && id != 0L && repository.categories(type).none { it.id == id }) return@write
repository.updateDbSettings { db -> db.copy(features = db.features.copy(
library = db.features.library.withDefaultCategory(type.toDb(), id),
)) }
}
fun create(name: String) = write { repository.createCategory(_state.value.itemType, name) }
fun rename(category: Category, name: String) = write { repository.updateCategory(category.id, name = name) }
fun toggleHidden(category: Category) = write { repository.updateCategory(category.id, hidden = !category.hidden) }
fun toggleShouldUpdate(category: Category) =
write { repository.updateCategory(category.id, shouldUpdate = !category.shouldUpdate) }
fun move(category: Category, offset: Int) = write { repository.moveCategory(_state.value.itemType, category.id, offset) }
fun remove(category: Category) = write { repository.removeCategory(category.id) }
// Writes publish synchronously so a dropped drag row never snaps back for a frame.
private inline fun write(block: () -> Unit) {
block()
reload()
}
private fun stateFor(type: ItemType): CategoriesState {
val categories = repository.categories(type)
val defaultId = repository.dbSettings().features.library.defaultCategory(type.toDb())
return CategoriesState(type, categories, defaultId?.takeIf { it == 0L || categories.any { category -> category.id == it } })
}
private fun reload() = _state.update { stateFor(it.itemType) }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/library/LibrarySettingsScreen.kt
- Source · implementation · 402 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
42: internal fun LibrarySettingsRoute(
66: internal fun LibrarySettingsScreen(
85: fun setConstraints(change: (DbAutomaticUpdateConstraints) -> DbAutomaticUpdateConstraints) = onUpdate { db ->
105: fun setRules(change: (DbSmartUpdateRules) -> DbSmartUpdateRules) = onUpdate { db ->
149: fun showCategoryTabs() = when (selectedType) {
154: fun showCounts() = when (selectedType) {
159: fun showLanguage() = when (selectedType) {
164: fun showSource() = when (selectedType) {
169: fun showDownloadBadge() = when (selectedType) {
363: private fun timeOfDayLabel(minutes: Int): String =
368: private fun TimeOfDayDialog(
393: internal fun periodicTaskFrequencyLabel(seconds: Int): String = when (seconds) {
Exact file bytes / download · SHA-256 8e721668763b6c7161594e1b0df981f532297648b3043168f8c2980f295402f0.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.library
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.DbGroupUpdateMode
import eu.friedcutlet.yokan.database.DbSmartUpdateRules
import eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints
import eu.friedcutlet.yokan.database.DbUpdateNetwork
import eu.friedcutlet.yokan.database.DbUnknownNetworkCost
import eu.friedcutlet.yokan.services.scheduling.UpdateDeferral
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.components.YokanChipTabs
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.Categories
import eu.friedcutlet.yokan.ui.screens.settings.RouteTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
@Composable
internal fun LibrarySettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
onOpen: (SettingsPage) -> Unit,
itemType: ItemType,
) {
val model = viewModel {
val owner = YokanRuntime.activeSession
AutomaticUpdateConditionsViewModel(owner.settings, owner.automaticUpdateGate)
}
val conditionState by model.state.collectAsStateWithLifecycle()
val isDesktop = remember { YokanRuntime.bootstrapReport().platform.platformName == "Desktop" }
LibrarySettingsScreen(
title, settings, onUpdate, onBack, onOpen, itemType,
isDesktop = isDesktop,
onRequestNotificationPermission = { YokanRuntime.notifications.requestPermission() },
conditionState = conditionState,
onCheckConditions = model::refresh,
)
}
@Composable
internal fun LibrarySettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
onOpen: (SettingsPage) -> Unit,
initialItemType: ItemType,
isDesktop: Boolean,
onRequestNotificationPermission: () -> Unit,
conditionState: AutomaticUpdateConditionsState = AutomaticUpdateConditionsState(),
onCheckConditions: () -> Unit = {},
) {
var selectedType by remember { mutableStateOf(initialItemType) }
var updateFrequencyDialog by remember { mutableStateOf(false) }
var updateTimeDialog by remember { mutableStateOf(false) }
var groupScopeDialog by remember { mutableStateOf(false) }
var networkDialog by remember { mutableStateOf(false) }
var costDialog by remember { mutableStateOf(false) }
val constraints = settings.features.library.deviceConstraints
fun setConstraints(change: (DbAutomaticUpdateConstraints) -> DbAutomaticUpdateConstraints) = onUpdate { db ->
db.copy(features = db.features.copy(library = db.features.library.copy(deviceConstraints = change(db.features.library.deviceConstraints))))
}
val networkLabels = mapOf(DbUpdateNetwork.Legacy to stringResource(Res.string.update_constraints_legacy),
DbUpdateNetwork.Connected to stringResource(Res.string.update_constraints_connected),
DbUpdateNetwork.Unmetered to stringResource(Res.string.update_constraints_unmetered),
DbUpdateNetwork.Wifi to stringResource(Res.string.update_constraints_wifi))
val costLabels = mapOf(DbUnknownNetworkCost.Wait to stringResource(Res.string.update_constraints_wait),
DbUnknownNetworkCost.Metered to stringResource(Res.string.update_constraints_assume_metered),
DbUnknownNetworkCost.Unmetered to stringResource(Res.string.update_constraints_assume_unmetered))
if (networkDialog) ChoiceDialog(
title = stringResource(Res.string.update_constraints_network), options = DbUpdateNetwork.entries,
selected = constraints.network, label = { networkLabels.getValue(it) },
onSelect = { value -> setConstraints { it.copy(network = value) } }, onDismiss = { networkDialog = false })
if (costDialog) ChoiceDialog(
title = stringResource(Res.string.update_constraints_unknown_cost), options = DbUnknownNetworkCost.entries,
selected = constraints.unknownNetworkCost, label = { costLabels.getValue(it) },
onSelect = { value -> setConstraints { it.copy(unknownNetworkCost = value) } }, onDismiss = { costDialog = false })
val updateRules = settings.features.library.updateRules(selectedType.toDb())
val groupScope = settings.features.library.updateGroupMode(selectedType.toDb())
fun setRules(change: (DbSmartUpdateRules) -> DbSmartUpdateRules) = onUpdate { db ->
db.copy(features = db.features.copy(library = db.features.library.withUpdateRules(selectedType.toDb(),
change(db.features.library.updateRules(selectedType.toDb())))))
}
val groupLabels = mapOf(DbGroupUpdateMode.Global to stringResource(Res.string.library_update_group_global),
DbGroupUpdateMode.CurrentGroup to stringResource(Res.string.library_update_group_current),
DbGroupUpdateMode.CurrentExceptUngrouped to stringResource(Res.string.library_update_group_except_ungrouped))
if (groupScopeDialog) ChoiceDialog(
title = stringResource(Res.string.library_update_group_scope), options = DbGroupUpdateMode.entries,
selected = groupScope, label = { groupLabels.getValue(it) }, onSelect = { mode ->
onUpdate { db -> db.copy(features = db.features.copy(library = db.features.library.withUpdateGroupMode(selectedType.toDb(), mode))) }
}, onDismiss = { groupScopeDialog = false })
val updatesEnabled = settings.libraryUpdateFrequencySeconds > 0
val dailyAt = settings.libraryUpdateDailyAtMinutes
if (updateFrequencyDialog) {
ChoiceDialog(
title = "Update schedule",
options = PeriodicTaskFrequencies.drop(1) + DailyAtFixedTime,
selected = if (dailyAt >= 0) DailyAtFixedTime else settings.libraryUpdateFrequencySeconds,
label = ::periodicTaskFrequencyLabel,
onSelect = { value ->
if (value == DailyAtFixedTime) {
updateTimeDialog = true
} else {
onUpdate { it.copy(libraryUpdateFrequencySeconds = value, libraryUpdateDailyAtMinutes = -1) }
}
},
onDismiss = { updateFrequencyDialog = false },
)
}
if (updateTimeDialog) {
TimeOfDayDialog(
title = "Update daily at",
initialMinutes = dailyAt.takeIf { it >= 0 } ?: (3 * 60),
onConfirm = { minutes ->
onUpdate { it.copy(libraryUpdateFrequencySeconds = 86400, libraryUpdateDailyAtMinutes = minutes) }
},
onDismiss = { updateTimeDialog = false },
)
}
// Per-type accessors so each toggle reads/writes the field for the
// currently selected library tab (manga/anime/novel).
fun showCategoryTabs() = when (selectedType) {
ItemType.Manga -> settings.libraryShowCategoryTabs
ItemType.Anime -> settings.animeLibraryShowCategoryTabs
ItemType.Novel -> settings.novelLibraryShowCategoryTabs
}
fun showCounts() = when (selectedType) {
ItemType.Manga -> settings.libraryShowNumbersOfItems
ItemType.Anime -> settings.animeLibraryShowNumbersOfItems
ItemType.Novel -> settings.novelLibraryShowNumbersOfItems
}
fun showLanguage() = when (selectedType) {
ItemType.Manga -> settings.libraryShowLanguage
ItemType.Anime -> settings.animeLibraryShowLanguage
ItemType.Novel -> settings.novelLibraryShowLanguage
}
fun showSource() = when (selectedType) {
ItemType.Manga -> settings.libraryShowSource
ItemType.Anime -> settings.animeLibraryShowSource
ItemType.Novel -> settings.novelLibraryShowSource
}
fun showDownloadBadge() = when (selectedType) {
ItemType.Manga -> settings.libraryDownloadedChapters
ItemType.Anime -> settings.animeLibraryDownloadedChapters
ItemType.Novel -> settings.novelLibraryDownloadedChapters
}
SettingsScaffold(title, onBack) {
item {
YokanChipTabs(
options = ItemType.entries.map { it.label },
selectedIndex = ItemType.entries.indexOf(selectedType),
onSelect = { idx -> selectedType = ItemType.entries[idx] },
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
item { SettingsSection("Background updates") }
item {
SwitchTile(
"Automatic library updates",
when {
!updatesEnabled -> "Off"
dailyAt >= 0 -> "Daily at ${timeOfDayLabel(dailyAt)}"
else -> periodicTaskFrequencyLabel(settings.libraryUpdateFrequencySeconds)
},
updatesEnabled,
{ value ->
if (value) onRequestNotificationPermission()
onUpdate { it.copy(libraryUpdateFrequencySeconds = if (value) 86400 else 0) }
},
)
}
if (updatesEnabled) {
item {
SettingTile(
"Schedule",
if (dailyAt >= 0) periodicTaskFrequencyLabel(DailyAtFixedTime) else periodicTaskFrequencyLabel(settings.libraryUpdateFrequencySeconds),
onClick = { updateFrequencyDialog = true },
)
}
if (dailyAt >= 0) {
item { SettingTile("Time", timeOfDayLabel(dailyAt), onClick = { updateTimeDialog = true }) }
}
if (isDesktop) {
item {
SwitchTile(
"Keep running in the tray",
"Closing the window hides Yokan so scheduled updates still run",
settings.desktopCloseToTray,
{ value -> onUpdate { it.copy(desktopCloseToTray = value, desktopLaunchAtLogin = it.desktopLaunchAtLogin && value) } },
)
}
item {
SwitchTile(
"Start at login",
"Launch Yokan hidden in the tray when you sign in",
settings.desktopLaunchAtLogin,
{ value -> onUpdate { it.copy(desktopLaunchAtLogin = value) } },
enabled = settings.desktopCloseToTray,
)
}
}
}
item { SettingsSection(stringResource(Res.string.update_constraints_section)) }
item { Text(stringResource(Res.string.update_constraints_help), modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) }
item { SettingTile(stringResource(Res.string.update_constraints_network), networkLabels.getValue(constraints.network), onClick = { networkDialog = true }) }
item { SwitchTile(stringResource(Res.string.update_constraints_power), stringResource(Res.string.update_constraints_power_help),
constraints.requireExternalPower, { value -> setConstraints { it.copy(requireExternalPower = value) } }) }
if (constraints.network == DbUpdateNetwork.Unmetered) {
item { SettingTile(stringResource(Res.string.update_constraints_unknown_cost), costLabels.getValue(constraints.unknownNetworkCost), onClick = { costDialog = true }) }
item { Text(stringResource(Res.string.update_constraints_unknown_help), modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) }
}
item {
val admission = conditionState.admission
val summary = when {
conditionState.checking -> stringResource(Res.string.update_constraints_checking)
admission == null -> ""
admission.allowed -> stringResource(Res.string.update_constraints_allowed)
else -> stringResource(Res.string.update_constraints_waiting, admission.reasons.map { reason ->
stringResource(when (reason) {
UpdateDeferral.NetworkUnavailable -> Res.string.update_constraints_no_network
UpdateDeferral.NetworkUnknown -> Res.string.update_constraints_unknown_network
UpdateDeferral.WifiRequired -> Res.string.update_constraints_need_wifi
UpdateDeferral.WifiUnknown -> Res.string.update_constraints_unknown_wifi
UpdateDeferral.UnmeteredRequired -> Res.string.update_constraints_need_unmetered
UpdateDeferral.NetworkCostUnknown -> Res.string.update_constraints_unknown_metering
UpdateDeferral.PowerRequired -> Res.string.update_constraints_need_power
UpdateDeferral.PowerUnknown -> Res.string.update_constraints_unknown_power
})
}.joinToString("; "))
}
SettingTile(stringResource(Res.string.update_constraints_check), summary, onClick = onCheckConditions, enabled = !conditionState.checking)
}
item { SettingsSection(stringResource(Res.string.library_update_rules)) }
item { SwitchTile(stringResource(Res.string.library_update_skip_completed), "", updateRules.skipCompleted,
{ value -> setRules { it.copy(skipCompleted = value) } }) }
item { SwitchTile(stringResource(Res.string.library_update_caught_up), stringResource(Res.string.library_update_caught_up_help), updateRules.onlyCaughtUp,
{ value -> setRules { it.copy(onlyCaughtUp = value) } }) }
item { SwitchTile(stringResource(Res.string.library_update_started), stringResource(Res.string.library_update_started_help), updateRules.onlyStarted,
{ value -> setRules { it.copy(onlyStarted = value) } }) }
item { SwitchTile(stringResource(Res.string.library_update_release_period), stringResource(Res.string.library_update_release_period_help), updateRules.respectExpectedReleasePeriod,
{ value -> setRules { it.copy(respectExpectedReleasePeriod = value) } }) }
item { SettingTile(stringResource(Res.string.library_update_group_scope), groupLabels.getValue(groupScope), onClick = { groupScopeDialog = true }) }
item { Text(stringResource(Res.string.library_update_group_help), modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) }
item { SettingsSection("Display") }
item {
SwitchTile(
"Display category tabs",
"Show a tab row for your ${selectedType.label.lowercase()} categories at the top of the library",
showCategoryTabs(),
{ value ->
onUpdate {
when (selectedType) {
ItemType.Manga -> it.copy(libraryShowCategoryTabs = value)
ItemType.Anime -> it.copy(animeLibraryShowCategoryTabs = value)
ItemType.Novel -> it.copy(novelLibraryShowCategoryTabs = value)
}
}
},
)
}
item {
SwitchTile(
"Show number of items",
"Display the entry count on each category",
showCounts(),
{ value ->
onUpdate {
when (selectedType) {
ItemType.Manga -> it.copy(libraryShowNumbersOfItems = value)
ItemType.Anime -> it.copy(animeLibraryShowNumbersOfItems = value)
ItemType.Novel -> it.copy(novelLibraryShowNumbersOfItems = value)
}
}
},
)
}
item {
SwitchTile(
"Show download badges",
"Highlight entries with downloaded chapters",
showDownloadBadge(),
{ value ->
onUpdate {
when (selectedType) {
ItemType.Manga -> it.copy(libraryDownloadedChapters = value)
ItemType.Anime -> it.copy(animeLibraryDownloadedChapters = value)
ItemType.Novel -> it.copy(novelLibraryDownloadedChapters = value)
}
}
},
)
}
item {
SwitchTile(
"Show source language",
"Display the source language on each entry",
showLanguage(),
{ value ->
onUpdate {
when (selectedType) {
ItemType.Manga -> it.copy(libraryShowLanguage = value)
ItemType.Anime -> it.copy(animeLibraryShowLanguage = value)
ItemType.Novel -> it.copy(novelLibraryShowLanguage = value)
}
}
},
)
}
item {
SwitchTile(
"Show source badge",
"Display the source badge on each library cover",
showSource(),
{ value ->
onUpdate {
when (selectedType) {
ItemType.Manga -> it.copy(libraryShowSource = value)
ItemType.Anime -> it.copy(animeLibraryShowSource = value)
ItemType.Novel -> it.copy(novelLibraryShowSource = value)
}
}
},
)
}
item { SettingsSection("Organisation") }
item { RouteTile(Categories, "Categories", "Create and order categories to group library entries", onOpen = onOpen) }
}
}
internal val PeriodicTaskFrequencies = listOf(0, 3600, 21600, 43200, 86400, 172800, 604800)
/** Sentinel option in the schedule picker; the actual time lives in `libraryUpdateDailyAtMinutes`. */
private const val DailyAtFixedTime = -1
private fun timeOfDayLabel(minutes: Int): String =
"${(minutes / 60).toString().padStart(2, '0')}:${(minutes % 60).toString().padStart(2, '0')}"
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TimeOfDayDialog(
title: String,
initialMinutes: Int,
onConfirm: (Int) -> Unit,
onDismiss: () -> Unit,
) {
val state = rememberTimePickerState(
initialHour = initialMinutes / 60,
initialMinute = initialMinutes % 60,
is24Hour = true,
)
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(title) },
text = { TimePicker(state = state) },
confirmButton = {
TextButton(onClick = {
onConfirm(state.hour * 60 + state.minute)
onDismiss()
}) { Text(stringResource(Res.string.ok)) }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
)
}
internal fun periodicTaskFrequencyLabel(seconds: Int): String = when (seconds) {
DailyAtFixedTime -> "Daily at a fixed time"
3600 -> "Every hour"
21600 -> "Every 6 hours"
43200 -> "Every 12 hours"
86400 -> "Daily"
172800 -> "Every 2 days"
604800 -> "Weekly"
else -> "Off"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/metadata/MetadataServerSettingsScreen.kt
- Source · implementation · 213 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
55: internal fun MetadataServerSettingsRoute(
77: private fun MetadataServerSettingsScreen(
Exact file bytes / download · SHA-256 9d8c103b1806d989b89a32952ea990719c89a441ddc4e4c1805621af2b0e5aa2.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.metadata
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.OpenInBrowser
import androidx.compose.material.icons.filled.Security
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Speed
import androidx.compose.material3.Button
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.library.PeriodicTaskFrequencies
import eu.friedcutlet.yokan.ui.screens.settings.library.periodicTaskFrequencyLabel
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_open
import yokan.composeapp.generated.resources.action_save
@Composable
internal fun MetadataServerSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val model = viewModel { MetadataServerSettingsViewModel(YokanRuntime.services.metadata, YokanRuntime.notifications) }
val state by model.state.collectAsStateWithLifecycle()
MetadataServerSettingsScreen(
title = title,
settings = settings,
status = state.status,
checking = state.checking,
onUpdate = onUpdate,
onRequestNotificationPermission = model::requestNotificationPermission,
onSaved = model::markSaved,
onCheck = model::check,
onBack = onBack,
)
}
@Composable
private fun MetadataServerSettingsScreen(
title: String,
settings: DbSettings,
status: String?,
checking: Boolean,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onRequestNotificationPermission: () -> Unit,
onSaved: () -> Unit,
onCheck: (serverUrl: String) -> Unit,
onBack: () -> Unit,
) {
var serverUrl by remember(settings.metadataServerUrl) { mutableStateOf(settings.metadataServerUrl) }
var token by remember(settings.metadataServerToken) { mutableStateOf(settings.metadataServerToken) }
var refreshFrequencyDialog by remember { mutableStateOf(false) }
if (refreshFrequencyDialog) {
ChoiceDialog(
title = "Automatic metadata refresh",
options = PeriodicTaskFrequencies,
selected = settings.metadataRefreshFrequencySeconds,
label = ::periodicTaskFrequencyLabel,
onSelect = { value ->
if (value > 0) onRequestNotificationPermission()
onUpdate { it.copy(metadataRefreshFrequencySeconds = value) }
},
onDismiss = { refreshFrequencyDialog = false },
)
}
SettingsScaffold(title, onBack) {
item { SettingsSection("Metadata lookup") }
item {
SwitchTile(
"Enable metadata check",
"Automatically check titles when opening details",
settings.metadataServerEnabled,
{ value -> onUpdate { it.copy(metadataServerEnabled = value) } },
)
}
item {
SettingTile(
"Automatic metadata refresh",
periodicTaskFrequencyLabel(settings.metadataRefreshFrequencySeconds),
enabled = settings.metadataServerEnabled,
onClick = { refreshFrequencyDialog = true },
)
}
item {
ElevatedCard(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp)) {
Column(Modifier.padding(horizontal = 16.dp, vertical = 16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.Filled.Dns, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
Text(
"Connection",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
)
}
OutlinedTextField(
value = serverUrl,
onValueChange = { serverUrl = it },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text("Metadata server URL") },
leadingIcon = { Icon(Icons.Filled.OpenInBrowser, contentDescription = null) },
)
OutlinedTextField(
value = token,
onValueChange = { token = it },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
label = { Text("API token") },
leadingIcon = { Icon(Icons.Filled.Security, contentDescription = null) },
)
}
}
}
item { SettingsSection("Actions") }
item {
FlowRow(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Button(
onClick = {
onUpdate {
it.copy(
metadataServerUrl = serverUrl.trim().ifBlank { "http://127.0.0.1:3000" },
metadataServerToken = token.trim(),
)
}
onSaved()
},
) {
Icon(Icons.Filled.Settings, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(stringResource(Res.string.action_save))
}
OutlinedButton(
enabled = !checking && serverUrl.startsWith("http"),
onClick = { onCheck(serverUrl) },
) {
Icon(Icons.Filled.Speed, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(if (checking) "Checking" else "Check")
}
OutlinedButton(
enabled = serverUrl.startsWith("http"),
onClick = { openSystemBrowser(serverUrl) },
) {
Icon(Icons.Filled.OpenInBrowser, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(stringResource(Res.string.action_open))
}
}
}
if (checking) {
item {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp))
}
}
status?.let { message ->
item {
ListItem(
headlineContent = { Text(message, style = MaterialTheme.typography.bodyMedium) },
leadingContent = {
Icon(Icons.Filled.Info, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
},
)
}
}
item {
InfoRow("The metadata server can be self-hosted or provided by another party. Public media search enriches titles and tags; the API token is only used for Metadata Server tracker library sync.")
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/metadata/MetadataServerSettingsViewModel.kt
- Source · implementation · 42 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
14: internal data class MetadataServerSettingsState(val status: String? = null, val checking: Boolean = false)
16: internal class MetadataServerSettingsViewModel(
23: fun requestNotificationPermission() = notifications.requestPermission()
25: fun markSaved() {
29: fun check(serverUrl: String) {
Exact file bytes / download · SHA-256 51eb09cf1a8eddb958ea68b71a981f325db11b75fbe102d638c4e9f7aa30b6fb.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.metadata
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.metadata.MetadataService
import eu.friedcutlet.yokan.services.notifications.NotificationService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
internal data class MetadataServerSettingsState(val status: String? = null, val checking: Boolean = false)
internal class MetadataServerSettingsViewModel(
private val metadata: MetadataService,
private val notifications: NotificationService,
) : ViewModel() {
private val _state = MutableStateFlow(MetadataServerSettingsState())
val state: StateFlow<MetadataServerSettingsState> = _state.asStateFlow()
fun requestNotificationPermission() = notifications.requestPermission()
fun markSaved() {
_state.update { it.copy(status = "Metadata server settings saved.") }
}
fun check(serverUrl: String) {
viewModelScope.launch {
_state.update { it.copy(checking = true) }
val checkUrl = serverUrl.trim().trimEnd('/')
val ok = catchingNonCancellation { metadata.health(checkUrl) }.getOrDefault(false)
val status = if (ok) {
"Metadata server is reachable at $checkUrl."
} else {
"Metadata server check failed at $checkUrl."
}
_state.update { it.copy(status = status, checking = false) }
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/player/CustomButtonsScreen.kt
- Source · implementation · 273 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
68: internal fun CustomButtonsRoute(title: String, onBack: () -> Unit) {
84: internal fun CustomButtonsScreen(
214: private fun CustomButtonEditDialog(
Exact file bytes / download · SHA-256 c72918cb28f5376376044b29a28a0224f7c9f4f5eb962cc85d391416b50a434e.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.player
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.DeleteSweep
import androidx.compose.material.icons.filled.DragHandle
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.ui.components.ConfirmDialog
import eu.friedcutlet.yokan.ui.components.ReorderableColumn
import eu.friedcutlet.yokan.ui.components.ScrollbarBox
import eu.friedcutlet.yokan.ui.components.YokanTopBar
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_add
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.delete
import yokan.composeapp.generated.resources.edit
import yokan.composeapp.generated.resources.ui_startup_command
import yokan.composeapp.generated.resources.ui_title_field
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
@Composable
internal fun CustomButtonsRoute(title: String, onBack: () -> Unit) {
val model = viewModel { CustomButtonsViewModel(YokanRuntime.database) }
val buttons by model.buttons.collectAsStateWithLifecycle()
CustomButtonsScreen(
title = title,
buttons = buttons,
onBack = onBack,
onSave = model::save,
onRemove = model::remove,
onMove = model::move,
onSetFavourite = model::setFavourite,
)
}
/** [buttons] are ordered by position. */
@Composable
internal fun CustomButtonsScreen(
title: String,
buttons: List<DbCustomButton>,
onBack: () -> Unit,
onSave: (DbCustomButton) -> Unit,
onRemove: (buttonId: Long) -> Unit,
onMove: (buttonId: Long, targetIndex: Int) -> Unit,
onSetFavourite: (buttonId: Long) -> Unit,
) {
var editing by remember { mutableStateOf<DbCustomButton?>(null) }
var creating by remember { mutableStateOf(false) }
var deleteTarget by remember { mutableStateOf<DbCustomButton?>(null) }
deleteTarget?.let { current ->
ConfirmDialog(
title = "Delete custom button",
message = "Delete \"${current.title ?: "Untitled"}\"?",
confirmLabel = stringResource(Res.string.delete),
danger = true,
onConfirm = { onRemove(current.id) },
onDismiss = { deleteTarget = null },
)
}
Scaffold(
topBar = { YokanTopBar(title = title, onBack = onBack) },
floatingActionButton = {
ExtendedFloatingActionButton(
onClick = { creating = true },
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
text = { Text(stringResource(Res.string.action_add)) },
)
},
) { padding ->
val listState = rememberLazyListState()
ScrollbarBox(
state = listState,
modifier = Modifier.fillMaxSize().padding(padding),
) {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(horizontal = 15.dp, vertical = 8.dp),
) {
if (buttons.isEmpty()) {
item {
Box(
Modifier.fillMaxWidth().height(240.dp),
contentAlignment = Alignment.Center,
) {
Text("Edit custom buttons", textAlign = TextAlign.Center)
}
}
}
if (buttons.isNotEmpty()) {
item(key = "custom-button-reorder") {
ReorderableColumn(
items = buttons,
key = { it.id },
onMove = { from, to -> onMove(buttons[from].id, to) },
) { button, dragHandle, isDragging ->
Surface(
tonalElevation = if (isDragging) 8.dp else 0.dp,
shadowElevation = if (isDragging) 4.dp else 0.dp,
) {
Column(modifier = Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(
modifier = Modifier.then(dragHandle).size(48.dp),
contentAlignment = Alignment.Center,
) {
Icon(Icons.Filled.DragHandle, contentDescription = "Reorder")
}
Text(
button.title ?: "Untitled",
modifier = Modifier.weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
IconButton(onClick = { onSetFavourite(button.id) }) {
Icon(
Icons.Filled.Star,
contentDescription = "Favourite",
tint = if (button.isFavourite) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.45f),
)
}
IconButton(onClick = { editing = button }) {
Icon(Icons.Filled.Edit, contentDescription = stringResource(Res.string.edit))
}
IconButton(onClick = { deleteTarget = button }) {
Icon(Icons.Filled.DeleteSweep, contentDescription = stringResource(Res.string.delete))
}
}
Text(
button.codePress.orEmpty(),
modifier = Modifier.padding(horizontal = 48.dp),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
}
}
}
}
}
if (creating) {
CustomButtonEditDialog(
initial = DbCustomButton(position = buttons.size),
onDismiss = { creating = false },
onSave = { button ->
onSave(button)
creating = false
},
)
}
editing?.let { current ->
CustomButtonEditDialog(
initial = current,
onDismiss = { editing = null },
onSave = { button ->
onSave(button)
editing = null
},
)
}
}
@Composable
private fun CustomButtonEditDialog(
initial: DbCustomButton,
onDismiss: () -> Unit,
onSave: (DbCustomButton) -> Unit,
) {
var titleField by remember(initial.id) { mutableStateOf(initial.title.orEmpty()) }
var press by remember(initial.id) { mutableStateOf(initial.codePress.orEmpty()) }
var longPress by remember(initial.id) { mutableStateOf(initial.codeLongPress) }
var startup by remember(initial.id) { mutableStateOf(initial.codeStartup) }
var favourite by remember(initial.id) { mutableStateOf(initial.isFavourite) }
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
confirmButton = {
Button(
onClick = {
onSave(
initial.copy(
title = titleField.ifBlank { null },
codePress = press.ifBlank { null },
codeLongPress = longPress,
codeStartup = startup,
isFavourite = favourite,
),
)
},
enabled = titleField.isNotBlank(),
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 8.dp),
) { Text(stringResource(Res.string.action_save)) }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
title = {
Text(
if (initial.id == 0L) "Add button" else "Edit button",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(value = titleField, onValueChange = { titleField = it }, singleLine = true, label = { Text(stringResource(Res.string.ui_title_field)) }, modifier = Modifier.fillMaxWidth())
OutlinedTextField(value = press, onValueChange = { press = it }, singleLine = false, label = { Text("Press command") }, modifier = Modifier.fillMaxWidth())
OutlinedTextField(value = longPress, onValueChange = { longPress = it }, singleLine = false, label = { Text("Long-press command") }, modifier = Modifier.fillMaxWidth())
OutlinedTextField(value = startup, onValueChange = { startup = it }, singleLine = false, label = { Text(stringResource(Res.string.ui_startup_command)) }, modifier = Modifier.fillMaxWidth())
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { favourite = !favourite },
verticalAlignment = Alignment.CenterVertically,
) {
Switch(checked = favourite, onCheckedChange = { favourite = it })
Spacer(Modifier.width(8.dp))
Text("Favourite (pin to player toolbar)")
}
}
},
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/player/CustomButtonsViewModel.kt
- Source · implementation · 55 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
15: internal class CustomButtonsViewModel(private val database: YokanDatabase) : ViewModel() {
24: fun save(button: DbCustomButton) = write { database.upsertCustomButton(button.copy(updatedAt = nowMillis())) }
26: fun remove(buttonId: Long) = write { database.removeCustomButton(buttonId) }
29: fun setFavourite(buttonId: Long) = write {
33: fun move(buttonId: Long, targetIndex: Int) = write {
45: private inline fun write(block: () -> Unit) {
50: private fun reload() {
54: private fun load(): List<DbCustomButton> = database.customButtons().sortedBy { it.position }
Exact file bytes / download · SHA-256 1f536f2a7947b32da889ba0c024e52ca3eb39c7477dc1a2898acac414a416da4.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.player
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.database.DbCustomButton
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.launch
/** Custom player buttons, ordered by position. */
internal class CustomButtonsViewModel(private val database: YokanDatabase) : ViewModel() {
private val _buttons = MutableStateFlow(load())
val buttons: StateFlow<List<DbCustomButton>> = _buttons.asStateFlow()
init {
// The player and the add-button deep link write buttons too.
viewModelScope.launch { database.snapshots().distinctUntilChangedBy { it.customButtons }.collect { reload() } }
}
fun save(button: DbCustomButton) = write { database.upsertCustomButton(button.copy(updatedAt = nowMillis())) }
fun remove(buttonId: Long) = write { database.removeCustomButton(buttonId) }
/** Makes [buttonId] the only favourite. */
fun setFavourite(buttonId: Long) = write {
_buttons.value.forEach { database.upsertCustomButton(it.copy(isFavourite = it.id == buttonId, updatedAt = nowMillis())) }
}
fun move(buttonId: Long, targetIndex: Int) = write {
val ordered = _buttons.value.toMutableList()
val index = ordered.indexOfFirst { it.id == buttonId }
val target = targetIndex.coerceIn(0, ordered.lastIndex.coerceAtLeast(0))
if (index < 0 || target == index) return@write
ordered.add(target, ordered.removeAt(index))
ordered.forEachIndexed { newIndex, button ->
if (button.position != newIndex) database.upsertCustomButton(button.copy(position = newIndex, updatedAt = nowMillis()))
}
}
// Writes publish synchronously so a dropped drag row never snaps back for a frame.
private inline fun write(block: () -> Unit) {
block()
reload()
}
private fun reload() {
_buttons.value = load()
}
private fun load(): List<DbCustomButton> = database.customButtons().sortedBy { it.position }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/player/PlayerAdvancedSettingsViewModel.kt
- Source · implementation · 32 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
16: internal class PlayerAdvancedSettingsViewModel(
23: fun redownloadMpvConfig() {
Exact file bytes / download · SHA-256 2161052d6383369bd7dfb4d4ad44d2689bbe2f854c643ccf78d57cb3cf0f1db3.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.player
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.media.player.DefaultMpvConf
import eu.friedcutlet.yokan.services.media.player.DefaultMpvInputConf
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
internal class PlayerAdvancedSettingsViewModel(
private val files: LocalFileService,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _redownloadStatus = MutableStateFlow<String?>(null)
val redownloadStatus: StateFlow<String?> = _redownloadStatus.asStateFlow()
fun redownloadMpvConfig() {
viewModelScope.launch {
withContext(workDispatcher) {
files.writeBytes("${files.cacheRoot}/mpv/mpv.conf", DefaultMpvConf.encodeToByteArray())
files.writeBytes("${files.cacheRoot}/mpv/input.conf", DefaultMpvInputConf.encodeToByteArray())
}
_redownloadStatus.value = "Wrote default mpv.conf and input.conf to ${files.cacheRoot}/mpv/"
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/player/PlayerSettingsScreens.kt
- Source · implementation · 308 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
70: internal fun PlayerOverviewScreen(title: String, onBack: () -> Unit, onOpen: (SettingsPage) -> Unit) {
82: internal fun InternalPlayerSettingsScreen(
143: internal fun PlayerDecoderSettingsScreen(
159: internal fun PlayerAudioSettingsScreen(
212: internal fun PlayerAdvancedSettingsRoute(
231: private fun PlayerAdvancedSettingsScreen(
283: private enum class PlayerListPreference(
Exact file bytes / download · SHA-256 b8ef01fecce347f34ca6fb8037468e23d965e09714dd7e3c8338fb3888f53c91.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.player
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbAudioChannel
import eu.friedcutlet.yokan.database.DbDebandingType
import eu.friedcutlet.yokan.database.DbL10nLocale
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbPlayerPreferences
import eu.friedcutlet.yokan.database.withPlayer
import eu.friedcutlet.yokan.services.media.player.ExternalPlayerChoice
import eu.friedcutlet.yokan.services.media.player.externalPlayerChoices
import eu.friedcutlet.yokan.services.media.player.parseSpeedPresets
import eu.friedcutlet.yokan.services.media.player.parseTermList
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.CustomButtons
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.Player
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.PlayerAdvanced
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.PlayerAudio
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.PlayerDecoder
import eu.friedcutlet.yokan.ui.screens.settings.ChoiceTile
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.RouteTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.TextInputDialog
import eu.friedcutlet.yokan.ui.screens.settings.appearance.languageLabel
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.debanding
import yokan.composeapp.generated.resources.default_subtitle_language
import yokan.composeapp.generated.resources.tile_aniskip
import yokan.composeapp.generated.resources.tile_aniskip_timeout
import yokan.composeapp.generated.resources.tile_audio_channel
import yokan.composeapp.generated.resources.tile_audio_pitch_correction
import yokan.composeapp.generated.resources.tile_auto_skip
import yokan.composeapp.generated.resources.tile_default_playback_speed
import yokan.composeapp.generated.resources.tile_default_skip_intro_length
import yokan.composeapp.generated.resources.tile_double_tap_skip_length
import yokan.composeapp.generated.resources.tile_enable_hardware_acceleration
import yokan.composeapp.generated.resources.tile_force_landscape
import yokan.composeapp.generated.resources.tile_force_yuv420p
import yokan.composeapp.generated.resources.tile_fullscreen_player
import yokan.composeapp.generated.resources.tile_gpu_next
import yokan.composeapp.generated.resources.tile_hardware_decoder
import yokan.composeapp.generated.resources.tile_mark_episode_as_seen
import yokan.composeapp.generated.resources.tile_use_libass
import yokan.composeapp.generated.resources.tile_use_mpv_config
@Composable
internal fun PlayerOverviewScreen(title: String, onBack: () -> Unit, onOpen: (SettingsPage) -> Unit) {
SettingsScaffold(title, onBack) {
item { RouteTile(Player, "Internal player", "Progress, controls, orientation", onOpen = onOpen) }
item { RouteTile(PlayerDecoder, "Decoder", "Hardware decoding, pixel format, debanding", onOpen = onOpen) }
item { RouteTile(PlayerAudio, "Video and audio", "Preferred languages, pitch correction, audio channels", onOpen = onOpen) }
item { RouteTile(CustomButtons, "Custom buttons", "Execute JavaScript with custom buttons", onOpen = onOpen) }
item { RouteTile(PlayerAdvanced, "Advanced", "mpv config", onOpen = onOpen) }
item { RouteTile(SettingsPage.Torrent, "Torrent streaming", "TorrServer, port, trackers, proxy", onOpen = onOpen) }
}
}
@Composable
internal fun InternalPlayerSettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val aniSkip = settings.enableAniSkip == true
val player = settings.features.player
val updatePlayer: ((DbPlayerPreferences) -> DbPlayerPreferences) -> Unit = { transform -> onUpdate { it.withPlayer(transform) } }
var editing by remember { mutableStateOf<PlayerListPreference?>(null) }
val externalPlayers = remember { externalPlayerChoices() }
editing?.let { preference ->
TextInputDialog(
title = preference.title,
initialValue = preference.read(player).joinToString(", "),
placeholder = preference.placeholder,
helperText = preference.helper,
onConfirm = { text -> preference.write(text)?.let { values -> updatePlayer { preference.store(it, values) } } },
onDismiss = { editing = null },
)
}
SettingsScaffold(title, onBack) {
val localeOptions = listOf<DbL10nLocale?>(null, DbL10nLocale("en"), DbL10nLocale("es"), DbL10nLocale("fr"), DbL10nLocale("pt"), DbL10nLocale("ja"))
item(key = "subtitle-language") { ChoiceTile(stringResource(Res.string.default_subtitle_language), localeOptions, settings.defaultSubtitleLang, { it.languageLabel() }) { value -> onUpdate { it.copy(defaultSubtitleLang = value) } } }
PlayerListPreference.entries.forEach { preference ->
item(key = preference.name) {
SettingTile(preference.title, preference.read(player).joinToString(", ").ifBlank { "None" }, onClick = { editing = preference })
}
}
item(key = "screenshot-subtitles") { SwitchTile("Include subtitles in screenshots", "mpv screenshots render the visible subtitles", player.screenshotSubtitles, { value -> updatePlayer { it.copy(screenshotSubtitles = value) } }) }
item { ChoiceTile(stringResource(Res.string.tile_mark_episode_as_seen), listOf(100, 95, 90, 85, 80, 75, 70), settings.markEpisodeAsSeenType, { "$it%" }) { value -> onUpdate { it.copy(markEpisodeAsSeenType = value) } } }
item { ChoiceTile(stringResource(Res.string.tile_default_skip_intro_length), (1..255).toList(), settings.defaultSkipIntroLength, { "${it}s" }) { value -> onUpdate { it.copy(defaultSkipIntroLength = value) } } }
item { ChoiceTile(stringResource(Res.string.tile_double_tap_skip_length), listOf(30, 20, 10, 5, 3, 1), settings.defaultDoubleTapToSkipLength, { "${it}s" }) { value -> onUpdate { it.copy(defaultDoubleTapToSkipLength = value) } } }
item(key = "playback-speed") { ChoiceTile(stringResource(Res.string.tile_default_playback_speed), (player.speedPresets + settings.defaultPlaybackSpeed).distinct().sorted(), settings.defaultPlaybackSpeed, { "x$it" }) { value -> onUpdate { it.copy(defaultPlaybackSpeed = value) } } }
item(key = "remember-volume") { SwitchTile("Remember volume", "Restore the last player volume in new sessions", player.rememberVolume, { value -> updatePlayer { it.copy(rememberVolume = value, volume = -1) } }) }
item(key = "remember-brightness") { SwitchTile("Remember brightness", "Restore the last player brightness in new sessions", player.rememberBrightness, { value -> updatePlayer { it.copy(rememberBrightness = value, brightness = -1f) } }) }
item(key = "switch-on-failure") { SwitchTile("Switch stream on failure", "Try the episode's next stream when playback fails", player.switchStreamOnFailure, { value -> updatePlayer { it.copy(switchStreamOnFailure = value) } }) }
item(key = "pip-enabled") { SwitchTile("Picture-in-picture", "Show the PiP button and enter PiP when leaving the app while playing", player.pipEnabled, { value -> updatePlayer { it.copy(pipEnabled = value) } }) }
item(key = "pip-exit") { SwitchTile("PiP on exit", "Back while playing enters PiP, or the mini player where the system has no PiP", player.pipOnExit, { value -> updatePlayer { it.copy(pipOnExit = value) } }) }
item(key = "pip-toasts") { SwitchTile("PiP episode notices", "Show the episode name when it changes in PiP", player.pipEpisodeToasts, { value -> updatePlayer { it.copy(pipEpisodeToasts = value) } }) }
item(key = "pip-previous") { SwitchTile("Replace +10 s with previous episode", "First PiP control", player.pipReplaceWithPrevious, { value -> updatePlayer { it.copy(pipReplaceWithPrevious = value) } }) }
if (externalPlayers.isEmpty()) {
item(key = "external-player") { InfoRow("This platform cannot launch external player apps.") }
} else {
val choices = listOf(ExternalPlayerChoice("", "Platform default")) + externalPlayers
item(key = "external-player") { ChoiceTile("External player", choices, choices.firstOrNull { it.id == player.externalPlayer } ?: choices.first(), { it.label }) { value -> updatePlayer { it.copy(externalPlayer = value.id) } } }
item(key = "always-external") { SwitchTile("Always use external player", "Open episodes in the external player instead of the built-in one", player.alwaysUseExternalPlayer, { value -> updatePlayer { it.copy(alwaysUseExternalPlayer = value) } }) }
}
item { SwitchTile(stringResource(Res.string.tile_use_libass), "Use libass based subtitle rendering for native backend.", settings.useLibass, { value -> onUpdate { it.copy(useLibass = value) } }) }
item(key = "aniskip") { SwitchTile(stringResource(Res.string.tile_aniskip), null, aniSkip, { value -> onUpdate { it.copy(enableAniSkip = value) } }) }
if (aniSkip) {
item { InfoRow("AniSkip requires the anime to be tracked with MyAnimeList or AniList to work.") }
item { SwitchTile(stringResource(Res.string.tile_auto_skip), null, settings.enableAutoSkip == true, { value -> onUpdate { it.copy(enableAutoSkip = value) } }) }
item { ChoiceTile(stringResource(Res.string.tile_aniskip_timeout), (5..10).toList(), settings.aniSkipTimeoutLength ?: 5, { "${it}s" }) { value -> onUpdate { it.copy(aniSkipTimeoutLength = value) } } }
}
item { SwitchTile(stringResource(Res.string.tile_fullscreen_player), "Automatically use fullscreen when playing a video.", settings.fullScreenPlayer, { value -> onUpdate { it.copy(fullScreenPlayer = value) } }) }
item { SwitchTile(stringResource(Res.string.tile_force_landscape), "Force the player to use landscape orientation.", settings.forceLandscapePlayer, { value -> onUpdate { it.copy(forceLandscapePlayer = value) } }) }
}
}
@Composable
internal fun PlayerDecoderSettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
SettingsScaffold(title, onBack) {
item(key = "hardware") { SwitchTile(stringResource(Res.string.tile_enable_hardware_acceleration), "Turn it on/off if you are experiencing bugs or crashes", settings.enableHardwareAcceleration == true, { value -> onUpdate { it.copy(enableHardwareAcceleration = value) } }) }
item(key = "hwdec") { ChoiceTile(stringResource(Res.string.tile_hardware_decoder), HwdecModes, settings.hwdecMode, { it }) { value -> onUpdate { it.copy(hwdecMode = value) } } }
item { SwitchTile(stringResource(Res.string.tile_gpu_next), "A new video rendering backend", settings.enableGpuNext, { value -> onUpdate { it.copy(enableGpuNext = value) } }) }
item { ChoiceTile(stringResource(Res.string.debanding), DbDebandingType.entries, settings.debandingType, { it.name }) { value -> onUpdate { it.copy(debandingType = value) } } }
item { SwitchTile(stringResource(Res.string.tile_force_yuv420p), "May fix black screens on some video codecs, can also improve performance at the cost of quality", settings.useYuv420p, { value -> onUpdate { it.copy(useYuv420p = value) } }) }
}
}
@Composable
internal fun PlayerAudioSettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
var langDialog by remember { mutableStateOf(false) }
val hapticFeedback = LocalHapticFeedback.current
val volumeCap = settings.volumeBoostCap ?: 30
if (langDialog) {
TextInputDialog(
title = "Preferred audio languages",
initialValue = settings.audioPreferredLanguages.orEmpty(),
placeholder = "jpn,eng",
onConfirm = { value -> onUpdate { it.copy(audioPreferredLanguages = value.trim().ifBlank { null }) } },
onDismiss = { langDialog = false },
)
}
SettingsScaffold(title, onBack) {
item {
SettingTile(
"Preferred audio languages",
settings.audioPreferredLanguages.orEmpty().ifBlank { "Default" },
onClick = { langDialog = true },
)
}
item { SwitchTile(stringResource(Res.string.tile_audio_pitch_correction), "Prevents the audio from becoming high-pitched at faster speeds and low-pitched at slower speeds", settings.enableAudioPitchCorrection == true, { value -> onUpdate { it.copy(enableAudioPitchCorrection = value) } }) }
item { ChoiceTile(stringResource(Res.string.tile_audio_channel), DbAudioChannel.entries, settings.audioChannels, { it.name }) { value -> onUpdate { it.copy(audioChannels = value) } } }
item {
Column(Modifier.padding(16.dp)) {
Text("Volume boost cap", fontWeight = FontWeight.Medium)
Text(volumeCap.toString(), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
Spacer(Modifier.height(20.dp))
Slider(
value = volumeCap.toFloat(),
onValueChange = { value ->
val nextCap = value.toInt().coerceIn(0, 200)
if (nextCap != volumeCap) {
hapticFeedback.performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)
}
onUpdate { it.copy(volumeBoostCap = nextCap) }
},
valueRange = 0f..200f,
steps = 199,
)
}
}
}
}
@Composable
internal fun PlayerAdvancedSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val model = viewModel { PlayerAdvancedSettingsViewModel(YokanRuntime.localFiles) }
val redownloadStatus by model.redownloadStatus.collectAsStateWithLifecycle()
PlayerAdvancedSettingsScreen(
title = title,
settings = settings,
redownloadStatus = redownloadStatus,
onUpdate = onUpdate,
onRedownloadMpvConfig = model::redownloadMpvConfig,
onBack = onBack,
)
}
@Composable
private fun PlayerAdvancedSettingsScreen(
title: String,
settings: DbSettings,
redownloadStatus: String?,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onRedownloadMpvConfig: () -> Unit,
onBack: () -> Unit,
) {
SettingsScaffold(title, onBack) {
item {
SwitchTile(
stringResource(Res.string.tile_use_mpv_config),
"Loads mpv.conf, input.conf, JavaScript scripts, and shaders from the mpv directory.",
settings.useMpvConfig,
{ value -> onUpdate { it.copy(useMpvConfig = value) } },
)
}
item {
SettingTile(
"Redownload mpv config files",
"Replaces old config files with new one!",
onClick = onRedownloadMpvConfig,
)
}
redownloadStatus?.let { msg ->
item {
Text(
msg,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
color = MaterialTheme.colorScheme.onSurfaceVariant,
style = MaterialTheme.typography.bodySmall,
)
}
}
}
}
private val HwdecModes = listOf(
"no",
"auto",
"d3d11va",
"d3d11va-copy",
"videotoolbox",
"videotoolbox-copy",
"nvdec",
"nvdec-copy",
"mediacodec",
"mediacodec-copy",
"crystalhd",
)
/** Comma-separated player list preferences edited through one text dialog. */
private enum class PlayerListPreference(
val title: String,
val placeholder: String,
val helper: String,
val read: (DbPlayerPreferences) -> List<Any>,
/** Null rejects the input and keeps the stored value. */
val write: (String) -> List<Any>?,
val store: (DbPlayerPreferences, List<Any>) -> DbPlayerPreferences,
) {
SpeedPresets(
"Playback speed presets", "0.5, 1, 1.5, 2", "Speeds from 0.25 to 4; an invalid list is ignored",
{ it.speedPresets }, ::parseSpeedPresets, { prefs, values -> prefs.copy(speedPresets = values.filterIsInstance<Double>()) },
),
SubtitleLanguages(
"Subtitle language priority", "en, ja", "Language codes or names, highest priority first",
{ it.subtitleLanguages }, ::parseTermList, { prefs, values -> prefs.copy(subtitleLanguages = values.filterIsInstance<String>()) },
),
SubtitleWhitelist(
"Preferred subtitle names", "Full, Signs", "Tracks whose name contains a term are preferred",
{ it.subtitleWhitelist }, ::parseTermList, { prefs, values -> prefs.copy(subtitleWhitelist = values.filterIsInstance<String>()) },
),
SubtitleBlacklist(
"Excluded subtitle names", "Forced, CC", "Tracks whose name contains a term are never auto-selected",
{ it.subtitleBlacklist }, ::parseTermList, { prefs, values -> prefs.copy(subtitleBlacklist = values.filterIsInstance<String>()) },
),
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/player/TorrentSettingsScreen.kt
- Source · implementation · 158 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
24: private enum class TorrentField(val title: String, val placeholder: String, val help: String? = null, val singleLine: Boolean = true) {
35: internal fun TorrentSettingsRoute(title: String, settings: DbSettings, onBack: () -> Unit) {
53: internal fun TorrentSettingsScreen(
Exact file bytes / download · SHA-256 dd15350cb6fe3a755a70b9d6716326e7afb4c062f41e929e1776f616b5af89a5.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.player
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbTorrentPreferences
import eu.friedcutlet.yokan.database.TorrServerMode
import eu.friedcutlet.yokan.database.TorrServerProxyMode
import eu.friedcutlet.yokan.ui.screens.settings.ButtonRow
import eu.friedcutlet.yokan.ui.screens.settings.ChoiceTile
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.TextInputDialog
private enum class TorrentField(val title: String, val placeholder: String, val help: String? = null, val singleLine: Boolean = true) {
Port("Port", "8090"),
Binary("TorrServer binary", "/path/to/TorrServer", "Leave empty to use the verified download."),
Url("Server URL", "http://192.168.1.10:8090", "TorrServer on another device, or the TorrServer app on this phone (http://127.0.0.1:8090). The web app needs https or localhost."),
User("Username", "Optional HTTP auth user"),
Password("Password", "Optional HTTP auth password"),
Trackers("Trackers", "udp://tracker.example:1337/announce", "One announce URL per line; pushed to the server's tracker list.", singleLine = false),
Proxy("Proxy URL", "socks5://user:password@127.0.0.1:1080"),
}
@Composable
internal fun TorrentSettingsRoute(title: String, settings: DbSettings, onBack: () -> Unit) {
val model = viewModel {
val owner = YokanRuntime.activeSession
TorrentSettingsViewModel(owner.settings, owner.services.torrents)
}
val state by model.state.collectAsStateWithLifecycle()
TorrentSettingsScreen(
title, settings.features.torrent, state,
onUpdate = model::update,
onCheck = model::check,
onResetTrackers = model::resetTrackers,
onInstall = model::install,
onStop = model::stop,
onBack = onBack,
)
}
@Composable
internal fun TorrentSettingsScreen(
title: String,
prefs: DbTorrentPreferences,
state: TorrentSettingsState,
onUpdate: ((DbTorrentPreferences) -> DbTorrentPreferences) -> Unit,
onCheck: () -> Unit,
onResetTrackers: () -> Unit,
onInstall: () -> Unit,
onStop: () -> Unit,
onBack: () -> Unit,
) {
var editing by remember { mutableStateOf<TorrentField?>(null) }
editing?.let { field ->
TextInputDialog(
title = field.title,
initialValue = when (field) {
TorrentField.Port -> prefs.port.toString()
TorrentField.Binary -> prefs.executablePath
TorrentField.Url -> prefs.remoteUrl
TorrentField.User -> prefs.username
TorrentField.Password -> prefs.password
TorrentField.Trackers -> prefs.trackers
TorrentField.Proxy -> prefs.proxyUrl
},
placeholder = field.placeholder,
helperText = field.help,
singleLine = field.singleLine,
onConfirm = { raw ->
val value = if (field == TorrentField.Trackers) raw else raw.trim()
onUpdate {
when (field) {
TorrentField.Port -> value.toIntOrNull()?.takeIf { port -> port in 1..65535 }?.let { port -> it.copy(port = port) } ?: it
TorrentField.Binary -> it.copy(executablePath = value)
TorrentField.Url -> it.copy(remoteUrl = value.trimEnd('/'))
TorrentField.User -> it.copy(username = value)
TorrentField.Password -> it.copy(password = value)
TorrentField.Trackers -> it.copy(trackers = value)
TorrentField.Proxy -> it.copy(proxyUrl = value)
}
}
},
onDismiss = { editing = null },
)
}
SettingsScaffold(title, onBack) {
item(key = "enabled") {
SwitchTile(
"Torrent streaming",
"Play and download magnet/.torrent videos through TorrServer. Streaming also uploads to other peers.",
prefs.enabled,
{ value -> onUpdate { it.copy(enabled = value) } },
)
}
item(key = "mode") {
ChoiceTile(
"Server",
TorrServerMode.entries.filter { it == TorrServerMode.Remote || state.canHost },
prefs.mode.takeIf { it == TorrServerMode.Remote || state.canHost },
{ if (it == TorrServerMode.Managed) "Run TorrServer on this device" else "Remote TorrServer" },
) { mode -> onUpdate { it.copy(mode = mode) } }
}
if (!state.canHost) item(key = "no-host") {
InfoRow("This platform cannot run TorrServer itself; connect to a TorrServer on your network or, on Android, the TorrServer app.")
}
if (prefs.mode == TorrServerMode.Managed && state.canHost) {
item(key = "status") { SettingTile("Status", state.hostStatus) }
item(key = "port") { SettingTile("Port", prefs.port.toString()) { editing = TorrentField.Port } }
item(key = "binary") {
SettingTile("TorrServer binary", state.installedPath ?: "Not installed") { editing = TorrentField.Binary }
}
if (prefs.executablePath.isBlank()) item(key = "install") {
ButtonRow(if (state.installedPath == null) "Download official TorrServer (~62 MB, GPL-3.0)" else "Verify/reinstall TorrServer", onClick = onInstall)
}
item(key = "stop") { ButtonRow("Stop TorrServer", onClick = onStop) }
} else {
item(key = "url") { SettingTile("Server URL", prefs.remoteUrl.ifBlank { "Not set" }) { editing = TorrentField.Url } }
item(key = "user") { SettingTile("Username", prefs.username.ifBlank { "None" }) { editing = TorrentField.User } }
item(key = "password") { SettingTile("Password", if (prefs.password.isBlank()) "None" else "••••••") { editing = TorrentField.Password } }
}
item(key = "trackers-section") { SettingsSection("Trackers") }
item(key = "trackers") {
SettingTile("Tracker list", "${prefs.trackers.lines().count(String::isNotBlank)} trackers") { editing = TorrentField.Trackers }
}
item(key = "trackers-reset") { ButtonRow("Reset tracker list", onClick = onResetTrackers) }
item(key = "proxy-section") { SettingsSection("Proxy") }
item(key = "proxy-mode") {
ChoiceTile("Proxy mode", TorrServerProxyMode.entries, prefs.proxyMode, {
when (it) {
TorrServerProxyMode.None -> "No proxy"
TorrServerProxyMode.Tracker -> "Trackers only"
TorrServerProxyMode.Peers -> "Peers and DHT"
TorrServerProxyMode.Full -> "All BitTorrent traffic"
}
}) { mode -> onUpdate { it.copy(proxyMode = mode) } }
}
item(key = "proxy-url") {
SettingTile("Proxy URL", prefs.proxyUrl.ifBlank { "Not set" }, enabled = prefs.proxyMode != TorrServerProxyMode.None) { editing = TorrentField.Proxy }
}
item(key = "proxy-note") {
InfoRow("The proxy is a TorrServer launch option: Yokan restarts its own server with it; a remote server needs --proxyurl/--proxymode where it runs.")
}
item(key = "check") { ButtonRow(if (state.busy) "Working…" else "Check server and apply trackers", onClick = onCheck) }
state.message?.let { message -> item(key = "message") { InfoRow(message) } }
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/player/TorrentSettingsViewModel.kt
- Source · implementation · 69 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
16: internal data class TorrentSettingsState(
25: internal class TorrentSettingsViewModel(
37: fun update(transform: (DbTorrentPreferences) -> DbTorrentPreferences) =
40: fun check() = run("Checking TorrServer…") { "Connected to TorrServer ${torrents.applySettings()}; trackers applied." }
42: fun resetTrackers() {
47: fun install() = run("Downloading TorrServer…") {
55: fun stop() = run("Stopping…") { torrents.stop(); "TorrServer stopped." }
57: fun dismissMessage() = _state.update { it.copy(message = null) }
59: private fun installed() = host?.executable(settings.db.value.features.torrent.executablePath)
61: private fun run(progress: String, action: suspend () -> String) {
Exact file bytes / download · SHA-256 139d878de34dcf6f06ef824768dbf10aaba994e361228c82dae0fcd0490c8471.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.player
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbTorrentPreferences
import eu.friedcutlet.yokan.database.DefaultTorrentTrackers
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.torrent.TorrentStreams
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
internal data class TorrentSettingsState(
val busy: Boolean = false,
val message: String? = null,
val hostStatus: String? = null,
val canHost: Boolean = false,
val installedPath: String? = null,
)
/** TorrServer install/check/stop; every check re-pushes the tracker list to the server. */
internal class TorrentSettingsViewModel(
private val settings: SettingsStore,
private val torrents: TorrentStreams,
) : ViewModel() {
private val host = torrents.host
private val _state = MutableStateFlow(TorrentSettingsState(canHost = host != null, installedPath = installed()))
val state: StateFlow<TorrentSettingsState> = _state.asStateFlow()
init {
host?.let { viewModelScope.launch { it.status.collect { status -> _state.update { s -> s.copy(hostStatus = status) } } } }
}
fun update(transform: (DbTorrentPreferences) -> DbTorrentPreferences) =
settings.updateDb { it.copy(features = it.features.copy(torrent = transform(it.features.torrent))) }
fun check() = run("Checking TorrServer…") { "Connected to TorrServer ${torrents.applySettings()}; trackers applied." }
fun resetTrackers() {
update { it.copy(trackers = DefaultTorrentTrackers) }
if (settings.db.value.features.torrent.enabled) check()
}
fun install() = run("Downloading TorrServer…") {
val path = checkNotNull(host).install { done, total ->
if (total > 0) _state.update { it.copy(message = "Downloading TorrServer… ${done * 100 / total}%") }
}
_state.update { it.copy(installedPath = path) }
"TorrServer installed and verified: $path"
}
fun stop() = run("Stopping…") { torrents.stop(); "TorrServer stopped." }
fun dismissMessage() = _state.update { it.copy(message = null) }
private fun installed() = host?.executable(settings.db.value.features.torrent.executablePath)
private fun run(progress: String, action: suspend () -> String) {
if (_state.value.busy) return
_state.update { it.copy(busy = true, message = progress) }
viewModelScope.launch {
val message = catchingNonCancellation { action() }.getOrElse { it.message ?: "TorrServer request failed" }
_state.update { it.copy(busy = false, message = message, installedPath = installed()) }
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/reader/ReaderSettingsScreen.kt
- Source · implementation · 131 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
69: internal fun ReaderSettingsScreen(
119: private fun LazyListScope.readerModeItems(paged: Boolean, settings: DbSettings, onUpdate: ((DbSettings) -> DbSettings) -> Unit) {
Exact file bytes / download · SHA-256 48de003c6da134a98d751576f9fbe586e09ec1b5198cf99b502d1cd46ca203ed.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.reader
import androidx.compose.runtime.Composable
import androidx.compose.foundation.lazy.LazyListScope
import eu.friedcutlet.yokan.database.DbBackgroundColor
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbReaderModePreferences
import eu.friedcutlet.yokan.database.DbScaleType
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.readerModePreferences
import eu.friedcutlet.yokan.database.withReader
import eu.friedcutlet.yokan.database.withReaderModePreferences
import yokan.composeapp.generated.resources.reader_always_show_transition
import yokan.composeapp.generated.resources.reader_always_show_transition_hint
import yokan.composeapp.generated.resources.reader_chapter_navigation
import yokan.composeapp.generated.resources.reader_invert_rotation
import yokan.composeapp.generated.resources.reader_invert_split
import yokan.composeapp.generated.resources.reader_invert_volume_keys
import yokan.composeapp.generated.resources.reader_paged_section
import yokan.composeapp.generated.resources.reader_rotate_wide_pages
import yokan.composeapp.generated.resources.reader_rotate_wide_pages_hint
import yokan.composeapp.generated.resources.reader_save_title_folder
import yokan.composeapp.generated.resources.reader_save_title_folder_hint
import yokan.composeapp.generated.resources.reader_skip_filtered
import yokan.composeapp.generated.resources.reader_skip_filtered_hint
import yokan.composeapp.generated.resources.reader_skip_read
import yokan.composeapp.generated.resources.reader_split_wide_pages
import yokan.composeapp.generated.resources.reader_split_wide_pages_hint
import yokan.composeapp.generated.resources.reader_volume_keys
import yokan.composeapp.generated.resources.reader_volume_keys_hint
import yokan.composeapp.generated.resources.reader_webtoon_section
import eu.friedcutlet.yokan.database.chapterReleasePreference
import eu.friedcutlet.yokan.database.withChapterReleasePreference
import eu.friedcutlet.yokan.database.movedScanlator
import eu.friedcutlet.yokan.ui.screens.detail.ScanlatorPriorityControls
import androidx.compose.ui.Modifier
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.unit.dp
import yokan.composeapp.generated.resources.releases_default_section
import eu.friedcutlet.yokan.ui.screens.settings.ChoiceTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.animate_page_transitions
import yokan.composeapp.generated.resources.background_color
import yokan.composeapp.generated.resources.crop_borders
import yokan.composeapp.generated.resources.default_reading_mode
import yokan.composeapp.generated.resources.double_tap_animation_speed
import yokan.composeapp.generated.resources.grayscale
import yokan.composeapp.generated.resources.invert_colors
import yokan.composeapp.generated.resources.keep_screen_on
import yokan.composeapp.generated.resources.page_preload_amount
import yokan.composeapp.generated.resources.scale_type
import yokan.composeapp.generated.resources.show_page_gaps
import yokan.composeapp.generated.resources.show_page_number
import yokan.composeapp.generated.resources.tile_auto_read_duplicate_chapters
import yokan.composeapp.generated.resources.tile_full_screen_reader
import yokan.composeapp.generated.resources.use_page_tap_zones
import yokan.composeapp.generated.resources.reader_layout_automatic
import yokan.composeapp.generated.resources.reader_layout_help
import yokan.composeapp.generated.resources.reader_hold_to_scroll
import yokan.composeapp.generated.resources.reader_hold_help
import yokan.composeapp.generated.resources.reader_layout_fallback
import yokan.composeapp.generated.resources.webtoon_side_padding
@Composable
internal fun ReaderSettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
scanlators: List<String> = emptyList(),
) {
val reader = settings.features.reader
SettingsScaffold(title, onBack) {
item(key = "release-defaults") {
SettingsSection(stringResource(Res.string.releases_default_section))
val preference = settings.chapterReleasePreference(null)
ScanlatorPriorityControls(preference.scanlatorPriority, scanlators + "", preference.skipDuplicateReleases,
onSkipDuplicates = { value -> onUpdate { db -> db.withChapterReleasePreference(db.chapterReleasePreference(null).copy(skipDuplicateReleases = value)) } },
onMove = { group, direction -> onUpdate { db ->
val current = db.chapterReleasePreference(null)
db.withChapterReleasePreference(current.copy(scanlatorPriority = movedScanlator(current.scanlatorPriority, scanlators + "", group, direction)))
} }, modifier = Modifier.padding(horizontal = 16.dp))
}
item { SettingsSection("Reading") }
item(key = "hold-to-scroll") { SwitchTile(stringResource(Res.string.reader_hold_to_scroll), stringResource(Res.string.reader_hold_help), settings.readerHoldToScroll, { value -> onUpdate { it.copy(readerHoldToScroll = value) } }) }
item(key = "automatic-layout") { SwitchTile(stringResource(Res.string.reader_layout_automatic), stringResource(Res.string.reader_layout_help), settings.automaticReaderLayout, { value -> onUpdate { it.copy(automaticReaderLayout = value) } }) }
item(key = "reader-mode") { ChoiceTile(stringResource(if (settings.automaticReaderLayout) Res.string.reader_layout_fallback else Res.string.default_reading_mode), DbReaderMode.entries, settings.defaultReaderMode, { it.name }) { value -> onUpdate { it.copy(defaultReaderMode = value) } } }
item { ChoiceTile(stringResource(Res.string.double_tap_animation_speed), listOf(0, 1, 2), settings.doubleTapAnimationSpeed.coerceIn(0, 2), { listOf("No animation", "Normal", "Fast")[it] }) { value -> onUpdate { it.copy(doubleTapAnimationSpeed = value) } } }
item { ChoiceTile(stringResource(Res.string.background_color), DbBackgroundColor.entries, settings.backgroundColor, { it.name }) { value -> onUpdate { it.copy(backgroundColor = value) } } }
item(key = "preload") { ChoiceTile(stringResource(Res.string.page_preload_amount), (1..10).toList(), settings.pagePreloadAmount, { "$it pages" }) { value -> onUpdate { it.copy(pagePreloadAmount = value) } } }
item { ChoiceTile(stringResource(Res.string.scale_type), DbScaleType.entries, settings.scaleType, { it.name }) { value -> onUpdate { it.copy(scaleType = value) } } }
item { SettingsSection("Display") }
item { SwitchTile(stringResource(Res.string.tile_full_screen_reader), "Use the full screen while reading", settings.fullScreenReader, { value -> onUpdate { it.copy(fullScreenReader = value) } }) }
item { SwitchTile(stringResource(Res.string.show_page_gaps), null, settings.showPageGaps, { value -> onUpdate { it.copy(showPageGaps = value) } }) }
item { SwitchTile(stringResource(Res.string.show_page_number), null, settings.showPagesNumber, { value -> onUpdate { it.copy(showPagesNumber = value) } }) }
item { ChoiceTile(stringResource(Res.string.webtoon_side_padding), listOf(0, 8, 16, 24, 32, 48), settings.webtoonSidePadding, { "${it}px" }) { value -> onUpdate { it.copy(webtoonSidePadding = value) } } }
item { SwitchTile(stringResource(Res.string.invert_colors), null, settings.invertColors, { value -> onUpdate { it.copy(invertColors = value) } }) }
item { SwitchTile(stringResource(Res.string.grayscale), null, settings.grayscale, { value -> onUpdate { it.copy(grayscale = value) } }) }
item { SettingsSection("Behavior") }
item { SwitchTile(stringResource(Res.string.keep_screen_on), null, settings.keepScreenOnReader, { value -> onUpdate { it.copy(keepScreenOnReader = value) } }) }
item { SwitchTile(stringResource(Res.string.tile_auto_read_duplicate_chapters), "Mark duplicate chapters as read automatically", settings.autoReadDuplicateChapters, { value -> onUpdate { it.copy(autoReadDuplicateChapters = value) } }) }
item(key = "save-title-folder") { SwitchTile(stringResource(Res.string.reader_save_title_folder), stringResource(Res.string.reader_save_title_folder_hint), reader.saveImagesInTitleFolder, { value -> onUpdate { db -> db.withReader { it.copy(saveImagesInTitleFolder = value) } } }) }
item(key = "volume-keys") { SwitchTile(stringResource(Res.string.reader_volume_keys), stringResource(Res.string.reader_volume_keys_hint), reader.volumeKeyNavigation, { value -> onUpdate { db -> db.withReader { it.copy(volumeKeyNavigation = value) } } }) }
if (reader.volumeKeyNavigation) item(key = "invert-volume-keys") { SwitchTile(stringResource(Res.string.reader_invert_volume_keys), null, reader.invertVolumeKeys, { value -> onUpdate { db -> db.withReader { it.copy(invertVolumeKeys = value) } } }) }
item(key = "chapter-navigation") { SettingsSection(stringResource(Res.string.reader_chapter_navigation)) }
item(key = "skip-read") { SwitchTile(stringResource(Res.string.reader_skip_read), null, reader.skipReadChapters, { value -> onUpdate { db -> db.withReader { it.copy(skipReadChapters = value) } } }) }
item(key = "skip-filtered") { SwitchTile(stringResource(Res.string.reader_skip_filtered), stringResource(Res.string.reader_skip_filtered_hint), reader.skipFilteredChapters, { value -> onUpdate { db -> db.withReader { it.copy(skipFilteredChapters = value) } } }) }
item(key = "always-transition") { SwitchTile(stringResource(Res.string.reader_always_show_transition), stringResource(Res.string.reader_always_show_transition_hint), reader.alwaysShowChapterTransition, { value -> onUpdate { db -> db.withReader { it.copy(alwaysShowChapterTransition = value) } } }) }
readerModeItems(paged = true, settings, onUpdate)
readerModeItems(paged = false, settings, onUpdate)
}
}
/** Settings that differ between paged and continuous readers; untouched groups follow the legacy globals. */
private fun LazyListScope.readerModeItems(paged: Boolean, settings: DbSettings, onUpdate: ((DbSettings) -> DbSettings) -> Unit) {
val mode = settings.readerModePreferences(paged)
val group = if (paged) "paged" else "webtoon"
val update: ((DbReaderModePreferences) -> DbReaderModePreferences) -> Unit = { transform -> onUpdate { it.withReaderModePreferences(paged, transform) } }
item(key = "$group-section") { SettingsSection(stringResource(if (paged) Res.string.reader_paged_section else Res.string.reader_webtoon_section)) }
item(key = "$group-animate") { SwitchTile(stringResource(Res.string.animate_page_transitions), null, mode.animatePageTransitions, { value -> update { it.copy(animatePageTransitions = value) } }) }
item(key = "$group-tap-zones") { SwitchTile(stringResource(Res.string.use_page_tap_zones), null, mode.usePageTapZones, { value -> update { it.copy(usePageTapZones = value) } }) }
item(key = "$group-crop") { SwitchTile(stringResource(Res.string.crop_borders), null, mode.cropBorders, { value -> update { it.copy(cropBorders = value) } }) }
item(key = "$group-split") { SwitchTile(stringResource(Res.string.reader_split_wide_pages), stringResource(Res.string.reader_split_wide_pages_hint), mode.splitWidePages, { value -> update { it.copy(splitWidePages = value) } }) }
if (mode.splitWidePages) item(key = "$group-split-invert") { SwitchTile(stringResource(Res.string.reader_invert_split), null, mode.invertSplit, { value -> update { it.copy(invertSplit = value) } }) }
item(key = "$group-rotate") { SwitchTile(stringResource(Res.string.reader_rotate_wide_pages), stringResource(Res.string.reader_rotate_wide_pages_hint), mode.rotateWidePages, { value -> update { it.copy(rotateWidePages = value) } }) }
if (mode.rotateWidePages) item(key = "$group-rotate-invert") { SwitchTile(stringResource(Res.string.reader_invert_rotation), null, mode.invertRotation, { value -> update { it.copy(invertRotation = value) } }) }
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/security/SecuritySettingsScreen.kt
- Source · implementation · 146 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
37: internal fun SecuritySettingsRoute(
49: internal fun SecuritySettingsScreen(
59: fun update(transform: (DbPrivacyPreferences) -> DbPrivacyPreferences) {
135: private fun lockTimeoutLabel(minutes: Int): String = when (minutes) {
142: private fun secureScreenLabel(mode: DbSecureScreen): String = when (mode) {
Exact file bytes / download · SHA-256 9ed3925d7882c69230e68c72f000cd12b02e036a23567787dd463af8e6a675d9.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.security
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.AppLockTimeoutChoices
import eu.friedcutlet.yokan.database.DbCategory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbPrivacyPreferences
import eu.friedcutlet.yokan.database.DbSecureScreen
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.ui.screens.settings.ChoiceTile
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.downloads.PolicyCategoryTile
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.app_lock
import yokan.composeapp.generated.resources.app_lock_description
import yokan.composeapp.generated.resources.biometric_or_device_credential_not_available
import yokan.composeapp.generated.resources.require_biometric_or_device_credential
import eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider as HorizontalDivider
@Composable
internal fun SecuritySettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
) {
val sources = remember { YokanRuntime.database.sources().filter { it.isAdded } }
val appLock = YokanRuntime.appLock
SecuritySettingsScreen(title, settings, sources, onUpdate, onBack, appLock.isSupported, appLock::requestUnlock)
}
@Composable
internal fun SecuritySettingsScreen(
title: String,
settings: DbSettings,
sources: List<DbSource>,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
canAuth: Boolean,
onRequestUnlock: (onResult: (Boolean) -> Unit) -> Unit,
) {
val privacy = settings.features.privacy
fun update(transform: (DbPrivacyPreferences) -> DbPrivacyPreferences) {
onUpdate { it.copy(features = it.features.copy(privacy = transform(it.features.privacy))) }
}
val subtitle = if (canAuth) {
stringResource(Res.string.require_biometric_or_device_credential)
} else {
stringResource(Res.string.biometric_or_device_credential_not_available)
}
SettingsScaffold(title, onBack) {
item { SettingsSection("App lock") }
item(key = "lock") {
SwitchTile(
stringResource(Res.string.app_lock),
subtitle,
settings.appLockEnabled,
{ desired ->
if (!canAuth) return@SwitchTile
onRequestUnlock { authenticated ->
if (authenticated) {
onUpdate { it.copy(appLockEnabled = desired) }
}
}
},
enabled = canAuth,
)
}
item(key = "lock-timeout") {
ChoiceTile("Lock when idle", AppLockTimeoutChoices, privacy.appLockTimeoutMinutes, ::lockTimeoutLabel, enabled = canAuth && settings.appLockEnabled) { minutes ->
onRequestUnlock { ok -> if (ok) update { it.copy(appLockTimeoutMinutes = minutes) } }
}
}
item { SettingsSection("Privacy") }
item(key = "secure-screen") {
ChoiceTile("Secure screen", DbSecureScreen.entries, privacy.secureScreen, ::secureScreenLabel) { mode -> update { it.copy(secureScreen = mode) } }
}
item(key = "secure-screen-info") {
InfoRow("Android blocks screenshots and recents previews. iOS covers the app switcher preview and screen recording; screenshots cannot be blocked. Desktop and web cannot hide windows from capture.")
}
item(key = "hide-notification-content") {
SwitchTile("Hide notification content", "Notifications show no titles", privacy.hideNotificationContent, { value -> update { it.copy(hideNotificationContent = value) } })
}
item(key = "incognito-sources") {
// The category picker renders any id/name list; sources reuse it.
PolicyCategoryTile(
title = "Incognito sources",
categories = sources.map { DbCategory(id = it.id, name = "${it.name} (${it.lang})", forItemType = DbItemType.Manga) },
selected = privacy.incognitoSourceIds,
allWhenEmpty = false,
label = { it.name },
) { ids -> update { it.copy(incognitoSourceIds = ids) } }
}
item(key = "incognito-sources-info") {
InfoRow("Titles from incognito sources leave no history or reading progress and stay private on Discord.")
}
item { HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) }
item {
ListItem(
headlineContent = {
Text(
stringResource(Res.string.app_lock_description),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
leadingContent = {
Icon(
Icons.Filled.Info,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
)
},
)
}
}
}
private fun lockTimeoutLabel(minutes: Int): String = when (minutes) {
0 -> "Always"
-1 -> "Never"
1 -> "After 1 minute"
else -> "After $minutes minutes"
}
private fun secureScreenLabel(mode: DbSecureScreen): String = when (mode) {
DbSecureScreen.Never -> "Never"
DbSecureScreen.Incognito -> "In incognito mode"
DbSecureScreen.Always -> "Always"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/statistics/StatisticsScreen.kt
- Source · implementation · 585 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
74: private fun stage(progress: Float, start: Float, span: Float): Float =
78: internal fun StatisticsSettingsRoute(title: String, initialItemType: ItemType, onBack: () -> Unit) {
97: internal fun StatisticsDashboard(
137: private fun StatisticsContent(state: StatisticsState, data: StatisticsData) {
166: private class Panel(val weight: Float = 1f, val content: @Composable (Modifier) -> Unit)
169: private fun PanelRows(rows: List<List<Panel>>) {
182: private fun ChartPanel(
205: private fun ActivityPanel(days: List<Int>, modifier: Modifier) {
246: private fun HourPanel(hourly: List<Int>, modifier: Modifier) {
263: fun direction(hour: Int): Offset {
287: private fun TopTitlesPanel(items: List<History>, modifier: Modifier) {
315: private fun ChaptersPanel(data: StatisticsData, anime: Boolean, modifier: Modifier) {
352: private fun LibraryPanel(data: StatisticsData, modifier: Modifier) {
396: private fun GenresPanel(genres: List<Pair<String, Int>>, modifier: Modifier) {
437: internal fun layoutTreemap(values: List<Int>, bounds: Rect): List<Rect> {
439: fun place(from: Int, to: Int, rect: Rect) {
460: private fun GrowthPanel(growth: List<Int>, modifier: Modifier) {
496: private fun CollectionPanel(data: StatisticsData, modifier: Modifier) {
525: private fun StoragePanel(state: StatisticsState, modifier: Modifier) {
563: private fun CountUp(target: Int, reveal: () -> Float, style: TextStyle, format: @Composable (Int) -> String) {
568: private fun Legend(label: String, value: String, color: Color) {
577: private fun statisticsDuration(seconds: Long): String = when {
585: private fun secondTone(): Color = lerp(MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.surfaceContainerHighest, 0.5f)
Exact file bytes / download · SHA-256 3745f65ab9b01855251878da60775511a3ef6cbd673f8a2b70fa6a981efc954f.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.statistics
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.EaseOutQuart
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.layout.onVisibilityChanged
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.ui.components.YokanChipTabs
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.data.formatBytes
import kotlin.math.PI
import kotlin.math.ceil
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
import org.jetbrains.compose.resources.pluralStringResource
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
/** One linear clock per chart; each mark eases in on its own slice of it. */
private const val REVEAL_MS = 1000
private fun stage(progress: Float, start: Float, span: Float): Float =
EaseOutQuart.transform(((progress - start) / span).coerceIn(0f, 1f))
@Composable
internal fun StatisticsSettingsRoute(title: String, initialItemType: ItemType, onBack: () -> Unit) {
val model = viewModel {
StatisticsViewModel(
initialItemType,
YokanRuntime.repository,
YokanRuntime.settings,
YokanRuntime.libraryIndex,
YokanRuntime.localFiles,
)
}
val state by model.state.collectAsStateWithLifecycle()
SettingsScaffold(title, onBack) {
item(key = "statistics", contentType = "dashboard") {
StatisticsDashboard(state, onSelect = model::select, onRetry = model::refresh)
}
}
}
@Composable
internal fun StatisticsDashboard(
state: StatisticsState,
modifier: Modifier = Modifier,
onSelect: (ItemType) -> Unit = {},
onRetry: () -> Unit = {},
) {
Column(modifier.fillMaxWidth().wrapContentWidth(Alignment.CenterHorizontally).widthIn(max = 1040.dp)
.padding(horizontal = 20.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(24.dp)) {
YokanChipTabs(ItemType.entries.map { it.label }, ItemType.entries.indexOf(state.type),
{ onSelect(ItemType.entries[it]) })
// Fade-through between media types and load phases; same-phase data updates morph in place instead.
AnimatedContent(
targetState = state,
contentKey = { Triple(it.type, it.data != null, it.failed) },
transitionSpec = {
(fadeIn(tween(220, delayMillis = 90)) + scaleIn(tween(220, delayMillis = 90), initialScale = 0.98f))
.togetherWith(fadeOut(tween(90))).using(SizeTransform(clip = false))
},
label = "statistics content",
) { shown ->
val data = shown.data
when {
shown.failed -> Column {
Text(stringResource(Res.string.stats_error))
TextButton(onClick = onRetry) { Text(stringResource(Res.string.stats_retry)) }
}
data == null -> {
val loading = stringResource(Res.string.stats_loading)
Box(Modifier.fillMaxWidth().height(240.dp), contentAlignment = Alignment.Center) {
CircularProgressIndicator(Modifier.size(28.dp).semantics { contentDescription = loading }, strokeWidth = 2.5.dp)
}
}
else -> StatisticsContent(shown, data)
}
}
Spacer(Modifier.height(8.dp))
}
}
@Composable
private fun StatisticsContent(state: StatisticsState, data: StatisticsData) {
val anime = state.type == ItemType.Anime
val empty = data.titles == 0 && data.activeTitles == 0
Column(verticalArrangement = Arrangement.spacedBy(32.dp)) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(stringResource(if (anime) Res.string.stats_title_watch else Res.string.stats_title_read),
style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold,
modifier = Modifier.semantics { heading() })
Text(
if (empty) stringResource(Res.string.stats_empty)
else pluralStringResource(Res.plurals.stats_subtitle, data.activeTitles, statisticsDuration(data.seconds), data.activeTitles),
style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
val activity = Panel(1.65f) { ActivityPanel(data.dailyActivity, it) }
val rows = if (empty) listOf(listOf(activity)) else listOf(
listOf(activity, Panel { HourPanel(data.hourly, it) }),
listOfNotNull(data.mostTime.takeIf { it.isNotEmpty() }?.let { top -> Panel { TopTitlesPanel(top, it) } },
Panel { ChaptersPanel(data, anime, it) }),
listOfNotNull(Panel { LibraryPanel(data, it) },
data.genres.takeIf { it.isNotEmpty() }?.let { genres -> Panel { GenresPanel(genres, it) } }),
listOfNotNull(data.growth.takeIf { it.size >= 2 && it.last() > 0 }?.let { growth -> Panel { GrowthPanel(growth, it) } },
Panel { CollectionPanel(data, it) }),
listOf(Panel { StoragePanel(state, it) }),
)
PanelRows(rows)
}
}
private class Panel(val weight: Float = 1f, val content: @Composable (Modifier) -> Unit)
@Composable
private fun PanelRows(rows: List<List<Panel>>) {
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = maxWidth >= 720.dp
Column(verticalArrangement = Arrangement.spacedBy(40.dp)) {
if (wide) rows.forEach { row ->
Row(horizontalArrangement = Arrangement.spacedBy(36.dp)) { row.forEach { it.content(Modifier.weight(it.weight)) } }
} else rows.flatten().forEach { it.content(Modifier) }
}
}
}
/** Starts the chart's reveal clock the first time a quarter of it is on screen, so off-screen charts still animate. */
@Composable
private fun ChartPanel(
title: String,
modifier: Modifier = Modifier,
trailing: String? = null,
content: @Composable (reveal: () -> Float) -> Unit,
) {
val reveal = remember { Animatable(0f) }
var seen by remember { mutableStateOf(false) }
LaunchedEffect(seen) { if (seen) reveal.animateTo(1f, tween(REVEAL_MS, easing = LinearEasing)) }
Column(modifier.fillMaxWidth().onVisibilityChanged(minFractionVisible = 0.25f) { visible -> if (visible) seen = true },
verticalArrangement = Arrangement.spacedBy(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(title, Modifier.weight(1f).semantics { heading() }, style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold)
if (trailing != null) Text(trailing, style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
content { reveal.value }
}
}
/** Calendar heatmap; the colour washes in as a diagonal wave across the already-drawn grid. */
@Composable
private fun ActivityPanel(days: List<Int>, modifier: Modifier) {
BoxWithConstraints(modifier.fillMaxWidth()) {
val gap = 3.dp
val weeks = (days.size + 6) / 7
val cols = ((maxWidth + gap) / (11.dp + gap)).toInt().coerceIn(1, weeks)
val cell = ((maxWidth - gap * (cols - 1)) / cols).coerceAtMost(22.dp)
val shown = days.drop((weeks - cols) * 7)
val max = (shown.maxOrNull() ?: 0).coerceAtLeast(1)
val activeDays = shown.count { it > 0 }
val track = MaterialTheme.colorScheme.surfaceContainerHighest
val ink = MaterialTheme.colorScheme.primary
val description = stringResource(Res.string.stats_activity_description, activeDays, cols)
ChartPanel(stringResource(Res.string.stats_activity),
trailing = pluralStringResource(Res.plurals.stats_active_days, activeDays, activeDays)) { reveal ->
Canvas(Modifier.size(cell * cols + gap * (cols - 1), cell * 7 + gap * 6)
.clearAndSetSemantics { contentDescription = description }) {
val c = cell.toPx()
val g = gap.toPx()
val radius = CornerRadius(c * 0.28f)
val p = reveal()
shown.forEachIndexed { i, value ->
val col = i / 7
val row = i % 7
val topLeft = Offset(col * (c + g), row * (c + g))
drawRoundRect(track, topLeft, Size(c, c), radius)
val t = if (value > 0) stage(p, (col + row * 0.6f) / (cols + 3.6f) * 0.6f, 0.4f) else 0f
if (t > 0f) {
val level = ceil(value * 4f / max) / 4f
val s = c * (0.4f + 0.6f * t)
drawRoundRect(lerp(track, ink, 0.25f + 0.75f * level), topLeft + Offset((c - s) / 2, (c - s) / 2),
Size(s, s), CornerRadius(s * 0.28f), alpha = t)
}
if (i == shown.lastIndex) drawRoundRect(ink, topLeft, Size(c, c), radius, style = Stroke(1.5.dp.toPx()))
}
}
}
}
}
/** 24-hour radial bars; rays grow outward, sweeping clockwise from midnight. */
@Composable
private fun HourPanel(hourly: List<Int>, modifier: Modifier) {
val peak = hourly.indices.maxByOrNull { hourly[it] }?.takeIf { hourly[it] > 0 }
val peakLabel = peak?.let { "${it.toString().padStart(2, '0')}:00" }
val description = peakLabel?.let { stringResource(Res.string.stats_peak_description, it) } ?: stringResource(Res.string.stats_no_activity)
ChartPanel(stringResource(Res.string.stats_time_of_day), modifier) { reveal ->
val measurer = rememberTextMeasurer()
val tickStyle = MaterialTheme.typography.labelSmall.copy(color = MaterialTheme.colorScheme.onSurfaceVariant)
val ink = MaterialTheme.colorScheme.primary
val track = MaterialTheme.colorScheme.surfaceContainerHighest
Box(Modifier.fillMaxWidth().clearAndSetSemantics { contentDescription = description }, contentAlignment = Alignment.Center) {
Canvas(Modifier.widthIn(max = 204.dp).fillMaxWidth().aspectRatio(1f)) {
val radius = size.minDimension / 2
val inner = radius * 0.38f
val outer = radius * 0.8f
val max = (hourly.maxOrNull() ?: 0).coerceAtLeast(1)
val stroke = (2 * PI * inner / 24 * 0.55).toFloat()
val p = reveal()
fun direction(hour: Int): Offset {
val angle = (hour * 15f - 90f) * PI.toFloat() / 180f
return Offset(cos(angle), sin(angle))
}
hourly.forEachIndexed { hour, value ->
val dir = direction(hour)
val start = center + dir * inner
drawLine(track, start, center + dir * outer, stroke, StrokeCap.Round, alpha = 0.55f)
val length = (outer - inner) * value / max * stage(p, hour / 24f * 0.45f, 0.55f)
if (length > 0f) drawLine(if (hour == peak) ink else ink.copy(alpha = 0.5f), start, start + dir * length,
stroke, StrokeCap.Round)
}
listOf(0, 6, 12, 18).forEach { hour ->
val layout = measurer.measure(hour.toString(), tickStyle)
drawText(layout, topLeft = center + direction(hour) * (radius * 0.93f) -
Offset(layout.size.width / 2f, layout.size.height / 2f))
}
}
Text(peakLabel ?: "—", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
}
}
}
@Composable
private fun TopTitlesPanel(items: List<History>, modifier: Modifier) {
ChartPanel(stringResource(Res.string.stats_top_titles), modifier) { reveal ->
val max = items.first().readingTimeSeconds.toFloat().coerceAtLeast(1f)
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
items.forEachIndexed { index, history ->
val fraction by animateFloatAsState(history.readingTimeSeconds / max, tween(450), label = "title time")
val color = if (index == 0) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.secondary
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
Text(history.title.ifBlank { stringResource(Res.string.stats_untitled) }, Modifier.weight(1f),
maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Medium)
Text(statisticsDuration(history.readingTimeSeconds.toLong()), style = MaterialTheme.typography.labelLarge)
}
Canvas(Modifier.fillMaxWidth().height(10.dp).clearAndSetSemantics { }) {
val radius = CornerRadius(size.height / 2)
drawRoundRect(color.copy(alpha = 0.12f), cornerRadius = radius)
val width = size.width * fraction * stage(reveal(), index * 0.08f, 0.6f)
if (width > 0f) drawRoundRect(color, size = Size(width.coerceAtLeast(size.height), size.height), cornerRadius = radius)
}
}
}
}
}
}
/** 10×10 waffle that fills from the bottom row up, one square per percent. */
@Composable
private fun ChaptersPanel(data: StatisticsData, anime: Boolean, modifier: Modifier) {
val rate = if (data.chapters > 0) data.read.toFloat() / data.chapters else 0f
val animatedRate by animateFloatAsState(rate, tween(450), label = "completion")
val description = stringResource(Res.string.stats_completion_description, data.read, data.chapters)
ChartPanel(stringResource(if (anime) Res.string.stats_episodes else Res.string.stats_chapters), modifier,
trailing = stringResource(Res.string.stats_fraction, data.read, data.chapters)) { reveal ->
val ink = MaterialTheme.colorScheme.primary
val track = MaterialTheme.colorScheme.surfaceContainerHighest
Row(horizontalArrangement = Arrangement.spacedBy(24.dp), verticalAlignment = Alignment.CenterVertically) {
Canvas(Modifier.size(156.dp).clearAndSetSemantics { contentDescription = description }) {
val g = 3.dp.toPx()
val c = (size.width - g * 9) / 10
val radius = CornerRadius(c * 0.25f)
val filled = (animatedRate * 100).roundToInt()
val p = reveal()
for (k in 0 until 100) {
val topLeft = Offset(k % 10 * (c + g), (9 - k / 10) * (c + g))
drawRoundRect(track, topLeft, Size(c, c), radius)
val t = if (k < filled) stage(p, k / 100f * 0.6f, 0.4f) else 0f
if (t > 0f) drawRoundRect(ink, topLeft, Size(c, c), radius, alpha = t)
}
}
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
if (data.chapters == 0) Text("—", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
else CountUp((rate * 100).roundToInt(), reveal, MaterialTheme.typography.headlineMedium) {
stringResource(Res.string.stats_percent, it)
}
Legend(stringResource(if (anime) Res.string.stats_seen else Res.string.stats_read), data.read.toString(), ink)
Legend(stringResource(if (anime) Res.string.stats_unseen else Res.string.stats_unread),
(data.chapters - data.read).toString(), MaterialTheme.colorScheme.outline)
}
}
}
}
/** Segmented donut; one sweep draws the segments in order. */
@Composable
private fun LibraryPanel(data: StatisticsData, modifier: Modifier) {
val labels = listOf(stringResource(Res.string.stats_caught_up), stringResource(Res.string.stats_in_progress),
stringResource(Res.string.stats_not_started))
val values = listOf(data.caughtUp, data.inProgress, data.notStarted)
val colors = listOf(MaterialTheme.colorScheme.primary, secondTone(), MaterialTheme.colorScheme.outline)
val fractions = values.mapIndexed { index, value ->
animateFloatAsState(if (data.titles > 0) value.toFloat() / data.titles else 0f, tween(450), label = "library $index")
}
val description = stringResource(Res.string.stats_library_description, data.caughtUp, data.inProgress, data.notStarted)
ChartPanel(stringResource(Res.string.stats_library), modifier) { reveal ->
val track = MaterialTheme.colorScheme.surfaceContainerHighest
Row(horizontalArrangement = Arrangement.spacedBy(24.dp), verticalAlignment = Alignment.CenterVertically) {
Box(Modifier.size(156.dp).clearAndSetSemantics { contentDescription = description }, contentAlignment = Alignment.Center) {
Canvas(Modifier.fillMaxSize()) {
val stroke = 18.dp.toPx()
val topLeft = Offset(stroke / 2, stroke / 2)
val arcSize = Size(size.width - stroke, size.height - stroke)
drawArc(track, 0f, 360f, false, topLeft, arcSize, style = Stroke(stroke))
val drawn = 360f * stage(reveal(), 0f, 0.85f)
val gap = if (values.count { it > 0 } > 1) 3f else 0f
var start = 0f
fractions.forEachIndexed { index, fraction ->
val sweep = 360f * fraction.value
val visible = (drawn - start).coerceIn(0f, sweep)
if (visible > gap) drawArc(colors[index], start - 90f + gap / 2, visible - gap, false, topLeft, arcSize,
style = Stroke(stroke))
start += sweep
}
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
CountUp(data.titles, reveal, MaterialTheme.typography.headlineMedium) { it.toString() }
Text(pluralStringResource(Res.plurals.stats_titles_unit, data.titles), style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
labels.forEachIndexed { index, label -> Legend(label, values[index].toString(), colors[index]) }
}
}
}
}
/** Treemap of the most common genres; cells settle in, largest first. */
@Composable
private fun GenresPanel(genres: List<Pair<String, Int>>, modifier: Modifier) {
ChartPanel(stringResource(Res.string.stats_genres), modifier) { reveal ->
val measurer = rememberTextMeasurer()
val scheme = MaterialTheme.colorScheme
val palette = listOf(scheme.primaryContainer to scheme.onPrimaryContainer,
scheme.secondaryContainer to scheme.onSecondaryContainer, scheme.tertiaryContainer to scheme.onTertiaryContainer)
val nameStyle = MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.SemiBold)
val countStyle = MaterialTheme.typography.labelMedium
val description = genres.joinToString { "${it.first} ${it.second}" }
Canvas(Modifier.fillMaxWidth().height(208.dp).clearAndSetSemantics { contentDescription = description }) {
val gap = 3.dp.toPx()
val pad = 10.dp.toPx()
val radius = CornerRadius(10.dp.toPx())
val p = reveal()
layoutTreemap(genres.map { it.second }, Rect(Offset.Zero, size)).forEachIndexed { index, bounds ->
val t = stage(p, index * 0.07f, 0.5f)
if (t <= 0f) return@forEachIndexed
val (fill, ink) = if (index == 0) scheme.primary to scheme.onPrimary else palette[(index - 1) % palette.size]
val cell = bounds.deflate(gap / 2)
scale(0.9f + 0.1f * t, pivot = cell.center) {
drawRoundRect(fill, cell.topLeft, cell.size, radius, alpha = t)
val room = (cell.width - pad * 2).toInt().coerceAtLeast(0)
val full = measurer.measure(genres[index].first, nameStyle, maxLines = 1)
// Only ellipsize when there is room for a readable stem; tiny cells stay unlabeled.
if (cell.height > 44.dp.toPx() && (full.size.width <= room || cell.width > 88.dp.toPx())) {
val name = if (full.size.width <= room) full else measurer.measure(genres[index].first, nameStyle,
TextOverflow.Ellipsis, maxLines = 1, constraints = Constraints(maxWidth = room))
drawText(name, ink, Offset(cell.left + pad, cell.top + pad), alpha = t)
drawText(measurer.measure(genres[index].second.toString(), countStyle), ink,
Offset(cell.left + pad, cell.top + pad + name.size.height), alpha = t * 0.8f)
}
}
}
}
}
}
/**
* Binary-split treemap: [values] sorted largest first, each rect's area proportional to its value.
* ponytail: halves by weight instead of squarifying; fine for ≤8 cells, squarify if more genres are shown.
*/
internal fun layoutTreemap(values: List<Int>, bounds: Rect): List<Rect> {
val out = arrayOfNulls<Rect>(values.size)
fun place(from: Int, to: Int, rect: Rect) {
if (to - from == 1) { out[from] = rect; return }
val total = (from until to).sumOf { values[it].toLong() }.toFloat().coerceAtLeast(1f)
var mid = from + 1
var head = values[from].toFloat()
while (mid < to - 1 && head + values[mid] <= total / 2) head += values[mid++]
val f = head / total
if (rect.width >= rect.height) {
val x = rect.left + rect.width * f
place(from, mid, Rect(rect.left, rect.top, x, rect.bottom)); place(mid, to, Rect(x, rect.top, rect.right, rect.bottom))
} else {
val y = rect.top + rect.height * f
place(from, mid, Rect(rect.left, rect.top, rect.right, y)); place(mid, to, Rect(rect.left, y, rect.right, rect.bottom))
}
}
if (values.isNotEmpty()) place(0, values.size, bounds)
return out.map { checkNotNull(it) }
}
/** Cumulative library size; the line draws left to right with a dot riding its tip. */
@Composable
private fun GrowthPanel(growth: List<Int>, modifier: Modifier) {
val description = stringResource(Res.string.stats_growth_description, growth.first(), growth.last(), growth.size)
ChartPanel(stringResource(Res.string.stats_growth), modifier,
trailing = stringResource(Res.string.stats_growth_delta, growth.last() - growth.first())) { reveal ->
val ink = MaterialTheme.colorScheme.primary
val grid = MaterialTheme.colorScheme.outlineVariant
val surface = MaterialTheme.colorScheme.surface
Canvas(Modifier.fillMaxWidth().height(168.dp).clearAndSetSemantics { contentDescription = description }) {
val max = growth.max().coerceAtLeast(1).toFloat()
val top = 8.dp.toPx()
val height = size.height - top
val step = size.width / (growth.size - 1)
val points = growth.mapIndexed { i, v -> Offset(i * step, top + height * (1 - v / max)) }
for (k in 0..2) {
val y = top + height * k / 2f
drawLine(grid, Offset(0f, y), Offset(size.width, y), 1.dp.toPx(), alpha = 0.6f)
}
val line = Path().apply { moveTo(points[0].x, points[0].y); points.drop(1).forEach { lineTo(it.x, it.y) } }
val area = Path().apply { addPath(line); lineTo(size.width, size.height); lineTo(0f, size.height); close() }
val t = stage(reveal(), 0f, 0.85f)
clipRect(right = size.width * t) {
drawPath(area, Brush.verticalGradient(listOf(ink.copy(alpha = 0.26f), ink.copy(alpha = 0f)), top, size.height))
drawPath(line, ink, style = Stroke(2.5.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
}
if (t > 0f) {
val x = size.width * t
val i = (x / step).toInt().coerceAtMost(points.size - 2)
val tip = Offset(x, points[i].y + (points[i + 1].y - points[i].y) * ((x - i * step) / step))
drawCircle(surface, 6.dp.toPx(), tip)
drawCircle(ink, 4.dp.toPx(), tip)
}
}
}
}
@Composable
private fun CollectionPanel(data: StatisticsData, modifier: Modifier) {
val items = listOf(Res.string.stats_downloaded to data.downloadedTitles, Res.string.stats_local to data.localTitles,
Res.string.stats_tracked to data.trackedTitles)
val color = MaterialTheme.colorScheme.primary
ChartPanel(stringResource(Res.string.stats_collection), modifier) { reveal ->
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
items.forEachIndexed { index, (label, count) ->
val fraction by animateFloatAsState(if (data.titles > 0) count.toFloat() / data.titles else 0f, tween(450),
label = "collection $index")
// One hue: the columns share a denominator (library size), so colour would imply categories that aren't there.
Column(Modifier.weight(1f).semantics(mergeDescendants = true) { }, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)) {
CountUp(count, reveal, MaterialTheme.typography.titleLarge) { it.toString() }
Canvas(Modifier.width(44.dp).height(112.dp)) {
val radius = CornerRadius(10.dp.toPx())
drawRoundRect(color.copy(alpha = 0.12f), cornerRadius = radius)
val height = size.height * fraction * stage(reveal(), index * 0.1f, 0.6f)
if (height > 0f) drawRoundRect(color, Offset(0f, size.height - height), Size(size.width, height), radius)
}
Text(stringResource(label), style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
}
/** Stacked bar of downloads vs local files; pulses while the disk scan runs. */
@Composable
private fun StoragePanel(state: StatisticsState, modifier: Modifier) {
val downloads = state.downloadBytes
val local = state.localBytes
val total = (downloads ?: 0L) + (local ?: 0L)
val loading = (downloads == null || local == null) && !state.storageFailed
val downloadShare by animateFloatAsState(if (total > 0) (downloads ?: 0L).toFloat() / total else 0f, tween(600), label = "download share")
val localShare by animateFloatAsState(if (total > 0) (local ?: 0L).toFloat() / total else 0f, tween(600), label = "local share")
ChartPanel(stringResource(Res.string.stats_storage), modifier, trailing = if (loading) null else formatBytes(total)) { reveal ->
val primary = MaterialTheme.colorScheme.primary
val localTone = secondTone()
val track = MaterialTheme.colorScheme.surfaceContainerHighest
val pulse = if (loading) {
val transition = rememberInfiniteTransition(label = "storage scan")
transition.animateFloat(0.45f, 1f, infiniteRepeatable(tween(800), RepeatMode.Reverse), label = "storage pulse")
} else null
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
Canvas(Modifier.fillMaxWidth().height(16.dp).clearAndSetSemantics { }) {
val bar = Path().apply { addRoundRect(RoundRect(Rect(Offset.Zero, size), CornerRadius(size.height / 2))) }
clipPath(bar) {
drawRect(track, alpha = pulse?.value ?: 1f)
val t = stage(reveal(), 0f, 0.8f)
val first = size.width * downloadShare * t
drawRect(primary, size = Size(first, size.height))
drawRect(localTone, Offset(first, 0f), Size(size.width * localShare * t, size.height))
}
}
FlowRow(horizontalArrangement = Arrangement.spacedBy(28.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Legend(stringResource(Res.string.stats_download_storage), downloads?.let(::formatBytes) ?: "—", primary)
Legend(stringResource(Res.string.stats_local_storage), local?.let(::formatBytes) ?: "—", localTone)
}
if (state.storageFailed) Text(stringResource(Res.string.stats_storage_error), style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
/** Counts up with the chart's reveal; isolated so only this text recomposes per frame. */
@Composable
private fun CountUp(target: Int, reveal: () -> Float, style: TextStyle, format: @Composable (Int) -> String) {
Text(format((target * stage(reveal(), 0f, 0.8f)).roundToInt()), style = style, fontWeight = FontWeight.Bold)
}
@Composable
private fun Legend(label: String, value: String, color: Color) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Box(Modifier.size(8.dp).clip(CircleShape).background(color))
Text(label, style = MaterialTheme.typography.bodyMedium)
Text(value, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold)
}
}
@Composable
private fun statisticsDuration(seconds: Long): String = when {
seconds >= 3600 -> stringResource(Res.string.stats_hours_minutes, seconds / 3600, seconds % 3600 / 60)
seconds >= 60 -> stringResource(Res.string.stats_minutes, seconds / 60)
else -> stringResource(Res.string.stats_seconds, seconds)
}
/** A lighter step of primary that stays distinct from it in every Flex scheme, unlike tertiary on blue themes. */
@Composable
private fun secondTone(): Color = lerp(MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.surfaceContainerHighest, 0.5f)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/statistics/StatisticsViewModel.kt
- Source · implementation · 216 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
43: internal data class StatisticsData(
68: internal fun summarizeStatistics(
77: fun local(millis: Long) = kotlin.time.Instant.fromEpochMilliseconds(millis).toLocalDateTime(zone)
100: fun monthIndex(millis: Long) = local(millis).let { it.year * 12 + it.month.number - 1 }
129: internal data class StatisticsState(
138: internal class StatisticsViewModel(
198: fun select(type: ItemType) {
204: fun refresh() = retries.update { it + 1 }
206: private fun summarize(type: ItemType, index: LibraryIndex): StatisticsData {
Exact file bytes / download · SHA-256 8fcbeb593495b753eee7530a21e9ee5032fd47c7c9215feb560f82a3762f84b4.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.statistics
import kotlinx.coroutines.CoroutineDispatcher
import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.configuredLocalFolders
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Status
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.download.downloadStorageRootCandidates
import eu.friedcutlet.yokan.services.files.LocalFileService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.datetime.TimeZone
import kotlinx.datetime.isoDayNumber
import kotlinx.datetime.number
import kotlinx.datetime.toLocalDateTime
import eu.friedcutlet.yokan.util.nowMillis
/** Weeks of activity kept for the heatmap; the UI shows the most recent weeks that fit. */
internal const val ACTIVITY_WEEKS = 26
private const val GROWTH_MONTHS = 24
private const val TOP_GENRES = 8
@Immutable
internal data class StatisticsData(
val titles: Int,
val chapters: Int,
val read: Int,
val caughtUp: Int,
val inProgress: Int,
val notStarted: Int,
val localTitles: Int,
val downloadedTitles: Int,
val trackedTitles: Int,
val seconds: Long,
val activeTitles: Int,
val mostTime: List<History>,
/** Titles last active per day, oldest first: starts on a Monday, ends today. */
val dailyActivity: List<Int>,
/** Titles last active per local hour of day (24 entries). */
val hourly: List<Int>,
/** Most common library genres, largest first. */
val genres: List<Pair<String, Int>>,
/** Library size at the end of each month, oldest first, ending this month. */
val growth: List<Int>,
)
/** History is one accumulated record per title, not a log of reading sessions. */
@OptIn(kotlin.time.ExperimentalTime::class)
internal fun summarizeStatistics(
titles: List<Manga>,
chapters: Map<Long, List<Chapter>>,
history: List<History>,
downloadedIds: Set<Long>,
trackedIds: Set<Long>,
now: Long = nowMillis(),
zone: TimeZone = TimeZone.currentSystemDefault(),
): StatisticsData {
fun local(millis: Long) = kotlin.time.Instant.fromEpochMilliseconds(millis).toLocalDateTime(zone)
val library = titles.filter { it.favorite }
val libraryChapters = library.flatMap { chapters[it.id].orEmpty() }
val caughtUp = library.count { title ->
chapters[title.id].orEmpty().let { it.isNotEmpty() && it.all(Chapter::isRead) }
}
val inProgress = library.count { title ->
chapters[title.id].orEmpty().let { rows ->
rows.any { it.isRead || it.lastPageRead.toFloatOrNull()?.let { page -> page > 0 } == true } &&
!rows.all(Chapter::isRead)
}
}
val today = local(now).date
val todayDay = today.toEpochDays()
val firstDay = todayDay - (today.dayOfWeek.isoDayNumber - 1) - (ACTIVITY_WEEKS - 1) * 7L
val daily = IntArray((todayDay - firstDay + 1).toInt())
val hourly = IntArray(24)
history.filter { it.updatedAt > 0 }.forEach {
val at = local(it.updatedAt)
hourly[at.hour]++
val day = at.date.toEpochDays()
if (day in firstDay..todayDay) daily[(day - firstDay).toInt()]++
}
fun monthIndex(millis: Long) = local(millis).let { it.year * 12 + it.month.number - 1 }
val nowMonth = monthIndex(now)
val addedMonths = library.map { if (it.dateAddedMillis > 0) monthIndex(it.dateAddedMillis) else Int.MIN_VALUE }
val firstMonth = maxOf(addedMonths.filter { it != Int.MIN_VALUE }.minOrNull() ?: nowMonth, nowMonth - GROWTH_MONTHS + 1)
val growth = (firstMonth..nowMonth).map { month -> addedMonths.count { it <= month } }
val genres = library.flatMap { title -> title.genres.map(String::trim).filter(String::isNotEmpty).distinctBy(String::lowercase) }
.groupBy(String::lowercase).values.map { it.first() to it.size }
.sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() }).take(TOP_GENRES)
return StatisticsData(
titles = library.size,
chapters = libraryChapters.size,
read = libraryChapters.count(Chapter::isRead),
caughtUp = caughtUp,
inProgress = inProgress,
notStarted = library.size - caughtUp - inProgress,
localTitles = library.count { it.isLocalArchive },
downloadedTitles = library.count { chapters[it.id].orEmpty().any { chapter -> chapter.id in downloadedIds } },
trackedTitles = library.count { it.id in trackedIds },
seconds = history.sumOf { it.readingTimeSeconds.coerceAtLeast(0).toLong() },
activeTitles = history.map { it.mangaId }.distinct().size,
mostTime = history.filter { it.readingTimeSeconds > 0 }.sortedByDescending { it.readingTimeSeconds }.take(5),
dailyActivity = daily.toList(),
hourly = hourly.toList(),
genres = genres,
growth = growth,
)
}
@Immutable
internal data class StatisticsState(
val type: ItemType,
val data: StatisticsData? = null,
val failed: Boolean = false,
val downloadBytes: Long? = null,
val localBytes: Long? = null,
val storageFailed: Boolean = false,
)
internal class StatisticsViewModel(
initialType: ItemType,
private val repository: YokanRepository,
private val settings: SettingsStore,
libraryIndex: LibraryIndexStore,
private val files: LocalFileService,
private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
private val _state = MutableStateFlow(StatisticsState(initialType))
val state = _state.asStateFlow()
private val selectedType = MutableStateFlow(initialType)
private val retries = MutableStateFlow(0)
init {
viewModelScope.launch {
combine(
selectedType,
retries,
// Empty is the placeholder before the first build, not an empty library.
libraryIndex.index.filter { it !== LibraryIndex.Empty },
repository.snapshots.distinctUntilChanged { old, new -> old.mangas === new.mangas && old.histories === new.histories },
) { type, _, index, _ -> type to index }.collectLatest { (type, index) ->
_state.update { it.copy(failed = false) }
val data = withContext(workDispatcher) { catchingNonCancellation { summarize(type, index) } }
_state.update { current ->
if (current.type != type) current else data.fold({ current.copy(data = it) }, { current.copy(failed = true) })
}
}
}
// Disk scanning must not delay rendering the charts.
viewModelScope.launch {
combine(
selectedType,
retries,
settings.db.map { Triple(it.downloadLocation, it.namedLocalFolders, it.localFolders) }.distinctUntilChanged(),
repository.snapshots.distinctUntilChanged { old, new -> old.downloads === new.downloads },
) { type, _, _, _ -> type }.collectLatest { type ->
_state.update { it.copy(storageFailed = false, downloadBytes = null, localBytes = null) }
val db = settings.db.value
val sizes = withContext(workDispatcher) {
catchingNonCancellation {
val location = db.downloadLocation.ifBlank { files.downloadRoot }
downloadStorageRootCandidates(location, files).sumOf { files.directorySize("$it/${type.name}") } to
db.configuredLocalFolders().sumOf { files.directorySize(it.path) }
}
}
_state.update { current ->
if (current.type != type) {
current
} else {
sizes.fold(
{ current.copy(downloadBytes = it.first, localBytes = it.second) },
{ current.copy(storageFailed = true) },
)
}
}
}
}
}
fun select(type: ItemType) {
if (type == selectedType.value) return
_state.value = StatisticsState(type)
selectedType.value = type
}
fun refresh() = retries.update { it + 1 }
private fun summarize(type: ItemType, index: LibraryIndex): StatisticsData {
val titles = repository.allTitles(type).filter { it.favorite }
return summarizeStatistics(
titles,
titles.associate { it.id to index.chapters(it.id) },
repository.history().filter { it.itemType == type },
index.downloadedChapterIds,
index.trackedMangaIds,
)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/sync/SyncDialogs.kt
- Source · implementation · 244 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
52: internal data class HubServerChoice(val name: String, val url: String, val removable: Boolean)
56: internal fun SyncLoginDialog(
72: fun submitLogin() {
184: internal fun CloudProviderConnectDialog(
193: fun submit() {
Exact file bytes / download · SHA-256 be4222cf1bc7a1c12ccd796c414b962a3fb901e1fc87c8d6d48fee85b2aa6131.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.sync
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.services.sync.CloudProviderDescriptor
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.password
import yokan.composeapp.generated.resources.ui_server_url
import yokan.composeapp.generated.resources.ui_username_optional
import yokan.composeapp.generated.resources.sync_email
import yokan.composeapp.generated.resources.sync_username
/** One row of the server dropdown; only servers the user added can be removed. */
internal data class HubServerChoice(val name: String, val url: String, val removable: Boolean)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun SyncLoginDialog(
provider: SyncServerProvider,
initialServer: String,
initialEmail: String,
servers: List<HubServerChoice>,
/** Null where the platform browser cannot report the pages it loads (the web build). */
onBrowserLogin: ((server: String) -> Unit)?,
onRemoveServer: (url: String) -> Unit,
onDismiss: () -> Unit,
onSubmit: (server: String, email: String, password: String) -> Unit,
) {
var server by remember { mutableStateOf(initialServer.ifBlank { servers.firstOrNull()?.url.orEmpty() }) }
var email by remember(provider) { mutableStateOf(initialEmail) }
var password by remember { mutableStateOf("") }
var serversOpen by remember { mutableStateOf(false) }
val canSubmit = server.isNotBlank() && email.isNotBlank() && password.isNotBlank()
fun submitLogin() {
if (!canSubmit) return
onSubmit(server, email, password)
onDismiss()
}
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = {
Text(
"Sign in to sync server",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
// Editable: pick a listed server or type any URL (kept in the list after a successful sign-in).
ExposedDropdownMenuBox(expanded = serversOpen && servers.isNotEmpty(), onExpandedChange = { serversOpen = it }) {
OutlinedTextField(
value = server,
onValueChange = { server = it },
label = { Text(stringResource(Res.string.ui_server_url)) },
singleLine = true,
shape = MaterialTheme.shapes.large,
trailingIcon = { if (servers.isNotEmpty()) ExposedDropdownMenuDefaults.TrailingIcon(expanded = serversOpen) },
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable),
)
ExposedDropdownMenu(expanded = serversOpen && servers.isNotEmpty(), onDismissRequest = { serversOpen = false }) {
servers.forEach { choice ->
DropdownMenuItem(
text = {
Column {
Text(choice.name)
if (choice.name != choice.url) {
Text(choice.url, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
},
onClick = {
server = choice.url
serversOpen = false
},
trailingIcon = if (choice.removable) {
{ IconButton(onClick = { onRemoveServer(choice.url) }) { Icon(Icons.Filled.Close, contentDescription = "Remove ${choice.url}") } }
} else {
null
},
)
}
}
}
OutlinedTextField(
value = email,
onValueChange = { email = it },
label = { Text(if (provider == SyncServerProvider.Mangayomi) stringResource(Res.string.sync_username) else stringResource(Res.string.sync_email)) },
singleLine = true,
shape = MaterialTheme.shapes.large,
modifier = Modifier.fillMaxWidth(),
)
var passwordVisible by remember { mutableStateOf(false) }
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text(stringResource(Res.string.password)) },
singleLine = true,
shape = MaterialTheme.shapes.large,
modifier = Modifier.fillMaxWidth(),
visualTransformation = if (passwordVisible)
VisualTransformation.None
else
PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
autoCorrectEnabled = false,
imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(onDone = { submitLogin() }),
trailingIcon = {
IconButton(onClick = { passwordVisible = !passwordVisible }) {
Icon(
imageVector = if (passwordVisible) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
contentDescription = if (passwordVisible) "Hide password" else "Show password",
)
}
},
)
if (onBrowserLogin != null) {
TextButton(
onClick = {
onBrowserLogin(server)
onDismiss()
},
enabled = server.isNotBlank(),
) { Text("Sign in in browser instead") }
}
}
},
confirmButton = {
Button(
onClick = { submitLogin() },
enabled = canSubmit,
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp),
) { Text("Log in", style = MaterialTheme.typography.labelLarge) }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
)
}
@Composable
internal fun CloudProviderConnectDialog(
provider: CloudProviderDescriptor,
initialAccount: String,
onDismiss: () -> Unit,
onSubmit: (accountLabel: String?, accessToken: String) -> Unit,
) {
var account by remember(provider.id) { mutableStateOf(initialAccount) }
var accessToken by remember(provider.id) { mutableStateOf("") }
val canSubmit = accessToken.isNotBlank()
fun submit() {
if (!canSubmit) return
onSubmit(account.ifBlank { null }, accessToken)
onDismiss()
}
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = {
Text(
"Connect ${provider.displayName}",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
provider.authInstructions,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedTextField(
value = account,
onValueChange = { account = it },
label = { Text(stringResource(Res.string.ui_username_optional)) },
singleLine = true,
shape = MaterialTheme.shapes.large,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = accessToken,
onValueChange = { accessToken = it.trim() },
label = { Text("OAuth access token") },
singleLine = true,
shape = MaterialTheme.shapes.large,
modifier = Modifier.fillMaxWidth(),
)
}
},
confirmButton = {
Button(
onClick = { submit() },
enabled = canSubmit,
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp),
) { Text("Connect", style = MaterialTheme.typography.labelLarge) }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/sync/SyncProviderDialogs.kt
- Source · implementation · 139 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
42: internal fun SyncYomiLoginDialog(
63: internal fun GoogleDriveSignInDialog(
102: private fun ProviderDialog(
129: private fun ProviderField(value: String, onValueChange: (String) -> Unit, label: String, secret: Boolean = false) {
Exact file bytes / download · SHA-256 a33b934e617c80b0a95cb50e9febaef215425773e01d318e078c1b32f1c02974.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.sync
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.sync_google_drive_client_id
import yokan.composeapp.generated.resources.sync_google_drive_client_secret
import yokan.composeapp.generated.resources.sync_google_drive_instructions
import yokan.composeapp.generated.resources.sync_google_drive_open_sign_in
import yokan.composeapp.generated.resources.sync_google_drive_paste
import yokan.composeapp.generated.resources.sync_google_drive_state
import yokan.composeapp.generated.resources.sync_syncyomi
import yokan.composeapp.generated.resources.sync_syncyomi_api_key
import yokan.composeapp.generated.resources.sync_syncyomi_host
@Composable
internal fun SyncYomiLoginDialog(
initialHost: String,
onDismiss: () -> Unit,
onSubmit: (host: String, apiKey: String) -> Unit,
) {
var host by remember { mutableStateOf(initialHost) }
var apiKey by remember { mutableStateOf("") }
ProviderDialog(
title = stringResource(Res.string.sync_syncyomi),
confirmLabel = "Connect",
canSubmit = host.isNotBlank() && apiKey.isNotBlank(),
onDismiss = onDismiss,
onSubmit = { onSubmit(host.trim(), apiKey.trim()) },
) {
ProviderField(host, { host = it }, stringResource(Res.string.sync_syncyomi_host))
ProviderField(apiKey, { apiKey = it }, stringResource(Res.string.sync_syncyomi_api_key), secret = true)
}
}
/** Two steps: open Google's consent page for the entered client, then paste the loopback address it ends on. */
@Composable
internal fun GoogleDriveSignInDialog(
initialClientId: String,
onOpenSignIn: (clientId: String) -> String?,
onDismiss: () -> Unit,
onSubmit: (clientId: String, clientSecret: String, pasted: String) -> Unit,
) {
var clientId by remember { mutableStateOf(initialClientId) }
var clientSecret by remember { mutableStateOf("") }
var pasted by remember { mutableStateOf("") }
var signInUrl by remember { mutableStateOf<String?>(null) }
ProviderDialog(
title = stringResource(Res.string.sync_google_drive_state),
confirmLabel = "Sign in",
canSubmit = signInUrl != null && clientId.isNotBlank() && pasted.isNotBlank(),
onDismiss = onDismiss,
onSubmit = { onSubmit(clientId.trim(), clientSecret.trim(), pasted.trim()) },
) {
Text(
stringResource(Res.string.sync_google_drive_instructions),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
ProviderField(clientId, { clientId = it; signInUrl = null }, stringResource(Res.string.sync_google_drive_client_id))
ProviderField(clientSecret, { clientSecret = it }, stringResource(Res.string.sync_google_drive_client_secret), secret = true)
OutlinedButton(
enabled = clientId.isNotBlank(),
onClick = {
signInUrl = onOpenSignIn(clientId.trim())?.also { openSystemBrowser(it) }
},
) { Text(stringResource(Res.string.sync_google_drive_open_sign_in)) }
// Shown so the page can still be opened by hand when the platform blocks the browser launch.
signInUrl?.let { url ->
SelectionContainer { Text(url, style = MaterialTheme.typography.bodySmall, maxLines = 3) }
ProviderField(pasted, { pasted = it }, stringResource(Res.string.sync_google_drive_paste))
}
}
}
@Composable
private fun ProviderDialog(
title: String,
confirmLabel: String,
canSubmit: Boolean,
onDismiss: () -> Unit,
onSubmit: () -> Unit,
content: @Composable () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
title = { Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) },
text = { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { content() } },
confirmButton = {
Button(
onClick = { onSubmit(); onDismiss() },
enabled = canSubmit,
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp),
) { Text(confirmLabel, style = MaterialTheme.typography.labelLarge) }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
)
}
@Composable
private fun ProviderField(value: String, onValueChange: (String) -> Unit, label: String, secret: Boolean = false) {
OutlinedTextField(
value = value,
onValueChange = onValueChange,
label = { Text(label) },
singleLine = true,
shape = MaterialTheme.shapes.large,
visualTransformation = if (secret) PasswordVisualTransformation() else VisualTransformation.None,
modifier = Modifier.fillMaxWidth(),
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/sync/SyncSettingsScreen.kt
- Source · implementation · 503 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
83: internal fun SyncSettingsRoute(
148: private fun BrowserLoginScreen(url: String, server: String, interceptUrlPrefix: String?, cookieJar: CookieJar, onNavigated: (String) -> Unit, onCancel: () -> Unit) {
164: private fun SyncSettingsScreen(
205: fun providerLabel(provider: SyncServerProvider) = when (provider) {
494: private fun autoSyncLabel(seconds: Int): String = when (seconds) {
Exact file bytes / download · SHA-256 20533545e2f5f02979b943d9512377ed6c558dd8ccc85a5998a8c70d9558d60c.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.sync
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudDownload
import androidx.compose.material.icons.filled.CloudUpload
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material.icons.filled.OpenInBrowser
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.navigationevent.NavigationEventInfo
import androidx.navigationevent.compose.NavigationBackHandler
import androidx.navigationevent.compose.rememberNavigationEventState
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.DbSyncTriggerPreferences
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.sync.CloudProviderDescriptor
import eu.friedcutlet.yokan.services.sync.cloudServerUri
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.ui.components.ChoiceDialog
import eu.friedcutlet.yokan.ui.components.ConfirmDialog
import eu.friedcutlet.yokan.ui.components.YokanTopBar
import eu.friedcutlet.yokan.ui.formatTimestamp
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import eu.friedcutlet.yokan.ui.screens.settings.YokanMenuTile
import eu.friedcutlet.yokan.ui.screens.webview.PlatformWebView
import eu.friedcutlet.yokan.ui.screens.webview.platformWebViewReportsNavigation
import eu.friedcutlet.yokan.ui.theme.YokanScaffold
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.log_out
import yokan.composeapp.generated.resources.sync_enable_settings
import yokan.composeapp.generated.resources.tile_auto_sync
import yokan.composeapp.generated.resources.tile_sync_histories
import yokan.composeapp.generated.resources.tile_sync_on
import yokan.composeapp.generated.resources.tile_sync_updates
import yokan.composeapp.generated.resources.tile_yokan_sync
import yokan.composeapp.generated.resources.sync_server_provider
import yokan.composeapp.generated.resources.sync_email
import yokan.composeapp.generated.resources.sync_username
import yokan.composeapp.generated.resources.sync_yokan_hub
import yokan.composeapp.generated.resources.mangayomi_sync_server
import yokan.composeapp.generated.resources.sync_mangayomi_subtitle
import yokan.composeapp.generated.resources.sync_settings_unsupported
import yokan.composeapp.generated.resources.sync_google_drive_state
import yokan.composeapp.generated.resources.sync_google_drive_subtitle
import yokan.composeapp.generated.resources.sync_syncyomi
import yokan.composeapp.generated.resources.sync_syncyomi_limits
import yokan.composeapp.generated.resources.sync_syncyomi_subtitle
@Composable
internal fun SyncSettingsRoute(
title: String,
settings: DbSettings,
sync: DbSyncPreference,
onUpdateSync: ((DbSyncPreference) -> DbSyncPreference) -> Unit,
onBack: () -> Unit,
) {
val services = remember { YokanRuntime.services }
val model = viewModel {
SyncSettingsViewModel(
services.sync, services.cloudSync, YokanRuntime.notifications, YokanRuntime.database,
YokanRuntime.settings, services.http,
)
}
val state by model.state.collectAsStateWithLifecycle()
DisposableEffect(model) {
onDispose { model.cancelBrowserLogin() }
}
val syncId = sync.syncId ?: 1L
state.browserLogin?.let { login ->
key(login.attempt) {
BrowserLoginScreen(
url = login.url,
server = login.server,
interceptUrlPrefix = login.attempt.callbackUrl?.let { "$it?" },
cookieJar = services.cookieJar,
onNavigated = { model.browserNavigated(login.attempt, it) },
onCancel = { model.cancelBrowserLogin(login.attempt) },
)
}
return
}
val published = state.publishedServers.map { HubServerChoice(it.name, it.url, removable = false) }
val custom = if (sync.serverProvider == SyncServerProvider.YokanHub) settings.customHubServers.filter { url -> published.none { it.url == url } }.map { HubServerChoice(it, it, removable = true) } else emptyList()
SyncSettingsScreen(
title = title,
settings = settings,
sync = sync,
state = state,
cloudProviders = model.cloudProviders,
isCloudSync = model.isCloudPreference(sync),
servers = if (sync.serverProvider == SyncServerProvider.YokanHub) published + custom else emptyList(),
onUpdateSync = onUpdateSync,
onSelectProvider = { model.selectServerProvider(syncId, it) },
onRequestNotificationPermission = model::requestNotificationPermission,
onLogin = { server, email, password -> model.login(syncId, server, email, password) },
onGoogleDriveSignIn = { clientId -> model.startGoogleDriveSignIn(syncId, clientId) },
onBrowserLogin = if (platformWebViewReportsNavigation) ({ server -> model.startBrowserLogin(syncId, server) }) else null,
onRemoveServer = model::removeCustomServer,
onConnectCloud = { providerId, account, accessToken -> model.connectCloud(syncId, providerId, account, accessToken) },
onLogout = { model.logout(syncId) },
onDeviceIdCopied = model::deviceIdCopied,
onSync = { model.syncNow(syncId, settings) },
onUploadOnly = { model.uploadOnly(syncId) },
onDownloadOnly = { model.downloadOnly(syncId) },
onUploadCloudBackup = { model.uploadCloudBackup(syncId, settings) },
onRestoreCloudBackup = { model.restoreCloudBackup(syncId) },
onSyncTriggersChange = model::setSyncTriggers,
onBack = onBack,
)
}
/** The hub's own sign-in page; it ends by loading `/login/done/#…`, which [onNavigated] hands to the ViewModel. */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun BrowserLoginScreen(url: String, server: String, interceptUrlPrefix: String?, cookieJar: CookieJar, onNavigated: (String) -> Unit, onCancel: () -> Unit) {
NavigationBackHandler(rememberNavigationEventState(NavigationEventInfo.None), onBackCompleted = onCancel)
YokanScaffold(
topBar = { YokanTopBar(title = "Sign in to $server", onBack = onCancel) },
) { padding ->
PlatformWebView(
url = url,
cookieJar = cookieJar,
modifier = Modifier.fillMaxSize().padding(padding),
onNavigated = onNavigated,
interceptUrlPrefix = interceptUrlPrefix,
)
}
}
@Composable
private fun SyncSettingsScreen(
title: String,
settings: DbSettings,
sync: DbSyncPreference,
state: SyncSettingsState,
cloudProviders: List<CloudProviderDescriptor>,
isCloudSync: Boolean,
servers: List<HubServerChoice>,
onUpdateSync: ((DbSyncPreference) -> DbSyncPreference) -> Unit,
onSelectProvider: (SyncServerProvider) -> Unit,
onRequestNotificationPermission: () -> Unit,
onLogin: (server: String, email: String, password: String) -> Unit,
onGoogleDriveSignIn: (clientId: String) -> String?,
onBrowserLogin: ((server: String) -> Unit)?,
onRemoveServer: (url: String) -> Unit,
onConnectCloud: (providerId: String, accountLabel: String?, accessToken: String) -> Unit,
onLogout: () -> Unit,
onDeviceIdCopied: () -> Unit,
onSync: () -> Unit,
onUploadOnly: () -> Unit,
onDownloadOnly: () -> Unit,
onUploadCloudBackup: () -> Unit,
onRestoreCloudBackup: () -> Unit,
onSyncTriggersChange: (DbSyncTriggerPreferences) -> Unit,
onBack: () -> Unit,
) {
val syncOn = sync.syncOn
val syncInProgress = state.operationInProgress
val cloudProvider = cloudProviders.firstOrNull { sync.server == cloudServerUri(it.id) }
val loggedIn = !sync.authToken.isNullOrBlank()
val serverLoggedIn = loggedIn && !isCloudSync
val cloudLoggedIn = loggedIn && isCloudSync
var loginDialog by remember { mutableStateOf(false) }
var cloudDialogProvider by remember { mutableStateOf<CloudProviderDescriptor?>(null) }
var logoutDialog by remember { mutableStateOf(false) }
var autoSyncDialog by remember { mutableStateOf(false) }
var providerDialog by remember { mutableStateOf(false) }
val yokanHubLabel = stringResource(Res.string.sync_yokan_hub)
val mangayomiLabel = stringResource(Res.string.mangayomi_sync_server)
val syncYomiLabel = stringResource(Res.string.sync_syncyomi)
val googleDriveLabel = stringResource(Res.string.sync_google_drive_state)
fun providerLabel(provider: SyncServerProvider) = when (provider) {
SyncServerProvider.YokanHub -> yokanHubLabel
SyncServerProvider.Mangayomi -> mangayomiLabel
SyncServerProvider.SyncYomi -> syncYomiLabel
SyncServerProvider.GoogleDrive -> googleDriveLabel
}
if (autoSyncDialog) {
ChoiceDialog(
title = stringResource(Res.string.tile_auto_sync),
options = AutoSyncFrequencies,
selected = sync.autoSyncFrequency,
label = ::autoSyncLabel,
onSelect = { value ->
if (value > 0) onRequestNotificationPermission()
onUpdateSync { it.copy(autoSyncFrequency = value) }
},
onDismiss = { autoSyncDialog = false },
)
}
if (providerDialog) ChoiceDialog(
title = stringResource(Res.string.sync_server_provider),
options = SyncServerProvider.entries,
selected = sync.serverProvider,
label = { providerLabel(it) },
onSelect = { onSelectProvider(it); providerDialog = false },
onDismiss = { providerDialog = false },
)
if (loginDialog) when (sync.serverProvider) {
SyncServerProvider.SyncYomi -> SyncYomiLoginDialog(
initialHost = sync.server.orEmpty(),
onDismiss = { loginDialog = false },
onSubmit = { host, apiKey -> onLogin(host, "", apiKey) },
)
SyncServerProvider.GoogleDrive -> GoogleDriveSignInDialog(
initialClientId = sync.server.orEmpty(),
onOpenSignIn = onGoogleDriveSignIn,
onDismiss = { loginDialog = false },
onSubmit = { clientId, clientSecret, pasted -> onLogin(clientId, clientSecret, pasted) },
)
SyncServerProvider.YokanHub, SyncServerProvider.Mangayomi -> SyncLoginDialog(
provider = sync.serverProvider,
initialServer = sync.server.orEmpty(),
initialEmail = sync.email.orEmpty(),
servers = servers,
onBrowserLogin = onBrowserLogin,
onRemoveServer = onRemoveServer,
onDismiss = { loginDialog = false },
onSubmit = onLogin,
)
}
cloudDialogProvider?.let { provider ->
CloudProviderConnectDialog(
provider = provider,
initialAccount = sync.email.orEmpty(),
onDismiss = { cloudDialogProvider = null },
onSubmit = { account, accessToken -> onConnectCloud(provider.id, account, accessToken) },
)
}
if (logoutDialog) {
ConfirmDialog(
title = stringResource(Res.string.log_out),
message = if (isCloudSync) "Disconnect ${cloudProvider?.displayName ?: "cloud sync"}? Your local data stays." else "Sign out of the sync server? Your local data stays.",
confirmLabel = stringResource(Res.string.log_out),
danger = true,
onConfirm = onLogout,
onDismiss = { logoutDialog = false },
)
}
SettingsScaffold(title, onBack) {
item {
SettingTile(
stringResource(Res.string.sync_server_provider),
providerLabel(sync.serverProvider),
enabled = !syncInProgress,
onClick = { providerDialog = true },
)
}
item(key = "sync-on") {
SwitchTile(
stringResource(Res.string.tile_sync_on),
null,
syncOn,
{ value -> if (!syncInProgress) onUpdateSync { it.copy(syncOn = value, autoSyncFrequency = if (value) it.autoSyncFrequency else 0) } },
enabled = !syncInProgress,
)
}
item {
SettingTile(
stringResource(Res.string.tile_auto_sync),
autoSyncLabel(sync.autoSyncFrequency),
enabled = syncOn && !syncInProgress,
onClick = { autoSyncDialog = true },
)
}
if (sync.serverProvider == SyncServerProvider.YokanHub) item { InfoRow("Automatic sync may cause data conflicts if the same items are edited on multiple devices at once.") }
item { SwitchTile(stringResource(Res.string.tile_sync_histories), null, sync.syncHistories, { value -> if (!syncInProgress) onUpdateSync { it.copy(syncHistories = value) } }, syncOn && !syncInProgress) }
item { SwitchTile(stringResource(Res.string.tile_sync_updates), null, sync.syncUpdates, { value -> if (!syncInProgress) onUpdateSync { it.copy(syncUpdates = value) } }, syncOn && !syncInProgress) }
item {
SwitchTile(
stringResource(Res.string.sync_enable_settings),
if (sync.serverProvider == SyncServerProvider.Mangayomi || sync.serverProvider == SyncServerProvider.SyncYomi) stringResource(Res.string.sync_settings_unsupported) else null,
sync.syncSettings,
{ value -> if (!syncInProgress) onUpdateSync { it.copy(syncSettings = value) } },
(sync.serverProvider == SyncServerProvider.YokanHub || sync.serverProvider == SyncServerProvider.GoogleDrive) && syncOn && !syncInProgress,
)
}
syncTriggerItems(settings.features.syncTriggers, syncOn && !syncInProgress, onSyncTriggersChange)
item { SettingsSection("Services") }
if (sync.serverProvider == SyncServerProvider.YokanHub) item {
YokanMenuTile(
title = stringResource(Res.string.tile_yokan_sync),
subtitle = if (serverLoggedIn) "Connected as ${sync.email ?: "user"}" else "Use a self-hosted yokan-hub",
trailing = if (serverLoggedIn) {
{ Icon(Icons.Filled.DoneAll, contentDescription = "Logged in", tint = MaterialTheme.colorScheme.primary) }
} else null,
enabled = !syncInProgress,
onClick = { if (serverLoggedIn) logoutDialog = true else loginDialog = true },
)
}
else item {
YokanMenuTile(
title = providerLabel(sync.serverProvider),
subtitle = when {
serverLoggedIn -> "Connected as ${sync.email ?: sync.server ?: "user"}"
sync.serverProvider == SyncServerProvider.SyncYomi -> stringResource(Res.string.sync_syncyomi_subtitle)
sync.serverProvider == SyncServerProvider.GoogleDrive -> stringResource(Res.string.sync_google_drive_subtitle)
else -> stringResource(Res.string.sync_mangayomi_subtitle)
},
trailing = if (serverLoggedIn) {
{ Icon(Icons.Filled.DoneAll, contentDescription = "Logged in", tint = MaterialTheme.colorScheme.primary) }
} else null,
enabled = !syncInProgress,
onClick = { if (serverLoggedIn) logoutDialog = true else loginDialog = true },
)
}
if (sync.serverProvider == SyncServerProvider.SyncYomi) item { InfoRow(stringResource(Res.string.sync_syncyomi_limits)) }
if (sync.serverProvider == SyncServerProvider.YokanHub) cloudProviders.forEach { provider ->
item(key = "cloud:${provider.id}") {
val selected = cloudProvider?.id == provider.id
YokanMenuTile(
title = provider.displayName,
subtitle = when {
selected && cloudLoggedIn -> "Connected as ${sync.email ?: "cloud account"}"
selected -> "Selected; access token missing"
else -> provider.description
},
trailing = if (selected && cloudLoggedIn) {
{ Icon(Icons.Filled.DoneAll, contentDescription = "Connected", tint = MaterialTheme.colorScheme.primary) }
} else null,
enabled = !syncInProgress,
onClick = { if (selected && cloudLoggedIn) logoutDialog = true else cloudDialogProvider = provider },
)
}
}
if (sync.serverProvider == SyncServerProvider.YokanHub && cloudLoggedIn && cloudProvider == null) {
item {
YokanMenuTile(
title = "Unknown sync provider",
subtitle = "${sync.server} is not available in this build; tap to disconnect",
enabled = !syncInProgress,
onClick = { logoutDialog = true },
)
}
}
if (sync.serverProvider == SyncServerProvider.YokanHub) item {
Row(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
OutlinedButton(onClick = {
openSystemBrowser("https://github.com/Schnitzel5/yokan-hub")
}) {
Icon(Icons.Filled.OpenInBrowser, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Get yokan-hub")
}
if (serverLoggedIn && !sync.server.isNullOrBlank()) {
Spacer(Modifier.width(8.dp))
OutlinedButton(onClick = { openSystemBrowser(sync.server) }) {
Icon(Icons.Filled.OpenInBrowser, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Open hub panel")
}
}
}
}
if (sync.serverProvider == SyncServerProvider.YokanHub) item { InfoRow("Cloud providers use backup snapshots for sync. Upload creates a cloud backup; download restores the latest cloud backup over local library, history, and progress.") }
item { SettingTile(if (sync.serverProvider == SyncServerProvider.YokanHub) "Last hub sync" else "Last sync", sync.lastSyncManga?.let { formatTimestamp(settings, it) } ?: "Never") }
if (sync.serverProvider == SyncServerProvider.YokanHub && serverLoggedIn && !sync.deviceId.isNullOrBlank()) {
item {
// Compose exposes no common constructor for ClipEntry yet; retain the text-only KMP API.
@Suppress("DEPRECATION")
val clipboard = LocalClipboardManager.current
SettingTile(
"This device",
"${sync.deviceId} • tap to copy; matches the Devices list in the hub panel",
onClick = {
clipboard.setText(AnnotatedString(sync.deviceId))
onDeviceIdCopied()
},
)
}
}
if (sync.serverProvider == SyncServerProvider.YokanHub) item {
val pending = state.pendingChanges
SettingTile("Pending changes", if (pending == 0) "Everything is on the hub" else "$pending change(s) waiting to upload")
}
item {
// Mangayomi confirms upload-only/download-only before running the
// destructive direction (sync.dart's alert dialogs).
var pendingSyncDirection by remember { mutableStateOf<String?>(null) }
pendingSyncDirection?.let { direction ->
val uploading = direction == "Upload"
ConfirmDialog(
title = if (uploading) "Upload only" else "Download only",
message = if (uploading) {
"Local changes will overwrite the data on the sync server. Continue?"
} else {
"Data from the sync server will overwrite local changes. Continue?"
},
confirmLabel = if (uploading) "Upload" else "Download",
danger = true,
onConfirm = if (uploading) onUploadOnly else onDownloadOnly,
onDismiss = { pendingSyncDirection = null },
)
}
FlowRow(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Button(
enabled = loggedIn && syncOn && !syncInProgress,
onClick = onSync,
) {
Icon(Icons.Filled.Sync, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text(if (syncInProgress) "Syncing…" else "Sync")
}
OutlinedButton(
enabled = loggedIn && syncOn && !syncInProgress,
onClick = { pendingSyncDirection = "Upload" },
) {
Icon(Icons.Filled.CloudUpload, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Upload only")
}
OutlinedButton(
enabled = loggedIn && syncOn && !syncInProgress,
onClick = { pendingSyncDirection = "Download" },
) {
Icon(Icons.Filled.CloudDownload, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Download only")
}
}
}
if (sync.serverProvider == SyncServerProvider.YokanHub && cloudLoggedIn) {
item {
FlowRow(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedButton(
enabled = !syncInProgress,
onClick = onUploadCloudBackup,
) {
Icon(Icons.Filled.CloudUpload, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Upload backup")
}
OutlinedButton(
enabled = !syncInProgress,
onClick = onRestoreCloudBackup,
) {
Icon(Icons.Filled.CloudDownload, contentDescription = null)
Spacer(Modifier.width(6.dp))
Text("Restore latest")
}
}
}
}
state.loginMessage?.let { item { InfoRow(it) } }
state.syncMessage?.let { item { InfoRow(it) } }
}
}
private val AutoSyncFrequencies = listOf(0, 300, 600, 1800, 3600, 10800, 21600, 43200)
private fun autoSyncLabel(seconds: Int): String = when (seconds) {
300 -> "Every 5 minutes"
600 -> "Every 10 minutes"
1800 -> "Every 30 minutes"
3600 -> "Every 1 hour"
10800 -> "Every 3 hours"
21600 -> "Every 6 hours"
43200 -> "Every 12 hours"
else -> "Off"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/sync/SyncSettingsViewModel.kt
- Source · implementation · 322 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
54: internal data class SyncSettingsState(
68: internal data class BrowserLogin(val attempt: BrowserLoginAttempt) {
73: internal class SyncSettingsViewModel(
105: fun isCloudPreference(preference: DbSyncPreference): Boolean = cloudSync.isCloudPreference(preference)
107: fun requestNotificationPermission() = notifications.requestPermission()
109: fun login(syncId: Long, server: String, email: String, password: String) {
119: fun selectServerProvider(syncId: Long, provider: SyncServerProvider) {
161: fun startBrowserLogin(syncId: Long, server: String) {
176: fun startGoogleDriveSignIn(syncId: Long, clientId: String): String? {
184: fun browserNavigated(attempt: BrowserLoginAttempt, loadedUrl: String) {
207: fun cancelBrowserLogin(attempt: BrowserLoginAttempt? = _state.value.browserLogin?.attempt) {
220: fun removeCustomServer(url: String) = settings.updateDb { it.copy(customHubServers = it.customHubServers - url) }
222: fun setSyncTriggers(value: DbSyncTriggerPreferences) =
226: private fun rememberServer(server: String) {
232: fun connectCloud(syncId: Long, providerId: String, accountLabel: String?, accessToken: String) {
240: fun logout(syncId: Long) {
249: fun deviceIdCopied() {
256: fun syncNow(syncId: Long, settings: DbSettings) = runSync(Res.string.sync_operation_sync) { sync.sync(syncId, settings) }
258: fun uploadOnly(syncId: Long) = runSync(Res.string.sync_operation_upload) { sync.pushChanges(syncId) }
260: fun downloadOnly(syncId: Long) = runSync(Res.string.sync_operation_download) { sync.pullChanges(syncId) }
262: fun uploadCloudBackup(syncId: Long, settings: DbSettings) = runCloud(Res.string.sync_operation_cloud_backup) {
267: fun restoreCloudBackup(syncId: Long) = runCloud(Res.string.sync_operation_cloud_restore) {
272: private fun showLoginMessage(message: StringResource) {
281: private fun runSync(label: StringResource, block: suspend () -> SyncResult) = runExclusive {
294: private fun runCloud(label: StringResource, block: suspend () -> String) = runExclusive {
300: private fun runExclusive(block: suspend () -> String) {
318: override fun onCleared() {
Exact file bytes / download · SHA-256 e7b7d94313459ca4b4fcdb62243905b0f642cc2963df87ea8b063adb536d20b6.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.sync
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.DbSyncTriggerPreferences
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.normalizeHubServer
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.sync.BrowserLoginAttempt
import eu.friedcutlet.yokan.services.sync.CloudBackupSyncService
import eu.friedcutlet.yokan.services.sync.CloudProviderDescriptor
import eu.friedcutlet.yokan.services.sync.HubServerEntry
import eu.friedcutlet.yokan.services.sync.SyncResult
import eu.friedcutlet.yokan.services.sync.SyncService
import eu.friedcutlet.yokan.services.sync.fetchHubServers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.Job
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.StringResource
import org.jetbrains.compose.resources.getString
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.sync_cloud_restored
import yokan.composeapp.generated.resources.sync_cloud_uploaded
import yokan.composeapp.generated.resources.sync_device_id_copied
import yokan.composeapp.generated.resources.sync_enter_valid_client_id
import yokan.composeapp.generated.resources.sync_enter_valid_server
import yokan.composeapp.generated.resources.sync_logged_out
import yokan.composeapp.generated.resources.sync_operation_cloud_backup
import yokan.composeapp.generated.resources.sync_operation_cloud_restore
import yokan.composeapp.generated.resources.sync_operation_counts
import yokan.composeapp.generated.resources.sync_operation_download
import yokan.composeapp.generated.resources.sync_operation_failed
import yokan.composeapp.generated.resources.sync_operation_label_failed
import yokan.composeapp.generated.resources.sync_operation_result
import yokan.composeapp.generated.resources.sync_operation_sync
import yokan.composeapp.generated.resources.sync_operation_upload
import yokan.composeapp.generated.resources.sync_provider_change_failed
import yokan.composeapp.generated.resources.sync_provider_changed
internal data class SyncSettingsState(
val loginMessage: String? = null,
val syncMessage: String? = null,
val syncInProgress: Boolean = false,
val externalOperationInProgress: Boolean = false,
val pendingChanges: Int = 0,
/** Servers published in the app's GitHub repository; empty until (or unless) the list loads. */
val publishedServers: List<HubServerEntry> = emptyList(),
/** Non-null while the hub's sign-in page is open in the in-app browser. */
val browserLogin: BrowserLogin? = null,
) {
val operationInProgress: Boolean get() = syncInProgress || externalOperationInProgress
}
internal data class BrowserLogin(val attempt: BrowserLoginAttempt) {
val server: String get() = attempt.server
val url: String get() = attempt.url
}
internal class SyncSettingsViewModel(
private val sync: SyncService,
private val cloudSync: CloudBackupSyncService,
private val notifications: NotificationService,
private val database: YokanDatabase,
private val settings: SettingsStore,
http: HttpService,
) : ViewModel() {
val cloudProviders: List<CloudProviderDescriptor> = cloudSync.providers()
private val _state = MutableStateFlow(SyncSettingsState(pendingChanges = database.outbox().size))
val state: StateFlow<SyncSettingsState> = _state.asStateFlow()
private var browserCompletionJob: Job? = null
private var browserCompletionGeneration = 0L
init {
viewModelScope.launch {
database.snapshots().map { it.outbox.size }.distinctUntilChanged().collect { pending ->
_state.update { it.copy(pendingChanges = pending) }
}
}
viewModelScope.launch {
combine(sync.operationState, cloudSync.operationState) { server, cloud -> server.isActive || cloud.isActive }
.distinctUntilChanged()
.collect { active -> _state.update { it.copy(externalOperationInProgress = active) } }
}
viewModelScope.launch {
val servers = fetchHubServers(http)
_state.update { it.copy(publishedServers = servers) }
}
}
fun isCloudPreference(preference: DbSyncPreference): Boolean = cloudSync.isCloudPreference(preference)
fun requestNotificationPermission() = notifications.requestPermission()
fun login(syncId: Long, server: String, email: String, password: String) {
if (_state.value.operationInProgress) return
cancelBrowserLogin()
runExclusive {
val result = sync.login(syncId, server, email, password)
if (result.success && database.syncPreferences().firstOrNull { it.syncId == syncId }?.serverProvider == SyncServerProvider.YokanHub) rememberServer(server)
result.message
}
}
fun selectServerProvider(syncId: Long, provider: SyncServerProvider) {
if (_state.value.operationInProgress) return
val current = database.syncPreferences().firstOrNull { it.syncId == syncId } ?: DbSyncPreference(syncId = syncId)
if (current.serverProvider == provider) return
browserCompletionGeneration++
cancelBrowserLogin()
_state.update { it.copy(syncInProgress = true, loginMessage = null, syncMessage = null) }
viewModelScope.launch {
try {
val result = catchingNonCancellation { sync.logout(syncId) }
if (result.isSuccess) database.upsertSyncPreference(
(database.syncPreferences().firstOrNull { it.syncId == syncId } ?: current).copy(
serverProvider = provider,
server = null,
email = null,
authToken = null,
syncOn = false,
autoSyncFrequency = 0,
lastSyncManga = null,
lastSyncHistory = null,
lastSyncUpdate = null,
hubHead = 0,
hubEpoch = 0,
hubHlc = 0,
hubBootstrapComplete = false,
hubRecoveryPending = false,
deviceId = null,
),
)
val message = result.exceptionOrNull()?.message ?: getString(Res.string.sync_provider_changed)
_state.update { it.copy(loginMessage = message) }
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Throwable) {
val message = error.message ?: getString(Res.string.sync_provider_change_failed)
_state.update { it.copy(loginMessage = message) }
} finally {
_state.update { it.copy(syncInProgress = false) }
}
}
}
fun startBrowserLogin(syncId: Long, server: String) {
if (_state.value.operationInProgress) return
cancelBrowserLogin()
val attempt = sync.beginBrowserLogin(syncId, server)
if (attempt == null) {
showLoginMessage(Res.string.sync_enter_valid_server)
return
}
_state.update { it.copy(browserLogin = BrowserLogin(attempt), loginMessage = null) }
}
/**
* Google Drive consent URL for the user's own OAuth client, opened in the system browser (Google refuses embedded
* web views). The pasted loopback address then completes sign-in through [login]; null when the client ID is invalid.
*/
fun startGoogleDriveSignIn(syncId: Long, clientId: String): String? {
if (_state.value.operationInProgress) return null
val url = sync.beginBrowserLogin(syncId, clientId)?.url
if (url == null) showLoginMessage(Res.string.sync_enter_valid_client_id) else _state.update { it.copy(loginMessage = null) }
return url
}
/** Every page the sign-in browser finishes loading, or the intercepted OAuth callback; the service decides which ends the flow. */
fun browserNavigated(attempt: BrowserLoginAttempt, loadedUrl: String) {
if (_state.value.browserLogin?.attempt !== attempt) return
// With an intercepted callback, ordinary page loads can't finish the flow; skipping them keeps a
// just-started no-op completion from swallowing the real callback below.
if (attempt.callbackUrl != null && !loadedUrl.startsWith("${attempt.callbackUrl}?")) return
if (browserCompletionJob?.isActive == true) return
val generation = ++browserCompletionGeneration
browserCompletionJob = viewModelScope.launch {
_state.update { it.copy(syncInProgress = true) }
try {
val result = sync.completeBrowserLogin(attempt, loadedUrl) ?: return@launch
if (_state.value.browserLogin?.attempt !== attempt) return@launch
if (result.success && database.syncPreferences().firstOrNull { it.syncId == attempt.syncId }?.serverProvider == SyncServerProvider.YokanHub) {
rememberServer(attempt.server)
}
if (!result.success) sync.cancelBrowserLogin(attempt)
_state.update { it.copy(browserLogin = null, loginMessage = result.message) }
} finally {
if (browserCompletionGeneration == generation) _state.update { it.copy(syncInProgress = false) }
}
}
}
fun cancelBrowserLogin(attempt: BrowserLoginAttempt? = _state.value.browserLogin?.attempt) {
if (attempt != null && _state.value.browserLogin?.attempt !== attempt) {
sync.cancelBrowserLogin(attempt)
return
}
browserCompletionJob?.cancel()
browserCompletionJob = null
if (attempt != null) sync.cancelBrowserLogin(attempt)
_state.update { current ->
if (attempt == null || current.browserLogin?.attempt === attempt) current.copy(browserLogin = null) else current
}
}
fun removeCustomServer(url: String) = settings.updateDb { it.copy(customHubServers = it.customHubServers - url) }
fun setSyncTriggers(value: DbSyncTriggerPreferences) =
settings.updateDb { it.copy(features = it.features.copy(syncTriggers = value)) }
/** Keeps a server the user typed in (and signed in to) in the dropdown; published ones are listed anyway. */
private fun rememberServer(server: String) {
val url = normalizeHubServer(server) ?: return
if (_state.value.publishedServers.any { it.url == url }) return
settings.updateDb { if (url in it.customHubServers) it else it.copy(customHubServers = it.customHubServers + url) }
}
fun connectCloud(syncId: Long, providerId: String, accountLabel: String?, accessToken: String) {
if (_state.value.operationInProgress) return
runExclusive {
val result = cloudSync.connect(syncId, providerId, accountLabel, accessToken)
result.message
}
}
fun logout(syncId: Long) {
if (_state.value.operationInProgress) return
cancelBrowserLogin()
runExclusive {
sync.logout(syncId)
getString(Res.string.sync_logged_out)
}
}
fun deviceIdCopied() {
viewModelScope.launch {
val message = getString(Res.string.sync_device_id_copied)
_state.update { it.copy(syncMessage = message) }
}
}
fun syncNow(syncId: Long, settings: DbSettings) = runSync(Res.string.sync_operation_sync) { sync.sync(syncId, settings) }
fun uploadOnly(syncId: Long) = runSync(Res.string.sync_operation_upload) { sync.pushChanges(syncId) }
fun downloadOnly(syncId: Long) = runSync(Res.string.sync_operation_download) { sync.pullChanges(syncId) }
fun uploadCloudBackup(syncId: Long, settings: DbSettings) = runCloud(Res.string.sync_operation_cloud_backup) {
val result = cloudSync.uploadBackup(syncId, BackupOptions(compressionLevel = settings.backupCompressionLevel ?: 6))
getString(Res.string.sync_cloud_uploaded, result.itemCount, result.fileName)
}
fun restoreCloudBackup(syncId: Long) = runCloud(Res.string.sync_operation_cloud_restore) {
val result = cloudSync.restoreLatestBackup(syncId)
getString(Res.string.sync_cloud_restored, result.preview.itemCount, result.fileName)
}
private fun showLoginMessage(message: StringResource) {
viewModelScope.launch {
val text = getString(message)
_state.update { it.copy(loginMessage = text) }
}
}
// Run a sync block, refresh, and report the upload/download counts. `label`
// distinguishes full sync vs the upload-only / download-only flows added from the old app.
private fun runSync(label: StringResource, block: suspend () -> SyncResult) = runExclusive {
val name = getString(label)
catchingNonCancellation { block() }
.map { result ->
if (result.errors.isEmpty()) {
getString(Res.string.sync_operation_counts, name, result.uploadedChanges, result.downloadedChanges)
} else {
result.errors.joinToString(" • ")
}
}
.getOrElse { error -> error.message ?: getString(Res.string.sync_operation_label_failed, name) }
}
private fun runCloud(label: StringResource, block: suspend () -> String) = runExclusive {
val name = getString(label)
catchingNonCancellation { getString(Res.string.sync_operation_result, name, block()) }
.getOrElse { error -> error.message ?: getString(Res.string.sync_operation_label_failed, name) }
}
private fun runExclusive(block: suspend () -> String) {
if (_state.value.operationInProgress) return
_state.update { it.copy(syncInProgress = true) }
viewModelScope.launch {
try {
val message = block()
_state.update { it.copy(syncMessage = message) }
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Throwable) {
val message = error.message ?: getString(Res.string.sync_operation_failed)
_state.update { it.copy(syncMessage = message) }
} finally {
_state.update { it.copy(syncInProgress = false) }
}
}
}
override fun onCleared() {
cancelBrowserLogin()
super.onCleared()
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/sync/SyncTriggerItems.kt
- Source · implementation · 53 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
23: internal fun LazyListScope.syncTriggerItems(
46: private fun DbSyncTriggerPreferences.with(kind: SyncTriggerKind, value: Boolean) = when (kind) {
Exact file bytes / download · SHA-256 9bdc579a4f3538b6611f36a1a79b32398085f6a176c97bfd33bc8524f2c30504.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.sync
import androidx.compose.foundation.lazy.LazyListScope
import eu.friedcutlet.yokan.database.DbSyncTriggerPreferences
import eu.friedcutlet.yokan.services.sync.SyncTriggerKind
import eu.friedcutlet.yokan.services.sync.enabled
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import org.jetbrains.compose.resources.StringResource
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.sync_on_app_resume
import yokan.composeapp.generated.resources.sync_on_app_start
import yokan.composeapp.generated.resources.sync_on_chapter_open
import yokan.composeapp.generated.resources.sync_on_chapter_read
import yokan.composeapp.generated.resources.sync_on_episode_open
import yokan.composeapp.generated.resources.sync_on_episode_seen
import yokan.composeapp.generated.resources.sync_triggers
import yokan.composeapp.generated.resources.sync_triggers_summary
/** Animetail's SyncTriggerOptions switches. */
internal fun LazyListScope.syncTriggerItems(
triggers: DbSyncTriggerPreferences,
enabled: Boolean,
onChange: (DbSyncTriggerPreferences) -> Unit,
) {
item(key = "sync-triggers") { SettingsSection(stringResource(Res.string.sync_triggers)) }
item(key = "sync-triggers-summary") { InfoRow(stringResource(Res.string.sync_triggers_summary)) }
SyncTriggerKind.entries.forEach { kind ->
item(key = "sync-trigger:${kind.name}") {
SwitchTile(stringResource(kind.label), null, triggers.enabled(kind), { onChange(triggers.with(kind, it)) }, enabled)
}
}
}
private val SyncTriggerKind.label: StringResource get() = when (this) {
SyncTriggerKind.ChapterRead -> Res.string.sync_on_chapter_read
SyncTriggerKind.ChapterOpen -> Res.string.sync_on_chapter_open
SyncTriggerKind.EpisodeSeen -> Res.string.sync_on_episode_seen
SyncTriggerKind.EpisodeOpen -> Res.string.sync_on_episode_open
SyncTriggerKind.AppStart -> Res.string.sync_on_app_start
SyncTriggerKind.AppResume -> Res.string.sync_on_app_resume
}
private fun DbSyncTriggerPreferences.with(kind: SyncTriggerKind, value: Boolean) = when (kind) {
SyncTriggerKind.ChapterRead -> copy(onChapterRead = value)
SyncTriggerKind.ChapterOpen -> copy(onChapterOpen = value)
SyncTriggerKind.EpisodeSeen -> copy(onEpisodeSeen = value)
SyncTriggerKind.EpisodeOpen -> copy(onEpisodeOpen = value)
SyncTriggerKind.AppStart -> copy(onAppStart = value)
SyncTriggerKind.AppResume -> copy(onAppResume = value)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/tracking/ManageTrackersScreen.kt
- Source · implementation · 140 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
40: internal fun ManageTrackersScreen(
Exact file bytes / download · SHA-256 0b258b141da88fe2375b01dbaeffe2fff385da7c0d450d4f3840c78ca7e25f05.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.tracking
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.domain.Track
import eu.friedcutlet.yokan.services.tracking.accountLabel
import eu.friedcutlet.yokan.ui.components.CoverImage
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
@Composable
internal fun ManageTrackersScreen(
title: String,
trackers: List<TrackerUi>,
state: TrackingSettingsState,
onBack: () -> Unit,
onRemoveTrack: (track: Track, removeRemote: Boolean) -> Unit,
onUpdateTrack: (track: Track, progress: Int, status: DbTrackStatus, score: Int) -> Unit,
) {
val connectedTrackers = trackers.filter { tracker ->
!state.preferences[tracker.syncId.toLong()]?.oauth.isNullOrBlank()
}
var selectedTrackerId by remember { mutableStateOf<Int?>(null) }
val selectedTracker = selectedTrackerId?.let { id -> trackers.firstOrNull { it.syncId == id } }
if (selectedTracker != null) {
TrackingDetailScreen(
title = selectedTracker.name,
allTracks = state.tracks,
onBack = { selectedTrackerId = null },
onRemoveTrack = onRemoveTrack,
onUpdateTrack = onUpdateTrack,
syncId = selectedTracker.syncId,
)
return
}
SettingsScaffold(title, onBack) {
if (connectedTrackers.isEmpty()) {
item { InfoRow("Sign in to a tracker from the Tracking screen to manage its library here.") }
}
connectedTrackers.chunked(2).forEach { rowItems ->
item(key = "trackers:${rowItems.first().syncId}") {
Row(
modifier = Modifier.fillMaxWidth().padding(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
rowItems.forEach { tracker ->
val pref = state.preferences[tracker.syncId.toLong()]
val accountLabel = pref?.accountLabel
Surface(
modifier = Modifier
.weight(1f)
.height(220.dp)
.clickable { selectedTrackerId = tracker.syncId },
shape = RoundedCornerShape(15.dp),
color = Color.Transparent,
) {
Column(
modifier = Modifier.fillMaxSize().padding(8.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Surface(
modifier = Modifier.fillMaxWidth().weight(1f),
shape = RoundedCornerShape(10.dp),
color = trackerBrandColor(tracker.syncId),
) {
Box(contentAlignment = Alignment.Center) {
TrackerLogo(tracker.syncId, compact = false)
}
}
Text(
tracker.name,
modifier = Modifier.padding(top = 10.dp),
fontWeight = FontWeight.Bold,
fontSize = 19.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (accountLabel != null) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier.padding(bottom = 8.dp),
) {
CoverImage(
model = pref.accountAvatarUrl,
contentDescription = accountLabel,
modifier = Modifier.size(18.dp).clip(RoundedCornerShape(50)),
shape = RoundedCornerShape(50),
fallbackInitials = accountLabel.firstOrNull()?.uppercaseChar()?.toString() ?: "?",
)
Spacer(Modifier.width(6.dp))
Text(
accountLabel,
fontSize = 13.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
} else {
Spacer(Modifier.height(10.dp))
}
}
}
}
if (rowItems.size == 1) Spacer(Modifier.weight(1f))
}
}
}
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/tracking/TrackerBranding.kt
- Source · implementation · 84 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
34: internal fun trackerBrandColor(syncId: Int): Color = when (syncId) {
54: internal fun TrackerLogo(syncId: Int, compact: Boolean) {
Exact file bytes / download · SHA-256 a06e1b1a24d10b187059ce38c312d37e526795fb9e6afcf98ef115acef67cbda.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.tracking
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material.icons.filled.Pets
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.BangumiTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.HikkaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.JellyfinTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KavitaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KitsuTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KomgaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MangaBakaTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MangaUpdatesTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.ShikimoriTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.SuwayomiTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId
internal fun trackerBrandColor(syncId: Int): Color = when (syncId) {
MalTrackerSyncId -> Color(0xFF2E51A2)
AnilistTrackerSyncId -> Color(0xFF332532)
KitsuTrackerSyncId -> Color(0xFF121923)
SimklTrackerSyncId -> Color(0xFF080808)
TraktTrackerSyncId -> Color(0xFFAF36A2)
MangaUpdatesTrackerSyncId -> Color(0xFF2B4767)
ShikimoriTrackerSyncId -> Color(0xFF343434)
BangumiTrackerSyncId -> Color(0xFFF09199)
HikkaTrackerSyncId -> Color(0xFF0F0F0F)
MangaBakaTrackerSyncId -> Color(0xFF1D4ED8)
TmdbTrackerSyncId -> Color(0xFF0D253F)
KomgaTrackerSyncId -> Color(0xFF332532)
KavitaTrackerSyncId -> Color(0xFF4AC694)
SuwayomiTrackerSyncId -> Color(0xFF253C54)
JellyfinTrackerSyncId -> Color(0xFF101828)
else -> Color(0xFF616161)
}
@Composable
internal fun TrackerLogo(syncId: Int, compact: Boolean) {
val textStyle = if (compact) MaterialTheme.typography.titleMedium else MaterialTheme.typography.headlineMedium
when (syncId) {
MalTrackerSyncId -> Text("MAL", color = Color.White, fontWeight = FontWeight.Black, style = textStyle)
AnilistTrackerSyncId -> Row(verticalAlignment = Alignment.Bottom) {
Text("A", color = Color.White, fontWeight = FontWeight.Black, style = textStyle)
Text("L", color = Color(0xFF02A9FF), fontWeight = FontWeight.Black, style = textStyle)
}
KitsuTrackerSyncId -> Icon(
Icons.Filled.Pets,
contentDescription = null,
tint = Color(0xFFFF563F),
modifier = Modifier.size(if (compact) 34.dp else 72.dp),
)
SimklTrackerSyncId -> Text("SIMKL", color = Color.White, fontWeight = FontWeight.Black, style = textStyle)
TraktTrackerSyncId -> Icon(
Icons.Filled.DoneAll,
contentDescription = null,
tint = Color.White,
modifier = Modifier.size(if (compact) 34.dp else 72.dp),
)
else -> trackerInitials[syncId]?.let { Text(it, color = Color.White, fontWeight = FontWeight.Black, style = textStyle) }
?: Icon(Icons.Filled.Sync, contentDescription = null, tint = Color.White)
}
}
private val trackerInitials = mapOf(
MangaUpdatesTrackerSyncId to "MU", ShikimoriTrackerSyncId to "SHIKI", BangumiTrackerSyncId to "BGM",
HikkaTrackerSyncId to "HIKKA", MangaBakaTrackerSyncId to "MB", TmdbTrackerSyncId to "TMDB",
KomgaTrackerSyncId to "KOMGA", KavitaTrackerSyncId to "KAVITA", SuwayomiTrackerSyncId to "SUWA", JellyfinTrackerSyncId to "JF",
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/tracking/TrackingDetailScreen.kt
- Source · implementation · 205 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
48: internal fun TrackingDetailScreen(
105: private fun TrackEditRow(
182: private fun String.toTrackStatus(itemType: ItemType): DbTrackStatus =
188: private fun trackStatusOptions(itemType: ItemType): List<DbTrackStatus> = when (itemType) {
Exact file bytes / download · SHA-256 9499ce1ec4b00675e968992f892daded27bc49e1c1fcf69e088e95c3a43f7198.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.tracking
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SecondaryTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Track
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.score
import yokan.composeapp.generated.resources.ui_save_tracking_progress
import yokan.composeapp.generated.resources.ui_unbind
import eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider as HorizontalDivider
@Composable
internal fun TrackingDetailScreen(
title: String,
allTracks: List<Track>,
onBack: () -> Unit,
onRemoveTrack: (track: Track, removeRemote: Boolean) -> Unit,
onUpdateTrack: (track: Track, progress: Int, status: DbTrackStatus, score: Int) -> Unit,
syncId: Int? = null,
) {
var selectedTab by remember { mutableStateOf(ItemType.Manga) }
var expandedTrackIds by remember(syncId) { mutableStateOf(emptySet<Long>()) }
val visibleTabs = listOf(ItemType.Manga, ItemType.Anime)
val filtered = allTracks.filter { track ->
track.itemType == selectedTab && (syncId == null || track.syncId == syncId)
}
SettingsScaffold(title, onBack) {
item {
SecondaryTabRow(selectedTabIndex = visibleTabs.indexOf(selectedTab).coerceAtLeast(0)) {
visibleTabs.forEach { type ->
Tab(selected = selectedTab == type, onClick = { selectedTab = type }, text = { Text(type.label) })
}
}
}
if (filtered.isEmpty()) {
item { InfoRow("Open a title detail page to add a tracking binding.") }
} else {
filtered.forEach { track ->
item(key = "track:${track.id}", contentType = "track") {
val expanded = track.id in expandedTrackIds
ListItem(
modifier = Modifier
.fillMaxWidth()
.clickable {
expandedTrackIds = if (expanded) {
expandedTrackIds - track.id
} else {
expandedTrackIds + track.id
}
},
headlineContent = { Text(track.title) },
trailingContent = {
Icon(
if (expanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown,
contentDescription = if (expanded) "Collapse" else "Expand",
)
},
)
if (expanded) {
TrackEditRow(track, onRemoveTrack, onUpdateTrack)
}
}
item(key = "track-divider:${track.id}", contentType = "divider") { HorizontalDivider() }
}
}
}
}
@Composable
private fun TrackEditRow(
track: Track,
onRemove: (track: Track, removeRemote: Boolean) -> Unit,
onUpdate: (track: Track, progress: Int, status: DbTrackStatus, score: Int) -> Unit,
) {
var progress by remember(track.id, track.progress) { mutableStateOf(track.progress.toString()) }
var score by remember(track.id, track.score) { mutableStateOf(track.score.toString()) }
var status by remember(track.id, track.status) { mutableStateOf(track.status.name.toTrackStatus(track.itemType)) }
var confirmUnbind by remember(track.id) { mutableStateOf(false) }
if (confirmUnbind) {
AlertDialog(
onDismissRequest = { confirmUnbind = false },
title = { Text("Unbind ${track.title}?") },
text = { Text("The local tracking entry is removed. Trackers that support it can also delete the entry from your list on the service.") },
confirmButton = {
TextButton(onClick = { confirmUnbind = false; onRemove(track, true) }) {
Text("Also remove from service", color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
Row {
TextButton(onClick = { confirmUnbind = false }) { Text(stringResource(Res.string.action_cancel)) }
TextButton(onClick = { confirmUnbind = false; onRemove(track, false) }) { Text("Unbind locally") }
}
},
)
}
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(Icons.Filled.Sync, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
Column(Modifier.weight(1f)) {
Text(track.title, fontWeight = FontWeight.SemiBold)
Text("${track.itemType.label} • ${track.progress}/${if (track.total > 0) track.total else "?"}", color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
}
TextButton(onClick = { confirmUnbind = true }) {
Text(stringResource(Res.string.ui_unbind), color = MaterialTheme.colorScheme.error)
}
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(
value = progress,
onValueChange = { progress = it.filter(Char::isDigit).take(4) },
modifier = Modifier.weight(1f),
singleLine = true,
label = { Text("Progress") },
)
OutlinedTextField(
value = score,
onValueChange = { score = it.filter(Char::isDigit).take(2) },
modifier = Modifier.weight(1f),
singleLine = true,
label = { Text(stringResource(Res.string.score)) },
)
}
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
trackStatusOptions(track.itemType).forEach { option ->
OutlinedButton(onClick = { status = option }) {
Text(if (status == option) "${option.name} selected" else option.name)
}
}
}
Button(
onClick = {
onUpdate(
track,
progress.toIntOrNull() ?: track.progress,
status,
score.toIntOrNull() ?: track.score,
)
},
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(Res.string.ui_save_tracking_progress))
}
}
}
private fun String.toTrackStatus(itemType: ItemType): DbTrackStatus =
DbTrackStatus.entries.firstOrNull { it.name.equals(this, ignoreCase = true) } ?: when (itemType) {
ItemType.Anime -> DbTrackStatus.Watching
else -> DbTrackStatus.Reading
}
private fun trackStatusOptions(itemType: ItemType): List<DbTrackStatus> = when (itemType) {
ItemType.Anime -> listOf(
DbTrackStatus.Watching,
DbTrackStatus.Completed,
DbTrackStatus.OnHold,
DbTrackStatus.Dropped,
DbTrackStatus.PlanToWatch,
DbTrackStatus.ReWatching,
)
else -> listOf(
DbTrackStatus.Reading,
DbTrackStatus.Completed,
DbTrackStatus.OnHold,
DbTrackStatus.Dropped,
DbTrackStatus.PlanToRead,
DbTrackStatus.ReReading,
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/tracking/TrackingSettingsRoute.kt
- Source · implementation · 66 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
14: internal fun TrackingSettingsRoute(
40: internal fun ManageTrackersRoute(title: String, settings: DbSettings, onBack: () -> Unit) {
56: internal fun TrackingDetailRoute(title: String, onBack: () -> Unit) {
63: private fun trackingViewModel(): TrackingSettingsViewModel = viewModel {
Exact file bytes / download · SHA-256 af52c4f5d7f351a604d3dc129f293c9f1b9ddc2aff3b67c45036ebd5e2c6e826.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.tracking
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.services.tracking.orderedTrackers
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
@Composable
internal fun TrackingSettingsRoute(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
onOpen: (SettingsPage) -> Unit,
) {
val model = trackingViewModel()
val state by model.state.collectAsStateWithLifecycle()
val login by model.login.collectAsStateWithLifecycle()
TrackingSettingsScreen(
title, settings, onUpdate, onBack, onOpen,
trackers = model.connectable,
preferences = state.preferences,
login = login,
onConnect = model::connect,
onOpenLogin = model::openLogin,
onLogin = model::login,
onAuthorize = model::authorize,
onLoginStatus = model::showLoginStatus,
onDismissLogin = model::dismissLogin,
onDisconnect = model::disconnect,
)
}
@Composable
internal fun ManageTrackersRoute(title: String, settings: DbSettings, onBack: () -> Unit) {
val model = trackingViewModel()
val state by model.state.collectAsStateWithLifecycle()
val all = remember { YokanRuntime.services.trackers }
// The metadata tracker is managed with the metadata server.
val trackers = remember(all, settings.trackerOrder) {
orderedTrackers(all, settings).filterNot { it.isMetadataSource }.map { it.toUi() }
}
ManageTrackersScreen(
title, trackers, state, onBack,
onRemoveTrack = model::removeTrack,
onUpdateTrack = model::updateTrack,
)
}
@Composable
internal fun TrackingDetailRoute(title: String, onBack: () -> Unit) {
val model = trackingViewModel()
val state by model.state.collectAsStateWithLifecycle()
TrackingDetailScreen(title, state.tracks, onBack, model::removeTrack, model::updateTrack)
}
@Composable
private fun trackingViewModel(): TrackingSettingsViewModel = viewModel {
val services = YokanRuntime.services
TrackingSettingsViewModel(YokanRuntime.repository, services.trackerAccounts, services.trackers)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/tracking/TrackingSettingsScreen.kt
- Source · implementation · 337 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.
Declaration checklist (source line numbers):
60: internal fun TrackingSettingsScreen(
115: private fun TrackerConnectionTile(
180: private fun TrackerConnectDialog(
274: private fun TrackerLoginDialog(
Exact file bytes / download · SHA-256 07326019948aeaec8e0108c8e80eb450fc202f184739b2ce3be818bf7e5a8a84.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.tracking
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.services.tracking.TrackerLoginField
import eu.friedcutlet.yokan.services.tracking.TrackerOAuth
import eu.friedcutlet.yokan.ui.components.ConfirmDialog
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.navigation.SettingsPage.ManageTrackers
import eu.friedcutlet.yokan.ui.components.compactDialogWidth
import eu.friedcutlet.yokan.ui.screens.settings.InfoRow
import eu.friedcutlet.yokan.ui.screens.settings.RouteTile
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.action_save
import yokan.composeapp.generated.resources.log_out
import yokan.composeapp.generated.resources.ui_username_optional
@Composable
internal fun TrackingSettingsScreen(
title: String,
settings: DbSettings,
onUpdate: ((DbSettings) -> DbSettings) -> Unit,
onBack: () -> Unit,
onOpen: (SettingsPage) -> Unit,
trackers: List<TrackerUi>,
preferences: Map<Long, DbTrackPreference>,
login: TrackerLoginState,
onConnect: (syncId: Long, username: String, token: String) -> Unit,
onOpenLogin: (syncId: Int) -> Unit,
onLogin: (values: Map<TrackerLoginField, String>) -> Unit,
onAuthorize: (values: Map<TrackerLoginField, String>) -> Unit,
onLoginStatus: (String) -> Unit,
onDismissLogin: () -> Unit,
onDisconnect: (syncId: Long) -> Unit,
) {
login.syncId?.let { syncId -> trackers.firstOrNull { it.syncId == syncId } }?.let { tracker ->
TrackerLoginDialog(tracker, login, onLogin, onAuthorize, onLoginStatus, onDismissLogin)
}
SettingsScaffold(title, onBack) {
item(key = "update-progress") {
SwitchTile(
"Update progress after reading",
null,
settings.updateProgressAfterReading,
{ value -> onUpdate { it.copy(updateProgressAfterReading = value) } },
)
}
item(key = "auto-bind") {
SwitchTile(
"Track when adding to library",
"Bind signed-in trackers whose search has exactly one result with the same title. Komga, Kavita, Suwayomi and Jellyfin always bind titles from their own server.",
settings.features.tracking.autoBindOnAdd,
{ value -> onUpdate { it.copy(features = it.features.copy(tracking = it.features.tracking.copy(autoBindOnAdd = value))) } },
)
}
item { SettingsSection("Services") }
trackers.forEach { tracker ->
item(key = "tracker:${tracker.syncId}") {
TrackerConnectionTile(
tracker = tracker,
connected = !preferences[tracker.syncId.toLong()]?.oauth.isNullOrBlank(),
onConnect = { username, token -> onConnect(tracker.syncId.toLong(), username, token) },
onOpenLogin = { onOpenLogin(tracker.syncId) },
onDisconnect = { onDisconnect(tracker.syncId.toLong()) },
)
}
}
item { InfoRow("One-way sync updates chapter or episode progress in tracking services. Set up tracking for individual entries from their tracking button; search accepts id:<provider id>. Server trackers sync progress both ways.") }
item { RouteTile(ManageTrackers, "Manage trackers", onOpen = onOpen) }
}
}
@Composable
private fun TrackerConnectionTile(
tracker: TrackerUi,
connected: Boolean,
onConnect: (username: String, token: String) -> Unit,
onOpenLogin: () -> Unit,
onDisconnect: () -> Unit,
) {
var showConnect by remember { mutableStateOf(false) }
var showDisconnect by remember { mutableStateOf(false) }
if (showDisconnect) {
ConfirmDialog(
title = "Log out from ${tracker.name}?",
message = "Your local tracking entries will be kept.",
confirmLabel = stringResource(Res.string.log_out),
danger = true,
onConfirm = onDisconnect,
onDismiss = { showDisconnect = false },
)
}
if (showConnect) {
TrackerConnectDialog(
tracker = tracker,
onConnect = onConnect,
onDismiss = { showConnect = false },
)
}
ListItem(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 5.dp)
.clickable {
when {
connected -> showDisconnect = true
tracker.loginFields.isEmpty() -> showConnect = true
else -> onOpenLogin()
}
},
headlineContent = { Text(tracker.name) },
leadingContent = {
Surface(
modifier = Modifier.size(width = 60.dp, height = 70.dp),
shape = RoundedCornerShape(10.dp),
color = trackerBrandColor(tracker.syncId),
) {
Box(contentAlignment = Alignment.Center) {
TrackerLogo(tracker.syncId, compact = true)
}
}
},
trailingContent = if (connected) {
{
Icon(
Icons.Filled.DoneAll,
contentDescription = "Connected",
tint = Color(0xFF2E7D32),
modifier = Modifier.size(30.dp),
)
}
} else null,
)
}
@Composable
private fun TrackerConnectDialog(
tracker: TrackerUi,
onConnect: (username: String, token: String) -> Unit,
onDismiss: () -> Unit,
) {
var username by remember { mutableStateOf("") }
var token by remember { mutableStateOf("") }
var clientId by remember { mutableStateOf("") }
var awaitingCallback by remember { mutableStateOf(false) }
var status by remember { mutableStateOf<String?>(null) }
val callbackUri = remember(tracker.syncId) { TrackerOAuth.redirectUri(tracker.syncId) }
DisposableEffect(tracker.syncId) {
val cleanup = TrackerOAuth.listenForCallback(tracker.syncId) { result ->
awaitingCallback = false
val received = result.accessToken ?: result.authorizationCode
if (received != null) {
token = received
status = "Received ${if (result.accessToken != null) "access token" else "auth code"} from ${tracker.name}"
} else if (result.error != null) {
status = "${tracker.name} returned error: ${result.error}"
}
}
onDispose { cleanup() }
}
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
confirmButton = {
Button(
onClick = {
onConnect(username, token)
onDismiss()
},
enabled = token.isNotBlank(),
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 8.dp),
) { Text(stringResource(Res.string.action_save), style = MaterialTheme.typography.labelLarge) }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
title = {
Text(
"Connect ${tracker.name}",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
"Provide an OAuth client ID then tap Sign in to open ${tracker.name}'s authorization page in your browser. The app listens on $callbackUri for the callback. You can also paste an existing token directly.",
style = MaterialTheme.typography.bodySmall,
)
OutlinedTextField(
value = username,
onValueChange = { username = it },
label = { Text(stringResource(Res.string.ui_username_optional)) },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = clientId,
onValueChange = { clientId = it },
label = { Text("OAuth client ID") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = token,
onValueChange = { token = it },
label = { Text("OAuth token / code") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(
enabled = clientId.isNotBlank() && !awaitingCallback,
onClick = {
val url = TrackerOAuth.authorizeUrl(tracker.syncId, clientId)
?: return@OutlinedButton
awaitingCallback = true
status = "Opening ${tracker.name} sign-in…"
openSystemBrowser(url)
},
) { Text(if (awaitingCallback) "Waiting…" else "Sign in") }
}
status?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) }
}
},
)
}
/** Credentials dialog of trackers that declare login fields; shows the provider's rejection. */
@Composable
private fun TrackerLoginDialog(
tracker: TrackerUi,
state: TrackerLoginState,
onLogin: (values: Map<TrackerLoginField, String>) -> Unit,
onAuthorize: (values: Map<TrackerLoginField, String>) -> Unit,
onStatus: (String) -> Unit,
onDismiss: () -> Unit,
) {
var values by remember(tracker.syncId) { mutableStateOf(emptyMap<TrackerLoginField, String>()) }
val callbackUri = remember(tracker.syncId) { TrackerOAuth.redirectUri(tracker.syncId) }
val hasBrowserStep = tracker.browserSignIn
if (hasBrowserStep) {
DisposableEffect(tracker.syncId) {
val cleanup = TrackerOAuth.listenForCallback(tracker.syncId) { result ->
// Android delivers the callback; other targets paste the code or callback URL.
values = values + (TrackerLoginField.AuthorizationCode to result.raw)
onStatus(result.error?.let { "${tracker.name} returned error: $it" } ?: "Received the ${tracker.name} callback")
}
onDispose { cleanup() }
}
}
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.compactDialogWidth(),
shape = MaterialTheme.shapes.extraLarge,
confirmButton = {
Button(
enabled = !state.busy,
onClick = { onLogin(values) },
shape = RoundedCornerShape(50),
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 8.dp),
) { Text(if (state.busy) "Signing in…" else stringResource(Res.string.action_save), style = MaterialTheme.typography.labelLarge) }
},
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
title = { Text("Connect ${tracker.name}", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (hasBrowserStep) {
Text(
"Enter your own ${tracker.name} credentials, tap Open sign-in and approve; register $callbackUri as the app redirect where asked. Android returns automatically; elsewhere paste the code or the address the browser was sent to (if there is a field for it), then Save.",
style = MaterialTheme.typography.bodySmall,
)
}
tracker.loginFields.forEach { field ->
OutlinedTextField(
value = values[field].orEmpty(),
onValueChange = { values = values + (field to it) },
label = { Text(field.label) },
singleLine = true,
visualTransformation = if (field.secret) PasswordVisualTransformation() else VisualTransformation.None,
modifier = Modifier.fillMaxWidth(),
)
}
if (hasBrowserStep) {
OutlinedButton(
enabled = !state.busy,
onClick = { onAuthorize(values) },
) { Text("Open sign-in") }
}
state.status?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.primary) }
}
},
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/tracking/TrackingSettingsViewModel.kt
- Source · implementation · 149 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
37: internal data class TrackingSettingsState(
44: internal data class TrackerUi(
51: internal fun TrackerService.toUi() = TrackerUi(syncId, name, loginFields, browserSignIn)
54: internal data class TrackerLoginState(
61: internal class TrackingSettingsViewModel(
88: fun connect(syncId: Long, username: String, token: String) = accounts.connect(syncId, username, token)
90: fun openLogin(syncId: Int) {
96: fun dismissLogin() {
102: fun showLoginStatus(status: String) = _login.update { it.copy(status = status) }
104: fun login(values: Map<TrackerLoginField, String>) {
120: fun authorize(values: Map<TrackerLoginField, String>) {
133: fun disconnect(syncId: Long) = accounts.disconnect(syncId)
135: fun updateTrack(track: Track, progress: Int, status: DbTrackStatus, score: Int) =
138: fun removeTrack(track: Track, removeRemote: Boolean) = repository.removeTrack(track.id, removeRemote)
140: private fun cancelLoginWork() {
148: private fun List<DbTrackPreference>.bySyncId(): Map<Long, DbTrackPreference> =
Exact file bytes / download · SHA-256 1cf57fe1e648b81a30187ab9c1e2c99acadceaa85df04f010812901706c96550.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.tracking
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observe
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.domain.Track
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.system.openSystemBrowser
import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.KitsuTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TrackerAccounts
import eu.friedcutlet.yokan.services.tracking.TrackerLoginField
import eu.friedcutlet.yokan.services.tracking.TrackerService
import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.getString
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.tracking_login_enter_fields
import yokan.composeapp.generated.resources.tracking_login_failed
import yokan.composeapp.generated.resources.tracking_login_start_failed
internal data class TrackingSettingsState(
/** Tracker preference by sync id. */
val preferences: Map<Long, DbTrackPreference> = emptyMap(),
val tracks: List<Track> = emptyList(),
)
/** What the tracker tiles and connect dialogs need from a [TrackerService]. */
internal data class TrackerUi(
val syncId: Int,
val name: String,
val loginFields: List<TrackerLoginField> = emptyList(),
val browserSignIn: Boolean = false,
)
internal fun TrackerService.toUi() = TrackerUi(syncId, name, loginFields, browserSignIn)
/** The credentials dialog of the tracker [syncId]; null when no dialog is open. */
internal data class TrackerLoginState(
val syncId: Int? = null,
val busy: Boolean = false,
val status: String? = null,
)
/** Shared by the Tracking, Manage trackers and Tracking detail pages (one instance per page entry). */
internal class TrackingSettingsViewModel(
private val repository: YokanRepository,
private val accounts: TrackerAccounts,
private val trackers: List<TrackerService>,
private val openBrowser: (String) -> Unit = { openSystemBrowser(it) },
) : ViewModel() {
val state: StateFlow<TrackingSettingsState> = combine(
repository.snapshots.map { it.trackPreferences }.distinctUntilChanged(),
repository.observe({ it.tracks }) { tracks() },
) { preferences, tracks -> TrackingSettingsState(preferences.bySyncId(), tracks) }
// Seeded synchronously so the first frame never shows "not connected".
.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5_000),
TrackingSettingsState(repository.snapshots.value.trackPreferences.bySyncId(), repository.tracks()),
)
/** The Tracking page's trackers: AniList, Kitsu, MAL, SIMKL, Trakt first; the metadata tracker belongs to the metadata server. */
val connectable: List<TrackerUi> = trackers.filterNot { it.isMetadataSource }
.sortedBy { LegacyOrder.indexOf(it.syncId).takeIf { i -> i >= 0 } ?: it.syncId }
.map { it.toUi() }
private val _login = MutableStateFlow(TrackerLoginState())
val login: StateFlow<TrackerLoginState> = _login.asStateFlow()
private var loginJob: Job? = null
private var authorizeJob: Job? = null
fun connect(syncId: Long, username: String, token: String) = accounts.connect(syncId, username, token)
fun openLogin(syncId: Int) {
cancelLoginWork()
_login.value = TrackerLoginState(syncId)
}
/** Closes the dialog; a sign-in or sign-in page request still running is cancelled and never reports back. */
fun dismissLogin() {
cancelLoginWork()
_login.value = TrackerLoginState()
}
/** A message from the dialog itself (the OAuth callback arrived or failed). */
fun showLoginStatus(status: String) = _login.update { it.copy(status = status) }
fun login(values: Map<TrackerLoginField, String>) {
val current = _login.value
val syncId = current.syncId ?: return
if (current.busy) return
_login.update { it.copy(busy = true, status = null) }
loginJob = viewModelScope.launch {
catchingNonCancellation { accounts.login(syncId.toLong(), values) }
.onSuccess { _login.value = TrackerLoginState() }
.onFailure { failure ->
val message = failure.message ?: getString(Res.string.tracking_login_failed)
_login.update { it.copy(busy = false, status = message) }
}
}
}
/** Opens the provider's sign-in page for [values]. */
fun authorize(values: Map<TrackerLoginField, String>) {
val tracker = trackers.firstOrNull { it.syncId == _login.value.syncId } ?: return
authorizeJob?.cancel()
authorizeJob = viewModelScope.launch {
catchingNonCancellation { tracker.authorizeUrl(values) }
.onSuccess { url ->
if (url != null) openBrowser(url)
else showLoginStatus(getString(Res.string.tracking_login_enter_fields))
}
.onFailure { failure -> showLoginStatus(failure.message ?: getString(Res.string.tracking_login_start_failed)) }
}
}
fun disconnect(syncId: Long) = accounts.disconnect(syncId)
fun updateTrack(track: Track, progress: Int, status: DbTrackStatus, score: Int) =
repository.updateTrack(track.id, progress, status, score)
fun removeTrack(track: Track, removeRemote: Boolean) = repository.removeTrack(track.id, removeRemote)
private fun cancelLoginWork() {
loginJob?.cancel()
authorizeJob?.cancel()
}
}
private val LegacyOrder = listOf(AnilistTrackerSyncId, KitsuTrackerSyncId, MalTrackerSyncId, SimklTrackerSyncId, TraktTrackerSyncId)
private fun List<DbTrackPreference>.bySyncId(): Map<Long, DbTrackPreference> =
mapNotNull { pref -> pref.syncId?.let { it to pref } }.toMap()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/status/GlobalStatus.kt
- Source · implementation · 440 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
80: fun GlobalStatusAccessButton(
96: fun GlobalStatusOverlayHost(
140: internal fun GlobalStatusPanel(
244: private fun StatusVisibilityChip(selected: Boolean, label: String, onClick: () -> Unit) {
249: private fun StatusToggleRow(
269: private fun StatusSummaryRow(
306: internal data class StatusRing(
314: internal fun downloadRing(downloads: GlobalDownloadStatus): StatusRing = StatusRing(
322: internal fun libraryRing(update: GlobalLibraryUpdateStatus): StatusRing = StatusRing(
330: internal fun syncRing(state: GlobalStatusUiState): StatusRing = StatusRing(
343: private fun StatusProgressRing(ring: StatusRing, color: Color, size: Dp) {
356: private fun GlobalStatusRings(state: GlobalStatusUiState) {
393: private fun ActiveMode(icon: ImageVector, title: String) {
403: private fun libraryStatusText(update: GlobalLibraryUpdateStatus): String = when {
411: private fun downloadStatusText(downloads: GlobalDownloadStatus): String = when {
430: private fun syncStatusText(state: GlobalStatusUiState): String = when (state.sync.stage) {
Exact file bytes / download · SHA-256 5cab75d9519546e6049147bed85aafa6641f13bc2b3f427b5c5be0dd98d968e1.
Complete file
package eu.friedcutlet.yokan.ui.status
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudSync
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.Update
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.Dp
import eu.friedcutlet.yokan.database.DbGlobalStatusVisibility
import eu.friedcutlet.yokan.services.sync.SyncOperationOutcome
import eu.friedcutlet.yokan.services.sync.SyncOperationStage
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.global_status
import yokan.composeapp.generated.resources.global_status_always
import yokan.composeapp.generated.resources.global_status_automatic
import yokan.composeapp.generated.resources.global_status_downloaded_only
import yokan.composeapp.generated.resources.global_status_downloads_active
import yokan.composeapp.generated.resources.global_status_downloads_failed
import yokan.composeapp.generated.resources.global_status_downloads_idle
import yokan.composeapp.generated.resources.global_status_downloads_paused
import yokan.composeapp.generated.resources.global_status_hidden
import yokan.composeapp.generated.resources.global_status_incognito
import yokan.composeapp.generated.resources.global_status_library_cancelled
import yokan.composeapp.generated.resources.global_status_library_complete
import yokan.composeapp.generated.resources.global_status_library_preparing
import yokan.composeapp.generated.resources.global_status_library_running
import yokan.composeapp.generated.resources.global_status_open_downloads
import yokan.composeapp.generated.resources.global_status_open_sync
import yokan.composeapp.generated.resources.global_status_sync_cancelled
import yokan.composeapp.generated.resources.global_status_sync_downloading
import yokan.composeapp.generated.resources.global_status_sync_failed
import yokan.composeapp.generated.resources.global_status_sync_idle
import yokan.composeapp.generated.resources.global_status_sync_succeeded
import yokan.composeapp.generated.resources.global_status_sync_syncing
import yokan.composeapp.generated.resources.global_status_sync_uploading
import yokan.composeapp.generated.resources.global_status_visibility
val LocalGlobalStatusOpener = staticCompositionLocalOf<() -> Unit> { {} }
@Composable
fun GlobalStatusAccessButton(
modifier: Modifier = Modifier,
tint: Color = MaterialTheme.colorScheme.onSurface,
) {
val open = LocalGlobalStatusOpener.current
IconButton(onClick = open, modifier = modifier) {
Icon(
imageVector = Icons.Filled.Info,
contentDescription = stringResource(Res.string.global_status),
tint = tint,
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GlobalStatusOverlayHost(
state: GlobalStatusUiState,
onOpen: () -> Unit,
onDismiss: () -> Unit,
onVisibilityChange: (DbGlobalStatusVisibility) -> Unit,
onToggleDownloadedOnly: () -> Unit,
onToggleIncognito: () -> Unit,
onOpenDownloads: () -> Unit,
onOpenSync: () -> Unit,
onCancelLibraryUpdate: () -> Unit,
modifier: Modifier = Modifier,
) {
val policy = statusOverlayPolicy(state)
if (policy.showCollapsed) {
Surface(
modifier = modifier
.padding(12.dp),
shape = CircleShape,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
tonalElevation = 4.dp,
shadowElevation = 4.dp,
) {
IconButton(onClick = onOpen, modifier = Modifier.size(48.dp)) {
GlobalStatusRings(state)
}
}
}
if (policy.showExpanded) {
ModalBottomSheet(onDismissRequest = onDismiss) {
GlobalStatusPanel(
state = state,
onVisibilityChange = onVisibilityChange,
onToggleDownloadedOnly = onToggleDownloadedOnly,
onToggleIncognito = onToggleIncognito,
onOpenDownloads = onOpenDownloads,
onOpenSync = onOpenSync,
onCancelLibraryUpdate = onCancelLibraryUpdate,
modifier = Modifier.navigationBarsPadding(),
)
}
}
}
@Composable
internal fun GlobalStatusPanel(
state: GlobalStatusUiState,
onVisibilityChange: (DbGlobalStatusVisibility) -> Unit,
onToggleDownloadedOnly: () -> Unit,
onToggleIncognito: () -> Unit,
onOpenDownloads: () -> Unit,
onOpenSync: () -> Unit,
onCancelLibraryUpdate: () -> Unit,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(bottom = 20.dp),
) {
Row(
modifier = Modifier.padding(horizontal = 24.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
GlobalStatusRings(state)
Text(stringResource(Res.string.global_status), style = MaterialTheme.typography.headlineSmall)
}
if (state.downloadedOnly || state.incognito) {
FlowRow(
modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
if (state.downloadedOnly) ActiveMode(Icons.Filled.Download, stringResource(Res.string.global_status_downloaded_only))
if (state.incognito) ActiveMode(Icons.Filled.VisibilityOff, stringResource(Res.string.global_status_incognito))
}
}
StatusSummaryRow(
icon = Icons.Filled.Download,
title = downloadStatusText(state.downloads),
ring = downloadRing(state.downloads),
color = MaterialTheme.colorScheme.primary,
actionLabel = stringResource(Res.string.global_status_open_downloads),
onAction = onOpenDownloads,
)
StatusSummaryRow(
icon = Icons.Filled.CloudSync,
title = syncStatusText(state),
ring = syncRing(state),
color = MaterialTheme.colorScheme.tertiary,
actionLabel = stringResource(Res.string.global_status_open_sync),
onAction = onOpenSync,
)
state.libraryUpdate?.let { update ->
StatusSummaryRow(
icon = Icons.Filled.Update,
title = libraryStatusText(update),
ring = libraryRing(update),
color = MaterialTheme.colorScheme.secondary,
actionLabel = if (update.running) stringResource(Res.string.action_cancel) else null,
actionEnabled = !update.cancelRequested,
onAction = onCancelLibraryUpdate,
)
}
Text(
text = stringResource(Res.string.global_status_visibility),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 16.dp),
)
FlowRow(
modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
StatusVisibilityChip(
selected = state.visibility == DbGlobalStatusVisibility.Automatic,
label = stringResource(Res.string.global_status_automatic),
onClick = { onVisibilityChange(DbGlobalStatusVisibility.Automatic) },
)
StatusVisibilityChip(
selected = state.visibility == DbGlobalStatusVisibility.AlwaysVisible,
label = stringResource(Res.string.global_status_always),
onClick = { onVisibilityChange(DbGlobalStatusVisibility.AlwaysVisible) },
)
StatusVisibilityChip(
selected = state.visibility == DbGlobalStatusVisibility.Hidden,
label = stringResource(Res.string.global_status_hidden),
onClick = { onVisibilityChange(DbGlobalStatusVisibility.Hidden) },
)
}
StatusToggleRow(
icon = Icons.Filled.Download,
title = stringResource(Res.string.global_status_downloaded_only),
checked = state.downloadedOnly,
onCheckedChange = onToggleDownloadedOnly,
)
StatusToggleRow(
icon = Icons.Filled.VisibilityOff,
title = stringResource(Res.string.global_status_incognito),
checked = state.incognito,
onCheckedChange = onToggleIncognito,
)
}
}
@Composable
private fun StatusVisibilityChip(selected: Boolean, label: String, onClick: () -> Unit) {
FilterChip(selected = selected, onClick = onClick, label = { Text(label, maxLines = 1) })
}
@Composable
private fun StatusToggleRow(
icon: ImageVector,
title: String,
checked: Boolean,
onCheckedChange: () -> Unit,
) {
ListItem(
headlineContent = { Text(title) },
leadingContent = { Icon(icon, contentDescription = null) },
trailingContent = {
Switch(
checked = checked,
onCheckedChange = { onCheckedChange() },
modifier = Modifier.semantics { contentDescription = title },
)
},
)
}
@Composable
private fun StatusSummaryRow(
icon: ImageVector,
title: String,
ring: StatusRing,
color: Color,
actionLabel: String?,
onAction: () -> Unit,
actionEnabled: Boolean = true,
) {
ListItem(
headlineContent = {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(title)
ring.progress?.let {
Text("${(it * 100).toInt()}%", style = MaterialTheme.typography.labelMedium, color = color)
}
}
},
leadingContent = {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).clearAndSetSemantics { }) {
StatusProgressRing(ring, color, 40.dp)
Icon(
if (ring.error) Icons.Filled.ErrorOutline else if (ring.paused) Icons.Filled.Pause else icon,
contentDescription = null,
tint = if (ring.error) MaterialTheme.colorScheme.error else color,
modifier = Modifier.size(20.dp),
)
}
},
trailingContent = {
actionLabel?.let {
TextButton(onClick = onAction, enabled = actionEnabled) { Text(it) }
}
},
)
}
internal data class StatusRing(
val visible: Boolean,
val progress: Float?,
val running: Boolean,
val paused: Boolean = false,
val error: Boolean = false,
)
internal fun downloadRing(downloads: GlobalDownloadStatus): StatusRing = StatusRing(
visible = downloads.isRelevant,
progress = downloads.progress?.takeIf { it.isFinite() }?.coerceIn(0f, 1f),
running = downloads.activeCount > 0 || (downloads.pendingCount > 0 && downloads.pausedCount == 0 && downloads.failedCount == 0),
paused = downloads.pausedCount > 0 && downloads.activeCount == 0,
error = downloads.failedCount > 0,
)
internal fun libraryRing(update: GlobalLibraryUpdateStatus): StatusRing = StatusRing(
visible = true,
progress = update.progress,
running = update.running && !update.cancelled,
paused = update.cancelled,
error = update.failed > 0,
)
internal fun syncRing(state: GlobalStatusUiState): StatusRing = StatusRing(
visible = state.sync.isActive || state.sync.lastOutcome == SyncOperationOutcome.Failed,
progress = when {
state.sync.isActive -> state.sync.progress
state.sync.lastOutcome == SyncOperationOutcome.Succeeded -> 1f
else -> null
},
running = state.sync.isActive,
paused = !state.sync.isActive && state.sync.lastOutcome == SyncOperationOutcome.Cancelled,
error = !state.sync.isActive && state.sync.lastOutcome == SyncOperationOutcome.Failed,
)
@Composable
private fun StatusProgressRing(ring: StatusRing, color: Color, size: Dp) {
val modifier = Modifier.size(size).clearAndSetSemantics { }
if (ring.running && ring.progress == null) {
CircularProgressIndicator(modifier = modifier, color = color, strokeWidth = 2.dp, trackColor = color.copy(alpha = 0.16f))
} else {
CircularProgressIndicator(
progress = { ring.progress ?: 0f }, modifier = modifier,
color = color, strokeWidth = 2.dp, trackColor = color.copy(alpha = 0.24f),
)
}
}
@Composable
private fun GlobalStatusRings(state: GlobalStatusUiState) {
val downloads = downloadRing(state.downloads)
val library = state.libraryUpdate?.let(::libraryRing)
val sync = syncRing(state)
val description = listOfNotNull(
stringResource(Res.string.global_status),
downloadStatusText(state.downloads).takeIf { downloads.visible },
downloads.progress?.let { "${(it * 100).toInt()}%" },
if (downloads.paused && downloads.error) stringResource(Res.string.global_status_downloads_paused, state.downloads.pausedCount) else null,
state.libraryUpdate?.let { libraryStatusText(it) },
library?.progress?.let { "${(it * 100).toInt()}%" },
syncStatusText(state).takeIf { sync.visible },
state.sync.progress?.let { "${(it * 100).toInt()}%" },
stringResource(Res.string.global_status_downloaded_only).takeIf { state.downloadedOnly },
stringResource(Res.string.global_status_incognito).takeIf { state.incognito },
).joinToString(", ")
Box(modifier = Modifier.size(40.dp).clearAndSetSemantics { contentDescription = description }, contentAlignment = Alignment.Center) {
if (downloads.visible) StatusProgressRing(downloads, MaterialTheme.colorScheme.primary, 40.dp)
if (library != null) StatusProgressRing(library, MaterialTheme.colorScheme.secondary, 30.dp)
if (sync.visible) StatusProgressRing(sync, MaterialTheme.colorScheme.tertiary, 20.dp)
val error = downloads.error || library?.error == true || sync.error
Icon(
imageVector = when {
error -> Icons.Filled.ErrorOutline
downloads.paused || library?.paused == true -> Icons.Filled.Pause
state.incognito -> Icons.Filled.VisibilityOff
state.downloadedOnly -> Icons.Filled.Download
else -> Icons.Filled.Info
},
contentDescription = null,
tint = if (error) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(if (downloads.visible || library != null || sync.visible) 12.dp else 24.dp),
)
}
}
@Composable
private fun ActiveMode(icon: ImageVector, title: String) {
Surface(shape = MaterialTheme.shapes.small, color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Icon(icon, contentDescription = null, modifier = Modifier.size(16.dp))
Text(title, style = MaterialTheme.typography.labelMedium)
}
}
}
@Composable
private fun libraryStatusText(update: GlobalLibraryUpdateStatus): String = when {
update.cancelled -> stringResource(Res.string.global_status_library_cancelled, update.label)
update.running && update.total <= 0 -> stringResource(Res.string.global_status_library_preparing, update.label)
update.running -> stringResource(Res.string.global_status_library_running, update.label, update.checked, update.total)
else -> stringResource(Res.string.global_status_library_complete, update.label, update.updated, update.failed)
}
@Composable
private fun downloadStatusText(downloads: GlobalDownloadStatus): String = when {
!downloads.isRelevant -> stringResource(Res.string.global_status_downloads_idle)
downloads.failedCount > 0 -> stringResource(
Res.string.global_status_downloads_failed,
downloads.pendingCount,
downloads.failedCount,
)
downloads.pausedCount > 0 && downloads.activeCount == 0 -> stringResource(
Res.string.global_status_downloads_paused,
downloads.pausedCount,
)
else -> stringResource(
Res.string.global_status_downloads_active,
downloads.activeCount,
downloads.pendingCount,
)
}
@Composable
private fun syncStatusText(state: GlobalStatusUiState): String = when (state.sync.stage) {
SyncOperationStage.Syncing -> stringResource(Res.string.global_status_sync_syncing)
SyncOperationStage.Uploading -> stringResource(Res.string.global_status_sync_uploading)
SyncOperationStage.Downloading -> stringResource(Res.string.global_status_sync_downloading)
null -> when (state.sync.lastOutcome) {
SyncOperationOutcome.Succeeded -> stringResource(Res.string.global_status_sync_succeeded)
SyncOperationOutcome.Failed -> stringResource(Res.string.global_status_sync_failed)
SyncOperationOutcome.Cancelled -> stringResource(Res.string.global_status_sync_cancelled)
null -> stringResource(Res.string.global_status_sync_idle)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/status/GlobalStatusViewModel.kt
- Source · implementation · 240 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.
Declaration checklist (source line numbers):
26: data class GlobalDownloadStatus(
39: data class GlobalLibraryUpdateStatus(
53: data class GlobalStatusUiState(
74: data class StatusOverlayPolicy(
79: internal fun reduceGlobalStatusExpansion(state: GlobalStatusUiState, expanded: Boolean): GlobalStatusUiState =
82: internal fun statusOverlayPolicy(state: GlobalStatusUiState): StatusOverlayPolicy {
96: internal fun aggregateDownloads(
140: private data class DownloadAggregateEntry(
149: private fun Int?.orZero(): Int = this ?: 0
151: private data class StatusSnapshotInput(
158: private fun YokanDatabaseSnapshot.toStatusInput() = StatusSnapshotInput(
165: class GlobalStatusViewModel(
209: fun open() = _state.update { reduceGlobalStatusExpansion(it, expanded = true) }
211: fun dismiss() = _state.update { reduceGlobalStatusExpansion(it, expanded = false) }
213: fun updateHostContext(
231: private fun LibraryUpdateProgressState.toGlobalStatus() = GlobalLibraryUpdateStatus(
Exact file bytes / download · SHA-256 ea1ecbfe045c7ccb89b0de9ab7b3546241ae457a735481c6dece049be04e908a.
Complete file
package eu.friedcutlet.yokan.ui.status
import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbGlobalStatusVisibility
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.services.download.DownloadProgress
import eu.friedcutlet.yokan.services.download.downloadTaskId
import eu.friedcutlet.yokan.services.library.LibraryUpdateProgressState
import eu.friedcutlet.yokan.services.sync.SyncOperationOutcome
import eu.friedcutlet.yokan.services.sync.SyncOperationState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
@Immutable
data class GlobalDownloadStatus(
val pendingCount: Int = 0,
val activeCount: Int = 0,
val pausedCount: Int = 0,
val failedCount: Int = 0,
val completedUnits: Int = 0,
val totalUnits: Int = 0,
val progress: Float? = null,
) {
val isRelevant: Boolean get() = pendingCount > 0 || activeCount > 0 || pausedCount > 0 || failedCount > 0
}
@Immutable
data class GlobalLibraryUpdateStatus(
val label: String,
val checked: Int,
val total: Int,
val updated: Int,
val failed: Int,
val running: Boolean,
val cancelRequested: Boolean,
val cancelled: Boolean,
) {
val progress: Float? get() = total.takeIf { it > 0 }?.let { (checked.toFloat() / it).coerceIn(0f, 1f) }
}
@Immutable
data class GlobalStatusUiState(
val downloadedOnly: Boolean = false,
val incognito: Boolean = false,
val downloads: GlobalDownloadStatus = GlobalDownloadStatus(),
val sync: SyncOperationState = SyncOperationState(),
val libraryUpdate: GlobalLibraryUpdateStatus? = null,
val visibility: DbGlobalStatusVisibility = DbGlobalStatusVisibility.Automatic,
val expanded: Boolean = false,
/** The top route is a reader or player (the status chrome moves out of the way). */
val immersive: Boolean = false,
val playerMinimized: Boolean = false,
val onboarding: Boolean = false,
val appLocked: Boolean = false,
val pictureInPicture: Boolean = false,
) {
val hasRelevantStatus: Boolean
get() = downloadedOnly || incognito || downloads.isRelevant || sync.isActive ||
sync.lastOutcome == SyncOperationOutcome.Failed || libraryUpdate != null
}
@Immutable
data class StatusOverlayPolicy(
val showCollapsed: Boolean,
val showExpanded: Boolean,
)
internal fun reduceGlobalStatusExpansion(state: GlobalStatusUiState, expanded: Boolean): GlobalStatusUiState =
state.copy(expanded = expanded)
internal fun statusOverlayPolicy(state: GlobalStatusUiState): StatusOverlayPolicy {
if (state.onboarding || state.appLocked || state.pictureInPicture) {
return StatusOverlayPolicy(showCollapsed = false, showExpanded = false)
}
if (state.expanded) return StatusOverlayPolicy(showCollapsed = false, showExpanded = true)
val immersive = state.immersive && !state.playerMinimized
val collapsed = when (state.visibility) {
DbGlobalStatusVisibility.Hidden -> false
DbGlobalStatusVisibility.AlwaysVisible -> true
DbGlobalStatusVisibility.Automatic -> state.hasRelevantStatus && !immersive
}
return StatusOverlayPolicy(showCollapsed = collapsed, showExpanded = false)
}
internal fun aggregateDownloads(
persisted: List<DbDownload>,
active: List<DownloadProgress>,
): GlobalDownloadStatus {
val activeByTask = active.associateBy(DownloadProgress::taskId)
val pending = persisted.filter { it.isDownload != true }
val pendingTaskIds = pending.mapTo(mutableSetOf()) { downloadTaskId(it.chapterId, it.id) }
val merged = pending.map { record ->
val taskId = downloadTaskId(record.chapterId, record.id)
val progress = activeByTask[taskId]
DownloadAggregateEntry(
taskId = taskId,
succeeded = progress?.succeeded ?: record.succeeded.orZero(),
failed = progress?.failed ?: record.failed.orZero(),
total = progress?.total ?: record.total.orZero(),
active = progress?.isCompleted == false,
paused = progress?.isPaused == true,
)
} + active.filter { progress ->
progress.taskId !in pendingTaskIds && !progress.isCompleted
}.map { progress ->
DownloadAggregateEntry(
taskId = progress.taskId,
succeeded = progress.succeeded,
failed = progress.failed,
total = progress.total,
active = true,
paused = progress.isPaused,
)
}
val totalUnits = merged.sumOf { it.total.coerceAtLeast(0) }
val completedUnits = merged.sumOf { (it.succeeded + it.failed).coerceIn(0, it.total.coerceAtLeast(0)) }
val determinate = merged.isNotEmpty() && merged.all { it.total > 0 } && totalUnits > 0
return GlobalDownloadStatus(
pendingCount = merged.size,
activeCount = merged.count { it.active && !it.paused },
pausedCount = merged.count { it.paused },
failedCount = merged.count { it.failed > 0 },
completedUnits = completedUnits,
totalUnits = totalUnits,
progress = if (determinate) (completedUnits.toFloat() / totalUnits).coerceIn(0f, 1f) else null,
)
}
private data class DownloadAggregateEntry(
val taskId: String,
val succeeded: Int,
val failed: Int,
val total: Int,
val active: Boolean,
val paused: Boolean,
)
private fun Int?.orZero(): Int = this ?: 0
private data class StatusSnapshotInput(
val downloadedOnly: Boolean,
val incognito: Boolean,
val visibility: DbGlobalStatusVisibility,
val downloads: List<DbDownload>,
)
private fun YokanDatabaseSnapshot.toStatusInput() = StatusSnapshotInput(
downloadedOnly = settings.downloadedOnlyMode,
incognito = settings.incognitoMode,
visibility = settings.globalStatusVisibility,
downloads = downloads,
)
class GlobalStatusViewModel(
databaseSnapshots: StateFlow<YokanDatabaseSnapshot>,
activeDownloads: StateFlow<List<DownloadProgress>>,
syncOperations: StateFlow<SyncOperationState>,
libraryUpdates: Flow<LibraryUpdateProgressState?>,
) : ViewModel() {
private val initialSnapshot = databaseSnapshots.value
private val _state = MutableStateFlow(
GlobalStatusUiState(
downloadedOnly = initialSnapshot.settings.downloadedOnlyMode,
incognito = initialSnapshot.settings.incognitoMode,
downloads = aggregateDownloads(initialSnapshot.downloads, activeDownloads.value),
sync = syncOperations.value,
visibility = initialSnapshot.settings.globalStatusVisibility,
),
)
val state: StateFlow<GlobalStatusUiState> = _state.asStateFlow()
init {
viewModelScope.launch {
val statusSnapshots = databaseSnapshots
.map(YokanDatabaseSnapshot::toStatusInput)
.distinctUntilChanged()
combine(statusSnapshots, activeDownloads, syncOperations) { snapshot, downloads, sync ->
Triple(snapshot, downloads, sync)
}.collect { (snapshot, downloads, sync) ->
_state.update { current ->
current.copy(
downloadedOnly = snapshot.downloadedOnly,
incognito = snapshot.incognito,
downloads = aggregateDownloads(snapshot.downloads, downloads),
sync = sync,
visibility = snapshot.visibility,
)
}
}
}
viewModelScope.launch {
libraryUpdates.collect { progress ->
_state.update { it.copy(libraryUpdate = progress?.toGlobalStatus()) }
}
}
}
fun open() = _state.update { reduceGlobalStatusExpansion(it, expanded = true) }
fun dismiss() = _state.update { reduceGlobalStatusExpansion(it, expanded = false) }
fun updateHostContext(
immersive: Boolean,
playerMinimized: Boolean,
onboarding: Boolean,
appLocked: Boolean,
pictureInPicture: Boolean,
) = _state.update {
it.copy(
immersive = immersive,
playerMinimized = playerMinimized,
onboarding = onboarding,
appLocked = appLocked,
pictureInPicture = pictureInPicture,
expanded = if (onboarding || appLocked || pictureInPicture) false else it.expanded,
)
}
}
private fun LibraryUpdateProgressState.toGlobalStatus() = GlobalLibraryUpdateStatus(
label = itemType.label,
checked = checked,
total = total,
updated = updated,
failed = failed,
running = running,
cancelRequested = cancelRequested,
cancelled = cancelled,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/status/InAppSnackbarEffect.kt
- Source · implementation · 25 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
14: fun InAppSnackbarEffect(snackbarHostState: SnackbarHostState, profileId: ProfileId) {
Exact file bytes / download · SHA-256 a138c4956812ab788768a33c8e775c6e656e7b0be3e2a5211c771c1427d2ebaa.
Complete file
package eu.friedcutlet.yokan.ui.status
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
/**
* In-app toasts: background services and screens post to [InAppNotifications]; messages visible to
* [profileId] surface through [snackbarHostState] instead of OS-level popups.
*/
@Composable
fun InAppSnackbarEffect(snackbarHostState: SnackbarHostState, profileId: ProfileId) {
LaunchedEffect(snackbarHostState, profileId) {
InAppNotifications.messages.collect { msg ->
if (!msg.visibleTo(profileId)) return@collect
val text = when {
msg.title.isNotBlank() && msg.message.isNotBlank() -> "${msg.title}: ${msg.message}"
else -> msg.title.ifBlank { msg.message }
}
if (text.isNotBlank()) snackbarHostState.showSnackbar(text)
}
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/discord/DiscordGatewayClientTest.kt
- Source · test / fixture · 38 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
14: class DiscordGatewayClientTest {
16: fun cancelledCoverLookupIsNotCached() = runTest {
Exact file bytes / download · SHA-256 e0e27773ed71daa867b971584b06a5d7ecfc10d358f9a3c585fe9c2b58d53bba.
Complete file
package eu.friedcutlet.yokan.services.discord
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.http.HttpStatusCode
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
class DiscordGatewayClientTest {
@Test
fun cancelledCoverLookupIsNotCached() = runTest {
var requests = 0
val firstRequestStarted = CompletableDeferred<Unit>()
val engine = MockEngine {
requests++
if (requests == 1) {
firstRequestStarted.complete(Unit)
awaitCancellation()
}
respond("""[{"external_asset_path":"external/abc"}]""", HttpStatusCode.OK)
}
val client = DiscordGatewayClient("token", engine, backgroundScope, onRejected = {})
val cancelled = launch { client.mediaProxyAsset("https://cover") }
firstRequestStarted.await()
cancelled.cancelAndJoin()
val path = client.mediaProxyAsset("https://cover")
assertEquals("mp:external/abc", path)
assertEquals(2, requests)
client.close()
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/discord/DiscordPresenceTest.kt
- Source · test / fixture · 104 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
19: class DiscordPresenceTest {
22: private fun settings(discord: DbDiscordPreferences = DbDiscordPreferences(), incognito: Boolean = false) =
Exact file bytes / download · SHA-256 a047760d8e35a3fd1f8c387920c30ae24307a38814f7eca7afcf9684a67873d1.
Complete file
package eu.friedcutlet.yokan.services.discord
import eu.friedcutlet.yokan.database.DbDiscordAccount
import eu.friedcutlet.yokan.database.DbDiscordButton
import eu.friedcutlet.yokan.database.DbDiscordPreferences
import eu.friedcutlet.yokan.database.DbDiscordStatus
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.UncategorizedActivityCategoryId
import eu.friedcutlet.yokan.ui.screens.settings.discord.cleanDiscordTokenResult
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class DiscordPresenceTest {
private val request = DiscordPresenceRequest("Frieren", "Episode 3", "https://cdn.test/c.jpg", watching = true, sourceId = 7, categoryIds = listOf(4))
private fun settings(discord: DbDiscordPreferences = DbDiscordPreferences(), incognito: Boolean = false) =
DbSettings(incognitoMode = incognito, features = DbSettings().features.copy(discord = discord))
@Test fun visibleTitleCarriesCustomisation() {
val activity = discordActivity(settings(DbDiscordPreferences(customMessage = " Binge night ", buttons = listOf(
DbDiscordButton("Site", "https://a.test"), DbDiscordButton("", "https://b.test"), DbDiscordButton("Bad", "ftp://c"), DbDiscordButton("Third", "https://d.test"),
))), request, 1_000)!!
assertEquals("Binge night", activity.details)
assertEquals("Episode 3", activity.state)
assertEquals("https://cdn.test/c.jpg", activity.coverUrl)
assertEquals(1_000, activity.startedAtMillis)
assertEquals(listOf("Site", "Third"), activity.buttons.map { it.label })
val plain = discordActivity(settings(DbDiscordPreferences(showTimestamp = false, showButtons = false)), request, 1_000)!!
assertEquals("Watching Frieren", plain.details)
assertNull(plain.startedAtMillis)
assertEquals(emptyList(), plain.buttons)
}
@Test fun privacyRulesHideTheTitle() {
assertNull(discordActivity(settings(incognito = true), request, 0), "hide-in-incognito publishes nothing")
// Incognito without the hide flag keeps the previous behaviour: the title is shown.
assertEquals("Watching Frieren", discordActivity(settings(incognito = true).copy(hideDiscordRpcInIncognito = false), request, 0)!!.details)
for (prefs in listOf(DbDiscordPreferences(alwaysPrivate = true), DbDiscordPreferences(privateCategoryIds = setOf(4)))) {
val idle = discordActivity(settings(prefs), request, 0)!!
assertEquals("Idle", idle.details)
assertEquals("-----", idle.state)
assertNull(idle.coverUrl)
}
val uncategorized = request.copy(categoryIds = emptyList())
assertEquals("Idle", discordActivity(settings(DbDiscordPreferences(privateCategoryIds = setOf(UncategorizedActivityCategoryId))), uncategorized, 0)!!.details)
assertEquals("Watching Frieren", discordActivity(settings(DbDiscordPreferences(privateCategoryIds = setOf(UncategorizedActivityCategoryId))), request, 0)!!.details)
}
@Test fun accountSwitchingKeepsOneActiveAccount() {
val a = DbDiscordAccount("1", "a", token = "ta")
val b = DbDiscordAccount("2", "b", token = "tb")
var prefs = DbDiscordPreferences().withAccount(a).withAccount(b)
assertEquals("2", prefs.activeAccountId)
prefs = prefs.withActive("1").withActive("missing")
assertEquals(a, prefs.activeAccount)
prefs = prefs.withAccount(a.copy(token = "ta2"))
assertEquals(listOf("tb", "ta2"), prefs.accounts.map { it.token })
prefs = prefs.withoutAccount("1")
assertEquals(b, prefs.activeAccount)
assertEquals(DbDiscordPreferences(), prefs.withoutAccount("2").copy(status = DbDiscordStatus.Online))
assertEquals(emptyList(), prefs.forExport().accounts)
assertEquals(false, prefs.toString().contains("tb"))
}
@Test fun gatewayPresenceUsesUserActivityShape() {
val activity = DiscordActivity("Reading One Piece", "Chapter 1", watching = false, startedAtMillis = 5, coverUrl = "https://x", buttons = listOf(DbDiscordButton("Site", "https://a.test")))
val payload = gatewayPresenceUpdate(activity, "mp:external/abc", DbDiscordStatus.DoNotDisturb, 9)
val d = payload["d"]!!.jsonObject
assertEquals("dnd", d["status"]!!.jsonPrimitive.content)
val sent = d["activities"]!!.jsonArray.single().jsonObject
assertEquals(0, sent["type"]!!.jsonPrimitive.content.toInt())
assertEquals(DiscordApplicationId, sent["application_id"]!!.jsonPrimitive.content)
assertEquals("mp:external/abc", sent["assets"]!!.jsonObject["large_image"]!!.jsonPrimitive.content)
assertEquals("Site", sent["buttons"]!!.jsonArray.single().jsonPrimitive.content)
assertEquals("https://a.test", sent["metadata"]!!.jsonObject["button_urls"]!!.jsonArray.single().jsonPrimitive.content)
assertEquals(5, sent["timestamps"]!!.jsonObject["start"]!!.jsonPrimitive.content.toLong())
val cleared = gatewayPresenceUpdate(null, null, DbDiscordStatus.Online, 9)["d"]!!.jsonObject
assertEquals(JsonArray(emptyList()), cleared["activities"])
assertNull((gatewayPresenceUpdate(activity.copy(buttons = emptyList()), null, DbDiscordStatus.Idle, 0)["d"]!!.jsonObject["activities"]!!.jsonArray.single() as JsonObject)["assets"])
}
@Test fun parsesDiscordResponsesAndTokens() {
assertEquals("mp:external/abc/https/x", parseExternalAssetPath("""[{"url":"https://x","external_asset_path":"external/abc/https/x"}]"""))
assertNull(parseExternalAssetPath("""{"message":"401: Unauthorized"}"""))
val profile = discordAccountFromProfile("""{"id":"42","username":"neo","global_name":"Neo","avatar":"hash"}""", "t")!!
assertEquals("Neo", profile.displayName)
assertEquals("https://cdn.discordapp.com/avatars/42/hash.png", profile.avatarUrl)
// "MTIzNDU2Nzg5" is base64("123456789").
assertEquals("123456789", discordAccountFromToken("MTIzNDU2Nzg5.GxYz.signature")!!.id)
assertNull(discordAccountFromToken("not-a-token"))
assertNull(discordAccountFromToken("aGVsbG8.a.b"))
assertEquals("MTIz.a.b", cleanDiscordTokenResult("\"\\\"MTIz.a.b\\\"\""))
assertNull(cleanDiscordTokenResult("\"\""))
assertNull(cleanDiscordTokenResult("null"))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/logging/CrashReportStoreTest.kt
- Source · test / fixture · 34 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
11: class CrashReportStoreTest {
13: fun persistsAndRedactsLatestReport() {
23: fun malformedAndOversizedInputRemainsSafeAndBounded() {
Exact file bytes / download · SHA-256 a6a507b88ae8106bcdcfbbe4fcd4c0c35e96dd5c0ad3ecab2c967eb6310547cc.
Complete file
package eu.friedcutlet.yokan.services.logging
import eu.friedcutlet.yokan.services.files.MemoryFiles
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
class CrashReportStoreTest {
@Test
fun persistsAndRedactsLatestReport() {
val files = MemoryFiles()
CrashReportStore.record(files, IllegalStateException("Authorization: Bearer secret-token"))
val report = CrashReportStore.read(files).orEmpty()
assertTrue(report.contains("[REDACTED]"))
assertFalse(report.contains("secret-token"))
}
@Test
fun malformedAndOversizedInputRemainsSafeAndBounded() {
val files = MemoryFiles()
CrashReportStore.record(files, Throwable("token=secret\u0000" + "x".repeat(100_000)))
assertTrue(CrashReportStore.read(files)!!.encodeToByteArray().size <= 32 * 1024)
files.writeBytes("/cache/crash/latest.txt", byteArrayOf(0xC3.toByte()))
assertNotNull(CrashReportStore.read(files))
CrashReportStore.delete(files)
assertNull(CrashReportStore.read(files))
assertEquals("", CrashReportStore.redact(""))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/notifications/ProfileNotificationsTest.kt
- Source · test / fixture · 83 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
13: class ProfileNotificationsTest {
Exact file bytes / download · SHA-256 edf5fff840e0c799da2fca392422587961386265b79f23f10ef78007a5cab48f.
Complete file
package eu.friedcutlet.yokan.services.notifications
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.ProfileSession
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class ProfileNotificationsTest {
@Test fun defaultAdoptsLegacyAndroidAndIosNotificationIdentities() {
val namespace = ProfileNotificationNamespace(ProfileId.Default)
for (tag in listOf(null, "", "chapter-42", "periodic.sync")) {
assertNull(namespace.androidTag(NotificationChannel.Downloads, tag))
assertEquals(("yokan_downloads" + tag.orEmpty()).hashCode(), namespace.androidId("yokan_downloads", tag))
assertEquals("yokan.downloads.${tag.orEmpty()}", namespace.iosIdentifier(NotificationChannel.Downloads, tag))
}
}
@Test fun identicalAndHashCollidingTagsCannotCrossExtraOwnersOrChannels() {
assertEquals("Aa".hashCode(), "BB".hashCode())
val android = mutableSetOf<Pair<String?, Int>>()
val ios = mutableSetOf<String>()
for (id in listOf(A, B)) for (channel in NotificationChannel.entries) for (tag in listOf("Aa", "BB", "chapter-42", "")) {
val namespace = ProfileNotificationNamespace(id)
assertTrue(android.add(namespace.androidTag(channel, tag) to namespace.androidId("channel", tag)))
assertTrue(ios.add(namespace.iosIdentifier(channel, tag)))
}
assertNotEquals(ProfileNotificationNamespace(A).androidTag(NotificationChannel.Downloads, ""),
ProfileNotificationNamespace(A).androidTag(NotificationChannel.Downloads, "0:"))
}
@Test fun aDefaultTagCannotImpersonateAnExtraOwnersNotificationKey() {
val extra = ProfileNotificationNamespace(A)
val forgedTag = extra.androidTag(NotificationChannel.Downloads, "chapter-42")
val default = ProfileNotificationNamespace(ProfileId.Default)
assertNotEquals(default.androidTag(NotificationChannel.Downloads, forgedTag) to default.androidId("channel", forgedTag),
extra.androidTag(NotificationChannel.Downloads, "chapter-42") to extra.androidId("channel", "chapter-42"))
}
@Test fun sessionForcesItsOriginAndSuppressesStaleNotificationReferences() = runTest {
val recording = RecordingNotifications()
val owner = ProfileSession(A, databaseFactory = { error("Notifications must not open storage") }, notificationsFactory = {
assertEquals(A, it); recording
})
val captured = owner.notifications
captured.notify(NotificationPayload(NotificationChannel.Downloads, "Title", "Progress", "chapter-42", profileId = B))
captured.requestPermission(); captured.cancel(NotificationChannel.Downloads, "chapter-42")
assertEquals(A, recording.posted.single().profileId)
assertEquals(1, recording.permissionRequests); assertEquals(1, recording.cancelled.size)
owner.close()
captured.notify(NotificationPayload(NotificationChannel.Downloads, "Stale", "Stale"))
captured.cancel(NotificationChannel.Downloads, "chapter-42"); captured.requestPermission()
assertFalse(captured.supported()); assertEquals(1, recording.posted.size)
assertEquals(1, recording.permissionRequests); assertEquals(1, recording.cancelled.size)
}
@Test fun retiringOneOwnerLeavesOtherOwnersNotificationEndpointUsable() = runTest {
val a = RecordingNotifications(); val b = RecordingNotifications()
val left = ProfileSession(A, notificationsFactory = { a }); val right = ProfileSession(B, notificationsFactory = { b })
val old = left.notifications; val current = right.notifications
left.close()
old.notify(NotificationPayload(NotificationChannel.Sync, "Old", "Old"))
current.notify(NotificationPayload(NotificationChannel.Sync, "B", "B"))
assertEquals(0, a.posted.size); assertEquals(B, b.posted.single().profileId); assertTrue(current.supported())
right.close()
}
@Test fun inAppMessagesKeepDeviceEventsVisibleAndSuppressForeignProfileEvents() {
val owned = InAppMessage("A", "Private", profileId = A)
assertTrue(owned.visibleTo(A)); assertFalse(owned.visibleTo(B)); assertFalse(owned.visibleTo(ProfileId.Default))
val device = InAppMessage("Device", "Permission")
assertTrue(device.visibleTo(A)); assertTrue(device.visibleTo(B)); assertTrue(device.visibleTo(ProfileId.Default))
}
private companion object {
val A = ProfileId("p_" + "a".repeat(32))
val B = ProfileId("p_" + "b".repeat(32))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/notifications/TestNotifications.kt
- Source · test / fixture · 18 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
3: internal object NoNotifications : NotificationService {
4: override fun supported(): Boolean = false
5: override fun notify(payload: NotificationPayload) = Unit
6: override fun cancel(channel: NotificationChannel, tag: String?) = Unit
9: internal class RecordingNotifications : NotificationService {
14: override fun supported() = true
15: override fun requestPermission() { permissionRequests++ }
16: override fun notify(payload: NotificationPayload) { posted += payload }
17: override fun cancel(channel: NotificationChannel, tag: String?) { cancelled += channel to tag }
Exact file bytes / download · SHA-256 c3f399df6e86cdd564b6b7e56e2ffe955237b39f806d550b7e7755d44feedf06.
Complete file
package eu.friedcutlet.yokan.services.notifications
internal object NoNotifications : NotificationService {
override fun supported(): Boolean = false
override fun notify(payload: NotificationPayload) = Unit
override fun cancel(channel: NotificationChannel, tag: String?) = Unit
}
internal class RecordingNotifications : NotificationService {
val posted = mutableListOf<NotificationPayload>()
val cancelled = mutableListOf<Pair<NotificationChannel, String?>>()
var permissionRequests = 0
override fun supported() = true
override fun requestPermission() { permissionRequests++ }
override fun notify(payload: NotificationPayload) { posted += payload }
override fun cancel(channel: NotificationChannel, tag: String?) { cancelled += channel to tag }
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/scheduling/AutomaticUpdateGateTest.kt
- Source · test / fixture · 136 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
8: class AutomaticUpdateGateTest {
9: private fun settings(constraints: DbAutomaticUpdateConstraints = DbAutomaticUpdateConstraints(), wifi: Boolean = false) =
Exact file bytes / download · SHA-256 a71682ba1afc92ad8a882c2e1b76c9e56ee256bdf23c65a542da3cd1b3d916d3.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.database.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*
class AutomaticUpdateGateTest {
private fun settings(constraints: DbAutomaticUpdateConstraints = DbAutomaticUpdateConstraints(), wifi: Boolean = false) =
DbSettings(downloadOnlyOnWifi = wifi, features = DbFeaturePreferences(library = DbLibraryPreferences(deviceConstraints = constraints)))
private val online = UpdateDeviceConditions(connected = true, wifi = true, unmetered = true, externalPower = true)
@Test fun defaultsPreserveLegacyPolicyWithoutReadingPlatformTelemetry() = runTest {
var legacy = 0
val gate = AutomaticUpdateGate(read = { error("No explicit constraints") }, legacyNetwork = { legacy++; false })
assertTrue(gate.check(settings()).allowed)
assertEquals(0, legacy)
assertEquals(setOf(UpdateDeferral.UnmeteredRequired), gate.check(settings(wifi = true)).reasons)
assertEquals(1, legacy)
}
@Test fun unknownExplicitReadingsFailClosedAndRestrictionsCombine() {
val all = DbAutomaticUpdateConstraints(DbUpdateNetwork.Unmetered, requireExternalPower = true)
assertEquals(setOf(UpdateDeferral.NetworkUnknown, UpdateDeferral.PowerUnknown),
evaluateUpdateConstraints(all, UpdateDeviceConditions(), true).reasons)
assertEquals(setOf(UpdateDeferral.UnmeteredRequired, UpdateDeferral.PowerRequired),
evaluateUpdateConstraints(all, online.copy(unmetered = false, externalPower = false), true).reasons)
assertTrue(evaluateUpdateConstraints(all, online, false).allowed)
assertEquals(setOf(UpdateDeferral.NetworkUnavailable), evaluateUpdateConstraints(all, online.copy(connected = false), true).reasons)
}
@Test fun wifiIsDistinctFromUnmeteredAndConnectedCanOverrideLegacyWifi() = runTest {
val paidWifi = online.copy(unmetered = false)
assertTrue(evaluateUpdateConstraints(DbAutomaticUpdateConstraints(DbUpdateNetwork.Wifi), paidWifi, true).allowed)
assertFalse(evaluateUpdateConstraints(DbAutomaticUpdateConstraints(DbUpdateNetwork.Unmetered), paidWifi, true).allowed)
assertEquals(setOf(UpdateDeferral.WifiUnknown), evaluateUpdateConstraints(DbAutomaticUpdateConstraints(DbUpdateNetwork.Wifi),
online.copy(wifi = null), true).reasons)
assertEquals(setOf(UpdateDeferral.WifiRequired), evaluateUpdateConstraints(DbAutomaticUpdateConstraints(DbUpdateNetwork.Wifi),
online.copy(wifi = false), true).reasons)
val gate = AutomaticUpdateGate(read = { online.copy(wifi = false) }, legacyNetwork = { false })
assertTrue(gate.check(settings(DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected), wifi = true)).allowed)
}
@Test fun userCostClassificationOnlyFillsUnknownAndNeverOverridesReportedMeteringOrOfflineState() {
val constraints = DbAutomaticUpdateConstraints(DbUpdateNetwork.Unmetered, unknownNetworkCost = DbUnknownNetworkCost.Unmetered)
assertTrue(evaluateUpdateConstraints(constraints, online.copy(unmetered = null), true).allowed)
assertFalse(evaluateUpdateConstraints(constraints, online.copy(unmetered = false), true).allowed)
assertFalse(evaluateUpdateConstraints(constraints, online.copy(connected = false, unmetered = null), true).allowed)
assertEquals(setOf(UpdateDeferral.NetworkCostUnknown), evaluateUpdateConstraints(constraints.copy(unknownNetworkCost = DbUnknownNetworkCost.Wait),
online.copy(unmetered = null), true).reasons)
assertEquals(setOf(UpdateDeferral.UnmeteredRequired), evaluateUpdateConstraints(constraints.copy(unknownNetworkCost = DbUnknownNetworkCost.Metered),
online.copy(unmetered = null), true).reasons)
}
@Test fun repeatedTitleChecksReuseReadingsAndStatusUntilFreshnessExpiresOrForceIsRequested() = runTest {
var time = 100L
var reads = 0
var sample = online
val gate = AutomaticUpdateGate(read = { reads++; sample }, clock = { time }, cacheMillis = 5000)
val db = settings(DbAutomaticUpdateConstraints(DbUpdateNetwork.Unmetered))
val first = gate.check(db)
time += 100
repeat(3000) { assertEquals(first, gate.check(db)) }
assertEquals(1, reads)
sample = online.copy(unmetered = false)
time = 5100
assertFalse(gate.check(db).allowed)
assertEquals(2, reads)
sample = online
assertTrue(gate.check(db, force = true).allowed)
assertEquals(3, reads)
time = 50 // Clock rollback cannot keep stale readings indefinitely.
gate.check(db)
assertEquals(4, reads)
}
@Test fun newlyRequiredPowerResamplesAndNetworkOnlyChecksDoNotRequestBatteryTelemetry() = runTest {
val requests = mutableListOf<Boolean>()
val gate = AutomaticUpdateGate(read = { power -> requests += power; online.copy(externalPower = if (power) true else null) }, clock = { 100 })
val networkOnly = DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected)
assertTrue(gate.check(settings(networkOnly)).allowed)
assertTrue(gate.check(settings(networkOnly.copy(requireExternalPower = true))).allowed)
assertEquals(listOf(false, true), requests)
}
@Test fun failedAndDeniedReadsRemainUnknownAndCanRecoverOnTheNextCheck() = runTest {
var fail = true
val gate = AutomaticUpdateGate(read = { if (fail) error("Permission denied") else online })
val db = settings(DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected, requireExternalPower = true))
assertEquals(setOf(UpdateDeferral.NetworkUnknown, UpdateDeferral.PowerUnknown), gate.check(db).reasons)
fail = false
assertTrue(gate.check(db, force = true).allowed)
}
@Test fun cancellationJoinsTheReadAndLeavesTheMutexUsableWithoutPublishingLateStatus() = runTest {
val started = CompletableDeferred<Unit>()
var finish = false
var slow = true
val gate = AutomaticUpdateGate(read = {
if (slow) { started.complete(Unit); try { awaitCancellation() } finally { finish = true } }
online
})
val db = settings(DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected))
val check = async { gate.check(db) }
started.await()
check.cancelAndJoin()
assertTrue(finish)
assertNull(gate.status.value)
slow = false
assertTrue(gate.check(db).allowed)
}
@Test fun profileGatesKeepTheirReadingsAndAdmissionIndependent() = runTest {
val a = AutomaticUpdateGate(read = { online.copy(externalPower = false) })
val b = AutomaticUpdateGate(read = { online })
val db = settings(DbAutomaticUpdateConstraints(requireExternalPower = true))
assertFalse(a.check(db).allowed)
assertTrue(b.check(db).allowed)
assertFalse(checkNotNull(a.status.value).allowed)
}
@Test fun legacyReaderCancellationAlsoPropagatesInsteadOfBecomingAnOrdinaryDeferral() = runTest {
val gate = AutomaticUpdateGate(legacyNetwork = { throw CancellationException("Owner retired") })
assertFailsWith<CancellationException> { gate.check(settings(wifi = true)) }
assertNull(gate.status.value)
}
@Test fun preferencesRoundTripAndDeferredOutcomesRetryWithoutConsumingTheScheduleSlot() {
val db = settings(DbAutomaticUpdateConstraints(DbUpdateNetwork.Wifi, true, DbUnknownNetworkCost.Metered))
assertEquals(db, DatabaseJson.decodeFromString(DbSettings.serializer(), DatabaseJson.encodeToString(DbSettings.serializer(), db)))
assertEquals(DbAutomaticUpdateConstraints(), DatabaseJson.decodeFromString(DbSettings.serializer(), "{}").features.library.deviceConstraints)
val deferred = PeriodicTaskOutcome(PeriodicTaskStatus.Deferred, "Waiting")
assertTrue(deferred.shouldRetry)
assertFalse(deferred.attempted)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundTaskCompletionTest.kt
- Source · test / fixture · 68 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
18: class BackgroundTaskCompletionTest {
Exact file bytes / download · SHA-256 484c5608cea5dec1aa16dc843080f73b0468f816ca3210470f0e549d07b1db95.
Complete file
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.services.scheduling
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class BackgroundTaskCompletionTest {
@Test fun expiryBeforeDispatchStillCompletesOnceWithoutRunningWork() = runTest {
var executed = false
val completions = mutableListOf<Boolean>()
val job = launchCompletingBackgroundTask(this, {
executed = true; ProfileWorkResult.Skipped
}, completions::add)
job.cancelAndJoin()
testScheduler.runCurrent()
assertFalse(executed); assertEquals(listOf(false), completions)
}
@Test fun expiryWaitsForFinalizersBeforeReportingFailure() = runTest {
val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
val completions = mutableListOf<Boolean>()
var finalized = false
val job = launchCompletingBackgroundTask(this, {
try { entered.complete(Unit); awaitCancellation() }
finally { withContext(NonCancellable) { release.await(); finalized = true } }
}, { completions += it; assertEquals(true, finalized) })
entered.await(); job.cancel(); testScheduler.runCurrent()
assertEquals(emptyList(), completions)
release.complete(Unit); job.join()
assertEquals(listOf(false), completions)
}
@Test fun completedAndStaleTasksSucceedWhileRecoverableFailuresDoNot() = runTest {
val outcomes = listOf(
ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Done")),
ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Disabled")),
ProfileWorkResult.Skipped,
ProfileWorkResult.Completed(PeriodicTaskOutcome(PeriodicTaskStatus.Failed, "Failed")),
ProfileWorkResult.Retry,
)
val completions = mutableListOf<Boolean>()
for (outcome in outcomes) launchCompletingBackgroundTask(this, { outcome }, completions::add).join()
assertEquals(listOf(true, true, true, false, false), completions)
}
@Test fun taskExceptionsCompleteWithFailureAndLeaveTheHostAlive() = runTest {
val parent = SupervisorJob()
val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
val completions = mutableListOf<Boolean>()
launchCompletingBackgroundTask(scope, { error("Task failure") }, completions::add).join()
assertEquals(listOf(false), completions)
assertEquals(true, parent.isActive)
launchCompletingBackgroundTask(scope, { ProfileWorkResult.Skipped }, completions::add).join()
assertEquals(listOf(false, true), completions)
parent.cancelAndJoin()
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/scheduling/PeriodicTaskRunnerTest.kt
- Source · test / fixture · 219 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
31: class PeriodicTaskRunnerTest {
33: fun deviceDeferralMakesNoRequestsOrSuccessNotificationAndRetriesWhenConditionsRecover() = runTest {
57: fun losingAConditionBetweenMediaTypesDefersTheRemainderWithoutConsumingTheScheduleSlot() = runTest {
75: fun metadataRefreshAppliesMatchesAndPostsSummary() = runTest {
98: fun libraryUpdateAggregatesEveryMediaTypeAndPostsSummary() = runTest {
113: fun syncErrorsRequestRetryAndLeaveFailureNotification() = runTest {
134: fun workManagerIntervalsAreDisabledOrAtLeastFifteenMinutes() {
142: fun dailySlotHelpersAnchorToLocalTimeOfDay() {
160: private fun runner(
178: private class FakeMetadataService(private val results: List<MetadataMedia>) : MetadataService {
179: override suspend fun health(baseUrl: String): Boolean = true
180: override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int): List<MetadataMedia> = results
181: override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>> = emptyList()
182: override suspend fun upsertLibraryEntry(
193: private class RecordingLibraryUpdater(private val afterType: () -> Unit = {}) : LibraryUpdaterService {
195: override suspend fun updateLibrary(
208: override suspend fun updateTitle(mangaId: Long): Boolean = true
211: private class FakeSyncService(private val result: SyncResult) : SyncService {
212: override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult =
214: override suspend fun logout(syncId: Long) = Unit
215: override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult = result
216: override suspend fun pushChanges(syncId: Long): SyncResult = result
217: override suspend fun pullChanges(syncId: Long): SyncResult = result
218: override fun status(syncId: Long): SyncConnectionStatus = SyncConnectionStatus(false, null, null, null)
Exact file bytes / download · SHA-256 195dd79fb6480ae600ae838bb8750eb4b99250319f7e8c2a162f1128395c4a9e.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.services.notifications.RecordingNotifications
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints
import eu.friedcutlet.yokan.database.DbUpdateNetwork
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.library.LibraryUpdateProgress
import eu.friedcutlet.yokan.services.library.LibraryUpdateResult
import eu.friedcutlet.yokan.services.library.LibraryUpdaterService
import eu.friedcutlet.yokan.services.metadata.MetadataLibraryEntry
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.services.metadata.MetadataService
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.notifications.NotificationPayload
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.sync.SyncConnectionStatus
import eu.friedcutlet.yokan.services.sync.SyncLoginResult
import eu.friedcutlet.yokan.services.sync.SyncResult
import eu.friedcutlet.yokan.services.sync.SyncService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
class PeriodicTaskRunnerTest {
@Test
fun deviceDeferralMakesNoRequestsOrSuccessNotificationAndRetriesWhenConditionsRecover() = runTest {
val database = InMemoryYokanDatabase()
database.updateSettings(database.settings().let { db -> db.copy(features = db.features.copy(library = db.features.library.copy(
deviceConstraints = DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected, requireExternalPower = true)))) })
var now = 0L
var power = false
val gate = AutomaticUpdateGate(read = { UpdateDeviceConditions(connected = true, externalPower = power) }, clock = { now })
val notifications = RecordingNotifications()
val updater = RecordingLibraryUpdater()
val runner = runner(database, updater = updater, notifications = notifications, gate = gate)
val deferred = runner.updateLibrary()
assertEquals(PeriodicTaskStatus.Deferred, deferred.status)
assertTrue(deferred.shouldRetry)
assertFalse(deferred.attempted)
assertTrue(updater.types.isEmpty())
assertTrue(notifications.posted.isEmpty())
now = 5001
power = true
assertEquals(PeriodicTaskStatus.Completed, runner.updateLibrary().status)
assertEquals(DbItemType.entries.toList(), updater.types)
assertEquals(1, notifications.posted.size)
}
@Test
fun losingAConditionBetweenMediaTypesDefersTheRemainderWithoutConsumingTheScheduleSlot() = runTest {
val database = InMemoryYokanDatabase()
database.updateSettings(database.settings().let { db -> db.copy(features = db.features.copy(library = db.features.library.copy(
deviceConstraints = DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected, requireExternalPower = true)))) })
var now = 0L
var power = true
val gate = AutomaticUpdateGate(read = { UpdateDeviceConditions(connected = true, externalPower = power) }, clock = { now })
val notifications = RecordingNotifications()
val updater = RecordingLibraryUpdater { power = false; now += 5001 }
val result = runner(database, updater = updater, notifications = notifications, gate = gate).updateLibrary()
assertEquals(listOf(DbItemType.Manga), updater.types)
assertEquals(PeriodicTaskStatus.Deferred, result.status)
assertTrue(result.message.contains("4 titles"))
assertTrue(result.shouldRetry)
assertFalse(result.attempted)
assertTrue(notifications.posted.isEmpty())
}
@Test
fun metadataRefreshAppliesMatchesAndPostsSummary() = runTest {
val database = InMemoryYokanDatabase().apply {
updateSettings(settings().copy(metadataServerEnabled = true, metadataServerUrl = "https://metadata.test"))
upsertManga(DbManga(id = 901, name = "Yokan", favorite = true, itemType = DbItemType.Manga))
}
val notifications = RecordingNotifications()
val runner = runner(
database = database,
metadata = FakeMetadataService(
listOf(MetadataMedia("media-1", "test", DbItemType.Manga, "Yokan", genres = listOf("Action"))),
),
notifications = notifications,
)
val outcome = runner.refreshMetadata()
assertEquals(PeriodicTaskStatus.Completed, outcome.status)
assertEquals(listOf("Action"), database.manga(901)?.genre)
assertEquals("Metadata refresh complete", notifications.posted.single().title)
assertTrue(notifications.posted.single().message.contains("1 of 1"))
}
@Test
fun libraryUpdateAggregatesEveryMediaTypeAndPostsSummary() = runTest {
val database = InMemoryYokanDatabase()
val notifications = RecordingNotifications()
val updater = RecordingLibraryUpdater()
val runner = runner(database, updater = updater, notifications = notifications)
val outcome = runner.updateLibrary()
assertEquals(DbItemType.entries.toList(), updater.types)
assertEquals(PeriodicTaskStatus.Completed, outcome.status)
assertTrue(outcome.message.contains("6 updated"))
assertEquals("Library update complete", notifications.posted.single().title)
}
@Test
fun syncErrorsRequestRetryAndLeaveFailureNotification() = runTest {
val database = InMemoryYokanDatabase().apply {
upsertSyncPreference(
DbSyncPreference(syncId = 1L, syncOn = true, authToken = "token", autoSyncFrequency = 3600),
)
}
val notifications = RecordingNotifications()
val runner = runner(
database,
sync = FakeSyncService(SyncResult(2, 3, settingsSynced = true, errors = listOf("offline"))),
notifications = notifications,
)
val outcome = runner.sync()
assertEquals(PeriodicTaskStatus.Failed, outcome.status)
assertTrue(outcome.shouldRetry)
assertEquals("Automatic sync failed", notifications.posted.single().title)
}
@Test
fun workManagerIntervalsAreDisabledOrAtLeastFifteenMinutes() {
assertEquals(0, periodicMinutes(0))
assertEquals(15, periodicMinutes(60))
assertEquals(60, periodicMinutes(3600))
assertFalse(PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "off").attempted)
}
@Test
fun dailySlotHelpersAnchorToLocalTimeOfDay() {
val utc = kotlinx.datetime.TimeZone.UTC
val threeAm = 3 * 60
val day = 86_400_000L
// 2024-01-02T10:00Z: today's 03:00 already passed, so the next slot is tomorrow 03:00.
val now = 1_704_189_600_000L
assertEquals(now - 7L * 3_600_000L, latestDailySlotMillis(threeAm, now, utc))
assertEquals(17L * 3_600_000L, nextDailySlotDelayMillis(threeAm, now, utc))
// 2024-01-02T01:00Z: today's 03:00 is ahead, so the latest slot is yesterday's.
val early = now - 9L * 3_600_000L
assertEquals(now - 7L * 3_600_000L - day, latestDailySlotMillis(threeAm, early, utc))
assertEquals(2L * 3_600_000L, nextDailySlotDelayMillis(threeAm, early, utc))
// Exactly on the slot counts as "already happened"; the next one is a full day away.
val onSlot = now - 7L * 3_600_000L
assertEquals(onSlot, latestDailySlotMillis(threeAm, onSlot, utc))
assertEquals(day, nextDailySlotDelayMillis(threeAm, onSlot, utc))
}
private fun runner(
database: InMemoryYokanDatabase,
metadata: MetadataService = FakeMetadataService(emptyList()),
updater: LibraryUpdaterService = RecordingLibraryUpdater(),
sync: SyncService = FakeSyncService(SyncResult(0, 0, false)),
notifications: NotificationService = RecordingNotifications(),
gate: AutomaticUpdateGate = AutomaticUpdateGate(),
): PeriodicTaskRunner = PeriodicTaskRunner(
database = database,
repository = DefaultYokanRepository(database),
metadata = metadata,
libraryUpdater = updater,
sync = sync,
notifications = notifications,
updateGate = gate,
)
}
private class FakeMetadataService(private val results: List<MetadataMedia>) : MetadataService {
override suspend fun health(baseUrl: String): Boolean = true
override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int): List<MetadataMedia> = results
override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>> = emptyList()
override suspend fun upsertLibraryEntry(
baseUrl: String,
token: String,
mediaId: String,
status: String,
progress: Int,
score: Int?,
isFavorite: Boolean,
): Boolean = true
}
private class RecordingLibraryUpdater(private val afterType: () -> Unit = {}) : LibraryUpdaterService {
val types = mutableListOf<DbItemType>()
override suspend fun updateLibrary(
itemType: DbItemType,
onProgress: (LibraryUpdateProgress) -> Unit,
shouldCancel: () -> Boolean,
titleIds: Set<Long>?,
mayStartTitle: suspend () -> Boolean,
): LibraryUpdateResult {
if (!mayStartTitle()) return LibraryUpdateResult(0, 0, 0, deferred = true)
types += itemType
afterType()
return LibraryUpdateResult(checked = 4, updated = 2, failed = 1)
}
override suspend fun updateTitle(mangaId: Long): Boolean = true
}
private class FakeSyncService(private val result: SyncResult) : SyncService {
override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult =
SyncLoginResult(true, "ok")
override suspend fun logout(syncId: Long) = Unit
override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult = result
override suspend fun pushChanges(syncId: Long): SyncResult = result
override suspend fun pullChanges(syncId: Long): SyncResult = result
override fun status(syncId: Long): SyncConnectionStatus = SyncConnectionStatus(false, null, null, null)
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/system/DeviceCapabilitiesTest.kt
- Source · test / fixture · 20 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class DeviceCapabilitiesTest {
9: fun tvUsesRailEvenAtCompactWidth() {
15: fun nonTvCompactKeepsBottomNavigation() {
Exact file bytes / download · SHA-256 85e6fd68235656f15a0e6334c0ee87c1ebbff3467ee877d36c9c34ffa6cf1c9e.
Complete file
package eu.friedcutlet.yokan.services.system
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class DeviceCapabilitiesTest {
@Test
fun tvUsesRailEvenAtCompactWidth() {
assertTrue(useRailNavigation(isTv = true, compact = true))
assertFalse(showBottomNavigation(isTv = true, compact = true, showRootNav = true))
}
@Test
fun nonTvCompactKeepsBottomNavigation() {
assertFalse(useRailNavigation(isTv = false, compact = true))
assertTrue(showBottomNavigation(isTv = false, compact = true, showRootNav = true))
assertFalse(showBottomNavigation(isTv = false, compact = true, showRootNav = false))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/translation/TranslatorServiceTest.kt
- Source · test / fixture · 84 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
14: class TranslatorServiceTest {
16: fun supportsEnglishGermanAndJapanese() {
34: fun postsLibreTranslateRequestAndParsesResponse() = runTest {
68: fun sameLanguageRequestReturnsOriginalTextWithoutNetworkCall() = runTest {
Exact file bytes / download · SHA-256 be25f3d8e3908d2da092ca86ab14d8e4d63a3bb5d17db5f5757d035015c962da.
Complete file
package eu.friedcutlet.yokan.services.translation
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
class TranslatorServiceTest {
@Test
fun supportsEnglishGermanAndJapanese() {
val service = LibreTranslateTranslatorService(HttpService { error("No network expected") })
assertEquals(
listOf(
TranslationLanguage.English,
TranslationLanguage.German,
TranslationLanguage.Japanese,
),
service.supportedLanguages(),
)
assertTrue(service.supports(TranslationLanguage.English, TranslationLanguage.German))
assertTrue(service.supports(TranslationLanguage.German, TranslationLanguage.Japanese))
assertTrue(service.supports(TranslationLanguage.Japanese, TranslationLanguage.English))
assertTrue(service.supports(TranslationLanguage.Auto, TranslationLanguage.English))
}
@Test
fun postsLibreTranslateRequestAndParsesResponse() = runTest {
val http = RecordingHttpService {
HttpResponse(
statusCode = 200,
body = """{"translatedText":"Guten Morgen","detectedLanguage":{"language":"en","confidence":0.95}}""",
)
}
val service = LibreTranslateTranslatorService(
http = http,
endpoint = "https://translator.example/translate",
)
val result = service.translate(
TranslationRequest(
text = "Good morning",
source = TranslationLanguage.Auto,
target = TranslationLanguage.German,
),
)
assertEquals("Guten Morgen", result.translatedText)
assertEquals(TranslationLanguage.English, result.source)
assertEquals(TranslationLanguage.German, result.target)
assertEquals("https://translator.example/translate", http.requests.single().url)
assertEquals("POST", http.requests.single().method)
val body = Json.parseToJsonElement(http.requests.single().body.orEmpty()).jsonObject
assertEquals("Good morning", body.getValue("q").jsonPrimitive.content)
assertEquals("auto", body.getValue("source").jsonPrimitive.content)
assertEquals("de", body.getValue("target").jsonPrimitive.content)
assertEquals("text", body.getValue("format").jsonPrimitive.content)
}
@Test
fun sameLanguageRequestReturnsOriginalTextWithoutNetworkCall() = runTest {
val http = RecordingHttpService { HttpResponse(statusCode = 200, body = """{"translatedText":"translated"}""") }
val service = LibreTranslateTranslatorService(http)
val result = service.translate(
TranslationRequest(
text = "Already English",
source = TranslationLanguage.English,
target = TranslationLanguage.English,
),
)
assertEquals("Already English", result.translatedText)
assertEquals(TranslationLanguage.English, result.source)
assertTrue(http.requests.isEmpty())
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tts/ProfileSpeechServiceTest.kt
- Source · test / fixture · 270 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
24: class ProfileSpeechServiceTest {
237: private class Fixture(test: TestScope) {
242: suspend fun close() { service.closeAndJoin(); owner.cancelAndJoin() }
245: private class Native : TextToSpeechService {
256: override suspend fun voices(language: String?): List<String> {
261: override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) {
267: override suspend fun stop() { stops++; events += "stop"; stopping() }
268: override suspend fun closeAndJoin() { releases++; events += "release"; releasing() }
Exact file bytes / download · SHA-256 c2efc84634589d3da79f18c340ef7f4a425bea41ee236fc261a1ff6809941f24.
Complete file
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.services.tts
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
class ProfileSpeechServiceTest {
@Test fun completedUtteranceCleansUpAndExpiresRetainedProgress() = runTest {
val f = Fixture(this)
var progress = 0
f.native.speech = { f.native.progress?.invoke(0, 2) }
try {
f.service.speak("First", TextToSpeechRequest()) { _, _ -> progress++ }
assertEquals(listOf("speak:First", "stop"), f.native.events)
assertEquals(1, progress)
f.native.progress?.invoke(2, 4)
assertEquals(1, progress)
assertEquals(listOf("voice"), f.service.voices(null))
} finally { f.close() }
}
@Test fun canceledCallerWaitsForNativeCleanup() = runTest {
val f = Fixture(this)
val release = CompletableDeferred<Unit>()
f.native.stopping = { release.await() }
try {
val call = async { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } }
runCurrent()
call.cancel()
runCurrent()
assertFalse(call.isCompleted)
assertEquals(listOf("speak:First", "stop"), f.native.events)
release.complete(Unit)
call.join()
assertTrue(call.isCancelled)
} finally { release.complete(Unit); f.close() }
}
@Test fun readerRetirementWaitsBeforeReplacementCanSpeak() = runTest {
val f = Fixture(this)
val release = CompletableDeferred<Unit>()
f.native.stopping = { release.await() }
try {
val first = f.service.reader()
val second = f.service.reader()
val oldCall = async { first.speak("Old", TextToSpeechRequest()) { _, _ -> } }
runCurrent()
first.retire()
val replacement = async { second.speak("New", TextToSpeechRequest()) { _, _ -> } }
runCurrent()
assertEquals(listOf("Old"), f.native.spoken)
assertFalse(oldCall.isCompleted)
assertFailsWith<CancellationException> { first.stop() }
release.complete(Unit)
runCurrent()
assertEquals(listOf("Old", "New"), f.native.spoken)
oldCall.join()
replacement.cancelAndJoin()
} finally { release.complete(Unit); f.close() }
}
@Test fun oldReadersStopCannotInterruptAnotherReader() = runTest {
val f = Fixture(this)
try {
val old = f.service.reader()
val current = f.service.reader()
val call = async { current.speak("Current", TextToSpeechRequest()) { _, _ -> } }
runCurrent()
old.stop()
assertTrue(call.isActive)
assertEquals(0, f.native.stops)
current.stop()
call.join()
assertTrue(call.isCancelled)
assertEquals(1, f.native.stops)
} finally { f.close() }
}
@Test fun queuedVoicesDoNotAccessNativeEngineUntilUtteranceCleansUp() = runTest {
val f = Fixture(this)
try {
val call = async { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } }
runCurrent()
val voices = async { f.service.voices(null) }
runCurrent()
assertEquals(0, f.native.voiceReads)
call.cancelAndJoin()
assertEquals(listOf("voice"), voices.await())
assertEquals(listOf("speak:First", "stop", "voices"), f.native.events)
} finally { f.close() }
}
@Test fun retiringStatusRejectsCallsAndProgressBeforeScopeCancellation() = runTest {
val f = Fixture(this)
var progress = 0
try {
val reader = f.service.reader()
val call = async { reader.speak("First", TextToSpeechRequest()) { _, _ -> progress++ } }
runCurrent()
f.open = false
f.native.progress?.invoke(0, 3)
assertEquals(0, progress)
assertTrue(f.owner.isActive)
assertFailsWith<CancellationException> { reader.voices(null) }
assertFailsWith<CancellationException> { f.service.speak("Late", TextToSpeechRequest()) { _, _ -> } }
assertFailsWith<CancellationException> { f.service.reader() }
assertEquals(listOf("First"), f.native.spoken)
call.cancelAndJoin()
} finally { f.close() }
}
@Test fun closeJoinsCleanupThenReleasesNativeEngineAndPreservesParent() = runTest {
val f = Fixture(this)
val release = CompletableDeferred<Unit>()
f.native.stopping = { release.await() }
try {
val call = async { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } }
runCurrent()
val close = async { f.service.closeAndJoin() }
runCurrent()
assertFalse(close.isCompleted)
assertEquals(0, f.native.releases)
assertFailsWith<CancellationException> { f.service.voices(null) }
release.complete(Unit)
close.await()
call.join()
f.service.closeAndJoin()
assertEquals(listOf("speak:First", "stop", "release"), f.native.events)
assertTrue(f.owner.isActive)
} finally { release.complete(Unit); f.close() }
}
@Test fun canceledCloseCallerStillJoinsEngineRelease() = runTest {
val f = Fixture(this)
val release = CompletableDeferred<Unit>()
f.native.releasing = { release.await() }
try {
val close = async { f.service.closeAndJoin() }
runCurrent()
close.cancel()
runCurrent()
assertFalse(close.isCompleted)
release.complete(Unit)
close.join()
assertEquals(1, f.native.releases)
f.service.closeAndJoin()
assertEquals(1, f.native.releases)
} finally { release.complete(Unit); f.close() }
}
@Test fun failedEngineReleaseRetainsCleanupForRetry() = runTest {
val f = Fixture(this)
f.native.releasing = { if (f.native.releases == 1) error("shutdown failed") }
try {
assertFailsWith<IllegalStateException> { f.service.closeAndJoin() }
assertFailsWith<CancellationException> { f.service.voices(null) }
f.service.closeAndJoin()
f.service.closeAndJoin()
assertEquals(2, f.native.releases)
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun failedStopMustBeRetriedBeforeAllocatingAnotherUtterance() = runTest {
val f = Fixture(this)
f.native.speech = { }
f.native.stopping = { if (f.native.stops < 3) error("native stop failed") }
try {
assertFailsWith<IllegalStateException> { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } }
assertFailsWith<IllegalStateException> { f.service.speak("Blocked", TextToSpeechRequest()) { _, _ -> } }
assertEquals(listOf("First"), f.native.spoken)
f.service.speak("Next", TextToSpeechRequest()) { _, _ -> }
assertEquals(listOf("speak:First", "stop", "stop", "stop", "speak:Next", "stop"), f.native.events)
} finally { f.close() }
}
@Test fun canceledVoiceLookupJoinsItsInitializationFinalizer() = runTest {
val f = Fixture(this)
val release = CompletableDeferred<Unit>()
f.native.voiceLookup = {
try { awaitCancellation() }
finally { withContext(NonCancellable) { release.await() } }
}
try {
val call = async { f.service.voices(null) }
runCurrent()
val close = async { f.service.closeAndJoin() }
runCurrent()
assertFalse(call.isCompleted)
assertFalse(close.isCompleted)
assertEquals(0, f.native.releases)
release.complete(Unit)
close.await()
call.join()
assertEquals(1, f.native.releases)
} finally { release.complete(Unit); f.close() }
}
@Test fun independentOwnersRetainTheirOwnEnginesAndCallbacks() = runTest {
val a = Fixture(this)
val b = Fixture(this)
var aProgress = 0
var bProgress = 0
try {
val old = async { a.service.speak("A", TextToSpeechRequest()) { _, _ -> aProgress++ } }
val current = async { b.service.speak("B", TextToSpeechRequest()) { _, _ -> bProgress++ } }
runCurrent()
a.service.closeAndJoin()
a.native.progress?.invoke(0, 1)
b.native.progress?.invoke(0, 1)
assertEquals(0, aProgress)
assertEquals(1, bProgress)
assertTrue(current.isActive)
assertEquals(0, b.native.stops)
old.join()
current.cancelAndJoin()
} finally { a.close(); b.close() }
}
private class Fixture(test: TestScope) {
val owner = SupervisorJob()
var open = true
val native = Native()
val service = ProfileSpeechService(native, CoroutineScope(owner + StandardTestDispatcher(test.testScheduler))) { open }
suspend fun close() { service.closeAndJoin(); owner.cancelAndJoin() }
}
private class Native : TextToSpeechService {
val events = mutableListOf<String>()
val spoken = mutableListOf<String>()
var progress: ((Int, Int) -> Unit)? = null
var stops = 0
var releases = 0
var voiceReads = 0
var speech: suspend () -> Unit = { awaitCancellation() }
var stopping: suspend () -> Unit = { }
var releasing: suspend () -> Unit = { }
var voiceLookup: suspend () -> List<String> = { listOf("voice") }
override suspend fun voices(language: String?): List<String> {
voiceReads++
events += "voices"
return voiceLookup()
}
override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) {
events += "speak:$text"
spoken += text
progress = onProgress
speech()
}
override suspend fun stop() { stops++; events += "stop"; stopping() }
override suspend fun closeAndJoin() { releases++; events += "release"; releasing() }
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/updates/AppUpdatesTest.kt
- Source · test / fixture · 104 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
12: class AppUpdatesTest {
14: fun requestsSchnitzel5ReleasesAndAppliesChannelFiltering() = runTest {
28: fun classifiesNumericReleaseChannels() {
42: fun stableUpdatesSkipDraftsPreviewsAndMalformedTags() {
57: fun previewChecksIncludePrereleasesAndAllowPromotion() {
74: fun ignoresIncompleteAssetsAndUnrelatedResponseShapes() {
82: fun comparesNumericComponents() {
91: fun ignoresPrereleaseAndBuildSuffixes() {
98: fun treatsMissingComponentsAsZero() {
Exact file bytes / download · SHA-256 ac711e741699167cc6df337828e5dc40ac1053b13add9c1d252058a3ce81b173.
Complete file
package eu.friedcutlet.yokan.services.updates
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.assertEquals
import kotlin.test.assertNull
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.coroutines.test.runTest
class AppUpdatesTest {
@Test
fun requestsSchnitzel5ReleasesAndAppliesChannelFiltering() = runTest {
val http = HttpService { request ->
assertEquals("https://api.github.com/repos/Schnitzel5/yokan/releases?per_page=100", request.url)
HttpResponse(200, """[
{"tag_name":"v2.0.0","prerelease":true},
{"tag_name":"v1.0.0","assets":[{"name":"app.apk","browser_download_url":"https://github.com/Schnitzel5/yokan/releases/download/v1.0.0/app.apk","size":42}]}
]""")
}
val release = fetchLatestRelease(http, ReleaseChannel.Stable)
assertEquals("v1.0.0", release?.tag)
assertEquals("https://github.com/Schnitzel5/yokan/releases/download/v1.0.0/app.apk", release?.assets?.single()?.url)
}
@Test
fun classifiesNumericReleaseChannels() {
assertEquals(ReleaseChannel.Alpha, releaseChannel("v0.0.1"))
assertEquals(ReleaseChannel.Alpha, releaseChannel("0.0.99"))
assertEquals(ReleaseChannel.Beta, releaseChannel("v0.1.0"))
assertEquals(ReleaseChannel.Beta, releaseChannel("0.99.9"))
assertEquals(ReleaseChannel.Stable, releaseChannel("v1.0.0"))
assertEquals(ReleaseChannel.Stable, releaseChannel("2.0.0"))
assertNull(releaseChannel("not-a-version"))
assertNull(releaseChannel("1.0.0-beta"))
assertNull(releaseChannel("0.1"))
assertNull(releaseChannel("0.bad.1"))
}
@Test
fun stableUpdatesSkipDraftsPreviewsAndMalformedTags() {
val releases = """[
{"tag_name":"v9.0.0","draft":true},
{"tag_name":"v3.0.0","prerelease":true},
{"tag_name":"v1.10.0","assets":[{"browser_download_url":"https://example.com/app.apk","size":42,"name":"app.apk"}]},
{"tag_name":"v1.9.0"},
{"tag_name":"v0.99.0"},
{"tag_name":"v9.invalid.0"}
]"""
val release = selectLatestRelease(releases, ReleaseChannel.Stable)
assertEquals("v1.10.0", release?.tag)
assertEquals(listOf(ReleaseAsset("app.apk", "https://example.com/app.apk", 42)), release?.assets)
}
@Test
fun previewChecksIncludePrereleasesAndAllowPromotion() {
val previews = """[
{"tag_name":"v0.0.2","prerelease":true},
{"tag_name":"v0.0.12","prerelease":true},
{"tag_name":"v0.1.1","prerelease":true}
]"""
assertEquals("v0.1.1", selectLatestRelease(previews, ReleaseChannel.Alpha)?.tag)
assertEquals("v0.1.1", selectLatestRelease(previews, ReleaseChannel.Beta)?.tag)
assertNull(selectLatestRelease(previews, ReleaseChannel.Stable))
val alphaOnly = """[{"tag_name":"v0.0.12","prerelease":true}]"""
assertNull(selectLatestRelease(alphaOnly, ReleaseChannel.Beta))
val promoted = """[{"tag_name":"v1.0.0"},{"tag_name":"v0.9.9","prerelease":true}]"""
assertEquals("v1.0.0", selectLatestRelease(promoted, ReleaseChannel.Beta)?.tag)
assertEquals("v1.0.0", selectLatestRelease(promoted, ReleaseChannel.Alpha)?.tag)
}
@Test
fun ignoresIncompleteAssetsAndUnrelatedResponseShapes() {
val releases = """[{"tag_name":"v1.0.0","assets":[{"name":"missing-url"},null]}]"""
assertEquals(emptyList(), selectLatestRelease(releases, ReleaseChannel.Stable)?.assets)
assertNull(selectLatestRelease("[]", ReleaseChannel.Stable))
assertNull(selectLatestRelease("{}", ReleaseChannel.Stable))
}
@Test
fun comparesNumericComponents() {
assertTrue(isNewerVersion("v0.2.0", "0.1.0"))
assertTrue(isNewerVersion("1.0.0", "0.9.9"))
assertTrue(isNewerVersion("0.1.1", "0.1.0"))
assertFalse(isNewerVersion("0.1.0", "0.1.0"))
assertFalse(isNewerVersion("v0.0.9", "0.1.0"))
}
@Test
fun ignoresPrereleaseAndBuildSuffixes() {
assertTrue(isNewerVersion("v0.2.0-beta", "0.1.0"))
assertFalse(isNewerVersion("0.1.0-hotfix", "0.1.0"))
assertTrue(isNewerVersion("0.2.0+45", "0.1.9"))
}
@Test
fun treatsMissingComponentsAsZero() {
assertFalse(isNewerVersion("0.1", "0.1.0"))
assertTrue(isNewerVersion("0.2", "0.1.9"))
assertFalse(isNewerVersion("not-a-version", "0.1.0"))
assertFalse(isNewerVersion("9.invalid.1", "0.1.0"))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/activity/ActivityFilterViewModelsTest.kt
- Source · test / fixture · 121 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
19: class ActivityFilterViewModelsTest {
24: private fun database() = InMemoryYokanDatabase(emptySnapshot().copy(
40: override fun updates() = error("Activity must project its published snapshot")
41: override fun allTitles(itemType: ItemType) = error("No live title reads")
42: override fun chapters(mangaId: Long) = error("No per-title chapter reads")
43: override fun downloads() = error("No live download reads")
44: override fun categories(itemType: ItemType) = error("No live category reads")
77: override fun updates() = error("Must use the published revision")
78: override fun allTitles(itemType: ItemType) = error("Must use the published revision")
105: private object NoUpdater : LibraryUpdaterService {
106: override suspend fun updateLibrary(itemType: DbItemType, onProgress: (LibraryUpdateProgress) -> Unit, shouldCancel: () -> Boolean, titleIds: Set<Long>?, mayStartTitle: suspend () -> Boolean) =
108: override suspend fun updateTitle(mangaId: Long) = false
111: private object NoDownloads : DownloadService {
112: override suspend fun initialize(poolSize: Int) = Unit
113: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
114: override fun cancel(taskId: String) = Unit
115: override fun pause(taskId: String) = Unit
116: override fun resume(taskId: String) = Unit
117: override fun retry(taskId: String) = false
118: override fun storageLocation(taskId: String): String? = null
119: override fun deleteArtifacts(taskId: String) = Unit
120: override fun activeDownloads(): List<DownloadProgress> = emptyList()
Exact file bytes / download · SHA-256 8564a7eb9addaf6391f031cd4d845b997ef50acfb6244e25098332272707daa3.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.data.*
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.download.*
import eu.friedcutlet.yokan.services.files.*
import eu.friedcutlet.yokan.services.library.*
import eu.friedcutlet.yokan.ui.screens.settings.calendar.CalendarViewModel
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.test.*
import kotlinx.datetime.LocalDate
import kotlin.test.*
@OptIn(ExperimentalCoroutinesApi::class)
class ActivityFilterViewModelsTest {
private val host = ViewModelTestHost()
private val dispatcher = host.dispatcher
@AfterTest fun after() = host.close()
private fun database() = InMemoryYokanDatabase(emptySnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "Manga one", favorite = true, categories = listOf(10)),
DbManga(id = 2, name = "Manga two", favorite = true),
DbManga(id = 3, name = "Anime", itemType = DbItemType.Anime, favorite = true)),
chapters = listOf(DbChapter(id = 11, mangaId = 1, name = "One"), DbChapter(id = 22, mangaId = 2, name = "Two"),
DbChapter(id = 33, mangaId = 3, name = "Episode")),
categories = listOf(DbCategory(id = 10, name = "Category", forItemType = DbItemType.Manga)),
updates = listOf(DbUpdate(id = 1, mangaId = 1, chapterId = 11, updatedAt = 1),
DbUpdate(id = 2, mangaId = 2, chapterId = 22, updatedAt = 2),
DbUpdate(id = 3, mangaId = 3, chapterId = 33, updatedAt = 3)),
))
@Test fun updatesReactToPreferencesProgressDownloadsAndCategoryDeletionWithoutLiveRepositoryReads() = runTest(dispatcher) {
val db = database()
val actual = DefaultYokanRepository(db)
val repo = object : YokanRepository by actual {
override fun updates() = error("Activity must project its published snapshot")
override fun allTitles(itemType: ItemType) = error("No live title reads")
override fun chapters(mangaId: Long) = error("No per-title chapter reads")
override fun downloads() = error("No live download reads")
override fun categories(itemType: ItemType) = error("No live category reads")
}
val settings = SettingsStore(repo, backgroundScope) {}
val index = LibraryIndexStore(repo, backgroundScope, dispatcher)
val controller = LibraryUpdateController(NoUpdater, repo, NoNotifications, backgroundScope)
val downloads = ChapterDownloads(repo, db, NoDownloads, NoNotifications, settings, NoFiles, backgroundScope)
val vm = host.create { UpdatesViewModel(repo, settings, index, controller, downloads, dispatcher) }
runCurrent()
assertEquals(listOf(2L, 1L), vm.state.value.rowsByType[ItemType.Manga]?.map { it.update.id })
vm.updateFilters(ItemType.Manga) { it.copy(unread = 1) }
db.upsertChapter(checkNotNull(db.chapter(22)).copy(isRead = true))
runCurrent()
assertEquals(listOf(1L), vm.state.value.rowsByType[ItemType.Manga]?.map { it.update.id })
vm.updateFilters(ItemType.Manga) { it.copy(downloaded = 1) }
runCurrent()
assertTrue(vm.state.value.rowsByType[ItemType.Manga].orEmpty().isEmpty())
db.upsertDownload(DbDownload(id = 7, chapterId = 11, isDownload = true))
runCurrent()
assertEquals(listOf(1L), vm.state.value.rowsByType[ItemType.Manga]?.map { it.update.id })
vm.updateFilters(ItemType.Manga) { DbUpdatesFilter(categories = DbActivityCategoryFilter(mapOf(10L to 1))) }
runCurrent()
assertEquals(listOf(1L), vm.state.value.rowsByType[ItemType.Manga]?.map { it.update.id })
db.removeCategory(10)
runCurrent()
assertEquals(listOf(2L, 1L), vm.state.value.rowsByType[ItemType.Manga]?.map { it.update.id })
assertEquals(listOf(3L), vm.state.value.rowsByType[ItemType.Anime]?.map { it.update.id })
assertEquals(1, repo.dbSettings().features.activity.updates(DbItemType.Manga).categories.value(10))
}
@Test fun upcomingFiltersPersistIndependentlyAndReactToCategoryAndMediaChanges() = runTest(dispatcher) {
val db = database()
val actual = DefaultYokanRepository(db)
val repo = object : YokanRepository by actual {
override fun updates() = error("Must use the published revision")
override fun allTitles(itemType: ItemType) = error("Must use the published revision")
}
val controller = LibraryUpdateController(NoUpdater, repo, NoNotifications, backgroundScope)
val vm = host.create { CalendarViewModel(ItemType.Manga, repo, controller, LocalDate(2026, 10, 15), dispatcher) }
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.state.collect {} }
runCurrent()
assertEquals(setOf(1L, 2L), vm.state.value.events.values.flatten().map { it.id }.toSet())
vm.updateCategoryFilter { it.cycled(10) }
runCurrent()
assertEquals(listOf(1L), vm.state.value.events.values.flatten().map { it.id })
assertEquals(listOf(1L), vm.state.value.updates.map { it.mangaId })
assertEquals(DbUpdatesFilter(), repo.dbSettings().features.activity.updates(DbItemType.Manga))
vm.selectType(ItemType.Anime)
runCurrent()
assertEquals(listOf(3L), vm.state.value.events.values.flatten().map { it.id })
assertTrue(vm.state.value.categoryFilter.states.isEmpty())
vm.selectType(ItemType.Manga)
runCurrent()
assertEquals(listOf(1L), vm.state.value.events.values.flatten().map { it.id })
db.removeCategory(10)
runCurrent()
assertEquals(setOf(1L, 2L), vm.state.value.events.values.flatten().map { it.id }.toSet())
val restored = checkNotNull(decodeDatabaseSnapshot(encodeDatabaseSnapshot(db.snapshot())))
assertEquals(1, restored.settings.features.activity.upcoming(DbItemType.Manga).value(10))
}
}
private object NoUpdater : LibraryUpdaterService {
override suspend fun updateLibrary(itemType: DbItemType, onProgress: (LibraryUpdateProgress) -> Unit, shouldCancel: () -> Boolean, titleIds: Set<Long>?, mayStartTitle: suspend () -> Boolean) =
LibraryUpdateResult(0, 0, 0)
override suspend fun updateTitle(mangaId: Long) = false
}
private object NoDownloads : DownloadService {
override suspend fun initialize(poolSize: Int) = Unit
override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
override fun cancel(taskId: String) = Unit
override fun pause(taskId: String) = Unit
override fun resume(taskId: String) = Unit
override fun retry(taskId: String) = false
override fun storageLocation(taskId: String): String? = null
override fun deleteArtifacts(taskId: String) = Unit
override fun activeDownloads(): List<DownloadProgress> = emptyList()
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/activity/ActivityRowsTest.kt
- Source · test / fixture · 99 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
14: class ActivityRowsTest {
15: private fun update(id: Long, mangaId: Long, chapterId: Long, updatedAt: Long, itemType: ItemType = ItemType.Manga) =
29: private fun history(id: Long, mangaId: Long, chapterId: Long, updatedAt: Long, itemType: ItemType = ItemType.Manga) =
43: fun updateRowsResolveTitleChapterAndFirstDownloadPerTypeNewestFirst() {
81: fun historyRowsKeepNewestEntryPerTitle() {
Exact file bytes / download · SHA-256 b1bdb1cd2a2a8587ac77aa2e76c1acbfbae43223eb69abb5d45a8fd554a35091.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import eu.friedcutlet.yokan.data.LibraryIndex
import eu.friedcutlet.yokan.domain.testManga
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.UpdateEntry
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class ActivityRowsTest {
private fun update(id: Long, mangaId: Long, chapterId: Long, updatedAt: Long, itemType: ItemType = ItemType.Manga) =
UpdateEntry(
id = id,
mangaId = mangaId,
chapterId = chapterId,
itemType = itemType,
title = "stored $mangaId",
chapterName = "stored ch $chapterId",
source = "src",
date = "",
isRead = false,
updatedAt = updatedAt,
)
private fun history(id: Long, mangaId: Long, chapterId: Long, updatedAt: Long, itemType: ItemType = ItemType.Manga) =
History(
id = id,
mangaId = mangaId,
chapterId = chapterId,
itemType = itemType,
title = "stored $mangaId",
chapterName = "stored ch $chapterId",
date = "",
readingTimeSeconds = 0,
updatedAt = updatedAt,
)
@Test
fun updateRowsResolveTitleChapterAndFirstDownloadPerTypeNewestFirst() {
val one = testManga(1, "One")
val index = LibraryIndex(
chaptersByManga = mapOf(1L to listOf(Chapter(10, 1, "Ch 10", "/10", isRead = true), Chapter(11, 1, "", "/11"))),
)
val downloads = listOf(
DbDownload(id = 7, chapterId = 10, succeeded = 1),
DbDownload(id = 8, chapterId = 10, succeeded = 2),
)
val rows = buildUpdateRows(
updates = listOf(
update(100, 1, 10, updatedAt = 1),
update(101, 1, 11, updatedAt = 3),
update(102, 2, 20, updatedAt = 2, itemType = ItemType.Anime),
),
titles = mapOf(1L to one),
index = index,
downloads = downloads,
)
val manga = rows.getValue(ItemType.Manga)
assertEquals(listOf(101L, 100L), manga.map { it.update.id })
val read = manga.last()
assertEquals(one, read.manga)
assertEquals("One", read.title)
assertEquals("Ch 10", read.chapterName)
assertEquals(true, read.isRead)
assertEquals(7L, read.download?.id)
// A blank chapter name falls back to the stored one.
assertEquals("stored ch 11", manga.first().chapterName)
val orphan = rows.getValue(ItemType.Anime).single()
assertNull(orphan.manga)
assertNull(orphan.chapter)
assertEquals("stored 2", orphan.title)
}
@Test
fun historyRowsKeepNewestEntryPerTitle() {
val index = LibraryIndex(chaptersByManga = mapOf(1L to listOf(Chapter(10, 1, "Ch 10", "/10"))))
val rows = buildHistoryRows(
history = listOf(
history(1, mangaId = 1, chapterId = 10, updatedAt = 5),
history(2, mangaId = 1, chapterId = 11, updatedAt = 1),
history(3, mangaId = 2, chapterId = 20, updatedAt = 9),
history(4, mangaId = 3, chapterId = 30, updatedAt = 7, itemType = ItemType.Novel),
),
titles = mapOf(1L to testManga(1, "One")),
index = index,
)
val manga = rows.getValue(ItemType.Manga)
assertEquals(listOf(3L, 1L), manga.map { it.history.id })
assertEquals("Ch 10", manga.last().chapter?.name)
assertEquals(listOf(4L), rows.getValue(ItemType.Novel).map { it.history.id })
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/activity/TrackerLibrarySectionsTest.kt
- Source · test / fixture · 47 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
8: class TrackerLibrarySectionsTest {
10: fun malMangaSectionsIncludeManhwaAndManhuaTops() {
19: fun malAnimeSectionsIncludeAiringAndUpcoming() {
29: fun anilistSectionsCarryLatestReleasingKey() {
36: fun simklAndTraktBrowseMoviesAndSeriesPairs() {
Exact file bytes / download · SHA-256 df8a79459b4b7aec7efdf07d9d9db2450d690f5e49e869b5d0a9c8ddee2fa4a5.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import eu.friedcutlet.yokan.domain.ItemType
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class TrackerLibrarySectionsTest {
@Test
fun malMangaSectionsIncludeManhwaAndManhuaTops() {
val labels = trackerLibrarySections(1, ItemType.Manga).map(TrackerLibrarySectionSpec::label)
assertEquals(
listOf("Continue reading", "Popular Manga", "Top Manga", "Top Manhwa", "Top Manhua"),
labels,
)
}
@Test
fun malAnimeSectionsIncludeAiringAndUpcoming() {
val specs = trackerLibrarySections(1, ItemType.Anime)
assertEquals(
listOf("Continue watching", "Airing Anime", "Popular Anime", "Upcoming Anime"),
specs.map(TrackerLibrarySectionSpec::label),
)
assertEquals(listOf(null, "airing", "bypopularity", "upcoming"), specs.map(TrackerLibrarySectionSpec::rankingType))
}
@Test
fun anilistSectionsCarryLatestReleasingKey() {
val specs = trackerLibrarySections(2, ItemType.Anime)
assertEquals("latest", specs.last().rankingType)
assertEquals(5, specs.size)
}
@Test
fun simklAndTraktBrowseMoviesAndSeriesPairs() {
val simkl = trackerLibrarySections(4, ItemType.Manga)
// Simkl/Trakt ignore the manga/anime cursor entirely.
assertEquals(simkl, trackerLibrarySections(4, ItemType.Anime))
assertTrue(simkl.any { it.label == "Trending Movies" && it.isMangaFlag })
assertTrue(simkl.any { it.label == "Trending Series" && !it.isMangaFlag })
val trakt = trackerLibrarySections(5, ItemType.Anime)
assertEquals(8, trakt.size)
assertTrue(trakt.any { it.label == "Top Movies (All Time)" && it.rankingType == "favorited/all" })
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/activity/UpdatesFiltersTest.kt
- Source · test / fixture · 89 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
9: class UpdatesFiltersTest {
11: private fun row(id: Long, read: Boolean = false, progress: String = "", bookmarked: Boolean = false,
19: private fun ids(filter: DbUpdatesFilter) = filterUpdateRows(rows, filter, categories, setOf(20L), mapOf(2L to setOf("hidden"))).map { it.update.id }
Exact file bytes / download · SHA-256 a58d592f96de0598da25875f7d4bf7a9ef102a2a6f89a8a40118bdb6b0ad3d63.
Complete file
package eu.friedcutlet.yokan.ui.screens.activity
import eu.friedcutlet.yokan.data.*
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.*
import eu.friedcutlet.yokan.services.library.ActivityCategoryMatcher
import kotlin.test.*
class UpdatesFiltersTest {
private val categories = listOf(Category(10, "One", ItemType.Manga, 0), Category(20, "Two", ItemType.Manga, 1))
private fun row(id: Long, read: Boolean = false, progress: String = "", bookmarked: Boolean = false,
categoryIds: List<Long> = emptyList(), scanlator: String = "") = UpdateRowModel(
UpdateEntry(id, id, id * 10, ItemType.Manga, "Title $id", "Chapter", "", "", false, id),
Manga(id = id, name = "Title $id", link = "/$id", description = "", status = Status.Ongoing, itemType = ItemType.Manga,
source = "", lang = "", dateAddedMillis = 0, lastUpdateMillis = 0, categories = categoryIds),
Chapter(id * 10, id, "Chapter", "/$id", isRead = read, lastPageRead = progress, isBookmarked = bookmarked, scanlator = scanlator), null)
private val rows = listOf(row(1), row(2, progress = "12.5", bookmarked = true, categoryIds = listOf(10), scanlator = "Hidden"),
row(3, read = true, progress = "100", categoryIds = listOf(10, 20)), row(4, categoryIds = listOf(20)))
private fun ids(filter: DbUpdatesFilter) = filterUpdateRows(rows, filter, categories, setOf(20L), mapOf(2L to setOf("hidden"))).map { it.update.id }
@Test fun rowFiltersCombineAndCompletedDownloadsAreIndependentOfTheDisplayedFirstRecord() {
assertEquals(listOf(2L), ids(DbUpdatesFilter(downloaded = 1)))
assertEquals(listOf(1L, 3L, 4L), ids(DbUpdatesFilter(downloaded = 2)))
assertEquals(listOf(1L, 2L, 4L), ids(DbUpdatesFilter(unread = 1)))
assertEquals(listOf(3L), ids(DbUpdatesFilter(unread = 2)))
assertEquals(listOf(2L), ids(DbUpdatesFilter(bookmarked = 1, downloaded = 1, unread = 1)))
assertEquals(emptyList(), ids(DbUpdatesFilter(bookmarked = 1, downloaded = 2)))
}
@Test fun startedAndUntouchedBothExcludeCompletedEntriesAndHandleInvalidProgress() {
assertEquals(listOf(2L), ids(DbUpdatesFilter(started = 1)))
assertEquals(listOf(1L, 4L), ids(DbUpdatesFilter(started = 2)))
val malformed = listOf(row(5, progress = "NaN"), row(6, progress = "Infinity"), row(7, progress = "bad"))
assertTrue(filterUpdateRows(malformed, DbUpdatesFilter(started = 1), categories, emptySet(), emptyMap()).isEmpty())
assertEquals(3, filterUpdateRows(malformed, DbUpdatesFilter(started = 2), categories, emptySet(), emptyMap()).size)
}
@Test fun categoryIncludesMatchAnyAndAnyExclusionWinsIncludingUncategorized() {
assertEquals(listOf(2L, 3L, 4L), ids(DbUpdatesFilter(categories = DbActivityCategoryFilter(mapOf(10L to 1, 20L to 1)))))
assertEquals(listOf(2L), ids(DbUpdatesFilter(categories = DbActivityCategoryFilter(mapOf(10L to 1, 20L to 2)))))
assertEquals(listOf(1L), ids(DbUpdatesFilter(categories = DbActivityCategoryFilter(mapOf(-1L to 1)))))
assertEquals(listOf(2L, 3L, 4L), ids(DbUpdatesFilter(categories = DbActivityCategoryFilter(mapOf(-1L to 2)))))
}
@Test fun deletedForeignAndMalformedCategorySelectionsDoNotHideActivity() {
val filter = DbActivityCategoryFilter(mapOf(999L to 1, 0L to 1, -50L to 2, 10L to 99))
assertTrue(ActivityCategoryMatcher(filter, setOf(10, 20)).matches(emptyList()))
assertEquals(listOf(1L, 2L, 3L, 4L), ids(DbUpdatesFilter(categories = filter)))
}
@Test fun hiddenScanlatorFilterUsesNormalizedPerTitleValuesAndCombinesWithOtherFilters() {
assertEquals(listOf(1L, 3L, 4L), ids(DbUpdatesFilter(hideExcludedScanlators = true)))
assertEquals(emptyList(), ids(DbUpdatesFilter(hideExcludedScanlators = true, bookmarked = 1)))
val variants = listOf(row(2, scanlator = " HIDDEN "), row(5, scanlator = "Hidden"))
assertEquals(listOf(5L), filterUpdateRows(variants, DbUpdatesFilter(hideExcludedScanlators = true), categories,
emptySet(), mapOf(2L to setOf("hidden"))).map { it.update.id })
}
@Test fun defaultAndInvalidTriStatesPreserveRowsIncludingOrphans() {
assertSame(rows, filterUpdateRows(rows, DbUpdatesFilter(), categories, emptySet(), emptyMap()))
assertSame(rows, filterUpdateRows(rows, DbUpdatesFilter(downloaded = 99, unread = -1), categories, emptySet(), emptyMap()))
val orphan = rows.first().copy(manga = null, chapter = null)
assertEquals(listOf(orphan), filterUpdateRows(listOf(orphan), DbUpdatesFilter(unread = 1, bookmarked = 2), categories, emptySet(), emptyMap()))
}
@Test fun preferencesCycleResetAndRoundTripIndependentlyByMediaAndActivity() {
var prefs = DbActivityPreferences()
for (type in DbItemType.entries) prefs = prefs.withUpdates(type, DbUpdatesFilter().cycled(UpdatesFilterKind.Unread))
prefs = prefs.withUpcoming(DbItemType.Manga, DbActivityCategoryFilter().cycled(10))
prefs = prefs.withUpdates(DbItemType.Manga, prefs.updates(DbItemType.Manga).cycled(UpdatesFilterKind.Unread))
assertEquals(2, prefs.updates(DbItemType.Manga).unread)
assertEquals(1, prefs.updates(DbItemType.Anime).unread)
assertTrue(prefs.updates(DbItemType.Manga).categories.states.isEmpty())
assertTrue(prefs.upcoming(DbItemType.Anime).states.isEmpty())
val settings = DbSettings(features = DbFeaturePreferences(activity = prefs))
assertEquals(settings, DatabaseJson.decodeFromString(DbSettings.serializer(), DatabaseJson.encodeToString(DbSettings.serializer(), settings)))
assertEquals(DbActivityPreferences(), DatabaseJson.decodeFromString(DbSettings.serializer(), "{}").features.activity)
assertFalse(prefs.withUpdates(DbItemType.Manga, DbUpdatesFilter()).updates.containsKey(DbItemType.Manga))
assertEquals(DbActivityCategoryFilter(), DbActivityCategoryFilter().cycled(10).cycled(10).cycled(10))
}
@Test fun manyUpdatesResolveChaptersOncePerTitleAndRetainNewestFirstOrder() {
val title = row(1).manga ?: error("fixture")
val chapters = (1L..3000L).map { Chapter(it, title.id, "Chapter $it", "/$it") }
val updates = chapters.map { UpdateEntry(it.id, title.id, it.id, ItemType.Manga, title.name, it.name, "", "", false, it.id) }
val built = buildUpdateRows(updates, mapOf(title.id to title), LibraryIndex(mapOf(title.id to chapters)), emptyList()).getValue(ItemType.Manga)
assertEquals((3000L downTo 1L).toList(), built.map { it.chapter?.id })
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/appearance/AppIconViewModelTest.kt
- Source · test / fixture · 143 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
24: class AppIconViewModelTest {
125: private fun model(service: AppIconService, stores: MutableList<ViewModelStore>): AppIconViewModel {
129: private class FakeIcons(override val capabilities: AppIconCapabilities = AppIconCapabilities(AppIconPlatform.Android, ExplicitAppIcons)) : AppIconService {
135: override suspend fun current() = icon
136: override suspend fun apply(selection: AppIconSelection) {
Exact file bytes / download · SHA-256 1fa3b7ac40f244106c96e7f34ec3a9aeb3f626749c5a5f160ab2ce17632b23d8.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.appearance
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import eu.friedcutlet.yokan.services.appicons.*
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
@OptIn(ExperimentalCoroutinesApi::class)
class AppIconViewModelTest {
@Test fun draftCancelApplyResetAndRestartReadInstallationState() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
val stores = mutableListOf<ViewModelStore>()
try {
val service = FakeIcons()
val vm = model(service, stores)
advanceUntilIdle()
assertEquals(AppIconSelection.Default, vm.state.value.selection)
vm.openPicker(); vm.chooseDesign(AppIconDesign.Torii); vm.chooseAppearance(ExplicitAppIcons[2])
assertEquals(ExplicitAppIcons[2], vm.state.value.draft)
vm.dismissPicker()
assertEquals(AppIconSelection.Default, service.icon)
assertEquals(0, service.writes)
vm.openPicker()
assertEquals(AppIconSelection.Default, vm.state.value.draft)
vm.chooseDesign(AppIconDesign.Torii); vm.chooseAppearance(ExplicitAppIcons[2]); vm.applyDraft()
advanceUntilIdle()
assertEquals(ExplicitAppIcons[2], service.icon)
assertFalse(vm.state.value.pickerOpen)
val restarted = model(service, stores)
advanceUntilIdle()
assertEquals(ExplicitAppIcons[2], restarted.state.value.selection)
restarted.openPicker(); restarted.chooseDesign(AppIconDesign.Default)
assertEquals(AppIconSelection.Default, restarted.state.value.draft)
restarted.select(AppIconSelection.Default); advanceUntilIdle()
assertEquals(AppIconSelection.Default, service.icon)
assertFalse(restarted.state.value.failed)
} finally { stores.forEach { it.clear() }; advanceUntilIdle(); Dispatchers.resetMain() }
}
@Test fun failedOrPartialOsChangeIsReadBackAndRetryRepairsUnknownState() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
val stores = mutableListOf<ViewModelStore>()
try {
val service = FakeIcons()
val vm = model(service, stores); advanceUntilIdle()
vm.openPicker()
service.reject = true
vm.select(ExplicitAppIcons[2]); advanceUntilIdle()
assertTrue(vm.state.value.failed)
assertTrue(vm.state.value.pickerOpen)
assertEquals(AppIconSelection.Default, vm.state.value.selection)
// An older Android launcher switch may partially apply before a failure.
service.icon = null
vm.refresh(); advanceUntilIdle()
assertNull(vm.state.value.selection)
assertTrue(vm.state.value.failed)
service.reject = false
vm.select(AppIconSelection.Default); advanceUntilIdle()
assertFalse(vm.state.value.failed)
assertEquals(AppIconSelection.Default, vm.state.value.selection)
service.ignoreChange = true
vm.select(ExplicitAppIcons[1]); advanceUntilIdle()
assertTrue(vm.state.value.failed) // Never claim success when the OS kept the previous icon.
assertEquals(AppIconSelection.Default, vm.state.value.selection)
} finally { stores.forEach { it.clear() }; advanceUntilIdle(); Dispatchers.resetMain() }
}
@Test fun unsupportedChoicesAreRejectedAndSystemAppearanceIsCapabilityGated() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
val stores = mutableListOf<ViewModelStore>()
try {
val android = FakeIcons()
val vm = model(android, stores); advanceUntilIdle()
vm.select(SystemAppIcon); advanceUntilIdle()
assertEquals(0, android.writes)
vm.openPicker(); vm.chooseDesign(AppIconDesign.Torii); vm.chooseAppearance(SystemAppIcon)
assertEquals(ExplicitAppIcons[1], vm.state.value.draft)
val ios = FakeIcons(AppIconCapabilities(AppIconPlatform.Ios, ExplicitAppIcons + SystemAppIcon))
val iosVm = model(ios, stores); advanceUntilIdle()
iosVm.openPicker(); iosVm.chooseDesign(AppIconDesign.Torii); iosVm.chooseAppearance(SystemAppIcon); iosVm.applyDraft()
advanceUntilIdle(); assertEquals(SystemAppIcon, iosVm.state.value.selection)
val static = model(StaticAppIconService(), stores); advanceUntilIdle()
assertFalse(static.state.value.capabilities.canChange)
static.select(ExplicitAppIcons[1]); advanceUntilIdle()
assertEquals(AppIconSelection.Default, static.state.value.selection)
} finally { stores.forEach { it.clear() }; advanceUntilIdle(); Dispatchers.resetMain() }
}
@Test fun changesSerializeAndFinishWhenSettingsRouteCloses() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
val stores = mutableListOf<ViewModelStore>()
try {
val service = FakeIcons()
val vm = model(service, stores); advanceUntilIdle()
service.pending = CompletableDeferred()
vm.openPicker(); vm.select(ExplicitAppIcons[2]); runCurrent()
assertTrue(vm.state.value.busy)
assertEquals(AppIconSelection.Default, vm.state.value.selection)
vm.select(ExplicitAppIcons[1]); vm.refresh()
stores.single().clear()
service.pending!!.complete(Unit); advanceUntilIdle()
assertEquals(1, service.writes)
assertEquals(ExplicitAppIcons[2], service.icon)
val next = model(service, stores); advanceUntilIdle()
assertEquals(ExplicitAppIcons[2], next.state.value.selection)
assertFalse(next.state.value.busy)
} finally { stores.forEach { it.clear() }; advanceUntilIdle(); Dispatchers.resetMain() }
}
private fun model(service: AppIconService, stores: MutableList<ViewModelStore>): AppIconViewModel {
val store = ViewModelStore().also(stores::add)
return ViewModelProvider.create(store, viewModelFactory { initializer { AppIconViewModel(service) } })[AppIconViewModel::class]
}
private class FakeIcons(override val capabilities: AppIconCapabilities = AppIconCapabilities(AppIconPlatform.Android, ExplicitAppIcons)) : AppIconService {
var icon: AppIconSelection? = AppIconSelection.Default
var writes = 0
var reject = false
var ignoreChange = false
var pending: CompletableDeferred<Unit>? = null
override suspend fun current() = icon
override suspend fun apply(selection: AppIconSelection) {
writes++
pending?.await()
if (reject) error("OS rejected change")
if (!ignoreChange) icon = selection
}
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/browse/BrowseClearViewModelTest.kt
- Source · test / fixture · 66 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
20: class BrowseClearViewModelTest {
24: fun tearDown() = host.close()
27: fun reportsSuccessOnlyAfterCommittedClearCompletes() = runTest {
38: fun keepsFailureAsActionableErrorWithoutSuccess() = runTest {
40: override fun supportsAtomicSnapshotPersistence() = false
50: private fun viewModel(database: YokanDatabase): BrowseClearViewModel {
56: private object NoActiveDownloads : DownloadService {
57: override suspend fun initialize(poolSize: Int) = Unit
58: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
59: override fun cancel(taskId: String) = Unit
60: override fun pause(taskId: String) = Unit
61: override fun resume(taskId: String) = Unit
62: override fun retry(taskId: String) = false
63: override fun storageLocation(taskId: String): String? = null
64: override fun deleteArtifacts(taskId: String) = Unit
65: override fun activeDownloads(): List<DownloadProgress> = emptyList()
Exact file bytes / download · SHA-256 4a56a1c49f3df40a47f06d3ab0265a5b852226fb90ec52ce6955075b3f13abd9.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.browse
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.download.DownloadProgress
import eu.friedcutlet.yokan.services.download.DownloadRequest
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.services.library.SelectiveDataClearService
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
@OptIn(ExperimentalCoroutinesApi::class)
class BrowseClearViewModelTest {
private val host = ViewModelTestHost()
@AfterTest
fun tearDown() = host.close()
@Test
fun reportsSuccessOnlyAfterCommittedClearCompletes() = runTest {
val vm = viewModel(InMemoryYokanDatabase())
vm.clearLibrary(setOf(ItemType.Manga))
assertFalse(vm.state.value.busy)
assertEquals("Library records cleared locally; no hub is configured.", vm.state.value.success)
assertEquals(null, vm.state.value.error)
}
@Test
fun keepsFailureAsActionableErrorWithoutSuccess() = runTest {
val vm = viewModel(object : YokanDatabase by InMemoryYokanDatabase() {
override fun supportsAtomicSnapshotPersistence() = false
})
vm.clearSources(setOf(ItemType.Manga))
assertFalse(vm.state.value.busy)
assertEquals("This database backend cannot atomically clear data; nothing was changed.", vm.state.value.error)
assertEquals(null, vm.state.value.success)
}
private fun viewModel(database: YokanDatabase): BrowseClearViewModel {
val service = SelectiveDataClearService(database, NoActiveDownloads)
return host.create { BrowseClearViewModel(service, hasConfiguredHub = { false }, workDispatcher = UnconfinedTestDispatcher()) }
}
}
private object NoActiveDownloads : DownloadService {
override suspend fun initialize(poolSize: Int) = Unit
override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
override fun cancel(taskId: String) = Unit
override fun pause(taskId: String) = Unit
override fun resume(taskId: String) = Unit
override fun retry(taskId: String) = false
override fun storageLocation(taskId: String): String? = null
override fun deleteArtifacts(taskId: String) = Unit
override fun activeDownloads(): List<DownloadProgress> = emptyList()
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/browse/ClearItemTypesParserTest.kt
- Source · test / fixture · 23 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
8: class ClearItemTypesParserTest {
10: fun trimsIgnoresCaseAndDeduplicatesTypes() {
18: fun rejectsBlankUnknownAllAndPartiallyValidInput() {
Exact file bytes / download · SHA-256 3b8d97b5b2073de3fb6fa78c129b13f07826127e6cd3288b50f409b4214c1089.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.browse
import eu.friedcutlet.yokan.domain.ItemType
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class ClearItemTypesParserTest {
@Test
fun trimsIgnoresCaseAndDeduplicatesTypes() {
assertEquals(
linkedSetOf(ItemType.Manga, ItemType.Anime),
parseClearItemTypes(" Manga, anime, MANGA "),
)
}
@Test
fun rejectsBlankUnknownAllAndPartiallyValidInput() {
listOf("", " ", ",manga", "manga,", "manga,,anime", "manga,unknown", "all").forEach { input ->
assertNull(parseClearItemTypes(input), input)
}
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/browse/CookiePrivacyTest.kt
- Source · test / fixture · 26 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class CookiePrivacyTest {
9: fun hiddenTextContainsNeitherCookieNamesNorValues() {
20: fun valuesRequireExplicitRevealAndCanBeHiddenAgain() {
Exact file bytes / download · SHA-256 4546e39f2f1a61c16efeae40094838b5319697d63e6a101997efac2d73b50c52.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.browse
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class CookiePrivacyTest {
@Test
fun hiddenTextContainsNeitherCookieNamesNorValues() {
val secret = "session=private-session-token; auth=private-auth-token"
val displayed = cookieValueText(secret, revealed = false)
assertEquals("•••••••• (hidden)", displayed)
assertFalse(displayed.contains("session"))
assertFalse(displayed.contains("auth"))
assertEquals(displayed, cookieValueText(null, revealed = false))
assertEquals(displayed, cookieValueText("", revealed = false))
}
@Test
fun valuesRequireExplicitRevealAndCanBeHiddenAgain() {
val secret = "session=private-session-token"
assertEquals(secret, cookieValueText(secret, revealed = true))
assertEquals("", cookieValueText(null, revealed = true))
assertEquals("•••••••• (hidden)", cookieValueText(secret, revealed = false))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/library/AutomaticUpdateConditionsViewModelTest.kt
- Source · test / fixture · 61 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
12: class AutomaticUpdateConditionsViewModelTest {
Exact file bytes / download · SHA-256 ffae4cb7cc82274c946e9243e31e2217afff0c49964fd764b78e4921e7d6a9f7.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.library
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.data.*
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.scheduling.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*
@OptIn(ExperimentalCoroutinesApi::class)
class AutomaticUpdateConditionsViewModelTest {
private val host = ViewModelTestHost()
private val dispatcher = host.dispatcher
@AfterTest fun after() = host.close()
@Test fun policyChangesCancelAndJoinOldTelemetryAndPublishTheNewCheck() = runTest(dispatcher) {
val repo = DefaultYokanRepository(InMemoryYokanDatabase(emptySnapshot()))
val settings = SettingsStore(repo, backgroundScope) {}
val requests = mutableListOf<Boolean>()
var finalized = false
val gate = AutomaticUpdateGate(read = { power ->
requests += power
if (!power) try { awaitCancellation() } finally { finalized = true }
UpdateDeviceConditions(connected = true, externalPower = true)
}, clock = { 100 })
val vm = host.create { AutomaticUpdateConditionsViewModel(settings, gate, dispatcher) }
runCurrent()
assertTrue(requests.isEmpty(), "Opening legacy defaults does not request device telemetry")
settings.updateDb { db -> db.copy(features = db.features.copy(library = db.features.library.copy(
deviceConstraints = DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected)))) }
runCurrent()
assertTrue(vm.state.value.checking)
settings.updateDb { db -> db.copy(features = db.features.copy(library = db.features.library.copy(
deviceConstraints = DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected, requireExternalPower = true)))) }
runCurrent()
assertTrue(finalized)
assertEquals(listOf(false, true), requests)
assertFalse(vm.state.value.checking)
assertTrue(checkNotNull(vm.state.value.admission).allowed)
}
@Test fun unrelatedSettingsDoNotReprobeAndExplicitChecksBypassTheCache() = runTest(dispatcher) {
val db = emptySnapshot().let { it.copy(settings = it.settings.copy(features = it.settings.features.copy(library = it.settings.features.library.copy(
deviceConstraints = DbAutomaticUpdateConstraints(DbUpdateNetwork.Connected))))) }
val repo = DefaultYokanRepository(InMemoryYokanDatabase(db))
val settings = SettingsStore(repo, backgroundScope) {}
var calls = 0
val gate = AutomaticUpdateGate(read = { calls++; UpdateDeviceConditions(connected = true) }, clock = { 100 })
val vm = host.create { AutomaticUpdateConditionsViewModel(settings, gate, dispatcher) }
runCurrent()
assertEquals(1, calls)
settings.updateDb { it.copy(incognitoMode = !it.incognitoMode) }
runCurrent()
assertEquals(1, calls)
vm.refresh()
runCurrent()
assertEquals(2, calls)
assertFalse(vm.state.value.checking)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/library/CategoryOrderingTest.kt
- Source · test / fixture · 31 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
10: class CategoryOrderingTest {
Exact file bytes / download · SHA-256 376ac86658eab46902d60b54c65cb4b4bc9f6c4d26a5da3be8092346390d54e9.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.library
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.domain.ItemType
import kotlin.test.Test
import kotlin.test.assertEquals
class CategoryOrderingTest {
@Test fun dragOffsetsAndSingleStepActionsPersistTheSameCategoryOrder() {
val database = InMemoryYokanDatabase(emptySnapshot())
val repository = DefaultYokanRepository(database)
val categories = listOf("First", "Second", "Third").map { repository.createCategory(ItemType.Manga, it) }
val anime = repository.createCategory(ItemType.Anime, "Anime only")
repository.updateCategory(categories[0].id, null, hidden = true, shouldUpdate = false)
// ReorderableColumn supplies from/to indices; the screen forwards their difference.
repository.moveCategory(ItemType.Manga, categories[0].id, 2 - 0)
assertEquals(listOf("Second", "Third", "First"), repository.categories(ItemType.Manga).map { it.name })
repository.moveCategory(ItemType.Manga, categories[0].id, -1)
assertEquals(listOf("Second", "First", "Third"), repository.categories(ItemType.Manga).map { it.name })
val restored = DefaultYokanRepository(InMemoryYokanDatabase(database.snapshot()))
assertEquals(repository.categories(ItemType.Manga), restored.categories(ItemType.Manga))
assertEquals(listOf(0, 1, 2), restored.categories(ItemType.Manga).map { it.position })
assertEquals(true, restored.categories(ItemType.Manga)[1].hidden)
assertEquals(false, restored.categories(ItemType.Manga)[1].shouldUpdate)
assertEquals(listOf(anime), restored.categories(ItemType.Anime))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/statistics/StatisticsTest.kt
- Source · test / fixture · 102 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
13: class StatisticsTest {
98: private fun title(id: Long) = Manga(id, "Title $id", link = "", description = "", status = Status.Ongoing,
100: private fun chapter(id: Long, title: Long, read: Boolean) = Chapter(id, title, "Chapter", "", isRead = read)
101: private fun history(id: Long, seconds: Int, updated: Long) = History(id, id, id, ItemType.Manga, "Title $id", "Chapter", "Now", seconds, updated)
Exact file bytes / download · SHA-256 ec661510d0423f51119b3774f3707274527ec76262e49a6f79f150a3274a34c6.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.statistics
import androidx.compose.ui.geometry.Rect
import kotlinx.datetime.isoDayNumber
import kotlinx.datetime.toLocalDateTime
import eu.friedcutlet.yokan.domain.*
import kotlinx.datetime.TimeZone
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class StatisticsTest {
@Test fun progressDistinguishesCaughtUpFromPublicationStatusAndPartialReading() {
val titles = listOf(title(1), title(2), title(3), title(4).copy(status = Status.Completed), title(5).copy(favorite = false))
val chapters = mapOf(
1L to listOf(chapter(1, 1, true)),
2L to listOf(chapter(2, 2, false).copy(lastPageRead = "4")),
3L to emptyList(),
4L to listOf(chapter(4, 4, false)),
5L to listOf(chapter(5, 5, true)),
)
val result = summarizeStatistics(titles, chapters, emptyList(), setOf(1), setOf(1, 5))
assertEquals(4, result.titles)
assertEquals(3, result.chapters)
assertEquals(1, result.read)
assertEquals(1, result.caughtUp)
assertEquals(1, result.inProgress)
assertEquals(2, result.notStarted)
assertEquals(1, result.downloadedTitles)
assertEquals(1, result.trackedTitles)
}
@Test fun historyTotalsDoNotOverflow() {
val history = listOf(history(1, Int.MAX_VALUE, 1), history(2, Int.MAX_VALUE, 2), history(3, -1, 3))
val result = summarizeStatistics(emptyList(), emptyMap(), history, emptySet(), emptySet())
assertEquals(Int.MAX_VALUE.toLong() * 2, result.seconds)
assertEquals(3, result.activeTitles)
}
@Test fun activityBucketsByLocalDayAndHourInsideAMondayAlignedWindow() {
val now = 1_790_000_000_000L // 2026-09-21T14:13Z
val day = 86_400_000L
val history = listOf(history(1, 60, now), history(2, 60, now - 1), history(3, 60, now - 3 * day),
history(4, 60, now - 400 * day), history(5, 60, 0))
val result = summarizeStatistics(emptyList(), emptyMap(), history, emptySet(), emptySet(), now, TimeZone.UTC)
val days = result.dailyActivity
assertTrue(days.size in (ACTIVITY_WEEKS - 1) * 7 + 1..ACTIVITY_WEEKS * 7)
val today = kotlin.time.Instant.fromEpochMilliseconds(now).toLocalDateTime(TimeZone.UTC).dayOfWeek.isoDayNumber
assertEquals(today, (days.size - 1) % 7 + 1) // window starts on a Monday and ends today
assertEquals(2, days.last())
assertEquals(1, days[days.size - 4])
assertEquals(3, days.sum()) // out-of-window and unknown timestamps are dropped
assertEquals(4, result.hourly[14]) // hour-of-day spans all history, not just the heatmap window
assertEquals(4, result.hourly.sum())
}
@Test fun growthIsCumulativeAndGenresMergeCaseAndRankBySize() {
val month = 31L * 86_400_000L
val now = 1_790_000_000_000L
val titles = listOf(
title(1).copy(dateAddedMillis = now - 3 * month, genres = listOf("Action", "Drama")),
title(2).copy(dateAddedMillis = now - month, genres = listOf("action ", "Comedy")),
title(3).copy(dateAddedMillis = 0, genres = listOf("Action", "ACTION")),
title(4).copy(dateAddedMillis = now, favorite = false, genres = listOf("Comedy")),
)
val result = summarizeStatistics(titles, emptyMap(), emptyList(), emptySet(), emptySet(), now, TimeZone.UTC)
assertEquals(result.growth.sorted(), result.growth)
assertEquals(2, result.growth.first()) // undated titles count from the start
assertEquals(3, result.growth.last())
assertEquals("Action" to 3, result.genres.first())
assertEquals(listOf("Action", "Comedy", "Drama"), result.genres.map { it.first })
}
@Test fun emptyLibraryHasNoInventedProgressOrActivity() {
val result = summarizeStatistics(emptyList(), emptyMap(), emptyList(), emptySet(), emptySet())
assertEquals(0, result.caughtUp)
assertEquals(0, result.notStarted)
assertEquals(0L, result.seconds)
assertEquals(0, result.dailyActivity.sum())
assertEquals(listOf(0), result.growth)
assertEquals(emptyList(), result.genres)
}
@Test fun treemapTilesBoundsWithAreasProportionalToValues() {
val values = listOf(40, 25, 15, 10, 6, 4)
val bounds = Rect(0f, 0f, 300f, 200f)
val rects = layoutTreemap(values, bounds)
assertEquals(values.size, rects.size)
val total = values.sum().toFloat()
rects.forEachIndexed { i, r ->
assertTrue(r.left >= 0f && r.top >= 0f && r.right <= 300.01f && r.bottom <= 200.01f)
assertTrue(abs(r.width * r.height - bounds.width * bounds.height * values[i] / total) < 1f, "cell $i area")
}
assertTrue(abs(rects.sumOf { (it.width * it.height).toDouble() } - 60_000.0) < 1.0)
}
private fun title(id: Long) = Manga(id, "Title $id", link = "", description = "", status = Status.Ongoing,
itemType = ItemType.Manga, favorite = true, source = "", lang = "en", dateAddedMillis = 0, lastUpdateMillis = 0)
private fun chapter(id: Long, title: Long, read: Boolean) = Chapter(id, title, "Chapter", "", isRead = read)
private fun history(id: Long, seconds: Int, updated: Long) = History(id, id, id, ItemType.Manga, "Title $id", "Chapter", "Now", seconds, updated)
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/statistics/StatisticsViewModelTest.kt
- Source · test / fixture · 71 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
23: class StatisticsViewModelTest {
41: fun tearDown() = host.close()
43: private fun viewModel(scope: CoroutineScope) = host.create {
55: fun summaryFollowsReadingWithoutARefreshAndSwitchesType() = runTest {
Exact file bytes / download · SHA-256 a00b8ec81c49892523296d7abb7d58855d380961f820f53e211afc20b1df9dd7.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.statistics
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.files.NoFiles
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
@OptIn(ExperimentalCoroutinesApi::class)
class StatisticsViewModelTest {
private val database = InMemoryYokanDatabase(
emptySnapshot().copy(
mangas = listOf(
DbManga(id = 1, name = "Manga", link = "/m", source = "Src", itemType = DbItemType.Manga, favorite = true),
DbManga(id = 2, name = "Anime", link = "/a", source = "Src", itemType = DbItemType.Anime, favorite = true),
),
chapters = listOf(
DbChapter(id = 10, mangaId = 1, name = "1"),
DbChapter(id = 11, mangaId = 1, name = "2"),
),
),
)
private val repository = DefaultYokanRepository(database)
private val host = ViewModelTestHost()
private val dispatcher = host.dispatcher
@AfterTest
fun tearDown() = host.close()
private fun viewModel(scope: CoroutineScope) = host.create {
StatisticsViewModel(
ItemType.Manga,
repository,
SettingsStore(repository, scope, onSchedulingChanged = {}),
LibraryIndexStore(repository, scope),
NoFiles,
workDispatcher = dispatcher,
)
}
@Test
fun summaryFollowsReadingWithoutARefreshAndSwitchesType() = runTest {
val vm = viewModel(backgroundScope)
val initial = vm.state.first { it.data != null }.data!!
assertEquals(1, initial.titles)
assertEquals(2, initial.chapters)
assertEquals(0, initial.read)
database.upsertChapter(database.chapters().first { it.id == 10L }.copy(isRead = true))
assertEquals(1, vm.state.first { it.data?.read == 1 }.data!!.inProgress)
vm.select(ItemType.Anime)
val anime = vm.state.first { it.type == ItemType.Anime && it.data != null }.data!!
assertEquals(1, anime.titles)
assertEquals(0, anime.chapters)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/sync/SyncSettingsViewModelTest.kt
- Source · test / fixture · 82 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
32: class SyncSettingsViewModelTest {
38: private open class GatedSync : SyncService {
42: override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult {
46: override suspend fun logout(syncId: Long) = Unit
47: override suspend fun sync(syncId: Long, settings: DbSettings) = SyncResult(0, 0, false)
48: override suspend fun pushChanges(syncId: Long) = SyncResult(0, 0, false)
49: override suspend fun pullChanges(syncId: Long) = SyncResult(0, 0, false)
50: override fun status(syncId: Long) = SyncConnectionStatus(false, null, null, null)
53: private class IdleCloud : GatedSync(), CloudBackupSyncService {
54: override fun providers() = emptyList<CloudProviderDescriptor>()
55: override fun isCloudPreference(syncPreference: DbSyncPreference?) = false
56: override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String) = error("unused")
57: override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult = error("unused")
58: override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult = error("unused")
Exact file bytes / download · SHA-256 15303f6f62526e22f4eb876adf2a1b420e2e4a1b259a709bacf4591e0f3e9026.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.sync
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.backup.BackupOptions
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.services.sync.CloudBackupResult
import eu.friedcutlet.yokan.services.sync.CloudBackupRestoreResult
import eu.friedcutlet.yokan.services.sync.CloudBackupSyncService
import eu.friedcutlet.yokan.services.sync.CloudProviderDescriptor
import eu.friedcutlet.yokan.services.sync.SyncConnectionStatus
import eu.friedcutlet.yokan.services.sync.SyncLoginResult
import eu.friedcutlet.yokan.services.sync.SyncResult
import eu.friedcutlet.yokan.services.sync.SyncService
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
@OptIn(ExperimentalCoroutinesApi::class)
class SyncSettingsViewModelTest {
private val host = ViewModelTestHost()
private val dispatcher = host.dispatcher
@AfterTest fun after() = host.close()
private open class GatedSync : SyncService {
val logins = mutableListOf<String>()
val result = CompletableDeferred<SyncLoginResult>()
override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult {
logins += email
return result.await()
}
override suspend fun logout(syncId: Long) = Unit
override suspend fun sync(syncId: Long, settings: DbSettings) = SyncResult(0, 0, false)
override suspend fun pushChanges(syncId: Long) = SyncResult(0, 0, false)
override suspend fun pullChanges(syncId: Long) = SyncResult(0, 0, false)
override fun status(syncId: Long) = SyncConnectionStatus(false, null, null, null)
}
private class IdleCloud : GatedSync(), CloudBackupSyncService {
override fun providers() = emptyList<CloudProviderDescriptor>()
override fun isCloudPreference(syncPreference: DbSyncPreference?) = false
override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String) = error("unused")
override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult = error("unused")
override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult = error("unused")
}
@Test fun signInIsExclusiveAndReportsTheServiceMessageWhenItEnds() = runTest(dispatcher) {
val database = InMemoryYokanDatabase()
val settings = SettingsStore(DefaultYokanRepository(database), backgroundScope) {}
val sync = GatedSync()
val http = HttpService { error("offline") }
val vm = host.create { SyncSettingsViewModel(sync, IdleCloud(), NoNotifications, database, settings, http) }
vm.login(1, "https://hub.example", "first@example.com", "secret")
vm.login(1, "https://hub.example", "second@example.com", "secret")
runCurrent()
assertTrue(vm.state.value.operationInProgress)
assertEquals(listOf("first@example.com"), sync.logins)
assertNull(vm.state.value.syncMessage)
sync.result.complete(SyncLoginResult(success = false, message = "Wrong password"))
runCurrent()
assertFalse(vm.state.value.operationInProgress)
assertEquals("Wrong password", vm.state.value.syncMessage)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/tracking/TrackingSettingsViewModelTest.kt
- Source · test / fixture · 109 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
24: class TrackingSettingsViewModelTest {
30: private class FakeTracker(override val syncId: Int, override val isMetadataSource: Boolean = false) : TrackerService {
36: override suspend fun login(values: Map<TrackerLoginField, String>) = pending.await()
37: override suspend fun authorizeUrl(values: Map<TrackerLoginField, String>): String? {
41: override suspend fun checkRefresh() = true
42: override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? = null
43: override suspend fun update(track: DbTrack, isManga: Boolean) = track
44: override fun statusList(isManga: Boolean) = emptyList<DbTrackStatus>()
45: override suspend fun search(query: String, isManga: Boolean) = emptyList<DbTrackSearch>()
46: override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String) = emptyList<DbTrackSearch>()
47: override suspend fun fetchUserData(isManga: Boolean) = emptyList<DbTrackSearch>()
48: override fun scoreValue() = 0 to 10
49: override fun displayScore(score: Int) = "$score"
52: private fun TestScope.viewModel(vararg trackers: TrackerService): Pair<DefaultYokanRepository, TrackingSettingsViewModel> {
59: private fun DefaultYokanRepository.preference(syncId: Int) =
Exact file bytes / download · SHA-256 70f4329fb5535f07032694202f75df9575f551d7708702d4db8f9bda383635c5.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.tracking
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.tracking.TrackerAccounts
import eu.friedcutlet.yokan.services.tracking.TrackerLoginField
import eu.friedcutlet.yokan.services.tracking.TrackerService
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@OptIn(ExperimentalCoroutinesApi::class)
class TrackingSettingsViewModelTest {
private val host = ViewModelTestHost()
private val dispatcher = host.dispatcher
@AfterTest fun after() = host.close()
private class FakeTracker(override val syncId: Int, override val isMetadataSource: Boolean = false) : TrackerService {
override val name = "Fake$syncId"
override val loginFields = listOf(TrackerLoginField.ApiKey)
val pending = CompletableDeferred<DbTrackPreference>()
var authorizeCalls = 0
override suspend fun login(values: Map<TrackerLoginField, String>) = pending.await()
override suspend fun authorizeUrl(values: Map<TrackerLoginField, String>): String? {
authorizeCalls++
return CompletableDeferred<String?>().await()
}
override suspend fun checkRefresh() = true
override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? = null
override suspend fun update(track: DbTrack, isManga: Boolean) = track
override fun statusList(isManga: Boolean) = emptyList<DbTrackStatus>()
override suspend fun search(query: String, isManga: Boolean) = emptyList<DbTrackSearch>()
override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String) = emptyList<DbTrackSearch>()
override suspend fun fetchUserData(isManga: Boolean) = emptyList<DbTrackSearch>()
override fun scoreValue() = 0 to 10
override fun displayScore(score: Int) = "$score"
}
private fun TestScope.viewModel(vararg trackers: TrackerService): Pair<DefaultYokanRepository, TrackingSettingsViewModel> {
val database = InMemoryYokanDatabase()
val accounts = TrackerAccounts(database, trackers.toList(), backgroundScope)
val repository = DefaultYokanRepository(database, trackerAccounts = accounts)
return repository to host.create { TrackingSettingsViewModel(repository, accounts, trackers.toList(), openBrowser = {}) }
}
private fun DefaultYokanRepository.preference(syncId: Int) =
snapshots.value.trackPreferences.firstOrNull { it.syncId == syncId.toLong() }
@Test fun dismissingAnInFlightSignInCancelsItAndNeverWritesStateAfterwards() = runTest(dispatcher) {
val tracker = FakeTracker(10)
val (repository, vm) = viewModel(tracker)
vm.openLogin(10)
vm.login(mapOf(TrackerLoginField.ApiKey to "key"))
vm.authorize(mapOf(TrackerLoginField.ApiKey to "key"))
assertTrue(vm.login.value.busy)
assertEquals(1, tracker.authorizeCalls)
vm.dismissLogin()
tracker.pending.complete(DbTrackPreference(syncId = 10, oauth = "token"))
runCurrent()
assertEquals(TrackerLoginState(), vm.login.value)
assertEquals(null, repository.preference(10)?.oauth)
}
@Test fun failedSignInKeepsTheDialogOpenWithTheProviderMessage() = runTest(dispatcher) {
val tracker = FakeTracker(10)
val (_, vm) = viewModel(tracker)
vm.openLogin(10)
vm.login(emptyMap())
tracker.pending.completeExceptionally(IllegalStateException("Wrong password"))
runCurrent()
assertEquals(TrackerLoginState(syncId = 10, busy = false, status = "Wrong password"), vm.login.value)
}
@Test fun successfulSignInStoresTheAccountAndClosesTheDialog() = runTest(dispatcher) {
val tracker = FakeTracker(10)
val (repository, vm) = viewModel(tracker)
vm.openLogin(10)
vm.login(mapOf(TrackerLoginField.ApiKey to "key"))
tracker.pending.complete(DbTrackPreference(syncId = 10, oauth = "token", accountName = "me"))
runCurrent()
assertEquals(TrackerLoginState(), vm.login.value)
assertEquals("token", repository.preference(10)?.oauth)
}
@Test fun trackingPageListsLegacyTrackersFirstAndLeavesOutTheMetadataTracker() = runTest(dispatcher) {
val (_, vm) = viewModel(FakeTracker(1), FakeTracker(10), FakeTracker(6, isMetadataSource = true), FakeTracker(5), FakeTracker(2))
assertEquals(listOf(2, 1, 5, 10), vm.connectable.map { it.syncId })
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/status/GlobalStatusRingTest.kt
- Source · test / fixture · 49 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
9: class GlobalStatusRingTest {
11: fun downloadsDistinguishIdleUnknownProgressPausedAndFailed() {
27: fun progressIsBoundedAndNonFiniteProgressIsUnknown() {
34: fun cancelledLibraryDoesNotAnimateAndRetainsProgressAndErrors() {
Exact file bytes / download · SHA-256 72565b0a56cd6adf35239593483570a3b3aaf3292dc33469f1b51905bb99eab9.
Complete file
package eu.friedcutlet.yokan.ui.status
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class GlobalStatusRingTest {
@Test
fun downloadsDistinguishIdleUnknownProgressPausedAndFailed() {
assertFalse(downloadRing(GlobalDownloadStatus()).visible)
val active = downloadRing(GlobalDownloadStatus(activeCount = 1))
assertTrue(active.running)
assertNull(active.progress)
val paused = downloadRing(GlobalDownloadStatus(pendingCount = 1, pausedCount = 1, progress = 0.4f))
assertTrue(paused.paused)
assertFalse(paused.running)
assertEquals(0.4f, paused.progress)
val failed = downloadRing(GlobalDownloadStatus(pendingCount = 1, failedCount = 1))
assertTrue(failed.error)
assertFalse(failed.running)
assertTrue(downloadRing(GlobalDownloadStatus(activeCount = 1, failedCount = 1)).running)
}
@Test
fun progressIsBoundedAndNonFiniteProgressIsUnknown() {
assertEquals(1f, downloadRing(GlobalDownloadStatus(progress = 2f)).progress)
assertEquals(0f, downloadRing(GlobalDownloadStatus(progress = -1f)).progress)
assertNull(downloadRing(GlobalDownloadStatus(progress = Float.NaN)).progress)
}
@Test
fun cancelledLibraryDoesNotAnimateAndRetainsProgressAndErrors() {
val update = GlobalLibraryUpdateStatus(
label = "Library", checked = 2, total = 4, updated = 1, failed = 1,
running = false, cancelRequested = true, cancelled = true,
)
val ring = libraryRing(update)
assertTrue(ring.visible)
assertTrue(ring.paused)
assertTrue(ring.error)
assertFalse(ring.running)
assertEquals(0.5f, ring.progress)
val preparing = libraryRing(update.copy(total = 0, running = true, cancelled = false))
assertTrue(preparing.running)
assertNull(preparing.progress)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/status/GlobalStatusTest.kt
- Source · test / fixture · 97 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
15: class GlobalStatusTest {
17: fun aggregationMergesLiveProgressWithoutDoubleCountingPersistedRows() {
37: fun unknownDownloadTotalIsIndeterminate() {
47: fun overlayPolicySeparatesImmersiveAndMinimizedPlayerRoutes() {
60: fun hiddenAndAutomaticModesStayOutOfImmersiveRoutes() {
74: fun expansionReducerDoesNotChangeRouteOrPlayerState() {
91: fun lockOnboardingAndPictureInPictureSynchronouslySuppressEverything() {
Exact file bytes / download · SHA-256 a43cc75eee7dadef8a7d7af66dcac10b0f757bf75ae9bb1ed6721f4329ab30c9.
Complete file
package eu.friedcutlet.yokan.ui.status
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbGlobalStatusVisibility
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.services.download.DownloadProgress
import eu.friedcutlet.yokan.services.sync.SyncOperationOutcome
import eu.friedcutlet.yokan.services.sync.SyncOperationState
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class GlobalStatusTest {
@Test
fun aggregationMergesLiveProgressWithoutDoubleCountingPersistedRows() {
val persisted = listOf(
DbDownload(id = 7, chapterId = 42, succeeded = 1, failed = 0, total = 10, isDownload = false, isStartDownload = true),
DbDownload(id = 8, chapterId = 43, succeeded = 2, failed = 1, total = 6, isDownload = false, isStartDownload = false),
DbDownload(id = 9, chapterId = 44, succeeded = 5, failed = 0, total = 5, isDownload = true, isStartDownload = false),
)
val live = listOf(
DownloadProgress("chapter-42", 4, 0, 10, DbItemType.Manga, isPaused = true),
)
val status = aggregateDownloads(persisted, live)
assertEquals(2, status.pendingCount)
assertEquals(0, status.activeCount)
assertEquals(1, status.pausedCount)
assertEquals(1, status.failedCount)
assertEquals(7, status.completedUnits)
assertEquals(16, status.totalUnits)
assertEquals(7f / 16f, status.progress)
}
@Test
fun unknownDownloadTotalIsIndeterminate() {
val status = aggregateDownloads(
persisted = listOf(DbDownload(id = 1, chapterId = 2, total = null, isDownload = false)),
active = emptyList(),
)
assertNull(status.progress)
assertTrue(status.isRelevant)
}
@Test
fun overlayPolicySeparatesImmersiveAndMinimizedPlayerRoutes() {
val active = GlobalStatusUiState(downloadedOnly = true)
assertTrue(statusOverlayPolicy(active).showCollapsed)
assertFalse(statusOverlayPolicy(active.copy(immersive = true)).showCollapsed)
assertTrue(statusOverlayPolicy(active.copy(immersive = true, playerMinimized = true)).showCollapsed)
assertTrue(
statusOverlayPolicy(
active.copy(immersive = true, visibility = DbGlobalStatusVisibility.AlwaysVisible),
).showCollapsed,
)
}
@Test
fun hiddenAndAutomaticModesStayOutOfImmersiveRoutes() {
assertFalse(
statusOverlayPolicy(
GlobalStatusUiState(immersive = true, visibility = DbGlobalStatusVisibility.Hidden),
).showCollapsed,
)
assertFalse(
statusOverlayPolicy(
GlobalStatusUiState(immersive = true, downloadedOnly = true),
).showCollapsed,
)
}
@Test
fun expansionReducerDoesNotChangeRouteOrPlayerState() {
val playing = GlobalStatusUiState(
immersive = true,
playerMinimized = false,
sync = SyncOperationState(lastOutcome = SyncOperationOutcome.Failed),
)
val expanded = reduceGlobalStatusExpansion(playing, true)
assertTrue(expanded.expanded)
assertEquals(playing.immersive, expanded.immersive)
assertEquals(playing.playerMinimized, expanded.playerMinimized)
val dismissed = reduceGlobalStatusExpansion(expanded, false)
assertFalse(dismissed.expanded)
assertEquals(playing.immersive, dismissed.immersive)
assertEquals(playing.playerMinimized, dismissed.playerMinimized)
}
@Test
fun lockOnboardingAndPictureInPictureSynchronouslySuppressEverything() {
val expanded = GlobalStatusUiState(expanded = true)
assertEquals(StatusOverlayPolicy(false, false), statusOverlayPolicy(expanded.copy(appLocked = true)))
assertEquals(StatusOverlayPolicy(false, false), statusOverlayPolicy(expanded.copy(onboarding = true)))
assertEquals(StatusOverlayPolicy(false, false), statusOverlayPolicy(expanded.copy(pictureInPicture = true)))
}
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/appicons/AppIconService.desktop.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun createPlatformAppIconService(): AppIconService = StaticAppIconService()
Exact file bytes / download · SHA-256 90f63822e2f4b14d3ff59a6eaa7d3897b167c650e310f14f85feb00ab8c177a7.
Complete file
package eu.friedcutlet.yokan.services.appicons
actual fun createPlatformAppIconService(): AppIconService = StaticAppIconService()
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/applock/AppLockController.desktop.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun createPlatformAppLockController(): AppLockController = NoOpAppLockController()
Exact file bytes / download · SHA-256 e034a60f78dea6a037fcbe70cbac24911f81641a92ee5f6492d4dd1e5ffe54a4.
Complete file
package eu.friedcutlet.yokan.services.applock
actual fun createPlatformAppLockController(): AppLockController = NoOpAppLockController()
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/discord/DiscordRpcService.desktop.kt
- Source · implementation · 166 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: actual fun createPlatformDiscordRpcService(): DiscordRpcService = DesktopDiscordRpcService()
21: private class DesktopDiscordRpcService : DiscordRpcService {
33: override fun initialize(settings: DbSettings): DiscordRpcStatus = publish(settings, null)
35: override fun showIdle(settings: DbSettings): DiscordRpcStatus = publish(settings, null)
37: override fun showActivity(settings: DbSettings, request: DiscordPresenceRequest): DiscordRpcStatus = publish(settings, request)
39: override fun shutdown() {
44: override fun status(): DiscordRpcStatus = if (usingGateway) gateway.status() else current
46: private fun publish(settings: DbSettings, request: DiscordPresenceRequest?): DiscordRpcStatus {
73: private fun connect(): Boolean {
96: private fun closeIpc() {
101: private fun sendActivity(activity: DiscordActivity) {
136: private fun writeFrame(opcode: Int, payload: String) {
153: private fun discordIpcCandidates() = buildList {
Exact file bytes / download · SHA-256 0313c4b7baea0f3dfb7ab394ab13d5a3bb1c518f33a79b0c0d8ca87f0722f4d4.
Complete file
package eu.friedcutlet.yokan.services.discord
import eu.friedcutlet.yokan.database.DbSettings
import java.net.StandardProtocolFamily
import java.net.UnixDomainSocketAddress
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.SocketChannel
import kotlin.io.path.exists
import kotlin.io.path.pathString
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
actual fun createPlatformDiscordRpcService(): DiscordRpcService = DesktopDiscordRpcService()
/**
* The local Discord client's IPC socket by default (no login needed); a Discord account chosen in
* Settings switches to the shared gateway transport so the selected account shows the presence.
*/
private class DesktopDiscordRpcService : DiscordRpcService {
private val gateway = GatewayDiscordRpcService()
private var channel: SocketChannel? = null
private val startedAt = System.currentTimeMillis()
private var usingGateway = false
private var current = DiscordRpcStatus(
supported = true,
enabled = false,
connected = false,
message = "Discord RPC not initialized.",
)
override fun initialize(settings: DbSettings): DiscordRpcStatus = publish(settings, null)
override fun showIdle(settings: DbSettings): DiscordRpcStatus = publish(settings, null)
override fun showActivity(settings: DbSettings, request: DiscordPresenceRequest): DiscordRpcStatus = publish(settings, request)
override fun shutdown() {
gateway.shutdown()
closeIpc()
}
override fun status(): DiscordRpcStatus = if (usingGateway) gateway.status() else current
private fun publish(settings: DbSettings, request: DiscordPresenceRequest?): DiscordRpcStatus {
if (!settings.enableDiscordRpc) {
shutdown()
current = DiscordRpcStatus(true, enabled = false, connected = false, message = "Discord RPC disabled in settings.")
return current
}
usingGateway = settings.features.discord.activeAccount != null
if (usingGateway) {
closeIpc()
return gateway.publish(settings, request)
}
gateway.shutdown()
val activity = discordActivity(settings, request, startedAt)
if (activity == null) {
closeIpc()
current = DiscordRpcStatus(true, enabled = true, connected = false, message = "Discord RPC hidden while incognito mode is enabled.")
return current
}
if (channel?.isOpen != true && !connect()) return current
return runCatching {
sendActivity(activity)
DiscordRpcStatus(true, enabled = true, connected = true, message = "Discord RPC activity updated.")
}.getOrElse { error ->
DiscordRpcStatus(true, enabled = true, connected = false, message = "Discord RPC update failed: ${error.message.orEmpty()}")
}.also { current = it }
}
private fun connect(): Boolean {
val socket = discordIpcCandidates().firstOrNull { it.exists() }
if (socket == null) {
current = DiscordRpcStatus(true, enabled = true, connected = false, message = "Discord IPC socket not found; Discord client may be closed.")
return false
}
return runCatching {
val next = SocketChannel.open(StandardProtocolFamily.UNIX)
// Own the descriptor before connect, so shutdown also closes failed attempts.
channel = next
next.connect(UnixDomainSocketAddress.of(socket))
writeFrame(0, buildJsonObject {
put("v", JsonPrimitive(1))
put("client_id", JsonPrimitive(DiscordApplicationId))
}.toString())
true
}.getOrElse { error ->
closeIpc()
current = DiscordRpcStatus(true, enabled = true, connected = false, message = "Discord RPC connection failed: ${error.message.orEmpty()}")
false
}
}
private fun closeIpc() {
runCatching { channel?.close() }
channel = null
}
private fun sendActivity(activity: DiscordActivity) {
val cover = activity.coverUrl
val assets = buildJsonObject {
put("large_image", JsonPrimitive(cover ?: "app-icon"))
put("large_text", JsonPrimitive(if (cover == null) "Yokan" else activity.details))
if (cover != null) {
put("small_image", JsonPrimitive("app-icon"))
put("small_text", JsonPrimitive("Yokan"))
}
}
val payload = buildJsonObject {
put("details", JsonPrimitive(activity.details))
put("state", JsonPrimitive(activity.state))
put("type", JsonPrimitive(if (activity.watching) 3 else 0))
activity.startedAtMillis?.let { start -> put("timestamps", buildJsonObject { put("start", JsonPrimitive(start)) }) }
put("assets", assets)
if (activity.buttons.isNotEmpty()) put("buttons", buildJsonArray {
activity.buttons.forEach { button ->
add(buildJsonObject {
put("label", JsonPrimitive(button.label.take(32)))
put("url", JsonPrimitive(button.url))
})
}
})
}
writeFrame(1, buildJsonObject {
put("cmd", JsonPrimitive("SET_ACTIVITY"))
put("args", buildJsonObject {
put("pid", JsonPrimitive(ProcessHandle.current().pid()))
put("activity", payload)
})
put("nonce", JsonPrimitive("${System.currentTimeMillis()}-${activity.details.hashCode()}"))
}.toString())
}
private fun writeFrame(opcode: Int, payload: String) {
val body = payload.encodeToByteArray()
val buffer = ByteBuffer.allocate(8 + body.size).order(ByteOrder.LITTLE_ENDIAN)
buffer.putInt(opcode)
buffer.putInt(body.size)
buffer.put(body)
buffer.flip()
val currentChannel = channel ?: return
try {
while (buffer.hasRemaining()) currentChannel.write(buffer)
} catch (failure: java.io.IOException) {
// Discord went away: drop the dead socket so the next call reconnects.
closeIpc()
throw failure
}
}
private fun discordIpcCandidates() = buildList {
val envCandidates = listOf(
System.getenv("XDG_RUNTIME_DIR"),
System.getenv("TMPDIR"),
System.getenv("TMP"),
System.getenv("TEMP"),
"/tmp",
).filterNotNull().distinct()
envCandidates.forEach { base ->
repeat(10) { index -> add(java.nio.file.Path.of(base, "discord-ipc-$index")) }
repeat(10) { index -> add(java.nio.file.Path.of(base, "app", "com.discordapp.Discord", "discord-ipc-$index")) }
}
}.distinctBy { it.pathString }
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/notifications/NotificationService.desktop.kt
- Source · implementation · 21 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: actual fun createPlatformNotificationService(profileId: ProfileId): NotificationService = DesktopNotificationService(profileId)
13: private class DesktopNotificationService(private val profileId: ProfileId) : NotificationService {
14: override fun supported(): Boolean = true
16: override fun notify(payload: NotificationPayload) {
20: override fun cancel(channel: NotificationChannel, tag: String?) = Unit
Exact file bytes / download · SHA-256 177d31082ff211782388427be06b2f2dd3ef013bf7a141becd5bf27c46e6ea85.
Complete file
package eu.friedcutlet.yokan.services.notifications
import eu.friedcutlet.yokan.domain.ProfileId
actual fun createPlatformNotificationService(profileId: ProfileId): NotificationService = DesktopNotificationService(profileId)
/**
* Desktop notifications render as in-app snackbars rather than OS system-tray
* balloons. The AWT `TrayIcon.displayMessage` path produced stale/duplicate
* popups on Linux, so everything now flows through [InAppNotifications] and is
* shown by the root composable's SnackbarHost.
*/
private class DesktopNotificationService(private val profileId: ProfileId) : NotificationService {
override fun supported(): Boolean = true
override fun notify(payload: NotificationPayload) {
InAppNotifications.post(payload.copy(profileId = profileId))
}
override fun cancel(channel: NotificationChannel, tag: String?) = Unit
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundScheduler.desktop.kt
- Source · implementation · 113 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler =
19: private class DesktopBackgroundScheduler(private val database: YokanDatabase) : BackgroundScheduler {
20: override fun schedule(
35: override fun cancelAll() = Unit
39: object DesktopSession {
47: object DesktopAutostart {
54: private fun launcher(): String? = ProcessHandle.current().info().command().orElse(null)
57: fun apply(enabled: Boolean) {
103: private fun reconcile(file: File, enabled: Boolean, content: () -> String) {
Exact file bytes / download · SHA-256 ea7baf632b8c965c8c43553e4d1623389baf2118fbdd156e72c2093ec5bac23a.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
import java.awt.Frame
import java.io.File
import kotlinx.coroutines.flow.MutableStateFlow
actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler =
DesktopBackgroundScheduler(database)
/**
* Desktop has no OS job runner for JVM code; [ForegroundScheduler] ticks while the process lives, so
* "background" work means keeping the process alive: close-to-tray plus an optional login item.
* [schedule] runs on every settings save, which makes it the one place that reconciles both with
* [eu.friedcutlet.yokan.database.DbSettings].
*/
private class DesktopBackgroundScheduler(private val database: YokanDatabase) : BackgroundScheduler {
override fun schedule(
metadataRefreshMinutes: Long,
libraryUpdateMinutes: Long,
libraryUpdateDailyAtMinutes: Int,
autoSyncMinutes: Long,
autoBackupHours: Long,
requireUnmetered: Boolean,
libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,
) {
val settings = database.settings()
DesktopSession.closeToTray.value = settings.desktopCloseToTray
runCatching { DesktopAutostart.apply(settings.desktopLaunchAtLogin) }
.onFailure { AppLogger.warn("Login item: ${it.message.orEmpty()}") }
}
override fun cancelAll() = Unit
}
/** Process-wide desktop window state read by `Main.kt`. */
object DesktopSession {
val closeToTray = MutableStateFlow(false)
/** The main window, for fullscreen and as the parent of native file dialogs. */
@Volatile var frame: Frame? = null
}
/** OS login item that starts the packaged app hidden in the tray. */
object DesktopAutostart {
const val TRAY_FLAG = "--tray"
private const val LABEL = "eu.friedcutlet.yokan"
private val os = System.getProperty("os.name").lowercase()
private val home = System.getProperty("user.home")
/** jpackage launcher, or null under Gradle/IDE where a login item would start bare `java`. */
private fun launcher(): String? = ProcessHandle.current().info().command().orElse(null)
?.takeUnless { File(it).nameWithoutExtension.equals("java", ignoreCase = true) }
fun apply(enabled: Boolean) {
val launcher = launcher()
if (enabled && launcher == null) {
AppLogger.warn("Login item skipped: not running from a packaged install.")
return
}
when {
os.contains("mac") -> reconcile(
File(home, "Library/LaunchAgents/$LABEL.plist"),
enabled,
) {
"""
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>$LABEL</string>
<key>ProgramArguments</key><array><string>$launcher</string><string>$TRAY_FLAG</string></array>
<key>RunAtLoad</key><true/>
</dict></plist>
""".trimIndent()
}
os.contains("win") -> {
val key = """HKCU\Software\Microsoft\Windows\CurrentVersion\Run"""
val args = if (enabled) {
listOf("reg", "add", key, "/v", "Yokan", "/t", "REG_SZ", "/d", "\"$launcher\" $TRAY_FLAG", "/f")
} else {
listOf("reg", "delete", key, "/v", "Yokan", "/f")
}
// reg delete exits non-zero when the value is already absent; that is the desired state.
ProcessBuilder(args).redirectErrorStream(true).start().waitFor()
}
else -> reconcile(
File(home, ".config/autostart/yokan.desktop"),
enabled,
) {
"""
[Desktop Entry]
Type=Application
Name=Yokan
Exec=$launcher $TRAY_FLAG
X-GNOME-Autostart-enabled=true
""".trimIndent()
}
}
}
private fun reconcile(file: File, enabled: Boolean, content: () -> String) {
if (!enabled) {
file.delete()
return
}
val text = content()
if (file.exists() && file.readText() == text) return
file.parentFile.mkdirs()
file.writeText(text)
}
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/scheduling/UpdateDeviceConditions.desktop.kt
- Source · implementation · 152 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions = runInterruptible(Dispatchers.IO) {
27: internal fun conditionCommand(command: List<String>, timeoutMillis: Long = 2_000, maximumBytes: Int = 8_192): String? {
47: internal fun decodeMacUpdateConditions(route: String?, hardware: String?, power: String?): UpdateDeviceConditions {
73: internal fun decodeWindowsUpdateConditions(json: String?): UpdateDeviceConditions {
84: private fun boundedText(path: String, maximum: Int = 65_536): String? = runCatching {
88: private fun readLinuxUpdateConditions(needPower: Boolean): UpdateDeviceConditions {
107: internal fun linuxDefaultInterface(ipv4: String?, ipv6: String?, up: Set<String>): String? {
119: internal fun decodeLinuxUnmetered(value: String?): Boolean? = when (value?.trim()?.lowercase()) {
125: internal fun decodeLinuxExternalPower(supplies: List<Pair<String, String?>>): Boolean? {
Exact file bytes / download · SHA-256 b070c6a93b6b0ccea76b8b6e5cdb99841c381cf79b460fc3d04e261e984f72fd.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.database.DatabaseJson
import java.io.File
import java.net.NetworkInterface
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runInterruptible
import kotlinx.serialization.json.*
actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions = runInterruptible(Dispatchers.IO) {
when {
System.getProperty("os.name").contains("win", true) -> decodeWindowsUpdateConditions(conditionCommand(
listOf("powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
"\$ReadPower = ${if (needPower) "\$true" else "\$false"};\n$WindowsConditionScript")))
System.getProperty("os.name").contains("mac", true) -> {
val route = conditionCommand(listOf("/sbin/route", "-n", "get", "default"))
val hardware = conditionCommand(listOf("/usr/sbin/networksetup", "-listallhardwareports"))
val power = if (needPower) conditionCommand(listOf("/usr/bin/pmset", "-g", "batt")) else null
decodeMacUpdateConditions(route, hardware, power)
}
else -> readLinuxUpdateConditions(needPower)
}
}
/** Fixed read-only commands, bounded runtime/output, no shell or user-controlled arguments. */
internal fun conditionCommand(command: List<String>, timeoutMillis: Long = 2_000, maximumBytes: Int = 8_192): String? {
val process = try { ProcessBuilder(command).redirectErrorStream(true).apply { environment()["LC_ALL"] = "C" }.start() }
catch (_: Exception) { return null }
return try {
if (!process.waitFor(timeoutMillis, TimeUnit.MILLISECONDS) || process.exitValue() != 0) null
else {
val available = process.inputStream.available()
if (available > maximumBytes) null else process.inputStream.readNBytes(available).toString(Charsets.UTF_8)
}
} finally {
if (process.isAlive) {
process.descendants().use { descendants -> descendants.forEach { it.destroyForcibly() } }
process.destroyForcibly()
}
process.inputStream.close()
process.errorStream.close()
process.outputStream.close()
}
}
internal fun decodeMacUpdateConditions(route: String?, hardware: String?, power: String?): UpdateDeviceConditions {
val active = route?.lineSequence()?.firstOrNull { it.trim().startsWith("interface:") }?.substringAfter(':')?.trim()
var port: String? = null
val wifiInterfaces = mutableSetOf<String>()
val knownInterfaces = mutableSetOf<String>()
hardware?.lineSequence()?.forEach { line ->
when {
line.startsWith("Hardware Port:") -> port = line.substringAfter(':').trim()
line.startsWith("Device:") -> {
val name = line.substringAfter(':').trim()
knownInterfaces += name
if (port in setOf("Wi-Fi", "AirPort")) wifiInterfaces += name
}
}
}
val connected = if (route == null) null else active?.isNotEmpty() == true
val wifi = if (connected == false) false else if (active == null || hardware == null || active !in knownInterfaces) null else active in wifiInterfaces
val external = when {
power?.lineSequence()?.firstOrNull()?.contains("'AC Power'") == true -> true
power?.lineSequence()?.firstOrNull()?.contains("'Battery Power'") == true -> false
else -> null
}
// macOS does not expose a reliable cost flag through these read-only command interfaces.
return UpdateDeviceConditions(connected, wifi, if (connected == false) false else null, external)
}
internal fun decodeWindowsUpdateConditions(json: String?): UpdateDeviceConditions {
if (json == null) return UpdateDeviceConditions()
return runCatching {
val obj = DatabaseJson.parseToJsonElement(json.trim().removePrefix("\uFEFF")) as? JsonObject ?: return@runCatching UpdateDeviceConditions()
if (obj.keys.any { it !in setOf("connected", "wifi", "unmetered", "externalPower") } || obj.values.any {
it != JsonNull && (it !is JsonPrimitive || it.isString || it.booleanOrNull == null)
}) return@runCatching UpdateDeviceConditions()
DatabaseJson.decodeFromJsonElement<UpdateDeviceConditions>(obj)
}.getOrElse { UpdateDeviceConditions() }
}
private fun boundedText(path: String, maximum: Int = 65_536): String? = runCatching {
File(path).inputStream().use { input -> input.readNBytes(maximum + 1).takeIf { it.size <= maximum }?.toString(Charsets.UTF_8) }
}.getOrNull()
private fun readLinuxUpdateConditions(needPower: Boolean): UpdateDeviceConditions {
val up = runCatching { NetworkInterface.getNetworkInterfaces().asSequence().filter { it.isUp && !it.isLoopback }
.take(128).map { it.name }.toSet() }.getOrDefault(emptySet())
val ipv4 = boundedText("/proc/net/route")
val ipv6 = boundedText("/proc/net/ipv6_route")
val active = linuxDefaultInterface(ipv4, ipv6, up)
val connected = if (ipv4 == null && ipv6 == null) null else active != null
val safeInterface = active?.takeIf { it.matches(Regex("[A-Za-z0-9_.-]{1,64}")) }
val wifi = if (connected == false) false else safeInterface?.let {
File("/sys/class/net/$it/wireless").isDirectory || File("/sys/class/net/$it/phy80211").exists()
}
val metered = safeInterface?.let { conditionCommand(listOf("nmcli", "-t", "-g", "GENERAL.METERED", "device", "show", it)) }
val supplies = (if (needPower) File("/sys/class/power_supply").listFiles().orEmpty().toList() else emptyList()).take(128).map { supply ->
boundedText("${supply.path}/type", 128)?.trim().orEmpty() to boundedText("${supply.path}/online", 32)?.trim()
}
return UpdateDeviceConditions(connected, wifi,
if (connected == false) false else decodeLinuxUnmetered(metered), decodeLinuxExternalPower(supplies))
}
internal fun linuxDefaultInterface(ipv4: String?, ipv6: String?, up: Set<String>): String? {
ipv4?.lineSequence()?.drop(1)?.forEach { line ->
val fields = line.trim().split(Regex("\\s+"))
if (fields.size >= 8 && fields[1] == "00000000" && fields[7] == "00000000" && fields[3].toIntOrNull(16)?.and(1) == 1 && fields[0] in up) return fields[0]
}
ipv6?.lineSequence()?.forEach { line ->
val fields = line.trim().split(Regex("\\s+"))
if (fields.size >= 10 && fields[0] == "0".repeat(32) && fields[1] == "00" && fields[8].toLongOrNull(16)?.and(1L) == 1L && fields.last() in up) return fields.last()
}
return null
}
internal fun decodeLinuxUnmetered(value: String?): Boolean? = when (value?.trim()?.lowercase()) {
"no" -> true
"yes", "yes (guessed)", "guess-yes" -> false
else -> null // A guess of free data is not affirmative evidence of an unmetered connection.
}
internal fun decodeLinuxExternalPower(supplies: List<Pair<String, String?>>): Boolean? {
val external = supplies.filter { (type, _) -> type == "Mains" || type.startsWith("USB") || type == "Wireless" }
.mapNotNull { (_, online) -> when (online) { "1" -> true; "0" -> false; else -> null } }
return when { true in external -> true; external.isNotEmpty() -> false; else -> null }
}
private val WindowsConditionScript = """
${'$'}ErrorActionPreference = 'Stop'
${'$'}connected = ${'$'}null; ${'$'}wifi = ${'$'}null; ${'$'}unmetered = ${'$'}null; ${'$'}externalPower = ${'$'}null
if (${'$'}ReadPower) { try {
Add-Type -AssemblyName System.Windows.Forms
${'$'}line = [System.Windows.Forms.SystemInformation]::PowerStatus.PowerLineStatus.ToString()
if (${'$'}line -eq 'Online') { ${'$'}externalPower = ${'$'}true }
elseif (${'$'}line -eq 'Offline') { ${'$'}externalPower = ${'$'}false }
} catch {} }
try {
${'$'}profile = [Windows.Networking.Connectivity.NetworkInformation, Windows.Networking.Connectivity, ContentType=WindowsRuntime]::GetInternetConnectionProfile()
if (${'$'}null -eq ${'$'}profile) { ${'$'}connected = ${'$'}false; ${'$'}wifi = ${'$'}false; ${'$'}unmetered = ${'$'}false }
else {
${'$'}connected = ${'$'}profile.GetNetworkConnectivityLevel().ToString() -eq 'InternetAccess'
${'$'}wifi = ${'$'}connected -and ${'$'}profile.IsWlanConnectionProfile
${'$'}cost = ${'$'}profile.GetConnectionCost()
${'$'}kind = ${'$'}cost.NetworkCostType.ToString()
if (${'$'}kind -ne 'Unknown') { ${'$'}unmetered = ${'$'}connected -and (${'$'}kind -eq 'Unrestricted') -and -not ${'$'}cost.Roaming -and -not ${'$'}cost.OverDataLimit }
}
} catch {}
@{connected=${'$'}connected; wifi=${'$'}wifi; unmetered=${'$'}unmetered; externalPower=${'$'}externalPower} | ConvertTo-Json -Compress
""".trimIndent()
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/system/DeviceCapabilities.desktop.kt
- Source · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun isTvDevice(): Boolean = false
5: internal actual fun isLocalLibraryManagerSupported(): Boolean = true
7: internal actual fun processMemoryUsage(): ProcessMemoryUsage? = Runtime.getRuntime().let { ProcessMemoryUsage(it.totalMemory() - it.freeMemory(), it.maxMemory()) }
Exact file bytes / download · SHA-256 866d236a7ec37e3d05f40e74f9f7f09f758e6117628897fa7a2062dfa6dfb7cb.
Complete file
package eu.friedcutlet.yokan.services.system
actual fun isTvDevice(): Boolean = false
internal actual fun isLocalLibraryManagerSupported(): Boolean = true
internal actual fun processMemoryUsage(): ProcessMemoryUsage? = Runtime.getRuntime().let { ProcessMemoryUsage(it.totalMemory() - it.freeMemory(), it.maxMemory()) }
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/system/SystemIntegration.desktop.kt
- Source · implementation · 32 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: actual fun isOnUnmeteredNetwork(): Boolean = true
9: actual fun createNetworkMonitor(): NetworkMonitor = UnmeteredNetwork
11: actual fun openSystemBrowser(url: String): Boolean {
25: actual fun applyAppLanguage(languageCode: String?) {
Exact file bytes / download · SHA-256 98b580072b6fc33c847bdeaebbf2aa81e213b4f6b6f04894ae0b2c570b89e2c2.
Complete file
package eu.friedcutlet.yokan.services.system
import java.awt.Desktop
import java.net.URI
import java.util.Locale
actual fun isOnUnmeteredNetwork(): Boolean = true
actual fun createNetworkMonitor(): NetworkMonitor = UnmeteredNetwork
actual fun openSystemBrowser(url: String): Boolean {
if (url.isBlank()) return false
return runCatching {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(URI(url))
true
} else false
}.getOrDefault(false)
}
// Cache the JVM-startup default so "follow system" can restore it after the
// user picks a specific language and later goes back to the default.
private val systemDefaultLocale: Locale = Locale.getDefault()
actual fun applyAppLanguage(languageCode: String?) {
val locale = if (languageCode.isNullOrBlank()) {
systemDefaultLocale
} else {
runCatching { Locale.forLanguageTag(languageCode) }.getOrDefault(systemDefaultLocale)
}
Locale.setDefault(locale)
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/tts/TextToSpeechService.desktop.kt
- Source · implementation · 104 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
9: actual fun createPlatformTextToSpeechService(): TextToSpeechService = DesktopTextToSpeechService()
11: private class DesktopTextToSpeechService : TextToSpeechService {
17: override suspend fun voices(language: String?): List<String> = listOf("System default")
19: override suspend fun speak(
44: override suspend fun stop() {
50: private suspend fun terminate(process: Process) = withContext(Dispatchers.IO) {
59: private fun pickCommand(text: String, request: TextToSpeechRequest): List<String>? {
97: private fun commandExists(name: String): Boolean = runCatching {
Exact file bytes / download · SHA-256 1ec19a2df8cac93fc60aeb2f23164d98dbe1d2d7f81308eedbd9409607d2b5a7.
Complete file
package eu.friedcutlet.yokan.services.tts
import kotlinx.coroutines.delay
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit
actual fun createPlatformTextToSpeechService(): TextToSpeechService = DesktopTextToSpeechService()
private class DesktopTextToSpeechService : TextToSpeechService {
@Volatile private var currentProcess: Process? = null
// Probe once per process instead of forking `which` for every paragraph.
private val hasSpdSay by lazy { commandExists("spd-say") }
private val hasEspeak by lazy { commandExists("espeak") }
override suspend fun voices(language: String?): List<String> = listOf("System default")
override suspend fun speak(
text: String,
request: TextToSpeechRequest,
onProgress: (startOffset: Int, endOffset: Int) -> Unit,
) {
if (text.isBlank()) return
stop()
val command = pickCommand(text, request) ?: return
val process = runCatching { ProcessBuilder(command).inheritIO().start() }.getOrNull() ?: return
currentProcess = process
try {
val wordsPerMinute = (request.speechRate * 350.0).toInt().coerceIn(80, 500)
val wordDelayMillis = (60_000L / wordsPerMinute).coerceAtLeast(40L)
Regex("\\S+").findAll(text).forEach { word ->
if (!process.isAlive) return@forEach
onProgress(word.range.first, word.range.last + 1)
delay(wordDelayMillis)
}
while (process.isAlive) delay(50)
} finally {
withContext(NonCancellable) { terminate(process) }
if (currentProcess === process) currentProcess = null
}
}
override suspend fun stop() {
val process = currentProcess ?: return
terminate(process)
if (currentProcess === process) currentProcess = null
}
private suspend fun terminate(process: Process) = withContext(Dispatchers.IO) {
if (process.isAlive) process.destroy()
if (!process.waitFor(2, TimeUnit.SECONDS)) {
process.destroyForcibly()
process.waitFor()
}
Unit
}
private fun pickCommand(text: String, request: TextToSpeechRequest): List<String>? {
val os = System.getProperty("os.name").orEmpty().lowercase()
val wordsPerMinute = (request.speechRate * 350.0).toInt().coerceIn(80, 500)
return when {
os.contains("mac") -> buildList {
add("say")
request.voice?.takeIf { it.isNotBlank() }?.let {
add("-v")
add(it)
}
add("-r")
add(wordsPerMinute.toString())
add(text)
}
os.contains("linux") -> when {
hasSpdSay -> listOf("spd-say", "-r", ((request.speechRate - 0.5) * 200).toInt().toString(), text)
hasEspeak -> listOf(
"espeak",
"-s",
wordsPerMinute.toString(),
"-p",
(request.pitch * 50.0).toInt().coerceIn(0, 99).toString(),
text,
)
else -> null
}
os.contains("win") -> listOf(
"powershell",
"-Command",
"Add-Type -AssemblyName System.Speech;" +
"\$s=New-Object System.Speech.Synthesis.SpeechSynthesizer;" +
"\$s.Rate=${((request.speechRate - 0.5) * 10).toInt().coerceIn(-10, 10)};" +
"\$s.Speak(\"${text.replace("\"", " ")}\")",
)
else -> null
}
}
private fun commandExists(name: String): Boolean = runCatching {
ProcessBuilder("which", name)
.redirectErrorStream(true)
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
.start()
.waitFor() == 0
}.getOrDefault(false)
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/updates/PackageInstaller.desktop.kt
- Source · implementation · 18 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: actual fun installPackageFromFile(path: String): Boolean {
Exact file bytes / download · SHA-256 d9dc7c87155b9e2ed7358033244d6c9e357a7de2364d71bb2bb02ff1c7c22abc.
Complete file
package eu.friedcutlet.yokan.services.updates
import eu.friedcutlet.yokan.services.logging.AppLogger
import java.awt.Desktop
import java.io.File
actual fun installPackageFromFile(path: String): Boolean {
if (path.isBlank()) return false
val file = File(path.removePrefix("file://"))
if (!file.exists()) return false
return runCatching {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
Desktop.getDesktop().open(file)
true
} else false
}.onFailure { AppLogger.warn("[update] opening package failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
.getOrDefault(false)
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/discord/DiscordLogin.desktop.kt
- Source · implementation · 10 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: internal actual fun DiscordLoginWebView(modifier: Modifier, onToken: (String) -> Unit) = Unit
Exact file bytes / download · SHA-256 7596f64e6cdc316ddcaae6eb7da7578c0f107d05cb263437abd6b4a5b7f64d3b.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.discord
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
// JavaFX WebKit cannot complete Discord's captcha-protected login; desktop uses IPC or a pasted token.
internal actual val discordWebLoginAvailable: Boolean = false
@Composable
internal actual fun DiscordLoginWebView(modifier: Modifier, onToken: (String) -> Unit) = Unit
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/appicons/AppIconPackagingTest.kt
- Source · test / fixture · 90 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
13: class AppIconPackagingTest {
88: private fun xml(file: File) = DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true }.newDocumentBuilder().parse(file)
89: private fun Element.android(name: String) = getAttributeNS("http://schemas.android.com/apk/res/android", name)
Exact file bytes / download · SHA-256 7876a180efbfb331440fde3d614386b1d56e09ee24e3102e79264f57c441a522.
Complete file
package eu.friedcutlet.yokan.services.appicons
import java.io.File
import javax.imageio.ImageIO
import javax.xml.parsers.DocumentBuilderFactory
import kotlinx.serialization.json.*
import org.w3c.dom.Element
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class AppIconPackagingTest {
@Test fun everyLauncherTargetsTheAlwaysEnabledDeepLinkActivityAndHasResolvableArtwork() {
val manifest = xml(File("src/androidMain/AndroidManifest.xml"))
val activity = manifest.getElementsByTagName("activity").item(0) as Element
assertEquals(".MainActivity", activity.android("name"))
assertEquals("true", activity.android("exported"))
assertFalse(activity.android("enabled") == "false")
val links = (0 until activity.getElementsByTagName("data").length).map { activity.getElementsByTagName("data").item(it) as Element }
val schemes = links.mapNotNull { it.android("scheme").ifEmpty { null } }.toSet()
val yokanHosts = links.filter { it.android("scheme") == "yokan" }.map { it.android("host") }.toSet()
// Deep links live on the always-enabled activity, so switching launcher icons never disables them.
assertEquals(setOf("add-repo", "add-button", ""), yokanHosts)
assertTrue(schemes.containsAll(setOf("tachiyomi", "mihon", "aniyomi", "animetail", "content", "file")), "$schemes")
val aliases = manifest.getElementsByTagName("activity-alias")
assertEquals(3, aliases.length)
var defaults = 0
repeat(aliases.length) { index ->
val alias = aliases.item(index) as Element
assertEquals(".MainActivity", alias.android("targetActivity"))
assertEquals("true", alias.android("exported"))
val categories = alias.getElementsByTagName("category")
assertEquals(setOf("android.intent.category.LAUNCHER", "android.intent.category.LEANBACK_LAUNCHER"),
(0 until categories.length).map { (categories.item(it) as Element).android("name") }.toSet())
if (alias.android("enabled") == "true") {
defaults++
assertEquals(".LauncherDefault", alias.android("name"))
assertEquals("@mipmap/ic_launcher", alias.android("icon"))
} else {
assertEquals("false", alias.android("enabled"))
val resource = alias.android("icon").substringAfter('/')
for (qualifier in listOf("mipmap-anydpi", "mipmap-anydpi-v33")) {
val icon = xml(File("src/androidMain/res/$qualifier/$resource.xml"))
assertEquals("adaptive-icon", icon.documentElement.tagName)
val foreground = icon.getElementsByTagName("foreground").item(0) as Element
assertTrue(File("src/androidMain/res/drawable/${foreground.android("drawable").substringAfter('/')}.xml").isFile)
assertEquals(if (qualifier.endsWith("v33")) 1 else 0, icon.getElementsByTagName("monochrome").length)
}
}
}
assertEquals(1, defaults)
}
@Test fun iosFixedAndSystemAssetsAreOpaqueAndInstallerIconsAreValidContainers() {
for (name in listOf("AppIcon", "ToriiLight", "ToriiDark", "ToriiSystem")) {
val directory = File("../iosApp/Assets.xcassets/$name.appiconset")
val images = Json.parseToJsonElement(File(directory, "Contents.json").readText()).jsonObject.getValue("images").jsonArray
assertEquals(if (name == "ToriiSystem") 3 else 1, images.size)
images.forEach { entry ->
val image = ImageIO.read(File(directory, entry.jsonObject.getValue("filename").jsonPrimitive.content))
assertEquals(1024, image.width)
assertEquals(1024, image.height)
assertFalse(image.colorModel.hasAlpha())
}
if (name == "ToriiSystem") {
assertEquals(setOf("dark", "tinted"), images.drop(1).map {
it.jsonObject.getValue("appearances").jsonArray.single().jsonObject.getValue("value").jsonPrimitive.content
}.toSet())
}
}
// Native artwork must use the same sRGB palette as the vector picker previews.
for ((name, background, foreground) in listOf(
Triple("ToriiLight", 0xFFF6EB, 0xB81932),
Triple("ToriiDark", 0x211B24, 0xFFBBC4),
)) {
val image = ImageIO.read(File("../iosApp/Assets.xcassets/$name.appiconset/icon.png"))
assertEquals(background, image.getRGB(0, 0) and 0xFFFFFF)
assertEquals(foreground, image.getRGB(512, 570) and 0xFFFFFF)
}
val icns = File("../packaging/icons/Yokan.icns").readBytes()
assertEquals("icns", String(icns.take(4).toByteArray()))
val ico = File("../packaging/icons/yokan.ico").readBytes()
assertEquals(listOf<Byte>(0, 0, 1, 0, 1, 0), ico.take(6))
assertEquals(256, ImageIO.read(File("../packaging/icons/yokan.png")).width)
assertEquals(192, ImageIO.read(File("src/wasmJsMain/resources/favicon.png")).width)
}
private fun xml(file: File) = DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true }.newDocumentBuilder().parse(file)
private fun Element.android(name: String) = getAttributeNS("http://schemas.android.com/apk/res/android", name)
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/logging/LogSinkAppendTest.kt
- Source · test / fixture · 79 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
10: class LogSinkAppendTest {
12: fun appendsWithoutReadingHistoryAndRotatesAtTheCap() {
20: override fun readBytes(path: String): ByteArray = error("Log append must not read history")
21: override fun writeBytes(path: String, bytes: ByteArray) = error("Log append must not replace history")
40: fun skipsAnEntryLargerThanTheFileCap() {
59: fun doesNotAppendWhenRotationPromotionFails() {
67: override fun promote(sourcePath: String, targetPath: String): Boolean = false
Exact file bytes / download · SHA-256 21474167cb2701af4d4e4fa0af28b7bc2c215324919d0b5a4fcf26d32313b56c.
Complete file
package eu.friedcutlet.yokan.services.logging
import eu.friedcutlet.yokan.services.files.JvmLocalFileService
import eu.friedcutlet.yokan.services.files.LocalFileService
import java.nio.file.Files
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class LogSinkAppendTest {
@Test
fun appendsWithoutReadingHistoryAndRotatesAtTheCap() {
val root = Files.createTempDirectory("yokan-log-test-").toFile()
try {
val disk = JvmLocalFileService(root.absolutePath, root.absolutePath, root.absolutePath)
val log = root.resolve("logs/yokan.log")
log.parentFile.mkdirs()
log.writeText("existing\n")
val files = object : LocalFileService by disk {
override fun readBytes(path: String): ByteArray = error("Log append must not read history")
override fun writeBytes(path: String, bytes: ByteArray) = error("Log append must not replace history")
}
val lines = (0..99).map { "line $it\n".encodeToByteArray() }
// Unknown size first, then the tracked size, exactly as LogSink does.
var size = -1L
lines.forEach { size = appendRotatingLog(files, log.absolutePath, size, it, maxBytes = 200) }
val rotated = root.resolve("logs/yokan.log.1")
assertTrue(log.length() <= 200 && rotated.length() <= 200, "each file stays under the cap")
assertEquals(log.length(), size)
// Nothing between the rotated file and the live file is lost or reordered.
val tail = (rotated.readLines() + log.readLines())
assertEquals((100 - tail.size until 100).map { "line $it" }, tail)
} finally {
root.deleteRecursively()
}
}
@Test
fun skipsAnEntryLargerThanTheFileCap() {
val root = Files.createTempDirectory("yokan-log-oversized-test-").toFile()
try {
val disk = JvmLocalFileService(root.absolutePath, root.absolutePath, root.absolutePath)
val log = root.resolve("logs/yokan.log")
log.parentFile.mkdirs()
log.writeBytes(ByteArray(190))
val size = appendRotatingLog(disk, log.absolutePath, 190L, ByteArray(201), maxBytes = 200)
assertEquals(190L, size)
assertEquals(190L, log.length())
assertTrue(!root.resolve("logs/yokan.log.1").exists())
} finally {
root.deleteRecursively()
}
}
@Test
fun doesNotAppendWhenRotationPromotionFails() {
val root = Files.createTempDirectory("yokan-log-promotion-test-").toFile()
try {
val disk = JvmLocalFileService(root.absolutePath, root.absolutePath, root.absolutePath)
val log = root.resolve("logs/yokan.log")
log.parentFile.mkdirs()
log.writeBytes(ByteArray(190))
val files = object : LocalFileService by disk {
override fun promote(sourcePath: String, targetPath: String): Boolean = false
}
val size = appendRotatingLog(files, log.absolutePath, 190L, ByteArray(11), maxBytes = 200)
assertEquals(190L, size)
assertEquals(190L, log.length())
assertTrue(!root.resolve("logs/yokan.log.1").exists())
} finally {
root.deleteRecursively()
}
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/scheduling/DesktopUpdateDeviceConditionsTest.kt
- Source · test / fixture · 73 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
12: class DesktopUpdateDeviceConditionsTest {
Exact file bytes / download · SHA-256 0829045617daa3f4ee952adf1278598d863856f913b78306156f7bf7080ac53c.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import kotlin.test.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.runInterruptible
import java.io.File
import kotlin.time.TimeSource
class DesktopUpdateDeviceConditionsTest {
@Test fun macReportsActiveHardwareAndPowerWithoutInferringNetworkCost() {
val hardware = "Hardware Port: Wi-Fi\nDevice: en0\n\nHardware Port: Ethernet\nDevice: en1\n"
val wifi = decodeMacUpdateConditions("interface: en0", hardware, "Now drawing from 'AC Power'\n")
assertEquals(UpdateDeviceConditions(true, true, null, true), wifi)
assertEquals(UpdateDeviceConditions(true, false, null, false), decodeMacUpdateConditions("interface: en1", hardware, "Now drawing from 'Battery Power'\n"))
assertEquals(UpdateDeviceConditions(), decodeMacUpdateConditions(null, null, null))
assertNull(decodeMacUpdateConditions("interface: en0", null, "invalid").wifi)
assertNull(decodeMacUpdateConditions("interface: utun0", hardware, null).wifi, "A virtual path is not evidence of a wired connection")
}
@Test fun windowsAcceptsOnlyTypedReadingsAndKeepsUnavailableFieldsUnknown() {
assertEquals(UpdateDeviceConditions(true, false, false, true), decodeWindowsUpdateConditions(
"{\"connected\":true,\"wifi\":false,\"unmetered\":false,\"externalPower\":true}"))
assertEquals(UpdateDeviceConditions(connected = false), decodeWindowsUpdateConditions("{\"connected\":false}"))
assertEquals(UpdateDeviceConditions(), decodeWindowsUpdateConditions("Access denied"))
assertEquals(UpdateDeviceConditions(), decodeWindowsUpdateConditions("{\"connected\":\"true\"}"))
}
@Test fun linuxUsesAnUpDefaultRouteIncludingIpv6AndRejectsPartialDisabledOrNonDefaultRoutes() {
val header = "Iface Destination Gateway Flags RefCnt Use Metric Mask\n"
val route = header + "eth0 00000000 0100000A 0003 0 0 100 00000000\n"
assertEquals("eth0", linuxDefaultInterface(route, null, setOf("eth0")))
assertNull(linuxDefaultInterface(route, null, emptySet()))
assertNull(linuxDefaultInterface(header + "eth0 00000000 0100000A 0000 0 0 100 00000000", null, setOf("eth0")))
assertNull(linuxDefaultInterface(route.replace("100 00000000", "100 00000080"), null, setOf("eth0")))
val ipv6 = "${"0".repeat(32)} 00 ${"0".repeat(32)} 00 ${"0".repeat(32)} 00000100 00000000 00000000 00000001 wlan0"
assertEquals("wlan0", linuxDefaultInterface(null, ipv6, setOf("wlan0")))
assertNull(linuxDefaultInterface(null, ipv6.replace("00000001 wlan0", "00000000 wlan0"), setOf("wlan0")))
}
@Test fun linuxGuessedFreeDataAndMissingPowerReadingsRemainUnknown() {
assertEquals(true, decodeLinuxUnmetered("no\n"))
assertEquals(false, decodeLinuxUnmetered("yes"))
assertEquals(false, decodeLinuxUnmetered("yes (guessed)"))
assertNull(decodeLinuxUnmetered("no (guessed)"))
assertNull(decodeLinuxUnmetered(null))
assertEquals(true, decodeLinuxExternalPower(listOf("Mains" to "0", "USB_PD" to "1")))
assertEquals(false, decodeLinuxExternalPower(listOf("Mains" to "0")))
assertNull(decodeLinuxExternalPower(listOf("Battery" to null)))
assertNull(decodeLinuxExternalPower(listOf("Mains" to "invalid")))
}
@Test fun commandReadsHaveRealRuntimeOutputBoundsAndMissingToolsDoNotBecomePositiveReadings() = runBlocking {
val java = File(System.getProperty("java.home"), "bin/${if (System.getProperty("os.name").contains("win", true)) "java.exe" else "java"}").path
val version = runInterruptible(Dispatchers.IO) { conditionCommand(listOf(java, "-version")) }
assertTrue(checkNotNull(version).contains("version", true))
assertNull(runInterruptible(Dispatchers.IO) { conditionCommand(listOf(java, "-version"), maximumBytes = 1) })
assertNull(runInterruptible(Dispatchers.IO) { conditionCommand(listOf("yokan-condition-unavailable-test-tool")) })
val sleep = if (System.getProperty("os.name").contains("win", true))
listOf("powershell.exe", "-NoProfile", "-Command", "Start-Sleep -Seconds 30")
else listOf("/bin/sh", "-c", "exec sleep 30")
val start = TimeSource.Monotonic.markNow()
assertNull(runInterruptible(Dispatchers.IO) { conditionCommand(sleep, timeoutMillis = 100) })
assertTrue(start.elapsedNow().inWholeMilliseconds < 3000)
val cancelled = async { runInterruptible(Dispatchers.IO) { conditionCommand(sleep, timeoutMillis = 30_000) } }
kotlinx.coroutines.delay(100)
val cancelAt = TimeSource.Monotonic.markNow()
cancelled.cancelAndJoin()
assertTrue(cancelAt.elapsedNow().inWholeMilliseconds < 3000, "Owner cancellation must terminate the command")
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/SettingsSearchAnchorsTest.kt
- Source · test / fixture · 36 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class SettingsSearchAnchorsTest {
27: private fun lazyItemKeys(source: String): Sequence<String> {
Exact file bytes / download · SHA-256 2f53fece4747f929f06c6388996fc7ad9269ac911f2d9e39cfa2df62deafcf2f.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings
import java.io.File
import kotlin.test.Test
import kotlin.test.assertTrue
class SettingsSearchAnchorsTest {
private val settingsDir = File("src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings")
@Test fun everyAnchoredSearchOptionMatchesALazyItemKey() {
val anchored = Regex("""SettingsSearchOption\("([^"]+)".*anchored = true""")
.findAll(settingsDir.resolve("SettingsSearch.kt").readText())
.map { it.groupValues[1] }
.toList()
val keys = settingsDir.walkTopDown()
.filter { it.extension == "kt" }
.flatMap { lazyItemKeys(it.readText()) }
.toSet()
assertTrue(anchored.isNotEmpty())
val missing = anchored.filterNot { it in keys }
assertTrue(missing.isEmpty(), "Anchored settings search ids without a matching item key: $missing")
}
/** Literal `key = "id"` values plus `key = "$variable-suffix"` templates expanded with the string literals assigned to `val variable`. */
private fun lazyItemKeys(source: String): Sequence<String> {
val literals = Regex("""key = "([^"$]+)"""").findAll(source).map { it.groupValues[1] }
val templates = Regex("""key = "\$(\w+)(-[^"$]+)"""").findAll(source).flatMap { match ->
val (variable, suffix) = match.destructured
val assignment = Regex("""val $variable = (.+)""").find(source)?.groupValues?.get(1).orEmpty()
Regex(""""([^"$]+)"""").findAll(assignment).map { it.groupValues[1] + suffix }
}
return literals + templates
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/SettingsSearchTest.kt
- Source · test / fixture · 47 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
11: class SettingsSearchTest {
Exact file bytes / download · SHA-256 a325f37a8690afc5ad8eb2a684b6111d699a459ff12a511752edd3ac141385b2.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings
import androidx.compose.ui.ImageComposeScene
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import javax.swing.SwingUtilities
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SettingsSearchTest {
@Test fun ranksTitlesBeforeAliasesAndSafeValuesWithoutMatchingRouteNames() {
val options = listOf(
SettingsSearchOption("alias", "Network restrictions", SettingsPage.Downloads, aliases = "wifi"),
SettingsSearchOption("exact", "Wi-Fi", SettingsPage.Downloads),
SettingsSearchOption("value", "Playback speed", SettingsPage.Player, currentValue = "1.25x"),
)
assertEquals(listOf("exact", "alias"), searchSettingsOptions(options, " WI FI ").map { it.id })
assertEquals("value", searchSettingsOptions(options, "1.25x").single().id)
assertTrue(searchSettingsOptions(options, "downloads").isEmpty())
assertTrue(searchSettingsOptions(options, " ").isEmpty())
assertTrue(searchSettingsOptions(options, "not a setting").isEmpty())
}
@Test fun realCatalogMapsLeafOptionsToExistingNestedDestinations() {
var options = emptyList<SettingsSearchOption>()
SwingUtilities.invokeAndWait {
val scene = ImageComposeScene(360, 640) { options = settingsSearchOptions(DbSettings()) }
try {
scene.render().close()
} finally {
scene.close()
}
}
assertTrue(options.size > 100)
assertEquals(options.size, options.map { it.id }.distinct().size)
assertEquals(SettingsPage.Downloads, searchSettingsOptions(options, "wifi").single().page)
assertEquals(SettingsPage.PlayerDecoder, searchSettingsOptions(options, "hwdec").single().page)
assertEquals(SettingsPage.PlayerAudio, searchSettingsOptions(options, "pitch").single().page)
assertEquals(SettingsPage.MangaRepositories, searchSettingsOptions(options, "add manga repository").first().page)
assertEquals(SettingsPage.CreateBackup, searchSettingsOptions(options, "create backup").first().page)
assertTrue(searchSettingsOptions(options, "auto skip").any { it.description.contains("AniSkip") })
assertTrue(options.filter { it.currentValue.isNotEmpty() }.all {
it.id in setOf("scale", "font", "reader-mode", "preload", "playback-speed")
})
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/appearance/AppIconPickerRenderTest.kt
- Source · test / fixture · 43 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
13: class AppIconPickerRenderTest {
38: private fun <T> ui(block: () -> T): T {
Exact file bytes / download · SHA-256 2c9817af45e78cb7efd1ca21192aed43f715bfbc63f7419c32425176c952a2af.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.appearance
import androidx.compose.material3.Surface
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.use
import eu.friedcutlet.yokan.services.appicons.*
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import java.io.File
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlin.test.Test
class AppIconPickerRenderTest {
@Test fun renderSupportedSystemAndStaticPickersInBothThemes() {
for ((name, capabilities, draft) in listOf(
Triple("android", AppIconCapabilities(AppIconPlatform.Android, ExplicitAppIcons), ExplicitAppIcons[2]),
Triple("ios", AppIconCapabilities(AppIconPlatform.Ios, ExplicitAppIcons + SystemAppIcon), SystemAppIcon),
Triple("static", StaticAppIconService().capabilities, AppIconSelection.Default),
)) for (dark in listOf(false, true)) {
val scene = ui { ImageComposeScene(360, 850) {
YokanTheme(darkTheme = dark) {
Surface {
AppIconPicker(AppIconState(capabilities, selection = draft, draft = draft, pickerOpen = true), {}, {}, {}, {}, {}, {})
}
}
} }
try {
repeat(12) { frame -> ui { scene.render(frame * 100_000_000L).close() } }
ui { scene.render(1_300_000_000L).use { image ->
checkNotNull(image.encodeToData()).use { data ->
File("build/reports/app-icons/$name-${if (dark) "dark" else "light"}.png")
.apply { parentFile.mkdirs(); writeBytes(data.bytes) }
}
} }
} finally { ui { scene.close() } }
}
}
private fun <T> ui(block: () -> T): T {
val task = FutureTask<T> { block() }
SwingUtilities.invokeAndWait(task)
return task.get()
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/settings/statistics/StatisticsRenderTest.kt
- Source · test / fixture · 55 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
18: class StatisticsRenderTest {
50: private fun <T> ui(block: () -> T): T {
Exact file bytes / download · SHA-256 23052b706259728d3aedd30b020b9a4663c1e11b6a86b7203e2ea704e2c213e7.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.statistics
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Surface
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier
import androidx.compose.ui.use
import eu.friedcutlet.yokan.domain.History
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import java.io.File
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlin.test.Test
class StatisticsRenderTest {
@Test fun renderPhoneAndDesktopLightDarkAndEmptyStates() {
val history = listOf("Frieren: Beyond Journey’s End", "Witch Hat Atelier", "Blue Period", "The Summer Hikaru Died", "Dungeon Meshi")
.mapIndexed { index, title -> History(index.toLong(), index.toLong(), index.toLong(), ItemType.Manga,
title, "Chapter ${42 - index * 3}", "Now", 39000 - index * 7000, 1790000000000L - index * 86400000L) }
val days = List(ACTIVITY_WEEKS * 7 - 3) { i -> if ((i * 7 + i / 5) % 5 < 2) 0 else (i * 13 % 9) }
val hourly = List(24) { h -> if (h in 2..6) 0 else ((h - 12) * (h - 12) % 11) + if (h in 20..23) 8 else 0 }
val genres = listOf("Fantasy" to 18, "Drama" to 14, "Adventure" to 11, "Slice of Life" to 8, "Comedy" to 6,
"Mystery" to 4, "Romance" to 3, "Horror" to 2)
val growth = listOf(4, 5, 5, 7, 9, 12, 13, 13, 15, 19, 22, 24, 25, 28, 30, 31, 33, 34, 36, 37, 39, 40, 41, 42)
val data = StatisticsData(42, 1280, 864, 12, 18, 12, 8, 14, 20, 156840L, 28, history, days, hourly, genres, growth)
for (width in listOf(360, 1000)) for (dark in listOf(false, true)) for (empty in listOf(false, true)) {
val fixture = if (empty) summarizeStatistics(emptyList(), emptyMap(), emptyList(), emptySet(), emptySet()) else data
val scene = ui { ImageComposeScene(width, if (width == 360) 3000 else 1700) {
YokanTheme(darkTheme = dark) {
Surface(Modifier.fillMaxSize()) {
StatisticsDashboard(StatisticsState(ItemType.Manga, data = fixture, downloadBytes = 8_200_000_000, localBytes = 12_600_000_000),
Modifier.verticalScroll(rememberScrollState()))
}
}
} }
try {
repeat(12) { frame -> ui { scene.render(frame * 100_000_000L).close() } }
ui { scene.render(1_300_000_000L).use { image ->
checkNotNull(image.encodeToData()).use { data ->
File("build/reports/statistics/$width-${if (dark) "dark" else "light"}-${if (empty) "empty" else "populated"}.png")
.apply { parentFile.mkdirs(); writeBytes(data.bytes) }
}
} }
} finally { ui { scene.close() } }
}
}
private fun <T> ui(block: () -> T): T {
val task = FutureTask<T> { block() }
SwingUtilities.invokeAndWait(task)
return task.get()
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/status/StatusAndCoverRenderTest.kt
- Source · test / fixture · 322 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
50: class StatusAndCoverRenderTest {
53: fun cancelledCoverActionAlwaysClearsBusyState() = runTest {
68: fun rendersStatusStatesAndCoverInspectionAtPhoneAndDesktopSizes() {
173: fun focusedZoomButtonConsumesEnterBeforeViewportShortcut() {
222: fun retryKeyRestartsTheSameImageModel() {
266: private fun saveScene(scene: ImageComposeScene, width: Int, path: String) {
282: private fun pumpFrames(scene: ImageComposeScene, count: Int = 12, startNanos: Long = 0L) {
286: private fun pumpUntil(
302: private fun coverBytes(): ByteArray {
317: private fun <T> ui(block: () -> T): T {
Exact file bytes / download · SHA-256 a13755230522f9f81b5b4cf87d8403def6d2efc2532b377b210717f492118b94.
Complete file
package eu.friedcutlet.yokan.ui.status
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.InternalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.use
import eu.friedcutlet.yokan.database.DbGlobalStatusVisibility
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.services.sync.SyncOperationOutcome
import eu.friedcutlet.yokan.services.sync.SyncOperationStage
import eu.friedcutlet.yokan.services.sync.SyncOperationState
import eu.friedcutlet.yokan.ui.screens.detail.CoverInspectionContent
import eu.friedcutlet.yokan.ui.screens.detail.CoverInspectionUiState
import eu.friedcutlet.yokan.ui.screens.detail.CoverInspectionViewModel
import eu.friedcutlet.yokan.ui.screens.detail.CoverLoadState
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.concurrent.FutureTask
import javax.imageio.ImageIO
import javax.swing.SwingUtilities
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
@OptIn(ExperimentalComposeUiApi::class, InternalComposeUiApi::class)
class StatusAndCoverRenderTest {
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun cancelledCoverActionAlwaysClearsBusyState() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
val viewModel = CoverInspectionViewModel()
viewModel.runAction { throw CancellationException("dialog closed") }
runCurrent()
assertEquals(false, viewModel.state.value.busy)
assertEquals(null, viewModel.state.value.notice)
} finally {
Dispatchers.resetMain()
}
}
@Test
fun rendersStatusStatesAndCoverInspectionAtPhoneAndDesktopSizes() {
val statusStates = listOf(
"idle-expanded" to GlobalStatusUiState(expanded = true),
"active-expanded" to GlobalStatusUiState(
downloadedOnly = true,
downloads = GlobalDownloadStatus(3, 2, 1, 0, 7, 20, 0.35f),
sync = SyncOperationState(1, SyncOperationStage.Syncing),
libraryUpdate = GlobalLibraryUpdateStatus("Manga", 12, 40, 3, 0, true, false, false),
expanded = true,
),
"error-expanded" to GlobalStatusUiState(
incognito = true,
downloads = GlobalDownloadStatus(2, 0, 0, 2, 3, 10, 0.3f),
sync = SyncOperationState(lastOutcome = SyncOperationOutcome.Failed),
expanded = true,
),
"immersive-hidden" to GlobalStatusUiState(
downloadedOnly = true,
immersive = true,
),
"preference-hidden" to GlobalStatusUiState(
downloadedOnly = true,
visibility = DbGlobalStatusVisibility.Hidden,
),
"immersive-always" to GlobalStatusUiState(
immersive = true,
visibility = DbGlobalStatusVisibility.AlwaysVisible,
),
)
for ((width, height) in listOf(360 to 800, 960 to 720)) {
for ((name, state) in statusStates) {
val scene = ui {
ImageComposeScene(width, height) {
YokanTheme(darkTheme = width == 360) {
Surface(Modifier.fillMaxSize()) {
if (state.expanded) {
GlobalStatusPanel(
state = state,
onVisibilityChange = {},
onToggleDownloadedOnly = {},
onToggleIncognito = {},
onOpenDownloads = {},
onOpenSync = {},
onCancelLibraryUpdate = {},
)
} else {
Box(Modifier.fillMaxSize()) {
GlobalStatusOverlayHost(
state = state,
onOpen = {},
onDismiss = {},
onVisibilityChange = {},
onToggleDownloadedOnly = {},
onToggleIncognito = {},
onOpenDownloads = {},
onOpenSync = {},
onCancelLibraryUpdate = {},
)
}
}
}
}
}
}
saveScene(scene, width, "build/reports/global-status/$name-$width.png")
}
}
val cover = coverBytes()
for ((width, height) in listOf(360 to 800, 960 to 720)) {
val scene = ui {
ImageComposeScene(width, height) {
YokanTheme(darkTheme = true) {
CoverInspectionContent(
title = "Frieren: Beyond Journey’s End",
identity = "render-cover",
model = cover,
state = CoverInspectionUiState(
imageSize = IntSize(600, 900),
viewportSize = IntSize(width, height),
loadState = CoverLoadState.Ready,
),
onDismiss = {},
onViewportChanged = {},
onImageLoading = {},
onImageReady = {},
onImageFailed = {},
onRetry = {},
onToggleControls = {},
onTransform = { _, _, _ -> },
onDoubleTap = {},
onZoomAtCenter = {},
onReset = {},
onSave = {},
onChange = {},
onShare = {},
)
}
}
}
saveScene(scene, width, "build/reports/cover-inspection/ready-$width.png")
}
}
@Test
fun focusedZoomButtonConsumesEnterBeforeViewportShortcut() {
var zoomCount = 0
var controlsToggleCount = 0
val scene = ui {
ImageComposeScene(480, 800) {
YokanTheme(darkTheme = true) {
CoverInspectionContent(
title = "Keyboard cover",
identity = "keyboard",
model = coverBytes(),
state = CoverInspectionUiState(
imageSize = IntSize(600, 900),
viewportSize = IntSize(480, 800),
loadState = CoverLoadState.Ready,
),
onDismiss = {},
onViewportChanged = {},
onImageLoading = {},
onImageReady = {},
onImageFailed = {},
onRetry = {},
onToggleControls = { controlsToggleCount += 1 },
onTransform = { _, _, _ -> },
onDoubleTap = {},
onZoomAtCenter = { zoomCount += 1 },
onReset = {},
onSave = {},
onChange = {},
onShare = {},
)
}
}
}
try {
pumpFrames(scene)
ui {
scene.sendPointerEvent(PointerEventType.Press, Offset(448f, 28f))
scene.sendPointerEvent(PointerEventType.Release, Offset(448f, 28f))
}
ui { scene.sendKeyEvent(KeyEvent(Key.Enter, KeyEventType.KeyDown)) }
ui { scene.sendKeyEvent(KeyEvent(Key.Enter, KeyEventType.KeyUp)) }
assertEquals(2, zoomCount, "pointer and keyboard should each activate zoom")
assertEquals(0, controlsToggleCount, "the viewport shortcut must not steal Enter from a focused button")
} finally {
ui { scene.close() }
}
}
@Test
fun retryKeyRestartsTheSameImageModel() {
val validCover = coverBytes()
val cover = ByteArray(validCover.size)
var state by mutableStateOf(CoverInspectionUiState(loadState = CoverLoadState.Loading))
var successes = 0
var failures = 0
val scene = ui {
ImageComposeScene(360, 700) {
YokanTheme(darkTheme = true) {
CoverInspectionContent(
title = "Retry cover",
identity = "same-model",
model = cover,
state = state,
onDismiss = {},
onViewportChanged = {},
onImageLoading = {},
onImageReady = { successes += 1 },
onImageFailed = { failures += 1 },
onRetry = {},
onToggleControls = {},
onTransform = { _, _, _ -> },
onDoubleTap = {},
onZoomAtCenter = {},
onReset = {},
onSave = {},
onChange = {},
onShare = {},
)
}
}
}
try {
pumpUntil(scene) { failures > 0 }
assertEquals(0, successes)
validCover.copyInto(cover)
ui { state = state.copy(retryAttempt = state.retryAttempt + 1, loadState = CoverLoadState.Loading) }
pumpUntil(scene, startNanos = 2_000_000_000L) { successes > 0 }
assertTrue(successes > 0, "a retry must restart loading even when the model value is unchanged")
} finally {
ui { scene.close() }
}
}
private fun saveScene(scene: ImageComposeScene, width: Int, path: String) {
try {
pumpFrames(scene)
ui {
scene.render(1_500_000_000L).use { image ->
assertEquals(width, image.width)
checkNotNull(image.encodeToData()).use { data ->
File(path).apply { parentFile.mkdirs(); writeBytes(data.bytes) }
}
}
}
} finally {
ui { scene.close() }
}
}
private fun pumpFrames(scene: ImageComposeScene, count: Int = 12, startNanos: Long = 0L) {
repeat(count) { frame -> ui { scene.render(startNanos + frame * 100_000_000L).close() } }
}
private fun pumpUntil(
scene: ImageComposeScene,
startNanos: Long = 0L,
timeoutMillis: Long = 3_000L,
condition: () -> Boolean,
) {
val deadline = System.nanoTime() + timeoutMillis * 1_000_000L
var frame = 0L
while (!condition() && System.nanoTime() < deadline) {
ui { scene.render(startNanos + frame * 100_000_000L).close() }
frame += 1
Thread.sleep(10)
}
assertTrue(condition(), "condition was not met before the render timeout")
}
private fun coverBytes(): ByteArray {
val image = BufferedImage(600, 900, BufferedImage.TYPE_INT_RGB)
image.createGraphics().apply {
color = Color(31, 36, 48); fillRect(0, 0, 600, 900)
color = Color(190, 198, 210); fillOval(90, 90, 420, 420)
color = Color(96, 132, 112); fillRect(70, 560, 460, 250)
dispose()
}
return ByteArrayOutputStream().use { output ->
ImageIO.write(image, "png", output)
image.flush()
output.toByteArray()
}
}
private fun <T> ui(block: () -> T): T {
val task = FutureTask<T> { block() }
SwingUtilities.invokeAndWait(task)
return task.get()
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/appicons/AppIconService.ios.kt
- Source · implementation · 61 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
20: actual fun createPlatformAppIconService(): AppIconService = IosAppIconService()
22: private class IosAppIconService : AppIconService {
25: private fun name(selection: AppIconSelection): String? = when (selection) {
42: override suspend fun current(): AppIconSelection? = withContext(Dispatchers.Main) {
45: override suspend fun apply(selection: AppIconSelection) = withContext(Dispatchers.Main) {
Exact file bytes / download · SHA-256 5c37281149d774c9193b860413a71da3c247aca3bf2aec87e3661e7884e94c0d.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.services.appicons
import kotlinx.cinterop.useContents
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import platform.Foundation.NSBundle
import platform.Foundation.NSProcessInfo
import platform.UIKit.UIApplication
import platform.UIKit.supportsAlternateIcons
import platform.UIKit.alternateIconName
import platform.UIKit.setAlternateIconName
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
actual fun createPlatformAppIconService(): AppIconService = IosAppIconService()
private class IosAppIconService : AppIconService {
private val app get() = UIApplication.sharedApplication
private val mutex = Mutex()
private fun name(selection: AppIconSelection): String? = when (selection) {
AppIconSelection.Default -> null
ExplicitAppIcons[1] -> "ToriiLight"
ExplicitAppIcons[2] -> "ToriiDark"
SystemAppIcon -> "ToriiSystem"
else -> error("Unsupported icon")
}
override val capabilities: AppIconCapabilities
get() {
val icons = NSBundle.mainBundle.objectForInfoDictionaryKey("CFBundleIcons") as? Map<*, *>
val alternates = icons?.get("CFBundleAlternateIcons") as? Map<*, *>
val choices = if (!app.supportsAlternateIcons) listOf(AppIconSelection.Default) else {
val candidates = ExplicitAppIcons + if (NSProcessInfo.processInfo.operatingSystemVersion.useContents { majorVersion } >= 18) listOf(SystemAppIcon) else emptyList()
candidates.filter { it == AppIconSelection.Default || alternates?.containsKey(name(it)) == true }
}
return AppIconCapabilities(AppIconPlatform.Ios, choices)
}
override suspend fun current(): AppIconSelection? = withContext(Dispatchers.Main) {
mutex.withLock { (ExplicitAppIcons + SystemAppIcon).singleOrNull { name(it) == app.alternateIconName } }
}
override suspend fun apply(selection: AppIconSelection) = withContext(Dispatchers.Main) {
require(selection in capabilities.choices)
mutex.withLock {
if (app.alternateIconName != name(selection)) {
suspendCancellableCoroutine<Unit> { continuation ->
app.setAlternateIconName(name(selection)) { error ->
if (continuation.isActive) {
if (error == null) continuation.resume(Unit)
else continuation.resumeWithException(IllegalStateException("Icon change rejected by iOS"))
}
}
}
}
check(app.alternateIconName == name(selection))
}
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/applock/AppLockController.ios.kt
- Source · implementation · 43 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: actual fun createPlatformAppLockController(): AppLockController = IosAppLockController()
17: internal class IosAppLockController : BaseAppLockController() {
25: override fun requestUnlock(onResult: (Boolean) -> Unit) {
Exact file bytes / download · SHA-256 4fa95d7c9c7649952f1f3ee6401f0151804ae4737a4c41ed5b90e776d31a91b4.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.services.applock
import platform.LocalAuthentication.LAContext
import platform.LocalAuthentication.LAPolicyDeviceOwnerAuthentication
import platform.darwin.dispatch_async
import platform.darwin.dispatch_get_main_queue
actual fun createPlatformAppLockController(): AppLockController = IosAppLockController()
/**
* Face ID / Touch ID / passcode via LocalAuthentication, mirroring
* Mangayomi's `local_auth` usage: device-owner authentication with a
* passcode fallback, resolving on the main queue.
*/
internal class IosAppLockController : BaseAppLockController() {
override val isSupported: Boolean
get() = LAContext().canEvaluatePolicy(LAPolicyDeviceOwnerAuthentication, error = null)
init {
_unlocked.value = true
}
override fun requestUnlock(onResult: (Boolean) -> Unit) {
val context = LAContext()
if (!context.canEvaluatePolicy(LAPolicyDeviceOwnerAuthentication, error = null)) {
// No passcode configured — nothing to authenticate against.
_unlocked.value = true
onResult(true)
return
}
context.evaluatePolicy(
LAPolicyDeviceOwnerAuthentication,
localizedReason = "Unlock Yokan",
) { success, _ ->
dispatch_async(dispatch_get_main_queue()) {
_unlocked.value = success
onResult(success)
}
}
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/discord/DiscordRpcService.ios.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun createPlatformDiscordRpcService(): DiscordRpcService = GatewayDiscordRpcService()
Exact file bytes / download · SHA-256 5548c3380213603626cba50be66efdaa666d0a0c05bf4bb749a70e5e110ad193.
Complete file
package eu.friedcutlet.yokan.services.discord
actual fun createPlatformDiscordRpcService(): DiscordRpcService = GatewayDiscordRpcService()
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/notifications/NotificationService.ios.kt
- Source · implementation · 48 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: actual fun createPlatformNotificationService(profileId: ProfileId): NotificationService = IosNotificationService(profileId)
15: private class IosNotificationService(profileId: ProfileId) : NotificationService {
17: override fun supported(): Boolean = true
18: override fun requestPermission() {
26: override fun notify(payload: NotificationPayload) {
41: override fun cancel(channel: NotificationChannel, tag: String?) {
Exact file bytes / download · SHA-256 13aee65a0246427ef7c3c3afc036aa236b8641b155f9f6c9a85073736f34f09e.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.services.notifications
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.domain.ProfileId
import platform.UserNotifications.UNAuthorizationOptionAlert
import platform.UserNotifications.UNAuthorizationOptionSound
import platform.UserNotifications.UNMutableNotificationContent
import platform.UserNotifications.UNNotificationRequest
import platform.UserNotifications.UNUserNotificationCenter
actual fun createPlatformNotificationService(profileId: ProfileId): NotificationService = IosNotificationService(profileId)
private class IosNotificationService(profileId: ProfileId) : NotificationService {
private val namespace = ProfileNotificationNamespace(profileId)
override fun supported(): Boolean = true
override fun requestPermission() {
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
UNAuthorizationOptionAlert or UNAuthorizationOptionSound,
) { _, error ->
error?.let { AppLogger.warn("Could not request notification permission: ${it.localizedDescription}") }
}
}
override fun notify(payload: NotificationPayload) {
val content = UNMutableNotificationContent().apply {
setTitle(payload.title)
setBody(payload.message)
}
val request = UNNotificationRequest.requestWithIdentifier(
namespace.iosIdentifier(payload.channel, payload.tag),
content,
trigger = null,
)
UNUserNotificationCenter.currentNotificationCenter().addNotificationRequest(request) { error ->
error?.let { AppLogger.warn("Could not post notification: ${it.localizedDescription}") }
}
}
override fun cancel(channel: NotificationChannel, tag: String?) {
val identifiers = listOf(namespace.iosIdentifier(channel, tag))
val center = UNUserNotificationCenter.currentNotificationCenter()
center.removeDeliveredNotificationsWithIdentifiers(identifiers)
center.removePendingNotificationRequestsWithIdentifiers(identifiers)
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundScheduler.ios.kt
- Source · implementation · 139 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
27: internal fun registerIosBackgroundTasks(
31: actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler {
41: private object IosBackgroundScheduler : BackgroundScheduler {
50: fun register(tasks: suspend (ProfileId, suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome) -> ProfileWorkResult<PeriodicTaskOutcome>) {
58: override fun schedule(
77: private fun libraryUpdateDelaySeconds(): Double = when {
83: override fun cancelAll() {
89: private fun register(
115: private fun submit(identifier: String, delaySeconds: Double) {
134: private object NoProfileBackgroundScheduler : BackgroundScheduler {
135: override fun schedule(metadataRefreshMinutes: Long, libraryUpdateMinutes: Long, libraryUpdateDailyAtMinutes: Int,
138: override fun cancelAll() = Unit
Exact file bytes / download · SHA-256 71a31e408d26ee19238cd14c461ed48a2993e184839ada76cd88a5949ed110b3.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import platform.BackgroundTasks.BGAppRefreshTaskRequest
import platform.BackgroundTasks.BGProcessingTaskRequest
import platform.BackgroundTasks.BGTask
import platform.BackgroundTasks.BGTaskScheduler
import platform.Foundation.NSDate
private const val METADATA_REFRESH_TASK = "eu.friedcutlet.yokan.metadata-refresh"
private const val LIBRARY_UPDATE_TASK = "eu.friedcutlet.yokan.library-update"
private const val AUTO_SYNC_TASK = "eu.friedcutlet.yokan.auto-sync"
private const val REGISTRY_RETRY_DELAY_SECONDS = 15.0 * 60.0
/**
* Registers BGTask handlers before launch returns. [tasks] validates and opens the recorded owner,
* since a background launch has no UI to do it.
*/
internal fun registerIosBackgroundTasks(
tasks: suspend (ProfileId, suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome) -> ProfileWorkResult<PeriodicTaskOutcome>,
) = IosBackgroundScheduler.register(tasks)
actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler {
// These fixed identifiers are permitted in Info.plist and permanently belong to Default.
return if (profileId == ProfileId.Default) IosBackgroundScheduler else NoProfileBackgroundScheduler
}
/**
* Metadata refresh and sync are `BGAppRefreshTask`s (~30 s budget). The library update is a
* `BGProcessingTask`: minutes of runtime, network required, run when iOS deems the device idle.
* A daily time is only an `earliestBeginDate`; iOS picks the actual moment.
*/
private object IosBackgroundScheduler : BackgroundScheduler {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private var registered = false
private var metadataRefreshMinutes = 0L
private var libraryUpdateMinutes = 0L
private var libraryUpdateDailyAtMinutes = -1
private var autoSyncMinutes = 0L
private var requireLibraryPower = false
fun register(tasks: suspend (ProfileId, suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome) -> ProfileWorkResult<PeriodicTaskOutcome>) {
if (registered) return
registered = true
register(METADATA_REFRESH_TASK, { metadataRefreshMinutes * 60.0 }) { tasks(ProfileId.Default, PeriodicTaskRunner::refreshMetadata) }
register(LIBRARY_UPDATE_TASK, ::libraryUpdateDelaySeconds) { tasks(ProfileId.Default, PeriodicTaskRunner::updateLibrary) }
register(AUTO_SYNC_TASK, { autoSyncMinutes * 60.0 }) { tasks(ProfileId.Default, PeriodicTaskRunner::sync) }
}
override fun schedule(
metadataRefreshMinutes: Long,
libraryUpdateMinutes: Long,
libraryUpdateDailyAtMinutes: Int,
autoSyncMinutes: Long,
autoBackupHours: Long,
requireUnmetered: Boolean,
libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,
) {
this.metadataRefreshMinutes = metadataRefreshMinutes
this.libraryUpdateMinutes = libraryUpdateMinutes
this.libraryUpdateDailyAtMinutes = libraryUpdateDailyAtMinutes
this.autoSyncMinutes = autoSyncMinutes
this.requireLibraryPower = libraryConstraints.requireExternalPower
submit(METADATA_REFRESH_TASK, metadataRefreshMinutes * 60.0)
submit(LIBRARY_UPDATE_TASK, libraryUpdateDelaySeconds())
submit(AUTO_SYNC_TASK, autoSyncMinutes * 60.0)
}
private fun libraryUpdateDelaySeconds(): Double = when {
libraryUpdateMinutes <= 0 -> 0.0
libraryUpdateDailyAtMinutes >= 0 -> nextDailySlotDelayMillis(libraryUpdateDailyAtMinutes) / 1000.0
else -> libraryUpdateMinutes * 60.0
}
override fun cancelAll() {
BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(METADATA_REFRESH_TASK)
BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(LIBRARY_UPDATE_TASK)
BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(AUTO_SYNC_TASK)
}
private fun register(
identifier: String,
delaySeconds: () -> Double,
run: suspend () -> ProfileWorkResult<PeriodicTaskOutcome>,
) {
BGTaskScheduler.sharedScheduler.registerForTaskWithIdentifier(identifier, usingQueue = null) { task ->
val bgTask = task ?: return@registerForTaskWithIdentifier
submit(identifier, delaySeconds())
val job = launchCompletingBackgroundTask(scope, {
val outcome = run()
// A cold launch has no in-memory schedule until admission opens the session.
// Preserve retry eligibility without opening a database when metadata is unavailable.
if (outcome == ProfileWorkResult.Retry) {
submit(identifier, maxOf(delaySeconds(), REGISTRY_RETRY_DELAY_SECONDS))
}
if (outcome is ProfileWorkResult.Completed && outcome.value.status == PeriodicTaskStatus.Deferred) {
submit(identifier, REGISTRY_RETRY_DELAY_SECONDS)
}
outcome
}) { success ->
bgTask.setTaskCompletedWithSuccess(success)
}
bgTask.expirationHandler = { job.cancel() }
}
}
private fun submit(identifier: String, delaySeconds: Double) {
BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(identifier)
if (delaySeconds <= 0.0) return
val request = if (identifier == LIBRARY_UPDATE_TASK) {
BGProcessingTaskRequest(identifier).apply {
requiresNetworkConnectivity = true
requiresExternalPower = requireLibraryPower
}
} else {
BGAppRefreshTaskRequest(identifier)
}
request.earliestBeginDate = NSDate(
timeIntervalSinceReferenceDate = NSDate().timeIntervalSinceReferenceDate + delaySeconds,
)
runCatching { BGTaskScheduler.sharedScheduler.submitTaskRequest(request, error = null) }
.onFailure { AppLogger.warn("Could not schedule $identifier: ${it.message.orEmpty()}") }
}
}
private object NoProfileBackgroundScheduler : BackgroundScheduler {
override fun schedule(metadataRefreshMinutes: Long, libraryUpdateMinutes: Long, libraryUpdateDailyAtMinutes: Int,
autoSyncMinutes: Long, autoBackupHours: Long, requireUnmetered: Boolean,
libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints) = Unit
override fun cancelAll() = Unit
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/scheduling/UpdateDeviceConditions.ios.kt
- Source · implementation · 62 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions {
Exact file bytes / download · SHA-256 5deaffdfe7b9a338ccf0727d78b111dc6821c88391ec14397ab4fb77de4dd78f.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.util.PlatformLock
import kotlin.coroutines.resume
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import platform.Network.*
import platform.UIKit.UIDevice
import platform.UIKit.UIDeviceBatteryState.UIDeviceBatteryStateCharging
import platform.UIKit.UIDeviceBatteryState.UIDeviceBatteryStateFull
import platform.UIKit.UIDeviceBatteryState.UIDeviceBatteryStateUnplugged
import platform.UIKit.UIDeviceBatteryState.UIDeviceBatteryStateUnknown
import platform.darwin.DISPATCH_QUEUE_PRIORITY_DEFAULT
import platform.darwin.dispatch_get_global_queue
actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions {
val monitor = nw_path_monitor_create()
val network = try {
withTimeoutOrNull(2_000) {
suspendCancellableCoroutine { continuation ->
val lock = PlatformLock()
var delivered = false
nw_path_monitor_set_update_handler(monitor) { path ->
lock.withLock {
if (!delivered && continuation.isActive) {
delivered = true
val connected = nw_path_get_status(path) == nw_path_status_satisfied
continuation.resume(UpdateDeviceConditions(connected,
connected && nw_path_uses_interface_type(path, nw_interface_type_wifi),
connected && !nw_path_is_expensive(path) && !nw_path_is_constrained(path)))
}
}
}
continuation.invokeOnCancellation { nw_path_monitor_cancel(monitor) }
nw_path_monitor_set_queue(monitor, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT.toLong(), 0u))
nw_path_monitor_start(monitor)
}
} ?: UpdateDeviceConditions()
} finally {
nw_path_monitor_cancel(monitor)
nw_path_monitor_set_update_handler(monitor) {}
}
val power = if (!needPower) null else withContext(Dispatchers.Main) {
val device = UIDevice.currentDevice
// Keep monitoring available to concurrent profile reads; device telemetry is process-wide.
device.batteryMonitoringEnabled = true
withTimeoutOrNull(1_000) {
while (device.batteryState == UIDeviceBatteryStateUnknown) delay(25)
when (device.batteryState) {
UIDeviceBatteryStateCharging, UIDeviceBatteryStateFull -> true
UIDeviceBatteryStateUnplugged -> false
else -> null
}
}
}
return network.copy(externalPower = power)
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/system/DeviceCapabilities.ios.kt
- Source · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun isTvDevice(): Boolean = false
5: internal actual fun isLocalLibraryManagerSupported(): Boolean = true
7: internal actual fun processMemoryUsage(): ProcessMemoryUsage? = null
Exact file bytes / download · SHA-256 15e3f72917f9f6fee40306851e39ab0298f3262b5a021745c69e718cc1416b3b.
Complete file
package eu.friedcutlet.yokan.services.system
actual fun isTvDevice(): Boolean = false
internal actual fun isLocalLibraryManagerSupported(): Boolean = true
internal actual fun processMemoryUsage(): ProcessMemoryUsage? = null
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/system/SystemIntegration.ios.kt
- Source · implementation · 92 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
35: actual fun isOnUnmeteredNetwork(): Boolean {
51: actual fun createNetworkMonitor(): NetworkMonitor = PathNetworkMonitor()
55: private class PathNetworkMonitor : NetworkMonitor {
73: actual fun openSystemBrowser(url: String): Boolean {
83: actual fun applyAppLanguage(languageCode: String?) {
Exact file bytes / download · SHA-256 c328830589a02630ed671893408c0ab8f68b7378d1efa93e455360f7bc427acc.
Complete file
package eu.friedcutlet.yokan.services.system
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.alloc
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.value
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import platform.CoreFoundation.CFRelease
import platform.Foundation.NSURL
import platform.Network.nw_path_get_status
import platform.Network.nw_path_is_constrained
import platform.Network.nw_path_is_expensive
import platform.Network.nw_path_monitor_create
import platform.Network.nw_path_monitor_set_queue
import platform.Network.nw_path_monitor_set_update_handler
import platform.Network.nw_path_monitor_start
import platform.Network.nw_path_status_satisfied
import platform.SystemConfiguration.SCNetworkReachabilityCreateWithName
import platform.SystemConfiguration.SCNetworkReachabilityFlagsVar
import platform.SystemConfiguration.SCNetworkReachabilityGetFlags
import platform.SystemConfiguration.kSCNetworkReachabilityFlagsIsWWAN
import platform.SystemConfiguration.kSCNetworkReachabilityFlagsReachable
import platform.UIKit.UIApplication
import platform.darwin.DISPATCH_QUEUE_PRIORITY_DEFAULT
import platform.darwin.dispatch_get_global_queue
/**
* Cellular (WWAN) counts as metered; Wi-Fi/wired/undeterminable count as
* unmetered — same permissive fallback as the Android implementation.
*/
@OptIn(ExperimentalForeignApi::class)
actual fun isOnUnmeteredNetwork(): Boolean {
val target = SCNetworkReachabilityCreateWithName(null, "apple.com") ?: return true
try {
memScoped {
val flags = alloc<SCNetworkReachabilityFlagsVar>()
if (!SCNetworkReachabilityGetFlags(target, flags.ptr)) return true
val value = flags.value
val reachable = (value and kSCNetworkReachabilityFlagsReachable) != 0u
val cellular = (value and kSCNetworkReachabilityFlagsIsWWAN) != 0u
return !(reachable && cellular)
}
} finally {
CFRelease(target)
}
}
actual fun createNetworkMonitor(): NetworkMonitor = PathNetworkMonitor()
/** NWPathMonitor: an expensive path (cellular, hotspot), Low Data Mode or no network counts as metered. */
@OptIn(ExperimentalForeignApi::class)
private class PathNetworkMonitor : NetworkMonitor {
private val state = MutableStateFlow(isOnUnmeteredNetwork())
override val unmetered: StateFlow<Boolean> = state.asStateFlow()
// Held for the process lifetime: a released monitor stops reporting.
private val monitor = nw_path_monitor_create()
init {
nw_path_monitor_set_update_handler(monitor) { path ->
state.value = nw_path_get_status(path) == nw_path_status_satisfied &&
!nw_path_is_expensive(path) &&
!nw_path_is_constrained(path)
}
nw_path_monitor_set_queue(monitor, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT.toLong(), 0u))
nw_path_monitor_start(monitor)
}
}
actual fun openSystemBrowser(url: String): Boolean {
if (url.isBlank()) return false
val nsUrl = NSURL.URLWithString(url) ?: return false
val app = UIApplication.sharedApplication
return if (app.canOpenURL(nsUrl)) {
app.openURL(nsUrl, options = emptyMap<Any?, Any?>(), completionHandler = null)
true
} else false
}
actual fun applyAppLanguage(languageCode: String?) {
// iOS reads the active bundle locale from `AppleLanguages` at process
// start and caches it; updating it here takes effect on the next launch.
val defaults = platform.Foundation.NSUserDefaults.standardUserDefaults
if (languageCode.isNullOrBlank()) {
defaults.removeObjectForKey("AppleLanguages")
} else {
defaults.setObject(listOf(languageCode), forKey = "AppleLanguages")
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/tts/TextToSpeechService.ios.kt
- Source · implementation · 61 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: actual fun createPlatformTextToSpeechService(): TextToSpeechService = IosTextToSpeechService()
12: private class IosTextToSpeechService : TextToSpeechService {
15: override suspend fun voices(language: String?): List<String> {
23: override suspend fun speak(
58: override suspend fun stop() {
Exact file bytes / download · SHA-256 4a3098a73e4453f716f0798bb2bd47587ef82e793abe16deb9898974a74cf8df.
Complete file
package eu.friedcutlet.yokan.services.tts
import kotlinx.coroutines.delay
import platform.AVFAudio.AVSpeechBoundary
import platform.AVFAudio.AVSpeechSynthesisVoice
import platform.AVFAudio.AVSpeechSynthesizer
import platform.AVFAudio.AVSpeechUtterance
actual fun createPlatformTextToSpeechService(): TextToSpeechService = IosTextToSpeechService()
private class IosTextToSpeechService : TextToSpeechService {
private val synthesizer = AVSpeechSynthesizer()
override suspend fun voices(language: String?): List<String> {
val all = AVSpeechSynthesisVoice.speechVoices()
@Suppress("UNCHECKED_CAST")
val typed = all as List<AVSpeechSynthesisVoice>
return typed.filter { language.isNullOrBlank() || it.language.equals(language, ignoreCase = true) }
.map { it.name }
}
override suspend fun speak(
text: String,
request: TextToSpeechRequest,
onProgress: (startOffset: Int, endOffset: Int) -> Unit,
) {
if (text.isBlank()) return
val utterance = AVSpeechUtterance.speechUtteranceWithString(text)
val resolvedVoice = when {
!request.voice.isNullOrBlank() -> {
val all = AVSpeechSynthesisVoice.speechVoices()
@Suppress("UNCHECKED_CAST")
(all as List<AVSpeechSynthesisVoice>).firstOrNull { it.name == request.voice }
}
!request.language.isNullOrBlank() -> AVSpeechSynthesisVoice.voiceWithLanguage(request.language)
else -> null
}
resolvedVoice?.let { utterance.voice = it }
utterance.rate = request.speechRate.toFloat().coerceIn(0.0f, 1.0f)
utterance.pitchMultiplier = request.pitch.toFloat().coerceIn(0.5f, 2.0f)
synthesizer.speakUtterance(utterance)
val wordsPerMinute = (request.speechRate * 350.0).toInt().coerceIn(80, 500)
val wordDelayMillis = (60_000L / wordsPerMinute).coerceAtLeast(40L)
try {
Regex("\\S+").findAll(text).forEach { word ->
if (!synthesizer.speaking) return@forEach
onProgress(word.range.first, word.range.last + 1)
delay(wordDelayMillis)
}
while (synthesizer.speaking) delay(50)
} finally {
// Cancelled mid-utterance: don't leave the synthesizer talking.
if (synthesizer.speaking) synthesizer.stopSpeakingAtBoundary(AVSpeechBoundary.AVSpeechBoundaryImmediate)
}
}
override suspend fun stop() {
synthesizer.stopSpeakingAtBoundary(AVSpeechBoundary.AVSpeechBoundaryImmediate)
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/updates/PackageInstaller.ios.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun installPackageFromFile(path: String): Boolean = false
Exact file bytes / download · SHA-256 48623d6907f9abe2ce81aed6576f63d22c4e647e2f57cd4cd490a5707030f670.
Complete file
package eu.friedcutlet.yokan.services.updates
actual fun installPackageFromFile(path: String): Boolean = false
composeApp/src/platformWebViewMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/discord/DiscordLogin.platformWebView.kt
- Source · implementation · 38 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
16: internal actual fun DiscordLoginWebView(modifier: Modifier, onToken: (String) -> Unit) {
Exact file bytes / download · SHA-256 cb758fb488cfbb378d6e2d9a6785692965b084cff1324b9e63c0ee14b34d5aa7.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.discord
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import com.multiplatform.webview.web.WebView
import com.multiplatform.webview.web.rememberWebViewNavigator
import com.multiplatform.webview.web.rememberWebViewState
import kotlinx.coroutines.delay
internal actual val discordWebLoginAvailable: Boolean = true
@Composable
internal actual fun DiscordLoginWebView(modifier: Modifier, onToken: (String) -> Unit) {
val currentOnToken by rememberUpdatedState(onToken)
val state = rememberWebViewState("https://discord.com/login") {
isJavaScriptEnabled = true
androidWebSettings.domStorageEnabled = true
}
val navigator = rememberWebViewNavigator()
// Discord routes client-side after login, so poll instead of waiting for a page load.
LaunchedEffect(navigator) {
var delivered = false
while (!delivered) {
delay(1_500)
navigator.evaluateJavaScript(DiscordTokenScript) { result ->
val token = cleanDiscordTokenResult(result)
if (token != null && !delivered) {
delivered = true
currentOnToken(token)
}
}
}
}
WebView(state = state, navigator = navigator, modifier = modifier)
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/appicons/AppIconService.wasmJs.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun createPlatformAppIconService(): AppIconService = StaticAppIconService()
Exact file bytes / download · SHA-256 90f63822e2f4b14d3ff59a6eaa7d3897b167c650e310f14f85feb00ab8c177a7.
Complete file
package eu.friedcutlet.yokan.services.appicons
actual fun createPlatformAppIconService(): AppIconService = StaticAppIconService()
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/applock/AppLockController.wasm.kt
- Source · implementation · 12 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun createPlatformAppLockController(): AppLockController = WasmAppLockController
5: private object WasmAppLockController : BaseAppLockController() {
8: override fun requestUnlock(onResult: (Boolean) -> Unit) {
Exact file bytes / download · SHA-256 57c3fcb71b68a60aa105703b735057da9b38fa3a38dd4bd5c8b82c1583a6fe56.
Complete file
package eu.friedcutlet.yokan.services.applock
actual fun createPlatformAppLockController(): AppLockController = WasmAppLockController
private object WasmAppLockController : BaseAppLockController() {
override val isSupported: Boolean = false
override fun requestUnlock(onResult: (Boolean) -> Unit) {
_unlocked.value = true
onResult(true)
}
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/discord/DiscordRpcService.wasm.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun createPlatformDiscordRpcService(): DiscordRpcService = GatewayDiscordRpcService()
Exact file bytes / download · SHA-256 5548c3380213603626cba50be66efdaa666d0a0c05bf4bb749a70e5e110ad193.
Complete file
package eu.friedcutlet.yokan.services.discord
actual fun createPlatformDiscordRpcService(): DiscordRpcService = GatewayDiscordRpcService()
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/notifications/NotificationService.wasm.kt
- Source · implementation · 11 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: actual fun createPlatformNotificationService(profileId: ProfileId): NotificationService = WasmNotificationService(profileId)
7: private class WasmNotificationService(private val profileId: ProfileId) : NotificationService {
8: override fun supported(): Boolean = true
9: override fun notify(payload: NotificationPayload) = InAppNotifications.post(payload.copy(profileId = profileId))
10: override fun cancel(channel: NotificationChannel, tag: String?) = Unit
Exact file bytes / download · SHA-256 d847808abb56067e62c5040ed18f947072f3e26b76d29f1573edde2caad0f1e5.
Complete file
package eu.friedcutlet.yokan.services.notifications
import eu.friedcutlet.yokan.domain.ProfileId
actual fun createPlatformNotificationService(profileId: ProfileId): NotificationService = WasmNotificationService(profileId)
private class WasmNotificationService(private val profileId: ProfileId) : NotificationService {
override fun supported(): Boolean = true
override fun notify(payload: NotificationPayload) = InAppNotifications.post(payload.copy(profileId = profileId))
override fun cancel(channel: NotificationChannel, tag: String?) = Unit
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/scheduling/BackgroundScheduler.wasm.kt
- Source · implementation · 19 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler = WasmBackgroundScheduler
8: private object WasmBackgroundScheduler : BackgroundScheduler {
9: override fun schedule(
18: override fun cancelAll() = Unit
Exact file bytes / download · SHA-256 bad0e3c604d987a096d03faf1fff68d5a2a2b0577b9c8e555dc0483918245d76.
Complete file
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler = WasmBackgroundScheduler
private object WasmBackgroundScheduler : BackgroundScheduler {
override fun schedule(
metadataRefreshMinutes: Long,
libraryUpdateMinutes: Long,
libraryUpdateDailyAtMinutes: Int,
autoSyncMinutes: Long,
autoBackupHours: Long,
requireUnmetered: Boolean,
libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints,
) = Unit
override fun cancelAll() = Unit
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/scheduling/UpdateDeviceConditions.wasm.kt
- Source · implementation · 37 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions =
13: private fun readBrowserUpdateConditions(needPower: Boolean): Promise<JsString> = js("""
Exact file bytes / download · SHA-256 a1aaf98a7b079c969e6c21f74a7b4405a5ade121b67f8623c83287d6b037cdba.
Complete file
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.database.DatabaseJson
import kotlinx.coroutines.await
import kotlin.js.JsString
import kotlin.js.Promise
actual suspend fun readUpdateDeviceConditions(needPower: Boolean): UpdateDeviceConditions =
DatabaseJson.decodeFromString(readBrowserUpdateConditions(needPower).await<JsString>().toString())
private fun readBrowserUpdateConditions(needPower: Boolean): Promise<JsString> = js("""
(async () => {
const n = globalThis.navigator || {};
const connection = n.connection || n.mozConnection || n.webkitConnection;
const connected = typeof n.onLine === 'boolean' ? n.onLine : null;
const type = connection && connection.type;
const wifi = connected === false ? false : type === 'wifi' ? true :
['ethernet', 'cellular', 'bluetooth', 'wimax', 'none'].includes(type) ? false : null;
// saveData is evidence to defer; its absence/false value is not evidence of free data.
const unmetered = connected === false || (connection && connection.saveData === true) ? false : null;
let externalPower = null;
if (needPower && globalThis.isSecureContext && typeof n.getBattery === 'function') {
let timer;
try {
const battery = await Promise.race([
Promise.resolve().then(() => n.getBattery()),
new Promise(resolve => { timer = setTimeout(() => resolve(null), 1500); })
]);
if (battery && typeof battery.charging === 'boolean') externalPower = battery.charging;
} catch (_) { /* Denied/unsupported telemetry stays unknown. */ }
finally { clearTimeout(timer); }
}
return JSON.stringify({ connected, wifi, unmetered, externalPower });
})()
""")
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/system/BrowserDownload.kt
- Source · implementation · 35 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: internal fun triggerBrowserDownload(bytes: ByteArray, fileName: String, mimeType: String): Boolean =
16: private fun triggerBrowserDownloadJs(base64: String, fileName: String, mimeType: String) {
Exact file bytes / download · SHA-256 1fa86c7a5dcc4914556c3faae16f30cfbfdd68a1ecce3452d8c54e0d955902da.
Complete file
package eu.friedcutlet.yokan.services.system
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
/**
* Hands [bytes] to the browser's download UI via a `Blob` object URL and a
* synthetic anchor click. Bytes cross the JS boundary base64-encoded because
* wasm `js()` parameters are limited to primitive/String types.
*/
@OptIn(ExperimentalEncodingApi::class)
internal fun triggerBrowserDownload(bytes: ByteArray, fileName: String, mimeType: String): Boolean =
runCatching { triggerBrowserDownloadJs(Base64.encode(bytes), fileName, mimeType) }.isSuccess
@OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
private fun triggerBrowserDownloadJs(base64: String, fileName: String, mimeType: String) {
js(
"""
{
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
const blob = new Blob([bytes], { type: mimeType });
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = fileName;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(url);
}
""",
)
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/system/DeviceCapabilities.wasm.kt
- Source · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun isTvDevice(): Boolean = false
5: internal actual fun isLocalLibraryManagerSupported(): Boolean = true
7: internal actual fun processMemoryUsage(): ProcessMemoryUsage? = null
Exact file bytes / download · SHA-256 15e3f72917f9f6fee40306851e39ab0298f3262b5a021745c69e718cc1416b3b.
Complete file
package eu.friedcutlet.yokan.services.system
actual fun isTvDevice(): Boolean = false
internal actual fun isLocalLibraryManagerSupported(): Boolean = true
internal actual fun processMemoryUsage(): ProcessMemoryUsage? = null
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/system/SystemIntegration.wasm.kt
- Source · implementation · 18 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: actual fun isOnUnmeteredNetwork(): Boolean = true
8: actual fun createNetworkMonitor(): NetworkMonitor = UnmeteredNetwork
10: actual fun openSystemBrowser(url: String): Boolean {
15: actual fun applyAppLanguage(languageCode: String?) {
Exact file bytes / download · SHA-256 72128e7f49a83b2eed1cb3358bb48f16f66f7e580f363897528d83682543ec9f.
Complete file
package eu.friedcutlet.yokan.services.system
import kotlinx.browser.window
/** The browser doesn't expose metering; assume unmetered like the desktop. */
actual fun isOnUnmeteredNetwork(): Boolean = true
actual fun createNetworkMonitor(): NetworkMonitor = UnmeteredNetwork
actual fun openSystemBrowser(url: String): Boolean {
if (url.isBlank()) return false
return window.open(url, "_blank") != null
}
actual fun applyAppLanguage(languageCode: String?) {
// Compose resources resolve from the browser locale; there is no
// process-level locale to override.
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/tts/TextToSpeechService.wasm.kt
- Source · implementation · 15 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun createPlatformTextToSpeechService(): TextToSpeechService = WasmTextToSpeechService
6: private object WasmTextToSpeechService : TextToSpeechService {
7: override suspend fun voices(language: String?): List<String> = emptyList()
8: override suspend fun speak(
14: override suspend fun stop() = Unit
Exact file bytes / download · SHA-256 630e3077779730afc3501f392c601b0911a7a1a1e3ff75b73dd275709ab1bdbb.
Complete file
package eu.friedcutlet.yokan.services.tts
actual fun createPlatformTextToSpeechService(): TextToSpeechService = WasmTextToSpeechService
// ponytail: browsers do have SpeechSynthesis; wire it up if web TTS is asked for.
private object WasmTextToSpeechService : TextToSpeechService {
override suspend fun voices(language: String?): List<String> = emptyList()
override suspend fun speak(
text: String,
request: TextToSpeechRequest,
onProgress: (startOffset: Int, endOffset: Int) -> Unit,
) = Unit
override suspend fun stop() = Unit
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/updates/PackageInstaller.wasm.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun installPackageFromFile(path: String): Boolean = false
Exact file bytes / download · SHA-256 48623d6907f9abe2ce81aed6576f63d22c4e647e2f57cd4cd490a5707030f670.
Complete file
package eu.friedcutlet.yokan.services.updates
actual fun installPackageFromFile(path: String): Boolean = false
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/discord/DiscordLogin.wasm.kt
- Source · implementation · 10 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: internal actual fun DiscordLoginWebView(modifier: Modifier, onToken: (String) -> Unit) = Unit
Exact file bytes / download · SHA-256 ea22603293fcaab93f810d082d82cb36acb2e9d050ac17facdc9e0368da8dd7a.
Complete file
package eu.friedcutlet.yokan.ui.screens.settings.discord
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
// A browser page cannot read discord.com's storage from another origin; web uses a pasted token.
internal actual val discordWebLoginAvailable: Boolean = false
@Composable
internal actual fun DiscordLoginWebView(modifier: Modifier, onToken: (String) -> Unit) = Unit
composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/scheduling/BrowserUpdateDeviceConditionsTest.kt
- Source · test / fixture · 75 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
10: class BrowserUpdateDeviceConditionsTest {
51: private fun installConditions(online: Boolean, type: String, saveData: Boolean, batteryKind: Int): JsAny = js("""
69: private fun batteryCalls(): Int = js("globalThis.__yokanConditionBatteryCalls || 0")
70: private fun restoreConditions(saved: JsAny): Unit = js("""
Exact file bytes / download · SHA-256 c8dae3d42af74a05b4636899ae258063175443ae03c427b6af5824ef50aa5d08.
Complete file
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package eu.friedcutlet.yokan.services.scheduling
import eu.friedcutlet.yokan.database.*
import kotlinx.coroutines.test.runTest
import kotlin.js.JsAny
import kotlin.test.*
class BrowserUpdateDeviceConditionsTest {
@Test fun browserWifiAndBatteryReadingsDoNotInferUnmeteredFromDisabledDataSaver() = runTest {
val saved = installConditions(true, "wifi", false, 0)
try {
assertEquals(UpdateDeviceConditions(true, true, null, false), readUpdateDeviceConditions())
assertEquals(1, batteryCalls())
} finally { restoreConditions(saved) }
}
@Test fun deniedBatteryAndDataSaverRemainConservativeEvenWithUserCostClassification() = runTest {
val saved = installConditions(true, "ethernet", true, 2)
try {
val conditions = readUpdateDeviceConditions()
assertEquals(UpdateDeviceConditions(true, false, false, null), conditions)
val policy = DbAutomaticUpdateConstraints(DbUpdateNetwork.Unmetered, true, DbUnknownNetworkCost.Unmetered)
assertEquals(setOf(UpdateDeferral.UnmeteredRequired, UpdateDeferral.PowerUnknown), evaluateUpdateConstraints(policy, conditions, true).reasons)
} finally { restoreConditions(saved) }
}
@Test fun missingBrowserApisStayUnknownAndNetworkOnlyChecksDoNotInvokeBattery() = runTest {
val saved = installConditions(true, "unknown", false, 3)
try {
assertEquals(UpdateDeviceConditions(connected = true), readUpdateDeviceConditions())
assertEquals(0, batteryCalls())
} finally { restoreConditions(saved) }
val pending = installConditions(false, "wifi", false, 4)
try {
assertEquals(UpdateDeviceConditions(false, false, false, null), readUpdateDeviceConditions(needPower = false))
assertEquals(0, batteryCalls())
} finally { restoreConditions(pending) }
}
@Test fun stalledBatteryPromiseTimesOutWhilePreservingNetworkReadings() = runTest {
val saved = installConditions(true, "wifi", false, 4)
try {
assertEquals(UpdateDeviceConditions(true, true, null, null), readUpdateDeviceConditions())
assertEquals(1, batteryCalls())
} finally { restoreConditions(saved) }
}
}
private fun installConditions(online: Boolean, type: String, saveData: Boolean, batteryKind: Int): JsAny = js("""
(() => {
const n = globalThis.navigator;
const keys = ['onLine', 'connection', 'getBattery'];
const saved = { descriptors: keys.map(key => [key, Object.getOwnPropertyDescriptor(n, key)]) };
globalThis.__yokanConditionBatteryCalls = 0;
Object.defineProperty(n, 'onLine', { configurable: true, value: online });
Object.defineProperty(n, 'connection', { configurable: true, value: { type, saveData } });
Object.defineProperty(n, 'getBattery', { configurable: true, value: batteryKind === 3 ? undefined : () => {
globalThis.__yokanConditionBatteryCalls++;
if (batteryKind === 2) return Promise.reject(new Error('Permission denied'));
if (batteryKind === 4) return new Promise(() => {});
return Promise.resolve({ charging: batteryKind === 1 });
}});
return saved;
})()
""")
private fun batteryCalls(): Int = js("globalThis.__yokanConditionBatteryCalls || 0")
private fun restoreConditions(saved: JsAny): Unit = js("""
saved.descriptors.forEach(([key, descriptor]) => {
if (descriptor) Object.defineProperty(globalThis.navigator, key, descriptor);
else delete globalThis.navigator[key];
})
""")