ReaderRuntime.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRuntime.kt
1package eu.friedcutlet.yokan.ui.screens.reader23import coil3.network.HttpException4import eu.friedcutlet.yokan.database.DbPageUrl5import eu.friedcutlet.yokan.database.DbReaderMode6import eu.friedcutlet.yokan.database.DbReaderModePreferences7import eu.friedcutlet.yokan.domain.Chapter89private val DeadPageLinkStatusCodes = setOf(401, 403, 404, 410)1011// Ktor's Darwin engine reports NSURLErrorCannotFindHost / NSURLErrorDNSLookupFailed in the message.12private val DarwinHostNotFound = Regex("NSURLErrorDomain Code=-100[36]\\b")1314/**15 * Whether a page image failed because its URL itself is gone (expired or removed page, or a host16 * that no longer resolves) rather than a transient error, so a fresh page list may fix it.17 */18internal fun isDeadPageLink(error: Throwable): Boolean =19 generateSequence(error) { it.cause?.takeIf { cause -> cause !== it } }.take(8).any { cause ->20 (cause as? HttpException)?.response?.code in DeadPageLinkStatusCodes ||21 cause::class.simpleName == "UnknownHostException" ||22 DarwinHostNotFound.containsMatchIn(cause.message.orEmpty())23 }2425internal fun DbReaderMode.isVerticalLike(): Boolean =26 this == DbReaderMode.VerticalContinuous || this == DbReaderMode.Webtoon2728internal fun DbReaderMode.isHorizontalContinuous(): Boolean =29 this == DbReaderMode.HorizontalContinuous || this == DbReaderMode.HorizontalContinuousRtl3031internal fun DbReaderMode.isPaged(): Boolean =32 this == DbReaderMode.Ltr || this == DbReaderMode.Rtl || this == DbReaderMode.Vertical3334internal fun DbReaderMode.isRightToLeft(): Boolean =35 this == DbReaderMode.Rtl || this == DbReaderMode.HorizontalContinuousRtl3637internal fun DbReaderMode.label(): String = when (this) {38 DbReaderMode.Ltr -> "LTR"39 DbReaderMode.Rtl -> "RTL"40 DbReaderMode.Vertical -> "Vertical"41 DbReaderMode.VerticalContinuous -> "Vertical continuous"42 DbReaderMode.HorizontalContinuous -> "Horizontal continuous"43 DbReaderMode.HorizontalContinuousRtl -> "Horizontal continuous (RTL)"44 DbReaderMode.Webtoon -> "Webtoon"45}4647internal fun DbReaderMode.supportsAutoScroll(): Boolean =48 isVerticalLike() || isHorizontalContinuous()4950internal data class ReaderImageFormat(val mimeType: String, val extension: String)5152internal fun readerImageFormat(bytes: ByteArray): ReaderImageFormat = when {53 bytes.hasPrefix(0x89, 0x50, 0x4E, 0x47) -> ReaderImageFormat("image/png", "png")54 bytes.hasPrefix(0xFF, 0xD8, 0xFF) -> ReaderImageFormat("image/jpeg", "jpg")55 bytes.hasPrefix(0x47, 0x49, 0x46, 0x38) -> ReaderImageFormat("image/gif", "gif")56 bytes.hasAscii(0, "RIFF") && bytes.hasAscii(8, "WEBP") -> ReaderImageFormat("image/webp", "webp")57 bytes.hasAscii(4, "ftypavif") || bytes.hasAscii(4, "ftypavis") -> ReaderImageFormat("image/avif", "avif")58 bytes.hasAscii(4, "ftypheic") || bytes.hasAscii(4, "ftypheif") -> ReaderImageFormat("image/heic", "heic")59 else -> ReaderImageFormat("image/png", "png")60}6162internal fun readerImageFileName(63 mangaTitle: String,64 chapterTitle: String,65 pageIndex: Int,66 extension: String,67): String {68 val base = "$mangaTitle $chapterTitle - $pageIndex"69 .replace(Regex("[^A-Za-z0-9 .()\\-\\s]"), "_")70 .trim()71 .ifBlank { "Yokan page $pageIndex" }72 return "$base.$extension"73}7475private fun ByteArray.hasPrefix(vararg expected: Int): Boolean =76 size >= expected.size && expected.indices.all { this[it].toInt() and 0xFF == expected[it] }7778private fun ByteArray.hasAscii(offset: Int, expected: String): Boolean =79 size >= offset + expected.length &&80 expected.indices.all { this[offset + it].toInt() and 0xFF == expected[it].code }818283internal fun readerDisplayUnits(84 items: List<ReaderStreamItem>,85 mode: DbReaderMode,86 doublePage: Boolean,87 shapes: Map<ReaderPageIdentity, ReaderPageShape> = emptyMap(),88 automaticPairing: Boolean = false,89): List<ReaderDisplayUnit> = buildList {90 var index = 091 while (index < items.size) {92 val item = items[index]93 val page = item as? ReaderStreamItem.Page94 val nextPage = items.getOrNull(index + 1) as? ReaderStreamItem.Page95 val pairPages = doublePage &&96 (!automaticPairing || (page != null && nextPage != null &&97 shapes[page.identity()]?.let { it.valid && !it.wide && !it.tall } == true &&98 shapes[nextPage.identity()]?.let { it.valid && !it.wide && !it.tall } == true)) &&99 !mode.isHorizontalContinuous() &&100 page != null &&101 !(mode.isVerticalLike() && page.chapterPageIndex == 0) &&102 nextPage?.chapter?.id == page.chapter.id &&103 nextPage.chapterPageIndex == page.chapterPageIndex + 1 &&104 page.split == null && nextPage.split == null105 val lastIndex = if (pairPages) index + 1 else index106 add(ReaderDisplayUnit(index..lastIndex, items.subList(index, lastIndex + 1)))107 index = lastIndex + 1108 }109}110111internal fun displayUnitIndexForStreamIndex(112 units: List<ReaderDisplayUnit>,113 streamIndex: Int,114): Int = units.indexOfFirst { streamIndex in it.streamIndexes }.let { index ->115 if (index >= 0) index else 0116}117118/** Renderer echoes must not move a resumed/regrouped second page back to the spread's first. */119internal fun readerRendererPageChange(120 units: List<ReaderDisplayUnit>,121 unitIndex: Int,122 logicalStreamIndex: Int,123): Int? = units.getOrNull(unitIndex)?.takeUnless { logicalStreamIndex in it.streamIndexes }?.firstStreamIndex124125internal fun streamIndexForChapterPage(126 items: List<ReaderStreamItem>,127 chapterId: Long,128 pageIndex: Int,129): Int = items.indexOfFirst { item ->130 item is ReaderStreamItem.Page &&131 item.chapter.id == chapterId &&132 item.chapterPageIndex == pageIndex133}134135internal const val ReaderPageTransitionDurationMillis = 150136137internal fun doubleTapZoomDurationMillis(setting: Int): Int = when (setting) {138 0 -> 10139 1 -> 800140 else -> 200141}142143internal fun readerPagesForChapter(144 items: List<ReaderStreamItem>,145 chapterId: Long,146): List<DbPageUrl> = items.mapNotNull { item ->147 (item as? ReaderStreamItem.Page)148 ?.takeIf { it.chapter.id == chapterId && it.split != ReaderPageHalf.Second }149 ?.page150}151152/**153 * Expands landscape pages into two halves when [enabled], or collapses halves otherwise, and maps154 * [currentIndex] onto the same page half. A split page stays split while its shape is unknown.155 */156internal fun splitWidePagesInStream(157 items: List<ReaderStreamItem>,158 currentIndex: Int,159 shapes: Map<ReaderPageIdentity, ReaderPageShape>,160 enabled: Boolean,161): Pair<List<ReaderStreamItem>, Int> {162 if (!enabled && items.none { (it as? ReaderStreamItem.Page)?.split != null }) return items to currentIndex163 val result = ArrayList<ReaderStreamItem>(items.size + 8)164 var index = currentIndex165 items.forEachIndexed { i, item ->166 val page = item as? ReaderStreamItem.Page167 when {168 page == null -> { if (i == currentIndex) index = result.size; result += item }169 // Halves are always adjacent: the second maps to whatever replaced its first half.170 page.split == ReaderPageHalf.Second -> if (i == currentIndex) index = result.lastIndex171 else -> {172 if (i == currentIndex) index = result.size173 val landscape = shapes[page.identity()]?.let { it.valid && it.width > it.height } ?: (page.split != null)174 if (enabled && landscape) {175 result += page.copy(split = ReaderPageHalf.First)176 result += page.copy(split = ReaderPageHalf.Second)177 } else {178 result += if (page.split == null) page else page.copy(split = null)179 }180 }181 }182 }183 if (result.size == items.size && result.indices.all { result[it] == items[it] }) return items to currentIndex184 return result to index.coerceIn(0, result.lastIndex.coerceAtLeast(0))185}186187/** Coil-side processing of one stream page under the current mode's preferences. */188internal data class ReaderPageProcessing(189 val cropBorders: Boolean = false,190 /** Null shows the whole image; otherwise whether the left (true) or right half is shown. */191 val leftHalf: Boolean? = null,192 /** Quarter turn applied to landscape images: 90 clockwise, -90 counter-clockwise, 0 none. */193 val rotation: Int = 0,194)195196/** The first half follows the reading direction (left for LTR, right for RTL); inversion swaps it. */197internal fun readerPageProcessing(198 item: ReaderStreamItem.Page,199 rightToLeft: Boolean,200 preferences: DbReaderModePreferences,201): ReaderPageProcessing = ReaderPageProcessing(202 cropBorders = preferences.cropBorders,203 leftHalf = item.split?.let { (it == ReaderPageHalf.First) != rightToLeft != preferences.invertSplit },204 rotation = when {205 item.split != null || !preferences.rotateWidePages -> 0206 preferences.invertRotation -> -90207 else -> 90208 },209)210211internal fun replaceChapterPagesInStream(212 items: List<ReaderStreamItem>,213 chapter: Chapter,214 pages: List<DbPageUrl>,215): List<ReaderStreamItem> {216 val first = items.indexOfFirst {217 it is ReaderStreamItem.Page && it.chapter.id == chapter.id218 }219 if (first < 0) {220 return if (items.isEmpty()) readerPageItems(chapter, pages) else items221 }222 var lastExclusive = first223 while (224 lastExclusive < items.size &&225 (items[lastExclusive] as? ReaderStreamItem.Page)?.chapter?.id == chapter.id226 ) {227 lastExclusive += 1228 }229 return buildList(items.size - (lastExclusive - first) + pages.size) {230 addAll(items.subList(0, first))231 addAll(readerPageItems(chapter, pages))232 addAll(items.subList(lastExclusive, items.size))233 }234}235236internal fun readerPrefetchPageItems(237 items: List<ReaderStreamItem>,238 currentStreamIndex: Int,239 forwardAmount: Int,240 backwardAmount: Int = 2,241): List<ReaderStreamItem.Page> {242 if (items.isEmpty()) return emptyList()243 val start = currentStreamIndex.coerceIn(items.indices)244 val forwardEnd = (start + forwardAmount.coerceAtLeast(0)).coerceAtMost(items.lastIndex)245 val backwardEnd = (start - backwardAmount.coerceAtLeast(0)).coerceAtLeast(0)246 return buildList {247 for (index in start..forwardEnd) {248 (items[index] as? ReaderStreamItem.Page)?.let(::add)249 }250 for (index in start - 1 downTo backwardEnd) {251 (items[index] as? ReaderStreamItem.Page)?.let(::add)252 }253 }254}255256internal fun readerPrefetchPages(257 items: List<ReaderStreamItem>,258 currentStreamIndex: Int,259 forwardAmount: Int,260 backwardAmount: Int = 2,261): List<DbPageUrl> =262 readerPrefetchPageItems(items, currentStreamIndex, forwardAmount, backwardAmount).map { it.page }263264/** Without [showTransition] the next chapter's pages follow directly; the end of the series always gets a card. */265internal fun appendNextChapterToStream(266 items: List<ReaderStreamItem>,267 completedChapter: Chapter,268 nextChapter: Chapter?,269 mangaTitle: String,270 nextPages: List<DbPageUrl>,271 showTransition: Boolean = true,272): List<ReaderStreamItem> {273 if (items.any {274 it is ReaderStreamItem.Transition && it.completedChapter.id == completedChapter.id ||275 nextChapter != null && it is ReaderStreamItem.Page && it.chapter.id == nextChapter.id276 }277 ) {278 return items279 }280 val nextItems = nextChapter?.let { readerPageItems(it, nextPages) }.orEmpty()281 return if (showTransition || nextChapter == null) {282 items + ReaderStreamItem.Transition(completedChapter, nextChapter, mangaTitle) + nextItems283 } else {284 items + nextItems285 }286}287