Yokan / rebuild
Course 1 8624561

NovelPagedReaderMeasureTest.kt

composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagedReaderMeasureTest.kt

test / fixture150 lines
1package eu.friedcutlet.yokan.ui.screens.novel23import androidx.compose.material3.MaterialTheme4import androidx.compose.runtime.Composable5import androidx.compose.ui.ImageComposeScene6import androidx.compose.ui.text.AnnotatedString7import androidx.compose.ui.text.TextStyle8import androidx.compose.ui.text.font.FontFamily9import androidx.compose.ui.text.rememberTextMeasurer10import androidx.compose.ui.use11import androidx.compose.ui.unit.Constraints12import androidx.compose.ui.unit.dp13import androidx.compose.ui.unit.sp14import androidx.compose.ui.platform.LocalDensity15import androidx.compose.ui.graphics.Color16import eu.friedcutlet.yokan.database.DbNovelPageMode17import eu.friedcutlet.yokan.database.DbNovelTextAlign18import java.util.concurrent.FutureTask19import javax.swing.SwingUtilities20import kotlin.test.Test21import kotlin.test.assertEquals22import kotlin.test.assertFalse23import kotlin.test.assertNotNull24import kotlin.test.assertTrue2526class NovelPagedReaderMeasureTest {27    @Test28    fun realComposeMeasurementPaginatesAndPreservesEverySourceCharacter() {29        listOf("A\nB", "A\n", "A\n\nB", "A\r\n\r\nB", "\nA", "\n\nA", "\n", "A\r\n", "one two three four five six seven eight nine ten").forEach { source ->30            val isBreakCase = source.contains('\n') || source.contains('\r')31            val width = if (isBreakCase) 320 else 39032            val height = if (isBreakCase) 80 else 56033            onUi {34                var invalid = false35                var readyPages: List<NovelPage>? = null36                val scene = ImageComposeScene(width, height) {37                    NovelPagedReader(38                        content = NovelRichContent(39                            blocks = listOf(NovelContentBlock.Text(AnnotatedString(source))),40                            plainText = source,41                        ),42                        pageMode = DbNovelPageMode.Single,43                        requestedPageRatio = 0.0,44                        sourceAnchor = null,45                        fontSize = 14,46                        lineHeight = 1.2,47                        textAlign = DbNovelTextAlign.Left,48                        fontFamily = FontFamily.Serif,49                        textColor = Color.Black,50                        imageHeaders = emptyMap(),51                        paragraphSpacing = 12.dp,52                        padding = 0.dp,53                        onPageChanged = { _, _ -> },54                        onComplete = { _, _ -> },55                        onInvalidLayout = { invalid = true },56                        onPagesReady = { readyPages = it },57                    )58                }59                try {60                    repeat(4) { scene.render(it * 16_000_000L).close() }61                    assertFalse(invalid, "source should fit across pages: ${source.escapeForTest()}")62                    val pages = assertNotNull(readyPages, "pagination should produce pages for ${source.escapeForTest()}")63                    assertTrue(pages.isNotEmpty())64                    val slices = pages.flatMap { it.slices }65                    var next = 066                    slices.forEach { slice ->67                        assertEquals(0, slice.blockIndex)68                        assertEquals(next, slice.start, "source gap or duplicate for ${source.escapeForTest()}")69                        assertTrue(slice.endExclusive > slice.start)70                        next = slice.endExclusive71                    }72                    assertEquals(source.length, next)73                    assertEquals(source, slices.joinToString("") { source.substring(it.start, it.endExclusive) })74                    if (source == "A\nB") assertEquals(2, pages.size, "one-line viewport should split at the newline")75                    val renderedPages = pages.map { page ->76                        page.slices.joinToString("") { slice ->77                            renderNovelTextFragment(source.toAnnotatedString(), slice.start, slice.endExclusive).text78                        }79                    }80                    when (source) {81                        "A\nB" -> assertEquals(listOf("A", "B"), renderedPages)82                        "A\n" -> assertEquals(listOf("A", "\u00A0"), renderedPages)83                        "A\n\nB", "A\r\n\r\nB" -> assertEquals(84                            listOf("A", "\u00A0", "B"),85                            renderedPages,86                            "${source.escapeForTest()} slices=${pages.map { it.slices }}",87                        )88                        "\nA" -> assertEquals(listOf("\u00A0", "A"), renderedPages)89                        "\n\nA" -> assertEquals(listOf("\u00A0", "\u00A0", "A"), renderedPages)90                        "\n" -> assertEquals(listOf("\u00A0"), renderedPages)91                        "A\r\n" -> assertEquals(listOf("A", "\u00A0"), renderedPages)92                    }93                } finally {94                    scene.close()95                }96            }97        }98    }99100    @Test101    fun everyAcceptedFragmentHasMeasuredHeightWithinPageBudget() {102        onUi {103            val source = "A\nB\n\nC\n"104            var allFragmentsFit = false105            val scene = ImageComposeScene(320, 80) {106                MeasurementProbe(source) { result -> allFragmentsFit = result }107            }108            try {109                scene.render().close()110                assertTrue(allFragmentsFit, "all source ranges should advance with measured height within the one-line page budget")111            } finally {112                scene.close()113            }114        }115    }116117    @Composable118    private fun MeasurementProbe(source: String, onComplete: (Boolean) -> Unit) {119        val density = LocalDensity.current120        val measurer = rememberTextMeasurer()121        val block = NovelContentBlock.Text(AnnotatedString(source))122        val style = MaterialTheme.typography.bodyLarge.merge(123            TextStyle(color = Color.Black, fontSize = 14.sp, lineHeight = 17.sp, fontFamily = FontFamily.Serif),124        )125        val width = with(density) { 280.dp.roundToPx() }126        val pageHeight = with(density) { 32.dp.roundToPx() }127        var cursor = 0128        var valid = true129        var steps = 0130        while (cursor < source.length && steps++ <= source.length) {131            val fit = measureNovelTextFit(measurer, block, cursor, pageHeight, width, style)132            if (fit == null || fit.endExclusive <= cursor || fit.heightPx !in 1..pageHeight) {133                valid = false134                break135            }136            cursor = fit.endExclusive137        }138        onComplete(valid && cursor == source.length)139    }140141    private fun String.escapeForTest() = replace("\n", "\\n")142143    private fun String.toAnnotatedString() = AnnotatedString(this)144145    private fun <T> onUi(block: () -> T): T {146        val task = FutureTask<T> { block() }147        SwingUtilities.invokeAndWait(task)148        return task.get()149    }150}151

Search chapters, reference and source filenames.