Modern Apps git

← Modern-Apps.git

nonogram: pinch-zoom and pan the grid, and undo the last stroke (#ux-audit)

Commit
8b2feb9e32c7519dbc2e0c0085c03d76e5b6f7d1
Author
Vayun Mathur <[email protected]>
When
2026-11-13 01:27 UTC (23 days ago)
Parents
a02fb80
Symptom: on 15x15 boards a phone cell is ~16dp - a third of the 48dp
touch-target guideline - so mis-taps were common, every mis-tap in
fill mode cost a heart, and there was no way to zoom in or take a
mis-placed mark back.

Root cause: NonogramBoard always laid the grid out at width / cells
with no transform, and the ViewModel had no move history.

Zoom and pan:
- New pure BoardZoom (scale + offsets in units of the grid side) and
  GridViewport (hit-testing, clue centres and grid-line positions).
  Offsets are fractions of the side, so a zoom survives a size change
  (rotation, resize, fold) and still shows the same cells.
- Two fingers pinch about their centre and pan with it. Clamped to
  1x..maxZoom and so the zoomed grid always covers its viewport;
  maxZoom brings a cell to ~64dp, capped at 4x (4x on a 15x15 phone,
  ~1.5x on a 5x5). A second finger landing mid-stroke ends the stroke
  and turns the rest of the gesture into a pinch.
- All touches are hit-tested in grid coordinates through the zoom,
  with the point clamped to the visible viewport, so a drag off the
  edge never edits cells scrolled out of view. RTL mirroring still
  applies under zoom.
- The cells are drawn through a graphicsLayer (semantics bounds follow
  it, so TalkBack still finds every cell); grid lines are drawn in
  viewport space so they stay hairline at any zoom.
- Clue stacks keep their size but are placed over wherever their line
  is drawn (a custom Layout reading the zoom only at placement), so
  clues stay aligned with the grid and are clipped when panned away.
- Double-tap on the clues or corner resets the zoom. Not on the grid:
  grid taps must fire immediately, which rules out waiting for a
  possible second tap.
- Zoom is rememberSaveable and resets on a new puzzle; a pinch never
  recomposes the board (state is read only in layout/draw/gestures).

Undo:
- Undo button beside Restart reverts the last stroke's fills and
  notes (history of up to 100 strokes, in memory, cleared on restart,
  new level, mode switch or day change).
- It fits the hearts model by never giving anything back: revealed
  mistakes stay revealed and spent hearts stay spent (pure
  NonogramMoves.undo), so undo fixes slips but can't be used to retry
  a wrong guess. Strokes that only revealed a mistake aren't pushed.
  Disabled once the board is won or failed.
- ClueMetrics / GridStyle bundle parameters to keep the composables
  within detekt's parameter limit.

User-visible effect: pinch to zoom dense boards to comfortable cell
sizes, pan with two fingers, double-tap the clues to reset; Undo
takes back the last fill/cross stroke without refunding hearts.

Verification: BoardGeometryTest (zoomed hit-testing LTR/RTL, clamping
to the visible area, size-change invariance, clues aligned through
zoom, pinch anchoring and clamps), NonogramMovesTest undo cases, a
Robolectric VM test (undo keeps the revealed mistake and the heart,
persists, and restart clears history), and Compose tests for the Undo
button and a real pinch: the same physical tap maps to column 4 when
zoomed and column 5 after the double-tap reset.

Diff

games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.ktindex 3e8a14048a..ad3be85843 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramMoves.kt@@ -38,6 +38,20 @@ object NonogramMoves {         return if (notes == game.crossed) game else game.copy(crossed = notes)     } +    /**+     * Takes [current] back to the marks it had at [before], without giving anything back.+     *+     * Fills and notes return to how they were, but every blank a mistake revealed stays revealed and+     * every heart spent stays spent — so undo is for a slip of the finger, never a way to un-make a+     * wrong guess and try the cell again. A note that sat on a cell the undone move revealed is not+     * restored, since that cell is settled now.+     */+    fun undo(current: NonogramGameState, before: NonogramGameState): NonogramGameState =+        current.copy(+            filled = before.filled - current.revealedBlanks,+            crossed = before.crossed - current.revealedBlanks,+        )+     /** Flips the note on [index]: the single-tap behaviour of cross mode. */     fun toggleNote(game: NonogramGameState, index: Int): NonogramGameState =         setNote(game, index, crossed = index !in game.crossed)
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.ktindex 1765302b02..b531c55a8d 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt@@ -33,6 +33,9 @@ interface NonogramGameActions {     /** The stroke's finger lifted (or the gesture was cancelled). */     fun endStroke() {} +    /** Reverts the last stroke's fills and notes. Never refunds a heart or hides a revealed blank. */+    fun undo() {}+     fun setMarkMode(mode: MarkMode) {}     fun nextLevel() {}     fun restartLevel() {}@@ -61,6 +64,8 @@ data class NonogramUiState(     val generating: Boolean = false,     /** Set when even a widened seed search found no fair puzzle, so the board can offer a retry. */     val generationFailed: Boolean = false,+    /** Whether there is a stroke to undo on the board in play. */+    val canUndo: Boolean = false, )  interface SettingsActions {
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.ktindex 6bd833fab8..03bc2f8f87 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt@@ -14,6 +14,7 @@ import com.vayunmathur.games.nonogram.data.STARTING_HEARTS import com.vayunmathur.games.nonogram.data.StoredBoard import com.vayunmathur.games.nonogram.data.sizeForLevel import com.vayunmathur.games.nonogram.domain.NonogramGenerator+import com.vayunmathur.games.nonogram.domain.NonogramMoves import com.vayunmathur.games.nonogram.domain.NonogramStrokes import com.vayunmathur.games.nonogram.domain.Stroke import com.vayunmathur.library.util.AchievementsManager@@ -169,8 +170,10 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application             val stale = daily && storedDay != day             (if (stale) StoredBoard() else board) to (lastCompleted == day)         }.collectLatest { (board, dailyDone) ->-            val onScreen = _uiState.value.game-                ?.takeIf { hasPendingWrites && it.isBoardFor(session, puzzle) }+            val previous = _uiState.value.game+            // Undo history belongs to one board; a different puzzle, level or mode starts afresh.+            if (previous?.isBoardFor(session, puzzle) != true) undoStack.clear()+            val onScreen = previous?.takeIf { hasPendingWrites && it.isBoardFor(session, puzzle) }             val game = onScreen ?: NonogramGameState(                 puzzle = puzzle,                 filled = board.filled,@@ -184,6 +187,7 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application                 game = game,                 generating = false,                 dailyDone = dailyDone,+                canUndo = canUndo(game),             )             if (game.isWon) onWin(game, daily, day)         }@@ -218,7 +222,7 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application     private fun commit(next: NonogramGameState) {         val previous = _uiState.value.game ?: return         if (next == previous) return-        _uiState.value = _uiState.value.copy(game = next)+        _uiState.value = _uiState.value.copy(game = next, canUndo = canUndo(next))         persist(next)         if (next.isWon) onWin(next, next.mode == GameMode.DAILY, boardDay)     }@@ -263,6 +267,17 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application     /** The stroke in progress, if a finger is down on the grid. See [NonogramStrokes]. */     private var stroke: Stroke? = null +    /** The board as it was when the current stroke began, pushed to [undoStack] if it changed. */+    private var strokeBefore: NonogramGameState? = null++    /**+     * Boards from before each recent stroke, newest last. In memory only, like Arrows' blocked-arrow+     * flash: it is a convenience for the session in hand, not progress worth persisting.+     */+    private val undoStack = ArrayDeque<NonogramGameState>()++    private fun canUndo(game: NonogramGameState) = undoStack.isNotEmpty() && !game.isOver+     override fun beginStroke(index: Int, alternate: Boolean) {         val state = _uiState.value         val game = state.game ?: return@@ -273,6 +288,7 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application         }         val step = NonogramStrokes.begin(game, index, mode)         stroke = step.stroke+        strokeBefore = game         commit(step.game)     } @@ -285,7 +301,29 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application     }      override fun endStroke() {+        val before = strokeBefore+        val after = _uiState.value.game         stroke = null+        strokeBefore = null+        // Only strokes that changed a fill or a note are worth undoing; one that only revealed a+        // mistake has nothing undo could give back.+        if (before == null || after == null) return+        if (before.filled == after.filled && before.crossed == after.crossed) return+        undoStack.addLast(before)+        while (undoStack.size > MAX_UNDO) undoStack.removeFirst()+        _uiState.value = _uiState.value.copy(canUndo = canUndo(after))+    }++    override fun undo() {+        val game = _uiState.value.game ?: return+        if (stroke != null || game.isOver) return+        val before = undoStack.removeLastOrNull() ?: return+        val next = NonogramMoves.undo(game, before)+        if (next == game) {+            _uiState.value = _uiState.value.copy(canUndo = canUndo(game))+        } else {+            commit(next)+        }     }      override fun setMarkMode(mode: MarkMode) {@@ -317,6 +355,9 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application     /** Clears every mark and restores the hearts, on screen at once and on disk behind it. */     override fun restartLevel() {         val game = _uiState.value.game ?: return+        // A fresh board has nothing to undo; undoing into the pre-restart marks would also hand back+        // a board with full hearts.+        undoStack.clear()         commit(             game.copy(                 filled = emptySet(),@@ -428,5 +469,8 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application          * longer search on every tap of Try again.          */         private const val MAX_GENERATION_ROUNDS = 64++        /** Strokes kept for undo. Plenty for "oops", bounded so a long session cannot grow it. */+        private const val MAX_UNDO = 100     } }
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.ktindex 05b6b1b082..b34b4d3753 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt@@ -192,9 +192,7 @@ fun NonogramGameScreen(                             HeartsRow(remaining = game.hearts, total = STARTING_HEARTS)                             NonogramControls(                                 game = game,-                                markMode = state.markMode,-                                daily = daily,-                                generating = state.generating,+                                state = state,                                 actions = actions,                             )                         }@@ -215,9 +213,7 @@ fun NonogramGameScreen(                      NonogramControls(                         game = game,-                        markMode = state.markMode,-                        daily = daily,-                        generating = state.generating,+                        state = state,                         actions = actions,                     )                 }@@ -235,11 +231,10 @@ fun NonogramGameScreen( @Composable private fun NonogramControls(     game: NonogramGameState,-    markMode: MarkMode,-    daily: Boolean,-    generating: Boolean,+    state: NonogramUiState,     actions: NonogramGameActions, ) {+    val daily = state.mode == GameMode.DAILY     var confirmRestart by remember { mutableStateOf(false) }     // Restart clears every mark, so only ask when there is something to lose:     // an untouched board restarts into itself.@@ -262,7 +257,7 @@ private fun NonogramControls(                 // Disabled while the next puzzle generates, so a double tap cannot advance twice.                 Button(                     onClick = { actions.nextLevel() },-                    enabled = !generating,+                    enabled = !state.generating,                     modifier = Modifier.fillMaxWidth(),                 ) { Text(stringResource(UiR.string.next_level)) }             }@@ -281,7 +276,7 @@ private fun NonogramControls(         }          else -> {-            MarkModeToggle(markMode, actions::setMarkMode)+            MarkModeToggle(state.markMode, actions::setMarkMode)             if (game.filled.isEmpty() && game.crossed.isEmpty() &&                 game.revealedBlanks.isEmpty()             ) {@@ -292,8 +287,14 @@ private fun NonogramControls(                     textAlign = TextAlign.Center,                 )             }-            OutlinedButton(onClick = { if (hasProgress) confirmRestart = true else actions.restartLevel() }) {-                Text(stringResource(UiR.string.restart))+            Row(horizontalArrangement = Arrangement.spacedBy(Spacing.sm)) {+                // Undo reverts the last stroke's marks; spent hearts and revealed mistakes stay.+                OutlinedButton(onClick = { actions.undo() }, enabled = state.canUndo) {+                    Text(stringResource(UiR.string.undo))+                }+                OutlinedButton(onClick = { if (hasProgress) confirmRestart = true else actions.restartLevel() }) {+                    Text(stringResource(UiR.string.restart))+                }             }         }     }
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.ktindex 1c4157c777..0713d192ad 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt@@ -11,6 +11,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription@@ -130,23 +131,24 @@ private fun Modifier.drawCross(color: Color, width: Dp) = drawBehind { }  /**- * Every cell edge, with a heavier stroke every five cells and around the outside.+ * Every visible cell edge, with a heavier stroke every five cells and around the outside.  *  * The five-cell grouping is the standard nonogram aid: it lets a player count along a long line- * without losing their place. Drawn in one pass over the whole grid so shared edges are painted once.+ * without losing their place. Drawn in one pass in viewport space, through the zoom, so shared edges+ * are painted once and the strokes stay hairline-thin however far the grid is zoomed in.  */-internal fun Modifier.drawGridLines(size: Int, thin: Color, thick: Color) = drawBehind {-    val step = this.size.width / size+internal fun DrawScope.drawGridLines(viewport: GridViewport, thin: Color, thick: Color) {     val thinPx = 1.dp.toPx()     val thickPx = 2f * thinPx--    for (i in 0..size) {-        val offset = i * step-        val heavy = i % GROUP == 0 || i == size+    val n = viewport.n+    for (i in 0..n) {+        val heavy = i % GROUP == 0 || i == n         val color = if (heavy) thick else thin         val width = if (heavy) thickPx else thinPx-        drawLine(color, Offset(offset, 0f), Offset(offset, this.size.height), width)-        drawLine(color, Offset(0f, offset), Offset(this.size.width, offset), width)+        val x = viewport.linePosition(i, viewport.zoom.offsetX)+        val y = viewport.linePosition(i, viewport.zoom.offsetY)+        drawLine(color, Offset(x, 0f), Offset(x, size.height), width)+        drawLine(color, Offset(0f, y), Offset(size.width, y), width)     } } 
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.ktindex 7c040a5334..eae96b7618 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt@@ -6,64 +6,119 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.State import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.layout.Layout+import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.TextUnit import com.vayunmathur.games.nonogram.data.NonogramGameState import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text+import kotlin.math.roundToInt -// The clue gutters of [NonogramBoard]: column clues across the top, row clues down the side.+/**+ * Sizes shared by both clue gutters.+ *+ * @property cell a grid cell's side at zoom 1.+ * @property clueCell one clue slot's depth into its gutter.+ * @property fontSize clue text size, already fitted to the slot.+ * @property lineHeight clue line box, equal to the slot.+ */+@Immutable+internal data class ClueMetrics(+    val cell: Dp,+    val clueCell: Dp,+    val fontSize: TextUnit,+    val lineHeight: TextUnit,+) +/**+ * The column clues across the top of [NonogramBoard].+ *+ * Each column's stack keeps its unzoomed size but is placed over wherever that column is currently+ * drawn, so the clues stay aligned with the grid at any zoom and pan, and the gutter clips the ones+ * that are panned out of view.+ */ @Composable internal fun ColumnClues(     game: NonogramGameState,     gutterCells: Int,-    cell: Dp,-    clueCell: Dp,-    fontSize: TextUnit,-    lineHeight: TextUnit,+    metrics: ClueMetrics,+    zoom: State<BoardZoom>, ) {-    Row {+    ZoomedLine(horizontal = true, zoom = zoom) {         for (col in 0 until game.size) {             val clues = game.puzzle.colClues[col]             Column(-                Modifier.size(cell, clueCell * gutterCells),+                Modifier.size(metrics.cell, metrics.clueCell * gutterCells),                 // Bottom-aligned so the last clue sits against the grid it describes.                 verticalArrangement = Arrangement.Bottom,                 horizontalAlignment = Alignment.CenterHorizontally,             ) {                 for (clue in clues.ifEmpty { listOf(0) }) {-                    ClueText(clue, fontSize, lineHeight, Modifier.size(cell, clueCell))+                    ClueText(clue, metrics, Modifier.size(metrics.cell, metrics.clueCell))                 }             }         }     } } +/** The row clues down the side of [NonogramBoard]; zoom-aligned like [ColumnClues]. */ @Composable internal fun RowClues(     game: NonogramGameState,     gutterCells: Int,-    cell: Dp,-    clueCell: Dp,-    fontSize: TextUnit,-    lineHeight: TextUnit,+    metrics: ClueMetrics,+    zoom: State<BoardZoom>, ) {-    Column {+    ZoomedLine(horizontal = false, zoom = zoom) {         for (row in 0 until game.size) {             val clues = game.puzzle.rowClues[row]             Row(-                Modifier.size(clueCell * gutterCells, cell),+                Modifier.size(metrics.clueCell * gutterCells, metrics.cell),                 // End-aligned for the same reason: the final clue abuts the grid.                 horizontalArrangement = Arrangement.End,                 verticalAlignment = Alignment.CenterVertically,             ) {                 for (clue in clues.ifEmpty { listOf(0) }) {-                    ClueText(clue, fontSize, lineHeight, Modifier.size(clueCell, cell))+                    ClueText(clue, metrics, Modifier.size(metrics.clueCell, metrics.cell))+                }+            }+        }+    }+}++/**+ * Lays its children (one per grid line, all the same size) end to end along one axis, each centred on+ * where its grid line is currently drawn ([GridViewport.columnCenter] / [GridViewport.rowCenter]).+ *+ * The zoom is read only in the placement block, so a pinch re-places the clue stacks every frame+ * without recomposing or re-measuring any of them.+ */+@Composable+private fun ZoomedLine(horizontal: Boolean, zoom: State<BoardZoom>, content: @Composable () -> Unit) {+    val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl+    Layout(content, Modifier.clipToBounds()) { measurables, _ ->+        val placeables = measurables.map { it.measure(Constraints()) }+        val n = placeables.size.coerceAtLeast(1)+        val side = if (horizontal) placeables.sumOf { it.width } else placeables.sumOf { it.height }+        val width = if (horizontal) side else (placeables.maxOfOrNull { it.width } ?: 0)+        val height = if (horizontal) (placeables.maxOfOrNull { it.height } ?: 0) else side+        layout(width, height) {+            val viewport = GridViewport(side.toFloat(), n, rtl, zoom.value)+            placeables.forEachIndexed { i, p ->+                if (horizontal) {+                    p.place((viewport.columnCenter(i) - p.width / 2f).roundToInt(), 0)+                } else {+                    p.place(0, (viewport.rowCenter(i) - p.height / 2f).roundToInt())                 }             }         }@@ -73,15 +128,14 @@ internal fun RowClues( @Composable private fun ClueText(     clue: Int,-    fontSize: TextUnit,-    lineHeight: TextUnit,+    metrics: ClueMetrics,     modifier: Modifier = Modifier, ) {     Box(modifier, contentAlignment = Alignment.Center) {         Text(             text = clue.toString(),-            fontSize = fontSize,-            lineHeight = lineHeight,+            fontSize = metrics.fontSize,+            lineHeight = metrics.lineHeight,             maxLines = 1,             softWrap = false,             fontWeight = FontWeight.Medium,
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometry.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometry.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometry.ktnew file mode 100644index 0000000000..b2da378e42--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometry.kt@@ -0,0 +1,123 @@+package com.vayunmathur.games.nonogram.ui.components++import kotlin.math.floor+import kotlin.math.max++/**+ * Pinch-zoom and pan of the grid, in units of the grid's own side.+ *+ * A content point `c` (0..1 across the unzoomed grid) is drawn at `c * scale + offset`. Storing the+ * offset as a fraction of the side rather than in pixels is what lets the same zoom survive a size+ * change — rotation, a window resize, a fold — and still show the same cells.+ *+ * Clamped so the zoomed grid always covers its viewport: scale in `1..maxScale` and each offset in+ * `(1 - scale)..0`, which means no empty margin can ever be panned into view.+ */+data class BoardZoom(+    val scale: Float = 1f,+    val offsetX: Float = 0f,+    val offsetY: Float = 0f,+) {+    val isZoomed: Boolean get() = scale > 1f++    /**+     * Applies one [frame] of a two-finger gesture, keeping the scale within `1..maxScale`.+     *+     * The content point that was under the previous centroid ends up under the current one, scaled+     * about it — so the grid zooms where the fingers are and follows them as they move.+     */+    fun transformed(frame: PinchFrame, maxScale: Float): BoardZoom {+        val newScale = (scale * frame.factor).coerceIn(1f, max(1f, maxScale))+        val contentX = (frame.centroidX - frame.panX - offsetX) / scale+        val contentY = (frame.centroidY - frame.panY - offsetY) / scale+        return BoardZoom(+            scale = newScale,+            offsetX = frame.centroidX - contentX * newScale,+            offsetY = frame.centroidY - contentY * newScale,+        ).clamped(maxScale)+    }++    /** This zoom pulled back inside the limits for a grid whose largest scale is [maxScale]. */+    fun clamped(maxScale: Float): BoardZoom {+        val s = scale.coerceIn(1f, max(1f, maxScale))+        val least = 1f - s+        return BoardZoom(s, offsetX.coerceIn(least, 0f), offsetY.coerceIn(least, 0f))+    }++    companion object {+        val Identity = BoardZoom()+    }+}++/**+ * One frame of a two-finger gesture, as fractions of the grid's side.+ *+ * @property centroidX where the fingers' centre is now, across.+ * @property centroidY where the fingers' centre is now, down.+ * @property panX how far that centre moved across this frame.+ * @property panY how far that centre moved down this frame.+ * @property factor this frame's pinch ratio (1 = no zoom change).+ */+data class PinchFrame(+    val centroidX: Float,+    val centroidY: Float,+    val panX: Float = 0f,+    val panY: Float = 0f,+    val factor: Float = 1f,+)++/**+ * Pure geometry of the grid's on-screen square, for touch input and clue placement.+ *+ * Kept free of Compose so hit-testing can be unit tested directly, including the right-to-left case:+ * the grid's columns are laid out with `Row`, which mirrors under RTL, so physical x = 0 is the+ * *last* column there. [zoom] is a physical transform applied on top of that mirrored layout.+ *+ * @property sidePx the viewport's side in pixels (the grid is square).+ * @property n cells per side.+ * @property rtl whether the layout direction is right-to-left.+ * @property zoom the current pinch-zoom and pan.+ */+internal data class GridViewport(+    val sidePx: Float,+    val n: Int,+    val rtl: Boolean,+    val zoom: BoardZoom = BoardZoom.Identity,+) {+    private val cellPx: Float get() = sidePx / n++    /**+     * The cell under ([x], [y]), in pixels from the viewport's top-left.+     *+     * The point is clamped to the viewport first and then mapped into grid coordinates, so a drag that+     * overshoots the board — or the visible part of a zoomed board — keeps extending along the edge it+     * left by, and never edits a cell that is scrolled out of view.+     */+    fun cellAt(x: Float, y: Float): Int {+        val inside = sidePx - EDGE_EPSILON+        val contentX = (x.coerceIn(0f, inside) - zoom.offsetX * sidePx) / zoom.scale+        val contentY = (y.coerceIn(0f, inside) - zoom.offsetY * sidePx) / zoom.scale+        val physicalCol = floor(contentX / cellPx).toInt().coerceIn(0, n - 1)+        val row = floor(contentY / cellPx).toInt().coerceIn(0, n - 1)+        val col = if (rtl) n - 1 - physicalCol else physicalCol+        return row * n + col+    }++    /** Where the centre of column [col] is drawn, across: what its clue stack is centred on. */+    fun columnCenter(col: Int): Float {+        val content = if (rtl) sidePx - (col + HALF) * cellPx else (col + HALF) * cellPx+        return content * zoom.scale + zoom.offsetX * sidePx+    }++    /** Where the centre of row [row] is drawn, down: what its clue stack is centred on. */+    fun rowCenter(row: Int): Float = (row + HALF) * cellPx * zoom.scale + zoom.offsetY * sidePx++    /** Where grid line [i] (0..n, from the physical left or top) is drawn, along [offset]'s axis. */+    fun linePosition(i: Int, offset: Float): Float = i * cellPx * zoom.scale + offset * sidePx++    private companion object {+        /** Keeps a clamped point strictly inside the last cell rather than on its far edge. */+        const val EDGE_EPSILON = 0.01f+        const val HALF = 0.5f+    }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGestures.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGestures.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGestures.ktindex 78d9dcb788..e97a151f42 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGestures.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGestures.kt@@ -2,41 +2,21 @@ package com.vayunmathur.games.nonogram.ui.components  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.MutableState import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.isSpecified import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerEvent import androidx.compose.ui.input.pointer.PointerId import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.positionChanged-import androidx.compose.ui.unit.IntSize import com.vayunmathur.games.nonogram.platform.NonogramGameActions-import kotlin.math.floor -/**- * Pure grid geometry for touch input.- *- * Kept free of Compose so the hit-testing can be unit tested directly, including the right-to-left- * case: the grid's columns are laid out with `Row`, which mirrors under RTL, so physical x = 0 is- * the *last* column there.- */-internal object BoardGeometry {--    /**-     * The cell under ([x], [y]), in pixels from the top-left of a [gridPx]-square grid of [n] x [n].-     *-     * Points outside the grid clamp onto its nearest edge cell, so a drag that overshoots the board-     * keeps extending along the edge instead of dropping out.-     */-    fun cellAt(x: Float, y: Float, gridPx: Float, n: Int, rtl: Boolean): Int {-        val cellPx = gridPx / n-        val physicalCol = floor(x / cellPx).toInt().coerceIn(0, n - 1)-        val row = floor(y / cellPx).toInt().coerceIn(0, n - 1)-        val col = if (rtl) n - 1 - physicalCol else physicalCol-        return row * n + col-    }-}--/** How the opening moments of a touch resolved, before it became a stroke. */+/** How the opening moments of a touch resolved, before it became a stroke or a pinch. */ private sealed interface Press {     /** Lifted within the long-press timeout without leaving touch slop. */     data object Tap : Press@@ -44,12 +24,19 @@ private sealed interface Press {     /** Left touch slop before the long-press timeout: a drag in the mode's own mark. */     data class Drag(val position: Offset) : Press +    /** A second finger came down: zoom and pan, never a mark. */+    data object Pinch : Press+     /** The pointer went away without lifting (the gesture was taken from us). */     data object Cancelled : Press } +/** The grid's size, layout direction and zoom limits, which the gesture handler restarts on. */+internal data class GridInput(val n: Int, val rtl: Boolean, val maxZoom: Float)+ /**- * One gesture handler for the whole grid, turning touches into strokes on [actions].+ * One gesture handler for the whole grid, turning touches into strokes on [actions] and pinches into+ * [zoom] changes.  *  *  - Tap: a one-cell stroke in the current mode.  *  - Drag: begins once the finger leaves touch slop; the stroke follows the finger cell by cell.@@ -57,71 +44,107 @@ private sealed interface Press {  *    the finger — so long-press-and-drag crosses a run in fill mode, or fills one in cross mode.  *    This keeps long press meaning exactly what it did before ("the other mark") while extending it  *    to runs, so the mode toggle stays the single answer to "what does a plain touch do".+ *  - Two fingers: pinch to zoom and drag to pan, clamped to the grid. A second finger landing during+ *    a stroke ends that stroke and turns the rest of the gesture into a pinch.  *- * [n] and [rtl] are keys: the handler restarts if the grid size or layout direction changes.+ * Every touch is hit-tested in grid coordinates through the current zoom ([GridViewport.cellAt]).  * Every change is consumed so an enclosing scroll or double-tap detector never sees grid touches.  */-internal fun Modifier.strokeGestures(-    n: Int,-    rtl: Boolean,+internal fun Modifier.boardGestures(+    input: GridInput,+    zoom: MutableState<BoardZoom>,     actions: () -> NonogramGameActions,     onLongPress: () -> Unit,-): Modifier = pointerInput(n, rtl) {-    fun cellAt(position: Offset, size: IntSize) =-        BoardGeometry.cellAt(position.x, position.y, size.width.toFloat(), n, rtl)+): Modifier = pointerInput(input, zoom) {+    fun cellAt(position: Offset) =+        GridViewport(size.width.toFloat(), input.n, input.rtl, zoom.value).cellAt(position.x, position.y)      awaitEachGesture {         val down = awaitFirstDown(requireUnconsumed = false)         down.consume()-        val start = cellAt(down.position, size)+        val start = cellAt(down.position)         val press = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {             awaitTapOrDrag(down.id, down.position, viewConfiguration.touchSlop)         }-        when (press) {+        val pinchAfter = when (press) {             Press.Tap -> {                 actions().beginStroke(start, alternate = false)                 actions().endStroke()+                false             }             is Press.Drag -> {                 actions().beginStroke(start, alternate = false)-                actions().extendStroke(cellAt(press.position, size))-                followStroke(down.id, actions) { cellAt(it, size) }+                actions().extendStroke(cellAt(press.position))+                followStroke(down.id, actions, ::cellAt)             }             null -> {                 onLongPress()                 actions().beginStroke(start, alternate = true)-                followStroke(down.id, actions) { cellAt(it, size) }+                followStroke(down.id, actions, ::cellAt)             }-            Press.Cancelled -> Unit+            Press.Pinch -> true+            Press.Cancelled -> false         }+        if (pinchAfter) trackPinch(zoom, input.maxZoom)     } } +private fun PointerEvent.pressedCount() = changes.count { it.pressed }+ private suspend fun AwaitPointerEventScope.awaitTapOrDrag(id: PointerId, origin: Offset, slop: Float): Press {     while (true) {-        val change = awaitPointerEvent().changes.firstOrNull { it.id == id } ?: return Press.Cancelled+        val event = awaitPointerEvent()+        if (event.pressedCount() > 1) return Press.Pinch+        val change = event.changes.firstOrNull { it.id == id } ?: return Press.Cancelled         change.consume()         if (!change.pressed) return Press.Tap         if ((change.position - origin).getDistance() > slop) return Press.Drag(change.position)     } } -/** Feeds the finger's cell to the stroke until it lifts; always ends the stroke, even if cancelled. */+/**+ * Feeds the finger's cell to the stroke until it lifts; always ends the stroke, even if cancelled.+ * Returns true if a second finger came down, so the caller carries on with a pinch.+ */ private suspend fun AwaitPointerEventScope.followStroke(     id: PointerId,     actions: () -> NonogramGameActions,     cellAt: (Offset) -> Int,-) {+): Boolean {     try {         while (true) {-            val change = awaitPointerEvent().changes.firstOrNull { it.id == id } ?: break+            val event = awaitPointerEvent()+            if (event.pressedCount() > 1) return true+            val change = event.changes.firstOrNull { it.id == id } ?: return false             // positionChanged() reads as false once consumed, so check before consuming.             val moved = change.positionChanged()             change.consume()-            if (!change.pressed) break+            if (!change.pressed) return false             if (moved) actions().extendStroke(cellAt(change.position))         }     } finally {         actions().endStroke()     } }++/** Zooms about the fingers' centre and pans with it until every finger has lifted. */+private suspend fun AwaitPointerEventScope.trackPinch(zoom: MutableState<BoardZoom>, maxZoom: Float) {+    while (true) {+        val event = awaitPointerEvent()+        if (event.pressedCount() == 0) break+        val side = size.width.toFloat()+        val centroid = event.calculateCentroid(useCurrent = true)+        if (centroid.isSpecified && side > 0f) {+            val pan = event.calculatePan()+            val frame = PinchFrame(+                centroidX = centroid.x / side,+                centroidY = centroid.y / side,+                panX = pan.x / side,+                panY = pan.y / side,+                factor = event.calculateZoom(),+            )+            zoom.value = zoom.value.transformed(frame, maxZoom)+        }+        event.changes.forEach { it.consume() }+    }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.ktindex d6da1f9ca3..0a98387f81 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt@@ -1,15 +1,27 @@ package com.vayunmathur.games.nonogram.ui.components +import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.saveable.listSaver+import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.stringResource@@ -62,30 +74,65 @@ fun NonogramBoard(         // scale back out, which is what pins the rendered height to the slot.         val density = LocalDensity.current         val textSize = minOf(clueCell * CLUE_TEXT_FRACTION, ClueTextPreferred * density.fontScale)-        val fontSize = with(density) { textSize.toSp() }-        val lineHeight = with(density) { clueCell.toSp() }+        val metrics = ClueMetrics(+            cell = cell,+            clueCell = clueCell,+            fontSize = with(density) { textSize.toSp() },+            lineHeight = with(density) { clueCell.toSp() },+        )++        // Pinch-zoom of the grid, shared with the clue gutters so they stay aligned with it. Kept+        // across recreation (it is stored in units of the grid side, so it survives the grid changing+        // size on rotation) and reset by a new puzzle. Only read inside layout, draw and gesture+        // callbacks, so a pinch never recomposes the board.+        val zoom = rememberSaveable(game.puzzle, stateSaver = BoardZoomSaver) {+            mutableStateOf(BoardZoom.Identity)+        }+        // Enough zoom to bring a cell up to MaxZoomedCell, within MAX_ZOOM: 4x on a 15x15 phone grid,+        // about 1.5x on a 5x5 whose cells are already big.+        val maxZoom = (MaxZoomedCell / cell).coerceIn(1f, MAX_ZOOM)+        // A zoom saved on a smaller grid can exceed this one's limit; pull it back in.+        LaunchedEffect(zoom, maxZoom) { zoom.value = zoom.value.clamped(maxZoom) } -        Column {+        Column(+            // Double-tapping the clues or the corner resets the zoom. Not the grid itself: grid taps+            // have to fire immediately, which rules out waiting to see whether a second tap follows.+            Modifier.pointerInput(zoom) {+                detectTapGestures(onDoubleTap = { zoom.value = BoardZoom.Identity })+            }+        ) {             Row {                 // Empty corner where the two gutters meet.                 Box(Modifier.size(clueCell * rowGutterCells, clueCell * colGutterCells))-                ColumnClues(game, colGutterCells, cell, clueCell, fontSize, lineHeight)+                ColumnClues(game, colGutterCells, metrics, zoom)             }             Row {-                RowClues(game, rowGutterCells, cell, clueCell, fontSize, lineHeight)-                Grid(game, markMode, cell, actions)+                RowClues(game, rowGutterCells, metrics, zoom)+                Grid(game, GridStyle(markMode, cell, maxZoom), zoom, actions)             }         }     } } +/** How the grid is drawn and labelled: the mark mode (for TalkBack labels), cell size and zoom limit. */+@Immutable+private data class GridStyle(val markMode: MarkMode, val cell: Dp, val maxZoom: Float)++/** Saves a [BoardZoom] as its three numbers. */+private val BoardZoomSaver = listSaver<BoardZoom, Float>(+    save = { listOf(it.scale, it.offsetX, it.offsetY) },+    restore = { BoardZoom(it[0], it[1], it[2]) },+)+ @Composable private fun Grid(     game: NonogramGameState,-    markMode: MarkMode,-    cell: Dp,+    style: GridStyle,+    zoom: MutableState<BoardZoom>,     actions: NonogramGameActions, ) {+    val markMode = style.markMode+    val cell = style.cell     val scheme = MaterialTheme.colorScheme     // Resolved once per grid rather than once per cell per tap.     val labels = CellLabels(@@ -109,9 +156,32 @@ private fun Grid(     Box(         Modifier             .size(cell * n)-            .strokeGestures(n, rtl, actions = { currentActions }, onLongPress = { haptics.longPress() })+            .clipToBounds()+            .boardGestures(+                input = GridInput(n, rtl, style.maxZoom),+                zoom = zoom,+                actions = { currentActions },+                onLongPress = { haptics.longPress() },+            )+            // Lines go over the cells in viewport space, so they stay hairline at any zoom.+            .drawWithContent {+                drawContent()+                val viewport = GridViewport(size.width, n, rtl, zoom.value)+                drawGridLines(viewport, scheme.outlineVariant, scheme.onSurface)+            }     ) {-        Column {+        Column(+            Modifier.graphicsLayer {+                // Scaled from the top-left corner, which is what BoardZoom's offsets are measured+                // from; semantics bounds follow the layer, so TalkBack still finds each cell.+                val z = zoom.value+                transformOrigin = TransformOrigin(0f, 0f)+                scaleX = z.scale+                scaleY = z.scale+                translationX = z.offsetX * size.width+                translationY = z.offsetY * size.height+            }+        ) {             for (row in 0 until n) {                 Row {                     for (col in 0 until n) {@@ -137,11 +207,6 @@ private fun Grid(                 }             }         }-        Box(-            Modifier-                .size(cell * n)-                .drawGridLines(n, scheme.outlineVariant, scheme.onSurface)-        )     } } @@ -151,5 +216,11 @@ private const val CLUE_TEXT_FRACTION = 0.78f /** Clue size at 100% font scale on a board roomy enough not to cap it. */ private val ClueTextPreferred = 13.dp +/** The largest a zoomed cell gets: comfortably above the 48dp touch-target guideline. */+private val MaxZoomedCell = 64.dp++/** Upper bound on zoom whatever the cell size, so a pinch can never lose the player in one cell. */+private const val MAX_ZOOM = 4f+ /** A clue slot's width as a fraction of a grid cell. Clues are digits, so they need less room. */ private const val CLUE_CELL_FRACTION = 0.62f
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.ktindex 0291442239..1cc6a5bc72 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramMovesTest.kt@@ -31,6 +31,23 @@ class NonogramMovesTest {         assertSame(failed, NonogramMoves.toggleNote(failed, 0))     } +    @Test fun undoRestoresMarksButNeverRefundsAHeart() {+        val before = NonogramMoves.setNote(game(), 0, true)+        // A stroke that filled 1, then hit blank 2: revealed and charged.+        val after = NonogramMoves.guess(NonogramMoves.guess(before, 1), 2)+        val undone = NonogramMoves.undo(after, before)+        assertEquals(emptySet(), undone.filled)+        assertEquals(setOf(0), undone.crossed)+        assertEquals(setOf(2), undone.revealedBlanks, "a revealed mistake stays revealed")+        assertEquals(STARTING_HEARTS - 1, undone.hearts, "undo never refunds a heart")+    }++    @Test fun undoDoesNotRestoreANoteOnACellThatWasRevealed() {+        val before = NonogramMoves.setNote(game(), 2, true)+        val after = NonogramMoves.guess(before, 2)+        assertEquals(emptySet(), NonogramMoves.undo(after, before).crossed)+    }+     @Test fun toggleNoteFlipsAndNeverCosts() {         val once = NonogramMoves.toggleNote(game(), 4)         assertEquals(setOf(4), once.crossed)
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.ktindex 435b537528..83294c68f0 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt@@ -144,6 +144,33 @@ class NonogramViewModelTest {         assertEquals(STARTING_HEARTS, vm.uiState.value.game!!.hearts)     } +    @Test fun undoRevertsTheLastStrokeWithoutRefundingHearts() {+        val vm = loadedVm()+        assertFalse(vm.uiState.value.canUndo)+        val g = vm.uiState.value.game!!+        val correct = g.puzzle.solution.indices.first { g.puzzle.solution[it] }+        val wrong = g.puzzle.solution.indices.first { !g.puzzle.solution[it] }+        vm.tapCell(correct)+        assertTrue(vm.uiState.value.canUndo)+        vm.tapCell(wrong) // only reveals: nothing for undo to give back, so not pushed+        assertEquals(STARTING_HEARTS - 1, vm.uiState.value.game!!.hearts)+        vm.undo()+        val s = vm.uiState.value.game!!+        assertFalse(correct in s.filled, "the fill is undone")+        assertTrue(wrong in s.revealedBlanks, "the revealed mistake stays")+        assertEquals(STARTING_HEARTS - 1, s.hearts, "undo never refunds a heart")+        assertFalse(vm.uiState.value.canUndo)+        vm.undo() // empty: no-op+        assertEquals(s, vm.uiState.value.game)+        // Undo is persisted like any move.+        await("undo persisted") { runBlocking { vm.dataStore.filledCells.first() }.isEmpty() }+        // Restart wipes the history.+        vm.crossCell(correct)+        assertTrue(vm.uiState.value.canUndo)+        vm.restartLevel()+        assertFalse(vm.uiState.value.canUndo)+    }+     @Test fun longPressInFillModeNotesAndRestartClears() {         val vm = loadedVm()         val g = vm.uiState.value.game!!
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.ktindex 4d2de6c32d..459fa0cf43 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt@@ -2,6 +2,14 @@ package com.vayunmathur.games.nonogram.ui  import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.pinch+import androidx.compose.ui.test.click+import androidx.compose.ui.test.doubleClick+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText@@ -45,7 +53,8 @@ class NonogramScreensTest {     class Recording : NonogramGameActions {         val taps = mutableListOf<Int>(); val crosses = mutableListOf<Int>()         val modes = mutableListOf<MarkMode>(); val gameModes = mutableListOf<GameMode>()-        var next = 0; var restarts = 0; var retries = 0+        var next = 0; var restarts = 0; var retries = 0; var undos = 0+        override fun undo() { undos++ }         /** Every stroke as the gesture handler reported it: begin cell, alternate?, then extensions. */         val strokes = mutableListOf<MutableList<Any>>(); var openStroke = false         override fun tapCell(index: Int) { taps += index }@@ -123,6 +132,42 @@ class NonogramScreensTest {         assertEquals(1, a.restarts, "untouched board restarts without confirmation")     } +    @Test fun undoButtonFollowsCanUndo() {+        val a = Recording()+        var state by androidx.compose.runtime.mutableStateOf(NonogramUiState(game = game(filled = setOf(1)), level = 2, canUndo = false))+        rule.setContent { NonogramGameScreen(state, a, {}, {}) }+        rule.onNodeWithText(str(UiR.string.undo)).assertIsNotEnabled()+        state = state.copy(canUndo = true)+        rule.onNodeWithText(str(UiR.string.undo)).assertIsEnabled().performClick()+        assertEquals(1, a.undos)+    }++    @Test fun pinchZoomHitTestsInGridCoordinatesAndDoubleTapResets() {+        // 5x5 in a 200dp box: about 32dp cells, so this board allows exactly 2x.+        val p = NonogramPuzzle.from(5, "##.#######.#.#..#.#.#.#.#".map { it == '#' })+        val g = NonogramGameState(p, emptySet(), emptySet(), emptySet(), STARTING_HEARTS, GameMode.CASUAL, 1)+        val a = Recording()+        rule.setContent { androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.size(200.dp)) { NonogramBoard(game = g, actions = a) } }+        fun node(row: Int, col: Int) = rule.onNodeWithContentDescription(str(R.string.cd_cell_position, row, col))+        // Unzoomed centre of row 3, column 5 (index 14): the physical point we will keep tapping.+        val point = node(3, 5).fetchSemanticsNode().boundsInRoot.center+        val centre = node(3, 3).fetchSemanticsNode().boundsInRoot.center+        rule.onRoot().performTouchInput {+            pinch(+                start0 = centre - androidx.compose.ui.geometry.Offset(10f, 0f), end0 = centre - androidx.compose.ui.geometry.Offset(40f, 0f),+                start1 = centre + androidx.compose.ui.geometry.Offset(10f, 0f), end1 = centre + androidx.compose.ui.geometry.Offset(40f, 0f),+            )+        }+        assertTrue(a.strokes.isEmpty(), "a pinch never marks a cell")+        // Zoomed 2x about the centre, that same point is now over row 3, column 4.+        rule.onRoot().performTouchInput { click(point) }+        assertEquals(listOf<Any>(13, false), a.strokes.last())+        // Double-tapping the clues resets the zoom: the point is back over column 5.+        rule.onAllNodesWithText("5")[0].performTouchInput { doubleClick() }+        rule.onRoot().performTouchInput { click(point) }+        assertEquals(listOf<Any>(14, false), a.strokes.last())+    }+     @Test fun restartWithProgressAsksConfirmation() {         val a = Recording()         rule.setContent { NonogramGameScreen(NonogramUiState(game = game(filled = setOf(1)), level = 2), a, {}, {}) }
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometryTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometryTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometryTest.ktindex 735f6a0c81..bb33601669 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometryTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometryTest.kt@@ -2,25 +2,81 @@ package com.vayunmathur.games.nonogram.ui.components  import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertTrue  class BoardGeometryTest {-    // 5x5 grid, 100px square: 20px cells.+    // 5x5 grid in a 100px viewport: 20px cells.+    private fun viewport(rtl: Boolean = false, zoom: BoardZoom = BoardZoom.Identity, side: Float = 100f) =+        GridViewport(side, 5, rtl, zoom)+     @Test fun ltrMapsPixelsToRowMajorCells() {-        assertEquals(0, BoardGeometry.cellAt(1f, 1f, 100f, 5, rtl = false))-        assertEquals(7, BoardGeometry.cellAt(45f, 30f, 100f, 5, rtl = false))-        assertEquals(24, BoardGeometry.cellAt(99f, 99f, 100f, 5, rtl = false))+        assertEquals(0, viewport().cellAt(1f, 1f))+        assertEquals(7, viewport().cellAt(45f, 30f))+        assertEquals(24, viewport().cellAt(99f, 99f))     }      @Test fun rtlMirrorsColumnsButNotRows() {         // Physical left edge is the last column under RTL.-        assertEquals(4, BoardGeometry.cellAt(1f, 1f, 100f, 5, rtl = true))-        assertEquals(5, BoardGeometry.cellAt(99f, 21f, 100f, 5, rtl = true))-        assertEquals(12, BoardGeometry.cellAt(50f, 50f, 100f, 5, rtl = true))+        assertEquals(4, viewport(rtl = true).cellAt(1f, 1f))+        assertEquals(5, viewport(rtl = true).cellAt(99f, 21f))+        assertEquals(12, viewport(rtl = true).cellAt(50f, 50f))+    }++    @Test fun pointsOffTheViewportClampToTheEdge() {+        assertEquals(0, viewport().cellAt(-30f, -5f))+        assertEquals(24, viewport().cellAt(400f, 101f))+        assertEquals(20, viewport(rtl = true).cellAt(400f, 101f))+    }++    @Test fun zoomedHitTestingWorksInGridCoordinates() {+        // 2x, panned to show the bottom-right quarter: the viewport's top-left is cell (2.5, 2.5).+        val z = BoardZoom(scale = 2f, offsetX = -1f, offsetY = -1f)+        assertEquals(2 * 5 + 2, viewport(zoom = z).cellAt(1f, 1f))+        assertEquals(24, viewport(zoom = z).cellAt(99f, 99f))+        // Each on-screen cell is now 40px, so 45px in is one cell further along.+        assertEquals(3 * 5 + 3, viewport(zoom = z).cellAt(45f, 45f))+        // RTL: the same physical point is the mirrored column.+        assertEquals(3 * 5 + 1, viewport(rtl = true, zoom = z).cellAt(45f, 45f))+        // Dragging off a zoomed viewport stays on the edge of what is visible, not hidden cells.+        assertEquals(2 * 5 + 2, viewport(zoom = z).cellAt(-500f, -500f))+    }++    @Test fun zoomSurvivesASizeChange() {+        // The same zoom on a viewport twice the size shows the same cells at the same relative spots.+        val z = BoardZoom(scale = 3f, offsetX = -1.2f, offsetY = -0.4f)+        for (fx in listOf(0.05f, 0.33f, 0.5f, 0.97f)) for (fy in listOf(0.1f, 0.6f, 0.9f)) {+            assertEquals(+                viewport(zoom = z, side = 100f).cellAt(fx * 100f, fy * 100f),+                viewport(zoom = z, side = 237f).cellAt(fx * 237f, fy * 237f),+            )+        }+    }++    @Test fun cluesFollowTheirLineThroughTheZoom() {+        val z = BoardZoom(scale = 2f, offsetX = -0.5f, offsetY = -0.25f)+        val v = viewport(zoom = z)+        for (i in 0 until 5) {+            // A clue's centre always hits the cell of the line it labels.+            val x = v.columnCenter(i)+            if (x in 0f..100f) assertEquals(i, v.cellAt(x, 50f) % 5)+            val y = v.rowCenter(i)+            if (y in 0f..100f) assertEquals(i, v.cellAt(50f, y) / 5)+        }+        assertEquals(10f, viewport().columnCenter(0)); assertEquals(90f, viewport(rtl = true).columnCenter(0))+        assertEquals(10f * 2 - 50f, v.columnCenter(0))     } -    @Test fun pointsOffTheGridClampToTheEdge() {-        assertEquals(0, BoardGeometry.cellAt(-30f, -5f, 100f, 5, rtl = false))-        assertEquals(24, BoardGeometry.cellAt(400f, 101f, 100f, 5, rtl = false))-        assertEquals(20, BoardGeometry.cellAt(400f, 101f, 100f, 5, rtl = true))+    @Test fun pinchZoomsAboutTheFingersAndClamps() {+        // Pinching 2x about the centre keeps the centre still.+        val z = BoardZoom.Identity.transformed(PinchFrame(0.5f, 0.5f, factor = 2f), maxScale = 4f)+        assertEquals(2f, z.scale); assertEquals(-0.5f, z.offsetX); assertEquals(-0.5f, z.offsetY)+        // Never past the max, never below 1x, and never panned past an edge.+        assertEquals(4f, z.transformed(PinchFrame(0.5f, 0.5f, factor = 10f), 4f).scale)+        assertEquals(BoardZoom.Identity, z.transformed(PinchFrame(0.5f, 0.5f, factor = 0.1f), 4f))+        val panned = z.transformed(PinchFrame(0.9f, 0.9f, panX = 0.9f, panY = 0.9f), 4f)+        assertEquals(0f, panned.offsetX); assertEquals(0f, panned.offsetY)+        // A zoom saved on a grid that allowed more is pulled back inside the new limit.+        val big = BoardZoom(4f, -3f, -3f).clamped(2f)+        assertEquals(2f, big.scale); assertTrue(big.offsetX >= -1f && big.offsetY >= -1f)     } }