package eu.friedcutlet.yokan.ui.screens.reader import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.CancellationException import kotlinx.coroutines.channels.Channel import coil3.Extras import coil3.getExtra import coil3.SingletonImageLoader import coil3.compose.LocalPlatformContext import coil3.network.NetworkHeaders import coil3.network.httpHeaders import coil3.request.ImageRequest import coil3.request.CachePolicy import coil3.intercept.Interceptor import coil3.request.transformations import eu.friedcutlet.yokan.database.DbPageUrl import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit /** * Starts a cancellable Coil prefetch session for the current reader position. * * Requests are processed in authority order with the same three-worker bound * as Mangayomi. This prevents a large preload window from becoming a burst of * simultaneous HTTP requests while still keeping the configured cache warm. */ @Composable internal fun ReaderPagePrefetch( items: List, currentStreamIndex: Int, forwardAmount: Int, layoutSampleKey: String = "", sampleChapterId: Long? = null, onShapeSampled: (String, ReaderPageIdentity, ReaderPageShape?) -> Unit = { _, _, _ -> }, ) { if (items.isEmpty()) return val context = LocalPlatformContext.current LaunchedEffect(currentStreamIndex, items, forwardAmount, layoutSampleKey, sampleChapterId) { val loader = SingletonImageLoader.get(context) loadReaderPagesBounded( pages = (readerPrefetchPageItems( items = items, currentStreamIndex = currentStreamIndex, forwardAmount = forwardAmount, ) + items.filterIsInstance().filter { it.chapter.id == sampleChapterId && it.split != ReaderPageHalf.Second } .take(AUTOMATIC_LAYOUT_SAMPLE_COUNT)).distinctBy { it.identity() }, ) { pageItem -> try { // Warm only the disk/network caches: a target-less request decodes at original size // without the visible page's transformations, so its bitmap would just evict usable ones. val result = loader.execute( ImageRequest.Builder(context) .readerPageData(pageItem.page, pageItem.chapter.id) .memoryCachePolicy(CachePolicy.DISABLED) .build(), ) val shape = (result as? coil3.request.SuccessResult)?.image?.let { ReaderPageShape(it.width, it.height) } onShapeSampled(layoutSampleKey, pageItem.identity(), shape) } catch (cancelled: CancellationException) { throw cancelled } catch (_: Throwable) { onShapeSampled(layoutSampleKey, pageItem.identity(), null) // Prefetch failures are rendered and retried by the visible page. } } } } internal const val READER_PREFETCH_CONCURRENCY = 3 private val ReaderPageRequestExtra = Extras.Key(default = false) internal class ReaderImageRequestLimiter( maxConcurrent: Int = READER_PREFETCH_CONCURRENCY, ) : Interceptor { private val semaphore = Semaphore(maxConcurrent) override suspend fun intercept(chain: Interceptor.Chain) = if (chain.request.getExtra(ReaderPageRequestExtra)) { limit { chain.proceed() } } else { chain.proceed() } internal suspend fun limit(block: suspend () -> T): T = semaphore.withPermit { block() } } internal val ReaderPageRequestLimiter = ReaderImageRequestLimiter() internal suspend fun loadReaderPagesBounded( pages: List, maxConcurrent: Int = READER_PREFETCH_CONCURRENCY, load: suspend (T) -> Unit, ) { require(maxConcurrent > 0) if (pages.isEmpty()) return coroutineScope { val queue = Channel(Channel.UNLIMITED) pages.forEach { queue.trySend(it) } queue.close() repeat(minOf(maxConcurrent, pages.size)) { launch { for (page in queue) load(page) } } } } internal fun chapterPageCacheKey( chapterId: Long?, url: String, headers: Map? = null, ): String { val prefix = if (chapterId != null && chapterId > 0L) "ch_${chapterId}_" else "" val headerSuffix = headers?.takeIf { it.isNotEmpty() }?.let { "#readerHeaders=${readerPageHeaderFingerprint(it)}" } ?: "" return "$prefix$url$headerSuffix" } /** Explicit memory keys ignore transformations; every processing variant adds its own key extra. */ internal fun ImageRequest.Builder.applyReaderPageProcessing(processing: ReaderPageProcessing): ImageRequest.Builder = apply { val steps = ArrayList(3) if (processing.cropBorders) { steps += createBorderCropTransformation() memoryCacheKeyExtra("borderCrop", "true") } processing.leftHalf?.let { left -> steps += createPageHalfTransformation(left) memoryCacheKeyExtra("pageHalf", if (left) "left" else "right") } if (processing.rotation != 0) { steps += createWidePageRotation(processing.rotation) memoryCacheKeyExtra("rotateWide", processing.rotation.toString()) } if (steps.isNotEmpty()) transformations(steps) } internal fun ImageRequest.Builder.readerPageData( page: DbPageUrl, chapterId: Long? = null, revision: Long = 0L, ): ImageRequest.Builder = apply { data(page.url) extras[ReaderPageRequestExtra] = true extras[eu.friedcutlet.yokan.ui.image.ImageChapterIdExtra] = chapterId val headers = page.headers.orEmpty() val cacheKey = chapterPageCacheKey(chapterId, page.url, headers.takeIf { it.isNotEmpty() }) + "#revision=$revision" memoryCacheKey(cacheKey) diskCacheKey(cacheKey) if (headers.isNotEmpty()) { val networkHeaders = NetworkHeaders.Builder().apply { headers.forEach { (name, value) -> set(name, value) } }.build() httpHeaders(networkHeaders) } } internal fun readerPageHeaderFingerprint(headers: Map): String { var hash = 14695981039346656037uL headers.entries .sortedWith(compareBy({ it.key.lowercase() }, { it.key }, { it.value })) .forEach { (name, value) -> for (character in name.lowercase()) { hash = (hash xor character.code.toULong()) * 1099511628211uL } hash = (hash xor 0uL) * 1099511628211uL for (character in value) { hash = (hash xor character.code.toULong()) * 1099511628211uL } hash = (hash xor 0xFFuL) * 1099511628211uL } return hash.toString(16) }