Yokan / rebuild
Course 1 8624561

ReaderPageDownloadProgress.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderPageDownloadProgress.kt

implementation48 lines
1package eu.friedcutlet.yokan.ui.screens.reader23import kotlinx.coroutines.flow.MutableStateFlow4import kotlinx.coroutines.flow.StateFlow5import kotlinx.coroutines.flow.Flow6import kotlinx.coroutines.flow.distinctUntilChanged7import kotlinx.coroutines.flow.map8import kotlinx.coroutines.flow.update910/**11 * Byte-level download progress for images loaded through Coil, keyed by URL.12 *13 * Mangayomi surfaces `ImageChunkEvent.cumulativeBytesLoaded / expectedTotalBytes`14 * on every reader page placeholder; Coil has no progress API, so the shared15 * [eu.friedcutlet.yokan.ui.image.ProfileImageHttpClient] taps Ktor's `onDownload` callback instead and this16 * registry fans the ratio out to the composables that render the placeholder.17 */18object ReaderPageDownloadProgress {19    private const val MAX_TRACKED = 1282021    private val state = MutableStateFlow<Map<String, Float>>(emptyMap())22    val progress: StateFlow<Map<String, Float>> get() = state2324    fun forUrl(url: String): Flow<Float?> = state.map { it[url] }.distinctUntilChanged()2526    fun report(url: String, receivedBytes: Long, totalBytes: Long?) {27        if (totalBytes == null || totalBytes <= 0L) return28        val ratio = (receivedBytes.toFloat() / totalBytes.toFloat()).coerceIn(0f, 1f)29        state.update { current ->30            if (ratio >= 1f) {31                return@update if (url in current) current - url else current32            }33            // Check before copying: most chunks leave the displayed percent unchanged.34            val previous = current[url]35            if (previous != null && (previous * 100).toInt() == (ratio * 100).toInt()) return@update current36            buildMap {37                putAll(current)38                put(url, ratio)39                if (size > MAX_TRACKED) keys.take(size - MAX_TRACKED).forEach(::remove)40            }41        }42    }4344    fun clear(url: String) {45        state.update { current -> if (url in current) current - url else current }46    }47    fun clearAll() { state.update { emptyMap() } }48}49

Search chapters, reference and source filenames.