From ba461c8b3e4e983b71c41426bf765fbac5fb2d2a Mon Sep 17 00:00:00 2001 From: Chagai Yisroel Wild Date: Tue, 10 Nov 2026 23:29:04 +0200 Subject: [PATCH] feat(reader): adjust the book selection with Shift+arrow keys With text selected in the book reader, Shift+arrows move the selection's focus end as in a text editor, the anchor end staying fixed: - Shift+Left/Right: one character (a letter with its nikud/teamim) - Ctrl+Shift+Left/Right: one word - Shift+Up/Down: one visual line, keeping a goal column across a run Left/Right follow the screen: in a right-to-left (Hebrew) line Left moves toward the end of the text and Right toward its start; in a left-to-right line the reverse. The direction is taken from the focus's line, from its own text. Only an existing selection (a drag, a double click, a Shift+click) is adjusted: without one, plain and Shift arrows keep scrolling/moving by line as before, and Ctrl+Alt/Meta combinations stay the window's. Signed-off-by: Chagai Yisroel Wild Co-Authored-By: Claude Opus 5.5 --- .../features/bookcontent/BookContentScreen.kt | 19 +- .../bookcontent/views/BookContentView.kt | 78 ++++++- .../panels/bookcontent/views/BookSelection.kt | 187 +++++++++++++-- .../bookcontent/views/SelectionMotion.kt | 214 ++++++++++++++++++ .../bookcontent/ShiftArrowSelectionUiTest.kt | 208 +++++++++++++++++ .../bookcontent/views/BookSelectionTest.kt | 114 ++++++++++ .../bookcontent/views/SelectionMotionTest.kt | 163 +++++++++++++ 7 files changed, 959 insertions(+), 24 deletions(-) create mode 100644 SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/SelectionMotion.kt create mode 100644 SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ShiftArrowSelectionUiTest.kt create mode 100644 SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/SelectionMotionTest.kt diff --git a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/BookContentScreen.kt b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/BookContentScreen.kt index 7b4fa7409..9028893e4 100644 --- a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/BookContentScreen.kt +++ b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/BookContentScreen.kt @@ -503,17 +503,25 @@ fun BookTextMenus( val rawText = textManager.selectedText.text // Mirror the current selection into the SelectionContext so the AWT // keyboard dispatcher can read it without touching Compose state directly. - // A new Compose selection (a drag) replaces the Shift+click one; a Shift+click leaves Compose's as is - LaunchedEffect(rawText) { if (rawText.isNotEmpty()) bookSelection?.clear() } + // A new Compose selection (a drag) replaces the book view's own one; a Shift+click or Shift+arrow leaves Compose's + // as is, hidden under it (BookSelectionContainer) + LaunchedEffect(rawText) { + bookSelection?.composeSelectionActive = rawText.isNotEmpty() + if (rawText.isNotEmpty()) bookSelection?.clear() + } LaunchedEffect(rawText, shiftRange, diacritics) { bookSelection?.resolved = null - // A Shift+click selection is not Compose's, still drawn from an earlier drag: nothing until read + // The book view's own selection is not Compose's, still held from an earlier drag: nothing until read selectionContext.setSelectedText(tabId, if (shiftRange != null) "" else rawText) val pressedAt = bookSelection?.pressedAt val resolved = when { bookSelection == null || bookId <= 0 -> null - shiftRange != null -> resolveRange(shiftRange, bookId, repository, diacritics) + shiftRange != null -> { + // Moved by held Shift+arrows: read once the keys rest (each move restarts this effect) + if (bookSelection?.adjustedByKeys == true) delay(KEY_SELECTION_SETTLE_MS) + resolveRange(shiftRange, bookId, repository, diacritics) + } rawText.isNotEmpty() && pressedAt != null -> { // Across lines, once the drag rests rather than on each of its moves; within a line (a // double click, a word) at once, a single line to read, before the menu opens @@ -886,3 +894,6 @@ private fun normalizeSearchQuery(text: String): String { // How long a Compose selection rests before it is located in the book private const val SELECTION_SETTLE_MS = 150L + +// How long Shift+arrow moves rest before their selection is read from the database +private const val KEY_SELECTION_SETTLE_MS = 80L diff --git a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookContentView.kt b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookContentView.kt index a0a8fbe78..66d4e544f 100644 --- a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookContentView.kt +++ b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookContentView.kt @@ -34,6 +34,7 @@ import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.input.key.* import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerEventType @@ -47,6 +48,7 @@ import androidx.compose.ui.input.pointer.onPointerEvent import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.onPlaced import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextLayoutResult @@ -864,12 +866,70 @@ fun BookContentView( scope.launch { listState.animateScrollToItem(targetIndex, 0) } } + // Both ends of a Shift+click selection, to copy the lines between them Compose never composed (not in shnayim + // mikra, whose items are more than their line). Its offsets index the text as displayed: new for another diacritics mode + val bookSelection = remember(bookId, shnayimMikra, diacritics) { if (shnayimMikra) null else BookSelection() } + // Read by the remembered key handler: a new selection comes with another diacritics mode + val currentBookSelection by rememberUpdatedState(bookSelection) + val currentDiacritics by rememberUpdatedState(diacritics) + val currentLazyPagingItems by rememberUpdatedState(lazyPagingItems) + + /** The displayed text of the book line [lineIndex]: from its layout when composed, else from the loaded lines. */ + fun displayedTextOf(lineIndex: Int): String? { + if (lineIndex < 0 || bookLineCount?.let { lineIndex >= it } == true) return null + currentBookSelection?.layoutOf(lineIndex)?.let { return it.layoutInput.text.text } + val loaded = currentLazyPagingItems.itemSnapshotList.items + val index = loaded.binarySearchBy(lineIndex) { it.lineIndex } + return loaded.getOrNull(index)?.let { displayedLineText(it.content, currentDiacritics) } + } + + /** Scrolls the list so the selection's focus [point] is on screen. */ + fun revealFocus( + selection: BookSelection, + point: TextPoint, + @StructuredScope scope: CoroutineScope, + ) { + val layout = selection.layoutOf(point.lineIndex) + val text = selection.coordinatesOf(point.lineIndex) + val list = findMatchLocator.list?.takeIf { it.isAttached } + if (layout == null || text == null || list == null) { + // Not composed: brought to the top of the list + scope.launch { loadLine(point.lineIndex)?.let { listState.scrollToItem(it) } } + return + } + val caret = layout.getCursorRect(point.offset.coerceIn(0, layout.layoutInput.text.length)) + val top = list.localPositionOf(text, Offset(0f, caret.top)).y + val bottom = top + caret.height + val viewport = list.size.height + val delta = + when { + top < 0f -> top + bottom > viewport -> bottom - viewport + else -> return + } + scope.launch { listState.scrollBy(delta) } + } + + /** Shift+arrows move the selection's focus ([moveFocusByKey]); not in shnayim mikra, which has no book selection. */ + fun adjustSelection( + keyEvent: KeyEvent, + @StructuredScope scope: CoroutineScope, + ): Boolean { + val selection = currentBookSelection ?: return false + if (!selection.moveFocusByKey(keyEvent, ::displayedTextOf)) return false + selection.focus?.let { revealFocus(selection, it, scope) } + return true + } + // Global preview handler: handle basic navigation keys regardless of inner focus val previewKeyHandler = remember(onEvent) { { keyEvent: KeyEvent -> // Ctrl/Cmd+F handled globally at window level; do not intercept here - if (keyEvent.type == KeyEventType.KeyDown) { + if (keyEvent.type == KeyEventType.KeyDown && adjustSelection(keyEvent, scope)) { + // Before the plain arrows: Shift+arrows extend the selection + true + } else if (keyEvent.type == KeyEventType.KeyDown) { when (keyEvent.key) { Key.DirectionUp -> { onEvent(BookContentEvent.NavigateToPreviousLine) @@ -938,9 +998,6 @@ fun BookContentView( } } - // Both ends of a Shift+click selection, to copy the lines between them Compose never composed (not in shnayim - // mikra, whose items are more than their line). Its offsets index the text as displayed: new for another diacritics mode - val bookSelection = remember(bookId, shnayimMikra, diacritics) { if (shnayimMikra) null else BookSelection() } BookSelectionContainer( selection = bookSelection, modifier = @@ -1664,7 +1721,13 @@ private fun LineItem( DisposableEffect(findMatchLocator, lineId) { onDispose { findMatchLocator.forget(lineId) } } } - val selectionBackground = LocalTextSelectionColors.current.backgroundColor + // Compose's selection color, which the container hides under the book view's own selection + val selectionBackground = LocalBookSelectionColor.current.takeOrElse { LocalTextSelectionColors.current.backgroundColor } + // The line's layout and place, for the Shift+arrow moves: dropped when the line leaves the composition + val selectionOwner = remember { Any() } + if (bookSelection != null) { + DisposableEffect(bookSelection, lineIndex) { onDispose { bookSelection.forgetLayout(lineIndex, selectionOwner) } } + } Text( text = displayText, textAlign = TextAlign.Justify, @@ -1674,7 +1737,9 @@ private fun LineItem( textModifier .then( if (bookSelection != null) { - Modifier.selectableLine(bookSelection, lineIndex) { noteLayout } + Modifier + .selectableLine(bookSelection, lineIndex) { noteLayout } + .onPlaced { bookSelection.publishCoordinates(lineIndex, selectionOwner, it) } } else { Modifier }, @@ -1706,6 +1771,7 @@ private fun LineItem( onTextLayout = { result -> noteLayout = result findMatchLocator?.publishLayout(lineId, result) + bookSelection?.publishLayout(lineIndex, selectionOwner, result) val cw = result.layoutInput.constraints.maxWidth if (cw > 0 && cw != Int.MAX_VALUE) onLayoutWidthMeasure(cw) }, diff --git a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookSelection.kt b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookSelection.kt index aee0e488d..aab783952 100644 --- a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookSelection.kt +++ b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookSelection.kt @@ -2,13 +2,20 @@ package io.github.kdroidfilter.seforimapp.features.bookcontent.ui.panels.bookcon import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.text.InlineTextContent +import androidx.compose.foundation.text.selection.LocalTextSelectionColors import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.text.selection.TextSelectionColors import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Stable +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @@ -27,6 +34,7 @@ import androidx.compose.ui.input.pointer.PointerType import androidx.compose.ui.input.pointer.isPrimaryPressed import androidx.compose.ui.input.pointer.isShiftPressed import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.text.Placeholder import androidx.compose.ui.text.PlaceholderVerticalAlign import androidx.compose.ui.text.TextLayoutResult @@ -40,9 +48,14 @@ import io.github.kdroidfilter.seforimapp.core.presentation.utils.rememberCopyToC import io.github.kdroidfilter.seforimlibrary.core.models.Line import io.github.kdroidfilter.seforimlibrary.dao.repository.SeforimRepository import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.jetbrains.skia.Codec import org.jetbrains.skia.Data +import kotlin.math.abs /** A character of the book: [offset] in the displayed text of the line at [lineIndex]. */ data class TextPoint( @@ -67,22 +80,54 @@ class BookSelection { var pressedAt: TextPoint? = null private set - /** The Shift+click selection, from its first character to its end in reading order; null without one. */ - var range: ClosedRange? by mutableStateOf(null) + /** The fixed end of the book view's own selection (Shift+click, Shift+arrows); null without one. */ + var anchor: TextPoint? by mutableStateOf(null) private set + /** The moving end of the book view's own selection, the one Shift+click and Shift+arrows move. */ + var focus: TextPoint? by mutableStateOf(null) + private set + + /** The book view's own selection, from its first character to its end in reading order; null without one. */ + val range: ClosedRange? + get() { + val from = anchor ?: return null + val to = focus ?: return null + return if (to < from) to..from else from..to + } + /** The current selection (Compose's or [range]) located in the book, once read from the database. */ var resolved: ResolvedSelection? by mutableStateOf(null) + /** + * Whether Compose holds a selection (a drag, a double click) right now, [resolved] locating it once read. Plain + * field: written by the selection's observer, read by the keys. + */ + var composeSelectionActive: Boolean = false + + /** True while [range] was last moved by the keyboard: its reading from the database can wait for the keys to rest. */ + var adjustedByKeys: Boolean = false + private set + + /** The x a run of Shift+Up/Down keeps to, as a text editor's goal column; null until the first vertical move. */ + var goalX: Float? = null + private set + + // The layouts and positions of the lines composed now, by line index, for the keyboard's moves + private val layouts = HashMap() + /** A primary press at [point]; true when it extends the selection, the press then being the book view's. */ fun press( point: TextPoint, shift: Boolean, ): Boolean { - val from = pressedAt + val from = anchor ?: pressedAt if (shift && from != null) { - range = if (point < from) point..from else from..point + anchor = from + focus = point resolved = null + adjustedByKeys = false + goalX = null return true } pressedAt = point @@ -91,17 +136,103 @@ class BookSelection { } fun clear() { - range = null + anchor = null + focus = null resolved = null + adjustedByKeys = false + goalX = null } - /** The offsets of [lineIndex]'s displayed text ([length] chars) inside the Shift+click selection. */ + /** + * Seeds [anchor] and [focus] from the current selection before the first keyboard move: the book view's own as + * it is; Compose's located one from its end nearest the press it started at, which stays fixed. False when + * nothing is selected (a plain click's caret does not start one, Shift+Up/Down then staying the line moves), or + * Compose's selection is not located yet. + */ + fun seedForKeys(): Boolean { + if (anchor != null && focus != null) return true + val compose = resolved?.takeIf { !it.owned }?.range ?: return false + val press = pressedAt ?: compose.start + if (press.distanceTo(compose.start) <= press.distanceTo(compose.endInclusive)) { + anchor = compose.start + focus = compose.endInclusive + } else { + anchor = compose.endInclusive + focus = compose.start + } + resolved = null + return true + } + + /** Moves [focus] to [point] from the keyboard, [anchor] staying; [goalX] is kept for vertical moves only. */ + fun extend( + point: TextPoint, + goalX: Float? = null, + ) { + if (anchor == null) anchor = focus ?: point + focus = point + resolved = null + adjustedByKeys = true + this.goalX = goalX + } + + /** The offsets of [lineIndex]'s displayed text ([length] chars) inside the book view's own selection. */ fun selectedRangeOf( lineIndex: Int, length: Int, ): IntRange = range?.offsetsIn(lineIndex, length) ?: IntRange.EMPTY + + /** Records the layout of [lineIndex] as composed by [owner] (a line's composition). */ + fun publishLayout( + lineIndex: Int, + owner: Any, + layout: TextLayoutResult, + ) { + layouts.getOrPut(lineIndex) { LineLayout(owner) }.also { + it.owner = owner + it.layout = layout + } + } + + /** Records where the text of [lineIndex] is placed, as composed by [owner]. */ + fun publishCoordinates( + lineIndex: Int, + owner: Any, + coordinates: LayoutCoordinates, + ) { + layouts.getOrPut(lineIndex) { LineLayout(owner) }.also { + it.owner = owner + it.coordinates = coordinates + } + } + + /** Forgets what [owner] published for [lineIndex], its composition leaving (another one may have taken over). */ + fun forgetLayout( + lineIndex: Int, + owner: Any, + ) { + if (layouts[lineIndex]?.owner === owner) layouts.remove(lineIndex) + } + + /** The layout of [lineIndex] while it is composed. */ + fun layoutOf(lineIndex: Int): TextLayoutResult? = layouts[lineIndex]?.layout + + /** Where the text of [lineIndex] is placed while it is composed and attached. */ + fun coordinatesOf(lineIndex: Int): LayoutCoordinates? = layouts[lineIndex]?.coordinates?.takeIf { it.isAttached } + + private class LineLayout( + var owner: Any, + ) { + var layout: TextLayoutResult? = null + var coordinates: LayoutCoordinates? = null + } } +// Lines apart first, then characters: the end of a selection nearer a press +private fun TextPoint.distanceTo(other: TextPoint): Pair = abs(lineIndex - other.lineIndex) to abs(offset - other.offset) + +private operator fun Pair.compareTo(other: Pair): Int = compareValuesBy(this, other, { it.first }, { it.second }) + /** The offsets of [lineIndex]'s displayed text ([length] chars) inside this range, empty when outside. */ internal fun ClosedRange.offsetsIn( lineIndex: Int, @@ -130,6 +261,12 @@ data class ResolvedSelection( /** The [BookSelection] of the book view around the current SelectionContainer; null elsewhere (commentaries…). */ val LocalBookSelection = staticCompositionLocalOf { null } +/** + * The color the book view draws its own selection in: Compose's selection color, captured before the container hides + * Compose's highlight under the book view's selection. + */ +val LocalBookSelectionColor = compositionLocalOf { Color.Unspecified } + /** A [SelectionContainer] whose lines record their presses in [selection], extend it on Shift+click, and copy it. */ @Composable fun BookSelectionContainer( @@ -138,7 +275,15 @@ fun BookSelectionContainer( content: @Composable () -> Unit, ) { val copyToClipboard = rememberCopyToClipboard() - CompositionLocalProvider(LocalBookSelection provides selection) { + val scope = rememberCoroutineScope() + val selectionColors = LocalTextSelectionColors.current + // While the book view's own selection is drawn, Compose's (a drag it was seeded from) would stay drawn under it + val hiddenColors = remember(selectionColors) { TextSelectionColors(selectionColors.handleColor, Color.Transparent) } + val ownSelection by remember(selection) { derivedStateOf { selection?.range != null } } + CompositionLocalProvider( + LocalBookSelection provides selection, + LocalBookSelectionColor provides selectionColors.backgroundColor, + ) { // On the container itself: its own Ctrl/Cmd+C would copy its (empty) selection SelectionContainer( modifier = @@ -157,19 +302,33 @@ fun BookSelectionContainer( Modifier }, ).onPreviewKeyEvent { event -> - val owned = selection?.resolved?.takeIf { it.owned } - if (owned != null && event.isPlainCopy()) { - copyToClipboard(owned.text) - true + if (selection?.range == null || !event.isPlainCopy()) return@onPreviewKeyEvent false + val owned = selection.resolved?.takeIf { it.owned } + if (owned != null) { + if (owned.text.isNotEmpty()) copyToClipboard(owned.text) } else { - false + // Moved by the keys and not read yet: the copy waits for it rather than take Compose's + scope.launch { + val read = + withTimeoutOrNull(COPY_WAIT_MS) { + snapshotFlow { selection.resolved?.takeIf { it.owned } }.filterNotNull().first() + } + read?.text?.takeIf { it.isNotEmpty() }?.let { copyToClipboard(it) } + } } + true }, - content = content, - ) + ) { + CompositionLocalProvider(LocalTextSelectionColors provides if (ownSelection) hiddenColors else selectionColors) { + content() + } + } } } +// How long a copy waits for a selection the keys just moved to be read +private const val COPY_WAIT_MS = 2_000L + /** * A line's primary presses for [selection], [layout] giving the character under the pointer (null while the line is a * placeholder). A Shift+press extending diff --git a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/SelectionMotion.kt b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/SelectionMotion.kt new file mode 100644 index 000000000..55c634636 --- /dev/null +++ b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/SelectionMotion.kt @@ -0,0 +1,214 @@ +package io.github.kdroidfilter.seforimapp.features.bookcontent.ui.panels.bookcontent.views + +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.isAltPressed +import androidx.compose.ui.input.key.isCtrlPressed +import androidx.compose.ui.input.key.isMetaPressed +import androidx.compose.ui.input.key.isShiftPressed +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.type +import androidx.compose.ui.text.TextLayoutResult +import java.text.Bidi +import java.text.BreakIterator + +/* + * The moves of a selection's focus by Shift+arrow keys, as in a text editor: a character, a word, a visual line. + * Points are characters of book lines ([TextPoint]); `textOf` gives a line's displayed text, null past the book's + * ends or for a line not loaded, which the moves then stop before. Pure, the layouts behind [LineGeometry]. + */ + +/** The visual lines of a laid-out book line, as the vertical moves read them. */ +internal interface LineGeometry { + val length: Int + val lineCount: Int + + fun lineOf(offset: Int): Int + + fun xOf(offset: Int): Float + + fun offsetAt( + visualLine: Int, + x: Float, + ): Int +} + +internal fun TextLayoutResult.geometry(): LineGeometry = + object : LineGeometry { + override val length get() = layoutInput.text.length + override val lineCount get() = this@geometry.lineCount + + override fun lineOf(offset: Int) = getLineForOffset(offset.coerceIn(0, length)) + + override fun xOf(offset: Int) = getHorizontalPosition(offset.coerceIn(0, length), usePrimaryDirection = true) + + override fun offsetAt( + visualLine: Int, + x: Float, + ): Int { + val y = (getLineTop(visualLine) + getLineBottom(visualLine)) / 2 + return getOffsetForPosition(Offset(x, y)) + } + } + +/** + * Whether Left or Right ([left]) moves toward the end of the text. The arrows follow the screen, as in a text editor: + * Hebrew runs right to left, so in a right-to-left line Left moves toward the end (the next letter, the one on its + * left) and Right toward the start; in a left-to-right line the reverse. The direction is the focus's line's, from + * its text (its first strong character), so a book mixing Hebrew and Latin lines feels natural in both. Moves are + * logical within the line (by offset), as a text editor's caret is across a short embedded run of the other direction. + */ +internal fun towardsEnd( + left: Boolean, + rtl: Boolean, +): Boolean = left == rtl + +/** Whether [text]'s paragraph runs right to left; a line without a strong character takes the book's direction. */ +internal fun isRtlText(text: String): Boolean = text.isEmpty() || !Bidi(text, Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT).baseIsLeftToRight() + +/** + * [focus] moved by one character toward the end ([forward]) or the start of the text: a letter with its nikud and + * teamim (a grapheme), the end of a line and the start of the next being one step apart, as the copied text's line + * break is. + */ +internal fun moveByCharacter( + focus: TextPoint, + forward: Boolean, + textOf: (Int) -> String?, +): TextPoint { + val text = textOf(focus.lineIndex) ?: return focus + val offset = focus.offset.coerceIn(0, text.length) + val characters = BreakIterator.getCharacterInstance().apply { setText(text) } + return when { + forward && offset < text.length -> TextPoint(focus.lineIndex, characters.following(offset)) + forward -> if (textOf(focus.lineIndex + 1) != null) TextPoint(focus.lineIndex + 1, 0) else TextPoint(focus.lineIndex, offset) + offset > 0 -> TextPoint(focus.lineIndex, characters.preceding(offset)) + else -> textOf(focus.lineIndex - 1)?.let { TextPoint(focus.lineIndex - 1, it.length) } ?: TextPoint(focus.lineIndex, 0) + } +} + +/** + * [focus] moved by one word: toward the end ([forward]) to the end of the word it is in or the next one, toward the + * start to the start of the word it is in or the previous one; from a line's edge, to the adjacent line's. + */ +internal fun moveByWord( + focus: TextPoint, + forward: Boolean, + textOf: (Int) -> String?, +): TextPoint { + val text = textOf(focus.lineIndex) ?: return focus + val offset = focus.offset.coerceIn(0, text.length) + if (forward && offset == text.length) return moveByCharacter(focus, forward = true, textOf) + if (!forward && offset == 0) return moveByCharacter(focus, forward = false, textOf) + val words = wordsOf(text) + val moved = + if (forward) { + words.firstOrNull { it.last + 1 > offset }?.let { it.last + 1 } ?: text.length + } else { + words.lastOrNull { it.first < offset }?.first ?: 0 + } + return TextPoint(focus.lineIndex, moved) +} + +/** + * The words of [text] (segments holding a letter or a digit), by their offsets. A geresh or gershayim between + * letters (רש״י, ר׳) is inside its word, which the JDK's word breaks are not aware of. + */ +internal fun wordsOf(text: String): List { + val boundaries = BreakIterator.getWordInstance().apply { setText(text) } + val words = mutableListOf() + var start = boundaries.first() + var end = boundaries.next() + while (end != BreakIterator.DONE) { + if ((start until end).any { text[it].isLetterOrDigit() }) { + val previous = words.lastOrNull() + words += + if (previous != null && previous.last + 2 == start && text[start - 1] in IN_WORD_MARKS) { + words.removeAt(words.lastIndex) + previous.first until end + } else { + start until end + } + } + start = end + end = boundaries.next() + } + return words +} + +// Geresh and gershayim, Hebrew and as typed (an apostrophe, a double quote): part of an abbreviation's word +private const val IN_WORD_MARKS = "׳״'\"" + +/** + * [focus] moved by one visual line, [down] or up, at the x [goalX] (the focus's own when null) — returned with the + * x it kept to. On the first or last visual line of a book line it moves into the adjacent book line, at the same x + * when that line is laid out, else at the same offset; without a layout for the focus's line, at the same offset. + * Past the book's first or last line it goes to that line's start or end. + */ +internal fun moveByVisualLine( + focus: TextPoint, + down: Boolean, + goalX: Float?, + geometryOf: (Int) -> LineGeometry?, + textOf: (Int) -> String?, +): Pair { + val target = focus.lineIndex + if (down) 1 else -1 + val geometry = geometryOf(focus.lineIndex) + + fun sameOffset(): Pair { + val targetText = textOf(target) + if (targetText == null) { + val length = geometry?.length ?: textOf(focus.lineIndex)?.length ?: focus.offset + return TextPoint(focus.lineIndex, if (down) length else 0) to goalX + } + return TextPoint(target, focus.offset.coerceIn(0, targetText.length)) to goalX + } + + if (geometry == null) return sameOffset() + val offset = focus.offset.coerceIn(0, geometry.length) + val x = goalX ?: geometry.xOf(offset) + val visualLine = geometry.lineOf(offset) + if (down) 1 else -1 + if (visualLine in 0 until geometry.lineCount) return TextPoint(focus.lineIndex, geometry.offsetAt(visualLine, x)) to x + val next = geometryOf(target) ?: return sameOffset().let { (point, _) -> point to x } + return TextPoint(target, next.offsetAt(if (down) 0 else next.lineCount - 1, x)) to x +} + +/** + * Shift+Left/Right (a character; a word with Ctrl) and Shift+Up/Down (a visual line) move the selection's focus, as + * in a text editor, the first move seeding it from the current selection ([BookSelection.seedForKeys]). [textOf] + * gives a line's displayed text, null past the book's ends or for a line not loaded. True when the key is taken: + * moved, or held while Compose's selection is still being located. False, the key left to the other handlers, for + * other keys and without a selection to move from. Ctrl+Shift+Up/Down and any Alt or Meta combination + * (Ctrl+Alt+Left/Right is the window's) are not moves. + */ +fun BookSelection.moveFocusByKey( + event: KeyEvent, + textOf: (Int) -> String?, +): Boolean { + if (event.type != KeyEventType.KeyDown || !event.isShiftPressed || event.isAltPressed || event.isMetaPressed) return false + val horizontal = event.key == Key.DirectionLeft || event.key == Key.DirectionRight + val vertical = event.key == Key.DirectionUp || event.key == Key.DirectionDown + if (!horizontal && !(vertical && !event.isCtrlPressed)) return false + if (!seedForKeys()) return composeSelectionActive + val from = focus ?: return false + if (horizontal) { + // From the text itself (its first strong character), not the layout's paragraph direction: Hebrew runs right + // to left on screen even in a paragraph laid out left to right + val rtl = isRtlText(layoutOf(from.lineIndex)?.layoutInput?.text?.text ?: textOf(from.lineIndex).orEmpty()) + val forward = towardsEnd(left = event.key == Key.DirectionLeft, rtl = rtl) + extend(if (event.isCtrlPressed) moveByWord(from, forward, textOf) else moveByCharacter(from, forward, textOf)) + } else { + val (moved, goalX) = + moveByVisualLine( + focus = from, + down = event.key == Key.DirectionDown, + goalX = goalX, + geometryOf = { layoutOf(it)?.geometry() }, + textOf = textOf, + ) + extend(moved, goalX) + } + return true +} diff --git a/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ShiftArrowSelectionUiTest.kt b/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ShiftArrowSelectionUiTest.kt new file mode 100644 index 000000000..751b22284 --- /dev/null +++ b/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ShiftArrowSelectionUiTest.kt @@ -0,0 +1,208 @@ +package io.github.kdroidfilter.seforimapp.features.bookcontent + +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.BasicText +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.layout.onPlaced +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.click +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performMouseInput +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.test.withKeyDown +import androidx.compose.ui.text.TextLayoutResult +import io.github.kdroidfilter.seforimapp.features.bookcontent.ui.panels.bookcontent.views.BookSelection +import io.github.kdroidfilter.seforimapp.features.bookcontent.ui.panels.bookcontent.views.BookSelectionContainer +import io.github.kdroidfilter.seforimapp.features.bookcontent.ui.panels.bookcontent.views.TextPoint +import io.github.kdroidfilter.seforimapp.features.bookcontent.ui.panels.bookcontent.views.moveFocusByKey +import io.github.kdroidfilter.seforimapp.features.bookcontent.ui.panels.bookcontent.views.selectableLine +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Shift+arrows adjust the book view's selection, as in a text editor: lines recording their presses and + * layouts as the book view's do, and the container's key handler moving the focus first, as BookContentView's does. + */ +@OptIn(ExperimentalTestApi::class) +class ShiftArrowSelectionUiTest { + private val lines = listOf("בראשית ברא אלהים", "את השמים ואת הארץ", "והארץ היתה תהו ובהו") + + private fun ComposeUiTest.setBook( + selection: BookSelection, + plainKeys: MutableList, + ) { + val focusRequester = FocusRequester() + setContent { + BookSelectionContainer( + selection = selection, + modifier = + Modifier + .fillMaxSize() + .focusRequester(focusRequester) + .onPreviewKeyEvent { event -> + when { + selection.moveFocusByKey(event) { lines.getOrNull(it) } -> true + event.type == KeyEventType.KeyDown -> { + plainKeys += event.key + false + } + else -> false + } + }.focusable(), + ) { + Column { + lines.forEachIndexed { i, text -> + val owner = remember { Any() } + val layout = remember { arrayOfNulls(1) } + BasicText( + text, + Modifier + .fillMaxWidth() + .testTag("l$i") + .selectableLine(selection, i) { layout[0] } + .onPlaced { selection.publishCoordinates(i, owner, it) }, + onTextLayout = { + layout[0] = it + selection.publishLayout(i, owner, it) + }, + ) + } + } + } + } + waitForIdle() + focusRequester.requestFocus() + waitForIdle() + } + + /** + * A click in the middle of line 0 then a one-character extension past it, as a Shift+click makes (that one's + * pointer path is ShiftClickSelectionUiTest's): the anchor at the click, the focus one character later. + */ + private fun ComposeUiTest.selectInFirstLine(selection: BookSelection): Pair { + // On the 8th character's box (the line is narrower than its node, and right to left) + val box = runOnIdle { assertNotNull(selection.layoutOf(0)).getBoundingBox(8) } + onNodeWithTag("l0").performMouseInput { click(box.center) } + waitForIdle() + val pressed = assertNotNull(selection.pressedAt) + assertEquals(0, pressed.lineIndex) + assertTrue(pressed.offset in 3..lines[0].length - 4, "a click inside the line: $pressed") + runOnIdle { assertTrue(selection.press(TextPoint(0, pressed.offset + 1), shift = true)) } + return assertNotNull(selection.anchor) to assertNotNull(selection.focus) + } + + @Test + fun `shift arrows adjust a selection's focus, left toward the end of hebrew text`() = + runComposeUiTest { + val selection = BookSelection() + val plainKeys = mutableStateListOf() + setBook(selection, plainKeys) + + val (anchor, start) = selectInFirstLine(selection) + assertEquals(0, anchor.lineIndex) + assertEquals(0, start.lineIndex) + assertEquals(TextPoint(0, anchor.offset + 1), start) + + // Right to left: Shift+Left selects the next characters + onNodeWithTag("l0").performKeyInput { + withKeyDown(Key.ShiftLeft) { + pressKey(Key.DirectionLeft) + pressKey(Key.DirectionLeft) + } + } + waitForIdle() + assertEquals(anchor, selection.anchor) + assertEquals(anchor..TextPoint(0, start.offset + 2), selection.range) + + // Shift+Right goes back, then past the anchor, which stays + onNodeWithTag("l0").performKeyInput { + withKeyDown(Key.ShiftLeft) { repeat(5) { pressKey(Key.DirectionRight) } } + } + waitForIdle() + assertEquals(anchor, selection.anchor) + assertEquals(TextPoint(0, anchor.offset - 2)..anchor, selection.range) + + // Shift+Down into the next line, the anchor staying + onNodeWithTag("l0").performKeyInput { withKeyDown(Key.ShiftLeft) { pressKey(Key.DirectionDown) } } + waitForIdle() + assertEquals(anchor, selection.anchor) + assertEquals(1, selection.focus?.lineIndex) + + // Ctrl+Shift+Left: to the end of a word + val before = assertNotNull(selection.focus) + onNodeWithTag("l0").performKeyInput { + withKeyDown(Key.CtrlLeft) { withKeyDown(Key.ShiftLeft) { pressKey(Key.DirectionLeft) } } + } + waitForIdle() + val after = assertNotNull(selection.focus) + assertTrue(after > before, "$after after $before") + val text = lines[after.lineIndex] + assertTrue(after.offset == text.length || text[after.offset] == ' ', "a word's end: $after") + assertTrue(plainKeys.none { it == Key.DirectionLeft || it == Key.DirectionRight || it == Key.DirectionDown }) + } + + @Test + fun `without a selection shift arrows and plain arrows are left to the view`() = + runComposeUiTest { + val selection = BookSelection() + val plainKeys = mutableStateListOf() + setBook(selection, plainKeys) + + onNodeWithTag("l0").performKeyInput { + withKeyDown(Key.ShiftLeft) { pressKey(Key.DirectionDown) } + pressKey(Key.DirectionDown) + } + waitForIdle() + assertNull(selection.range) + assertEquals(2, plainKeys.count { it == Key.DirectionDown }) + + // A click is no selection: plain and Shift arrows still are the view's (its line moves) + onNodeWithTag("l1").performMouseInput { click(center) } + waitForIdle() + onNodeWithTag("l1").performKeyInput { + pressKey(Key.DirectionUp) + withKeyDown(Key.ShiftLeft) { + pressKey(Key.DirectionUp) + pressKey(Key.DirectionLeft) + } + } + waitForIdle() + assertNull(selection.range) + assertEquals(2, plainKeys.count { it == Key.DirectionUp }) + assertEquals(1, plainKeys.count { it == Key.DirectionLeft }) + } + + @Test + fun `a plain click drops the keys' selection`() = + runComposeUiTest { + val selection = BookSelection() + setBook(selection, mutableListOf()) + + selectInFirstLine(selection) + onNodeWithTag("l0").performKeyInput { withKeyDown(Key.ShiftLeft) { pressKey(Key.DirectionLeft) } } + waitForIdle() + assertNotNull(selection.range) + onNodeWithTag("l2").performMouseInput { click(center) } + waitForIdle() + assertNull(selection.range) + } +} diff --git a/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookSelectionTest.kt b/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookSelectionTest.kt index 7fad52431..bb65d0c86 100644 --- a/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookSelectionTest.kt +++ b/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/BookSelectionTest.kt @@ -129,4 +129,118 @@ class BookSelectionTest { val mode = io.github.kdroidfilter.seforimapp.core.presentation.text.DiacriticsMode.None assertNull(highlightRangesOf(TextPoint(4, 0)..TextPoint(4, 4), listOf(line), mode)) } + + // ==================== Anchor and focus (Shift+arrows) ==================== + + @Test + fun `a Shift press sets the anchor and the focus, the range sorted`() { + val selection = BookSelection() + selection.press(TextPoint(5, 2), shift = false) + selection.press(TextPoint(3, 1), shift = true) + assertEquals(TextPoint(5, 2), selection.anchor) + assertEquals(TextPoint(3, 1), selection.focus) + assertEquals(TextPoint(3, 1)..TextPoint(5, 2), selection.range) + } + + @Test + fun `extending moves the focus only, across the anchor`() { + val selection = BookSelection() + selection.press(TextPoint(2, 5), shift = false) + selection.press(TextPoint(2, 5), shift = true) + assertTrue(selection.seedForKeys()) + selection.extend(TextPoint(2, 6)) + assertEquals(TextPoint(2, 5)..TextPoint(2, 6), selection.range) + selection.extend(TextPoint(2, 4)) + assertEquals(TextPoint(2, 5), selection.anchor) + assertEquals(TextPoint(2, 4)..TextPoint(2, 5), selection.range) + assertTrue(selection.adjustedByKeys) + } + + @Test + fun `back on the anchor the selection is empty but kept`() { + val selection = BookSelection() + selection.press(TextPoint(2, 5), shift = false) + selection.press(TextPoint(2, 5), shift = true) + assertTrue(selection.seedForKeys()) + selection.extend(TextPoint(2, 6)) + selection.extend(TextPoint(2, 5)) + assertEquals(TextPoint(2, 5)..TextPoint(2, 5), selection.range) + assertTrue(selection.selectedRangeOf(2, 10).isEmpty()) + } + + @Test + fun `nothing to seed from without a selection`() { + assertFalse(BookSelection().seedForKeys()) + // A plain click is a caret, not a selection: Shift+arrows stay the view's line moves + val clicked = BookSelection() + clicked.press(TextPoint(2, 5), shift = false) + assertFalse(clicked.seedForKeys()) + assertNull(clicked.range) + } + + @Test + fun `a Shift+click selection is adjusted from its own focus`() { + val selection = BookSelection() + selection.press(TextPoint(2, 5), shift = false) + selection.press(TextPoint(4, 1), shift = true) + assertTrue(selection.seedForKeys()) + assertEquals(TextPoint(2, 5), selection.anchor) + assertEquals(TextPoint(4, 1), selection.focus) + } + + @Test + fun `a Compose selection is anchored at its end nearest the press`() { + val down = BookSelection() + down.press(TextPoint(2, 9), shift = false) + down.resolved = ResolvedSelection("x", TextPoint(2, 9)..TextPoint(4, 5), emptyList(), owned = false) + assertTrue(down.seedForKeys()) + assertEquals(TextPoint(2, 9), down.anchor) + assertEquals(TextPoint(4, 5), down.focus) + assertNull(down.resolved) + + // Dragged upward: pressed at the end + val up = BookSelection() + up.press(TextPoint(4, 5), shift = false) + up.resolved = ResolvedSelection("x", TextPoint(2, 9)..TextPoint(4, 5), emptyList(), owned = false) + up.seedForKeys() + assertEquals(TextPoint(4, 5), up.anchor) + assertEquals(TextPoint(2, 9), up.focus) + } + + @Test + fun `a Compose selection not located yet is not replaced by the caret`() { + val selection = BookSelection() + selection.press(TextPoint(2, 9), shift = false) + selection.composeSelectionActive = true + assertFalse(selection.seedForKeys()) + assertNull(selection.range) + } + + @Test + fun `a Shift press after the keys extends from their anchor`() { + val selection = BookSelection() + selection.press(TextPoint(2, 9), shift = false) + selection.resolved = ResolvedSelection("x", TextPoint(2, 9)..TextPoint(4, 5), emptyList(), owned = false) + selection.seedForKeys() + selection.extend(TextPoint(4, 6)) + assertTrue(selection.press(TextPoint(6, 0), shift = true)) + assertEquals(TextPoint(2, 9)..TextPoint(6, 0), selection.range) + // A plain press drops it all + selection.press(TextPoint(1, 0), shift = false) + assertNull(selection.anchor) + assertNull(selection.focus) + assertNull(selection.goalX) + } + + @Test + fun `the goal x is kept by vertical moves only`() { + val selection = BookSelection() + selection.press(TextPoint(1, 0), shift = false) + selection.press(TextPoint(1, 3), shift = true) + assertTrue(selection.seedForKeys()) + selection.extend(TextPoint(2, 0), goalX = 40f) + assertEquals(40f, selection.goalX) + selection.extend(TextPoint(2, 1)) + assertNull(selection.goalX) + } } diff --git a/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/SelectionMotionTest.kt b/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/SelectionMotionTest.kt new file mode 100644 index 000000000..681685094 --- /dev/null +++ b/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/features/bookcontent/ui/panels/bookcontent/views/SelectionMotionTest.kt @@ -0,0 +1,163 @@ +package io.github.kdroidfilter.seforimapp.features.bookcontent.ui.panels.bookcontent.views + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class SelectionMotionTest { + private val lines = mapOf(0 to "בראשית ברא", 1 to "את השמים", 2 to "ואת הארץ") + private val textOf: (Int) -> String? = { lines[it] } + + // ==================== Direction ==================== + + @Test + fun `left moves toward the end in a right-to-left paragraph, right in a left-to-right one`() { + assertTrue(towardsEnd(left = true, rtl = true)) + assertFalse(towardsEnd(left = false, rtl = true)) + assertTrue(towardsEnd(left = false, rtl = false)) + assertFalse(towardsEnd(left = true, rtl = false)) + } + + @Test + fun `a paragraph's direction from its text`() { + assertTrue(isRtlText("בראשית ברא")) + assertFalse(isRtlText("In the beginning")) + // No strong character: the book's direction + assertTrue(isRtlText("12, 13")) + assertTrue(isRtlText("")) + } + + // ==================== Characters ==================== + + @Test + fun `a character forward and back within a line`() { + assertEquals(TextPoint(0, 4), moveByCharacter(TextPoint(0, 3), forward = true, textOf)) + assertEquals(TextPoint(0, 2), moveByCharacter(TextPoint(0, 3), forward = false, textOf)) + } + + @Test + fun `a character crosses into the adjacent line at the edges`() { + assertEquals(TextPoint(1, 0), moveByCharacter(TextPoint(0, 10), forward = true, textOf)) + assertEquals(TextPoint(0, 10), moveByCharacter(TextPoint(1, 0), forward = false, textOf)) + } + + @Test + fun `a character stops at the book's ends`() { + assertEquals(TextPoint(2, 8), moveByCharacter(TextPoint(2, 8), forward = true, textOf)) + assertEquals(TextPoint(0, 0), moveByCharacter(TextPoint(0, 0), forward = false, textOf)) + } + + @Test + fun `a letter moves with its nikud`() { + // בְּ: bet, sheva, dagesh, one character on screen + val pointed = mapOf(0 to "בְּרֵאשִׁית") + assertEquals(TextPoint(0, 3), moveByCharacter(TextPoint(0, 0), forward = true) { pointed[it] }) + assertEquals(TextPoint(0, 0), moveByCharacter(TextPoint(0, 3), forward = false) { pointed[it] }) + } + + @Test + fun `an offset past the line's end is taken as its end`() { + assertEquals(TextPoint(0, 9), moveByCharacter(TextPoint(0, 99), forward = false, textOf)) + } + + // ==================== Words ==================== + + @Test + fun `a word forward goes to the end of the word, then of the next`() { + assertEquals(TextPoint(0, 6), moveByWord(TextPoint(0, 0), forward = true, textOf)) + assertEquals(TextPoint(0, 6), moveByWord(TextPoint(0, 2), forward = true, textOf)) + assertEquals(TextPoint(0, 10), moveByWord(TextPoint(0, 6), forward = true, textOf)) + } + + @Test + fun `a word back goes to the start of the word, then of the previous`() { + assertEquals(TextPoint(0, 7), moveByWord(TextPoint(0, 10), forward = false, textOf)) + assertEquals(TextPoint(0, 0), moveByWord(TextPoint(0, 7), forward = false, textOf)) + assertEquals(TextPoint(0, 0), moveByWord(TextPoint(0, 3), forward = false, textOf)) + } + + @Test + fun `a word crosses lines from a line's edge`() { + assertEquals(TextPoint(1, 0), moveByWord(TextPoint(0, 10), forward = true, textOf)) + assertEquals(TextPoint(0, 10), moveByWord(TextPoint(1, 0), forward = false, textOf)) + } + + @Test + fun `punctuation is not a word, an abbreviation is one`() { + val text = mapOf(0 to "אמר רש״י, וכן") + assertEquals(listOf(0 until 3, 4 until 8, 10 until 13), wordsOf(text.getValue(0))) + assertEquals(TextPoint(0, 13), moveByWord(TextPoint(0, 8), forward = true) { text[it] }) + } + + // ==================== Visual lines ==================== + + /** A line wrapped every [perLine] characters, each [width] px wide; x grows with the offset (direction aside). */ + private class Wrapped( + override val length: Int, + private val perLine: Int, + private val width: Float = 10f, + ) : LineGeometry { + override val lineCount = (length + perLine - 1) / perLine + + override fun lineOf(offset: Int) = (offset / perLine).coerceAtMost(lineCount - 1) + + override fun xOf(offset: Int) = (offset - lineOf(offset) * perLine) * width + + override fun offsetAt( + visualLine: Int, + x: Float, + ): Int { + val start = visualLine * perLine + val end = minOf(start + perLine, length) + return (start + (x / width).toInt()).coerceIn(start, end) + } + } + + @Test + fun `down and up within a wrapped line keep the x`() { + val geometry = Wrapped(length = 30, perLine = 10) + val (down, x) = moveByVisualLine(TextPoint(0, 3), down = true, goalX = null, geometryOf = { geometry }, textOf = { "x".repeat(30) }) + assertEquals(TextPoint(0, 13), down) + assertEquals(30f, x) + val (up, _) = moveByVisualLine(down, down = false, goalX = x, geometryOf = { geometry }, textOf = { "x".repeat(30) }) + assertEquals(TextPoint(0, 3), up) + } + + @Test + fun `the goal x is kept through a short line`() { + val geometries = mapOf(0 to Wrapped(30, 10), 1 to Wrapped(2, 10), 2 to Wrapped(30, 10)) + val texts = mapOf(0 to "x".repeat(30), 1 to "xx", 2 to "x".repeat(30)) + val (short, x) = moveByVisualLine(TextPoint(0, 27), true, null, { geometries[it] }, { texts[it] }) + assertEquals(TextPoint(1, 2), short) + val (back, _) = moveByVisualLine(short, true, x, { geometries[it] }, { texts[it] }) + assertEquals(TextPoint(2, 7), back) + } + + @Test + fun `from the last visual line down into the next book line's first, from the first up into the previous one's last`() { + val geometries = mapOf(0 to Wrapped(25, 10), 1 to Wrapped(25, 10)) + val texts = mapOf(0 to "x".repeat(25), 1 to "x".repeat(25)) + assertEquals(TextPoint(1, 4), moveByVisualLine(TextPoint(0, 24), true, null, { geometries[it] }, { texts[it] }).first) + assertEquals(TextPoint(0, 23), moveByVisualLine(TextPoint(1, 3), false, null, { geometries[it] }, { texts[it] }).first) + } + + @Test + fun `into a line not laid out at the same offset`() { + val geometry = Wrapped(10, 10) + assertEquals( + TextPoint(1, 4), + moveByVisualLine(TextPoint(0, 4), true, null, { if (it == 0) geometry else null }, textOf).first, + ) + // Without the focus line's layout either + assertEquals(TextPoint(2, 5), moveByVisualLine(TextPoint(1, 5), true, null, { null }, textOf).first) + // Cut to the shorter line + assertEquals(TextPoint(1, 8), moveByVisualLine(TextPoint(0, 10), true, null, { null }, textOf).first) + } + + @Test + fun `past the book's ends, to the line's start or end`() { + assertEquals(TextPoint(2, 8), moveByVisualLine(TextPoint(2, 3), true, null, { null }, textOf).first) + assertEquals(TextPoint(0, 0), moveByVisualLine(TextPoint(0, 3), false, null, { null }, textOf).first) + } +}