Yokan / rebuild
Course 1 8624561

ReaderGestures.kt

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

implementation264 lines
1package eu.friedcutlet.yokan.ui.screens.reader23import androidx.compose.foundation.gestures.detectTapGestures4import androidx.compose.runtime.Composable5import androidx.compose.runtime.getValue6import androidx.compose.runtime.rememberUpdatedState7import androidx.compose.ui.Modifier8import androidx.compose.ui.geometry.Offset9import androidx.compose.ui.input.key.Key10import androidx.compose.ui.input.key.KeyEvent11import androidx.compose.ui.input.key.KeyEventType12import androidx.compose.ui.input.key.isShiftPressed13import androidx.compose.ui.input.key.key14import androidx.compose.ui.input.key.onPreviewKeyEvent15import androidx.compose.ui.input.key.type16import androidx.compose.ui.input.pointer.PointerEventType17import androidx.compose.ui.input.pointer.PointerInputScope18import androidx.compose.ui.input.pointer.pointerInput19import androidx.compose.ui.unit.IntSize2021/**22 * Six navigation layouts mirroring the Flutter `reader_gesture_handler.dart`23 * (which mirrors Mihon). Index lives in `DbReaderModePreferences.navigationLayout`.24 *25 * 0 Default       3-column + top/bottom strips26 * 1 L-shaped      top-left = prev, bottom-right = next, rest = chrome27 * 2 Kindle        top = chrome, bottom split (left = prev, right = next)28 * 3 Edge          thin strips at left/right for prev/next, middle = chrome29 * 4 Right/Left    left half = prev, right half = next30 * 5 Disabled      whole surface only toggles chrome31 *32 * For RTL modes, only left/right zone semantics are flipped; Default's33 * top/bottom actions remain previous/next.34 */35internal enum class TapNavLayout {36    Default, LShaped, Kindle, Edge, RightLeft, Disabled;3738    companion object {39        fun fromIndex(i: Int): TapNavLayout = entries.getOrNull(i) ?: Default40    }41}4243internal sealed interface TapZoneAction {44    data object Prev : TapZoneAction45    data object Next : TapZoneAction46    data object ToggleChrome : TapZoneAction47}4849/**50 * Maps a tap offset within the reader viewport to a navigation action. Pure51 * function — no Compose state — so it's trivially testable.52 *53 * `xRatio` / `yRatio` are normalized in [0, 1]. Zone fractions match the54 * Flutter implementation: Default uses 2:5:2 vertically, L-shaped corners55 * use quarter-height rows, Kindle reserves the top quarter for chrome, and56 * Edge uses 1:5:1 columns.57 */58internal fun computeTapAction(59    layout: TapNavLayout,60    offset: Offset,61    size: IntSize,62    usePageTapZones: Boolean,63    isRightToLeft: Boolean = false,64    hasImageError: Boolean = false,65): TapZoneAction {66    if (!usePageTapZones) return TapZoneAction.ToggleChrome67    if (size.width <= 0 || size.height <= 0) return TapZoneAction.ToggleChrome68    val x = (offset.x / size.width).coerceIn(0f, 1f)69    val y = (offset.y / size.height).coerceIn(0f, 1f)70    fun sideAction(action: TapZoneAction): TapZoneAction =71        if (!isRightToLeft) action else when (action) {72            TapZoneAction.Prev -> TapZoneAction.Next73            TapZoneAction.Next -> TapZoneAction.Prev74            TapZoneAction.ToggleChrome -> TapZoneAction.ToggleChrome75        }76    return when (layout) {77        TapNavLayout.Default -> when {78            y < 2f / 9f -> if (hasImageError) TapZoneAction.ToggleChrome else TapZoneAction.Prev79            y > 7f / 9f -> if (hasImageError) TapZoneAction.ToggleChrome else TapZoneAction.Next80            x < 1f / 3f -> sideAction(TapZoneAction.Prev)81            x > 2f / 3f -> sideAction(TapZoneAction.Next)82            else -> TapZoneAction.ToggleChrome83        }84        TapNavLayout.LShaped -> when {85            y < 0.25f && x < 1f / 3f -> sideAction(TapZoneAction.Prev)86            y > 0.75f && x > 2f / 3f -> sideAction(TapZoneAction.Next)87            else -> TapZoneAction.ToggleChrome88        }89        TapNavLayout.Kindle -> when {90            y < 0.25f -> TapZoneAction.ToggleChrome91            x < 0.5f -> sideAction(TapZoneAction.Prev)92            else -> sideAction(TapZoneAction.Next)93        }94        TapNavLayout.Edge -> when {95            x < 1f / 7f -> sideAction(TapZoneAction.Prev)96            x > 6f / 7f -> sideAction(TapZoneAction.Next)97            else -> TapZoneAction.ToggleChrome98        }99        TapNavLayout.RightLeft ->100            sideAction(if (x < 0.5f) TapZoneAction.Prev else TapZoneAction.Next)101        TapNavLayout.Disabled -> TapZoneAction.ToggleChrome102    }103}104105/**106 * Single full-screen tap detector. Applied to the Box that contains the107 * page renderer — does NOT replace the page renderer's own pointer input,108 * so HorizontalPager swipes and LazyList scrolling continue to work109 * (`detectTapGestures` cancels on drag and parent + child pointerInputs110 * coexist via Compose's gesture pass system).111 *112 * Single tap → zone-mapped action via [computeTapAction].113 * Double tap → delegated to the page renderer (zoom) while suppressing two single taps.114 */115@Composable116internal fun Modifier.readerTapZones(117    layout: TapNavLayout,118    usePageTapZones: Boolean,119    hasImageError: Boolean,120    isRightToLeft: Boolean,121    onToggleChrome: () -> Unit,122    onPreviousPage: () -> Unit,123    onNextPage: () -> Unit,124    onDoubleTap: (Offset, IntSize) -> Unit,125    onLongPress: (Offset, IntSize) -> Unit,126    longPressImageActions: Boolean = true,127): Modifier {128    val layoutRef by rememberUpdatedState(layout)129    val zonesRef by rememberUpdatedState(usePageTapZones)130    val rtlRef by rememberUpdatedState(isRightToLeft)131    val errorRef by rememberUpdatedState(hasImageError)132    val toggleRef by rememberUpdatedState(onToggleChrome)133    val prevRef by rememberUpdatedState(onPreviousPage)134    val nextRef by rememberUpdatedState(onNextPage)135    val doubleRef by rememberUpdatedState(onDoubleTap)136    val longPressRef by rememberUpdatedState(onLongPress)137    return this.then(138        Modifier.pointerInput(longPressImageActions) {139            detectTapGestures(140                onTap = { offset ->141                    when (computeTapAction(layoutRef, offset, size, zonesRef, rtlRef, errorRef)) {142                        TapZoneAction.Prev -> prevRef()143                        TapZoneAction.Next -> nextRef()144                        TapZoneAction.ToggleChrome -> toggleRef()145                    }146                },147                onDoubleTap = { offset -> doubleRef(offset, size) },148                onLongPress = if (longPressImageActions) ({ offset -> longPressRef(offset, size) }) else null,149            )150        },151    )152}153154/**155 * Keyboard handler — direct port of `ReaderKeyboardHandler` from the Flutter156 * implementation. Mounted on a stable focused ancestor of the Scaffold so it157 * fires regardless of which chrome element currently owns focus (Slider, IconButton, etc.).158 *159 * With [volumeKeys], hardware volume down/up turn to the next/previous page (swapped by160 * [invertVolumeKeys]); both key edges are consumed so the system volume stays unchanged.161 */162internal fun readerKeyEventHandler(163    isRightToLeft: Boolean,164    onBack: () -> Unit,165    onFullscreen: () -> Unit,166    onPreviousPage: () -> Unit,167    onNextPage: () -> Unit,168    onPreviousChapter: () -> Unit,169    onNextChapter: () -> Unit,170    volumeKeys: Boolean = false,171    invertVolumeKeys: Boolean = false,172): (KeyEvent) -> Boolean = handler@{ event ->173    val volumeStep = readerVolumeKeyStep(event.key, volumeKeys, invertVolumeKeys)174    if (volumeStep != 0) {175        if (event.type == KeyEventType.KeyDown) {176            if (volumeStep > 0) onNextPage() else onPreviousPage()177        }178        return@handler true179    }180    if (event.type != KeyEventType.KeyDown) return@handler false181    when (event.key) {182        Key.F11 -> { onFullscreen(); true }183        Key.Escape, Key.Backspace -> { onBack(); true }184        Key.DirectionUp -> { onPreviousPage(); true }185        Key.DirectionDown, Key.Spacebar -> { onNextPage(); true }186        Key.DirectionLeft -> { if (isRightToLeft) onNextPage() else onPreviousPage(); true }187        Key.DirectionRight -> { if (isRightToLeft) onPreviousPage() else onNextPage(); true }188        Key.N -> { onNextChapter(); true }189        Key.P -> { onPreviousChapter(); true }190        Key.PageDown -> { onNextChapter(); true }191        Key.PageUp -> { onPreviousChapter(); true }192        Key.ShiftLeft -> if (event.isShiftPressed) { onPreviousChapter(); true } else false193        Key.ShiftRight -> if (event.isShiftPressed) { onNextChapter(); true } else false194        else -> false195    }196}197198/** Page step for a hardware volume key: +1 next, -1 previous, 0 when not handled. */199internal fun readerVolumeKeyStep(key: Key, enabled: Boolean, invert: Boolean): Int {200    if (!enabled) return 0201    val step = when (key) {202        Key.VolumeDown -> 1203        Key.VolumeUp -> -1204        else -> return 0205    }206    return if (invert) -step else step207}208209internal fun Modifier.readerKeyEvents(210    isRightToLeft: Boolean,211    volumeKeys: Boolean,212    invertVolumeKeys: Boolean,213    onBack: () -> Unit,214    onFullscreen: () -> Unit,215    onPreviousPage: () -> Unit,216    onNextPage: () -> Unit,217    onPreviousChapter: () -> Unit,218    onNextChapter: () -> Unit,219): Modifier = onPreviewKeyEvent(220    readerKeyEventHandler(221        isRightToLeft = isRightToLeft,222        onBack = onBack,223        onFullscreen = onFullscreen,224        onPreviousPage = onPreviousPage,225        onNextPage = onNextPage,226        onPreviousChapter = onPreviousChapter,227        onNextChapter = onNextChapter,228        volumeKeys = volumeKeys,229        invertVolumeKeys = invertVolumeKeys,230    ),231)232233/**234 * Mouse-wheel page nav. Only active in paged modes (Ltr/Rtl + double-page);235 * continuous modes let the lazy lists handle wheel naturally.236 *237 * `vertical.scrollDelta > 0` is wheel-down → next page. The caller resolves238 * RTL before passing callbacks.239 */240@Composable241internal fun Modifier.readerMouseWheelNav(242    enabled: Boolean,243    onPreviousPage: () -> Unit,244    onNextPage: () -> Unit,245): Modifier {246    val prev by rememberUpdatedState(onPreviousPage)247    val next by rememberUpdatedState(onNextPage)248    return if (!enabled) this else this.then(249        Modifier.pointerInput(Unit) { handleMouseWheel(prev, next) }250    )251}252253private suspend fun PointerInputScope.handleMouseWheel(onPrev: () -> Unit, onNext: () -> Unit) {254    awaitPointerEventScope {255        while (true) {256            val event = awaitPointerEvent()257            if (event.type != PointerEventType.Scroll) continue258            val change = event.changes.firstOrNull() ?: continue259            val deltaY = change.scrollDelta.y260            if (deltaY > 0f) onNext() else if (deltaY < 0f) onPrev()261            change.consume()262        }263    }264}265

Search chapters, reference and source filenames.