package eu.friedcutlet.yokan.ui.screens.reader import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.CubicBezierEasing import androidx.compose.animation.core.VectorConverter import androidx.compose.animation.core.animate import androidx.compose.animation.core.tween import androidx.compose.animation.core.exponentialDecay import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.calculateCentroid import androidx.compose.foundation.gestures.calculatePan import androidx.compose.foundation.gestures.calculateZoom import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.isSecondaryPressed import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.Velocity import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch internal class ReaderZoomState { var scale by mutableFloatStateOf(1f) private set var offset by mutableStateOf(Offset.Zero) private set var lastPointerPosition by mutableStateOf(Offset.Zero) internal set private var viewportSize by mutableStateOf(IntSize.Zero) fun updateViewport(size: IntSize) { viewportSize = size offset = constrainZoomOffset(offset, scale, viewportSize) } fun applyInitialTransform(transform: ReaderInitialTransform) { scale = transform.scale.coerceIn(MIN_ZOOM, MAX_ZOOM) offset = constrainZoomOffset(transform.offset, scale, viewportSize) } fun transform(centroid: Offset, pan: Offset, zoomChange: Float) { val oldScale = scale val newScale = (oldScale * zoomChange).coerceIn(MIN_ZOOM, MAX_ZOOM) val center = viewportSize.centerOffset() val ratio = newScale / oldScale val transformed = offset * ratio + pan + (centroid - center) * (1f - ratio) scale = newScale offset = if (newScale == MIN_ZOOM) { Offset.Zero } else { constrainZoomOffset(transformed, newScale, viewportSize) } } suspend fun toggleZoom(tapPosition: Offset, durationMillis: Int) { val targetScale = if (scale > MIN_ZOOM + 0.01f) MIN_ZOOM else DOUBLE_TAP_ZOOM val targetOffset = if (targetScale == MIN_ZOOM) { Offset.Zero } else { doubleTapZoomOffset(tapPosition, targetScale, viewportSize) } val startScale = scale val startOffset = offset animate( initialValue = 0f, targetValue = 1f, animationSpec = tween(durationMillis, easing = ReaderZoomEasing), ) { progress, _ -> scale = startScale + (targetScale - startScale) * progress offset = Offset( x = startOffset.x + (targetOffset.x - startOffset.x) * progress, y = startOffset.y + (targetOffset.y - startOffset.y) * progress, ) } } suspend fun fling(velocity: Velocity) { if (scale <= MIN_ZOOM) return val animation = Animatable(offset, Offset.VectorConverter) animation.animateDecay( initialVelocity = Offset(velocity.x, velocity.y), animationSpec = exponentialDecay(), ) { val constrained = constrainZoomOffset(value, scale, viewportSize) offset = constrained } } } internal fun Modifier.readerZoomGestures(state: ReaderZoomState): Modifier = pointerInput(state) { coroutineScope { var flingJob: Job? = null awaitEachGesture { flingJob?.cancel() val velocityTracker = VelocityTracker() var handled = false val firstDown = awaitFirstDown(requireUnconsumed = false) state.lastPointerPosition = firstDown.position do { val event = awaitPointerEvent(PointerEventPass.Main) event.changes.firstOrNull { it.pressed && !it.previousPressed }?.let { state.lastPointerPosition = it.position } val pressedCount = event.changes.count { it.pressed } val zoomChange = event.calculateZoom() if (pressedCount > 0 && (pressedCount > 1 || state.scale > MIN_ZOOM)) { val centroid = event.calculateCentroid(useCurrent = true) velocityTracker.addPosition(event.changes.first().uptimeMillis, centroid) state.transform( centroid = centroid, pan = event.calculatePan(), zoomChange = zoomChange, ) handled = true event.changes.forEach { it.consume() } } } while (event.changes.any { it.pressed }) if (handled && state.scale > MIN_ZOOM) { val velocity = velocityTracker.calculateVelocity() flingJob = launch { state.fling(velocity) } } } } } internal fun Modifier.readerSecondaryClickZoom( state: ReaderZoomState, durationMillis: Int, ): Modifier = pointerInput(state, durationMillis) { coroutineScope { val animationScope = this var animationJob: Job? = null awaitPointerEventScope { while (true) { val event = awaitPointerEvent(PointerEventPass.Main) if (event.type == PointerEventType.Press && event.buttons.isSecondaryPressed) { val position = event.changes.firstOrNull()?.position ?: continue state.lastPointerPosition = position event.changes.forEach { it.consume() } animationJob?.cancel() animationJob = animationScope.launch { state.toggleZoom(position, durationMillis) } } } } } } internal fun doubleTapZoomOffset( tapPosition: Offset, targetScale: Float, viewportSize: IntSize, ): Offset { val center = viewportSize.centerOffset() return constrainZoomOffset( offset = (center - tapPosition) * (targetScale - 1f), scale = targetScale, viewportSize = viewportSize, ) } internal fun constrainZoomOffset(offset: Offset, scale: Float, viewportSize: IntSize): Offset { if (scale <= MIN_ZOOM || viewportSize.width <= 0 || viewportSize.height <= 0) return Offset.Zero val maxX = viewportSize.width * (scale - 1f) / 2f val maxY = viewportSize.height * (scale - 1f) / 2f return Offset(offset.x.coerceIn(-maxX, maxX), offset.y.coerceIn(-maxY, maxY)) } private fun IntSize.centerOffset(): Offset = Offset(width / 2f, height / 2f) internal const val MIN_ZOOM = 1f private const val DOUBLE_TAP_ZOOM = 2f internal const val MAX_ZOOM = 8f private val ReaderZoomEasing = CubicBezierEasing(0.25f, 0.1f, 0.25f, 1f)