package eu.friedcutlet.yokan.ui.screens.reader import coil3.network.HttpException import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.database.DbReaderMode import eu.friedcutlet.yokan.database.DbReaderModePreferences import eu.friedcutlet.yokan.domain.Chapter private val DeadPageLinkStatusCodes = setOf(401, 403, 404, 410) // Ktor's Darwin engine reports NSURLErrorCannotFindHost / NSURLErrorDNSLookupFailed in the message. private val DarwinHostNotFound = Regex("NSURLErrorDomain Code=-100[36]\\b") /** * Whether a page image failed because its URL itself is gone (expired or removed page, or a host * that no longer resolves) rather than a transient error, so a fresh page list may fix it. */ internal fun isDeadPageLink(error: Throwable): Boolean = generateSequence(error) { it.cause?.takeIf { cause -> cause !== it } }.take(8).any { cause -> (cause as? HttpException)?.response?.code in DeadPageLinkStatusCodes || cause::class.simpleName == "UnknownHostException" || DarwinHostNotFound.containsMatchIn(cause.message.orEmpty()) } internal fun DbReaderMode.isVerticalLike(): Boolean = this == DbReaderMode.VerticalContinuous || this == DbReaderMode.Webtoon internal fun DbReaderMode.isHorizontalContinuous(): Boolean = this == DbReaderMode.HorizontalContinuous || this == DbReaderMode.HorizontalContinuousRtl internal fun DbReaderMode.isPaged(): Boolean = this == DbReaderMode.Ltr || this == DbReaderMode.Rtl || this == DbReaderMode.Vertical internal fun DbReaderMode.isRightToLeft(): Boolean = this == DbReaderMode.Rtl || this == DbReaderMode.HorizontalContinuousRtl internal fun DbReaderMode.label(): String = when (this) { DbReaderMode.Ltr -> "LTR" DbReaderMode.Rtl -> "RTL" DbReaderMode.Vertical -> "Vertical" DbReaderMode.VerticalContinuous -> "Vertical continuous" DbReaderMode.HorizontalContinuous -> "Horizontal continuous" DbReaderMode.HorizontalContinuousRtl -> "Horizontal continuous (RTL)" DbReaderMode.Webtoon -> "Webtoon" } internal fun DbReaderMode.supportsAutoScroll(): Boolean = isVerticalLike() || isHorizontalContinuous() internal data class ReaderImageFormat(val mimeType: String, val extension: String) internal fun readerImageFormat(bytes: ByteArray): ReaderImageFormat = when { bytes.hasPrefix(0x89, 0x50, 0x4E, 0x47) -> ReaderImageFormat("image/png", "png") bytes.hasPrefix(0xFF, 0xD8, 0xFF) -> ReaderImageFormat("image/jpeg", "jpg") bytes.hasPrefix(0x47, 0x49, 0x46, 0x38) -> ReaderImageFormat("image/gif", "gif") bytes.hasAscii(0, "RIFF") && bytes.hasAscii(8, "WEBP") -> ReaderImageFormat("image/webp", "webp") bytes.hasAscii(4, "ftypavif") || bytes.hasAscii(4, "ftypavis") -> ReaderImageFormat("image/avif", "avif") bytes.hasAscii(4, "ftypheic") || bytes.hasAscii(4, "ftypheif") -> ReaderImageFormat("image/heic", "heic") else -> ReaderImageFormat("image/png", "png") } internal fun readerImageFileName( mangaTitle: String, chapterTitle: String, pageIndex: Int, extension: String, ): String { val base = "$mangaTitle $chapterTitle - $pageIndex" .replace(Regex("[^A-Za-z0-9 .()\\-\\s]"), "_") .trim() .ifBlank { "Yokan page $pageIndex" } return "$base.$extension" } private fun ByteArray.hasPrefix(vararg expected: Int): Boolean = size >= expected.size && expected.indices.all { this[it].toInt() and 0xFF == expected[it] } private fun ByteArray.hasAscii(offset: Int, expected: String): Boolean = size >= offset + expected.length && expected.indices.all { this[offset + it].toInt() and 0xFF == expected[it].code } internal fun readerDisplayUnits( items: List, mode: DbReaderMode, doublePage: Boolean, shapes: Map = emptyMap(), automaticPairing: Boolean = false, ): List = buildList { var index = 0 while (index < items.size) { val item = items[index] val page = item as? ReaderStreamItem.Page val nextPage = items.getOrNull(index + 1) as? ReaderStreamItem.Page val pairPages = doublePage && (!automaticPairing || (page != null && nextPage != null && shapes[page.identity()]?.let { it.valid && !it.wide && !it.tall } == true && shapes[nextPage.identity()]?.let { it.valid && !it.wide && !it.tall } == true)) && !mode.isHorizontalContinuous() && page != null && !(mode.isVerticalLike() && page.chapterPageIndex == 0) && nextPage?.chapter?.id == page.chapter.id && nextPage.chapterPageIndex == page.chapterPageIndex + 1 && page.split == null && nextPage.split == null val lastIndex = if (pairPages) index + 1 else index add(ReaderDisplayUnit(index..lastIndex, items.subList(index, lastIndex + 1))) index = lastIndex + 1 } } internal fun displayUnitIndexForStreamIndex( units: List, streamIndex: Int, ): Int = units.indexOfFirst { streamIndex in it.streamIndexes }.let { index -> if (index >= 0) index else 0 } /** Renderer echoes must not move a resumed/regrouped second page back to the spread's first. */ internal fun readerRendererPageChange( units: List, unitIndex: Int, logicalStreamIndex: Int, ): Int? = units.getOrNull(unitIndex)?.takeUnless { logicalStreamIndex in it.streamIndexes }?.firstStreamIndex internal fun streamIndexForChapterPage( items: List, chapterId: Long, pageIndex: Int, ): Int = items.indexOfFirst { item -> item is ReaderStreamItem.Page && item.chapter.id == chapterId && item.chapterPageIndex == pageIndex } internal const val ReaderPageTransitionDurationMillis = 150 internal fun doubleTapZoomDurationMillis(setting: Int): Int = when (setting) { 0 -> 10 1 -> 800 else -> 200 } internal fun readerPagesForChapter( items: List, chapterId: Long, ): List = items.mapNotNull { item -> (item as? ReaderStreamItem.Page) ?.takeIf { it.chapter.id == chapterId && it.split != ReaderPageHalf.Second } ?.page } /** * Expands landscape pages into two halves when [enabled], or collapses halves otherwise, and maps * [currentIndex] onto the same page half. A split page stays split while its shape is unknown. */ internal fun splitWidePagesInStream( items: List, currentIndex: Int, shapes: Map, enabled: Boolean, ): Pair, Int> { if (!enabled && items.none { (it as? ReaderStreamItem.Page)?.split != null }) return items to currentIndex val result = ArrayList(items.size + 8) var index = currentIndex items.forEachIndexed { i, item -> val page = item as? ReaderStreamItem.Page when { page == null -> { if (i == currentIndex) index = result.size; result += item } // Halves are always adjacent: the second maps to whatever replaced its first half. page.split == ReaderPageHalf.Second -> if (i == currentIndex) index = result.lastIndex else -> { if (i == currentIndex) index = result.size val landscape = shapes[page.identity()]?.let { it.valid && it.width > it.height } ?: (page.split != null) if (enabled && landscape) { result += page.copy(split = ReaderPageHalf.First) result += page.copy(split = ReaderPageHalf.Second) } else { result += if (page.split == null) page else page.copy(split = null) } } } } if (result.size == items.size && result.indices.all { result[it] == items[it] }) return items to currentIndex return result to index.coerceIn(0, result.lastIndex.coerceAtLeast(0)) } /** Coil-side processing of one stream page under the current mode's preferences. */ internal data class ReaderPageProcessing( val cropBorders: Boolean = false, /** Null shows the whole image; otherwise whether the left (true) or right half is shown. */ val leftHalf: Boolean? = null, /** Quarter turn applied to landscape images: 90 clockwise, -90 counter-clockwise, 0 none. */ val rotation: Int = 0, ) /** The first half follows the reading direction (left for LTR, right for RTL); inversion swaps it. */ internal fun readerPageProcessing( item: ReaderStreamItem.Page, rightToLeft: Boolean, preferences: DbReaderModePreferences, ): ReaderPageProcessing = ReaderPageProcessing( cropBorders = preferences.cropBorders, leftHalf = item.split?.let { (it == ReaderPageHalf.First) != rightToLeft != preferences.invertSplit }, rotation = when { item.split != null || !preferences.rotateWidePages -> 0 preferences.invertRotation -> -90 else -> 90 }, ) internal fun replaceChapterPagesInStream( items: List, chapter: Chapter, pages: List, ): List { val first = items.indexOfFirst { it is ReaderStreamItem.Page && it.chapter.id == chapter.id } if (first < 0) { return if (items.isEmpty()) readerPageItems(chapter, pages) else items } var lastExclusive = first while ( lastExclusive < items.size && (items[lastExclusive] as? ReaderStreamItem.Page)?.chapter?.id == chapter.id ) { lastExclusive += 1 } return buildList(items.size - (lastExclusive - first) + pages.size) { addAll(items.subList(0, first)) addAll(readerPageItems(chapter, pages)) addAll(items.subList(lastExclusive, items.size)) } } internal fun readerPrefetchPageItems( items: List, currentStreamIndex: Int, forwardAmount: Int, backwardAmount: Int = 2, ): List { if (items.isEmpty()) return emptyList() val start = currentStreamIndex.coerceIn(items.indices) val forwardEnd = (start + forwardAmount.coerceAtLeast(0)).coerceAtMost(items.lastIndex) val backwardEnd = (start - backwardAmount.coerceAtLeast(0)).coerceAtLeast(0) return buildList { for (index in start..forwardEnd) { (items[index] as? ReaderStreamItem.Page)?.let(::add) } for (index in start - 1 downTo backwardEnd) { (items[index] as? ReaderStreamItem.Page)?.let(::add) } } } internal fun readerPrefetchPages( items: List, currentStreamIndex: Int, forwardAmount: Int, backwardAmount: Int = 2, ): List = readerPrefetchPageItems(items, currentStreamIndex, forwardAmount, backwardAmount).map { it.page } /** Without [showTransition] the next chapter's pages follow directly; the end of the series always gets a card. */ internal fun appendNextChapterToStream( items: List, completedChapter: Chapter, nextChapter: Chapter?, mangaTitle: String, nextPages: List, showTransition: Boolean = true, ): List { if (items.any { it is ReaderStreamItem.Transition && it.completedChapter.id == completedChapter.id || nextChapter != null && it is ReaderStreamItem.Page && it.chapter.id == nextChapter.id } ) { return items } val nextItems = nextChapter?.let { readerPageItems(it, nextPages) }.orEmpty() return if (showTransition || nextChapter == null) { items + ReaderStreamItem.Transition(completedChapter, nextChapter, mangaTitle) + nextItems } else { items + nextItems } }