@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class) package eu.friedcutlet.yokan.ui.screens.novel import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.SideEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.ImageComposeScene import androidx.compose.ui.text.LinkAnnotation import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.compose.LocalLifecycleOwner import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest import java.util.concurrent.CountDownLatch import java.util.concurrent.FutureTask import java.util.concurrent.TimeUnit import javax.swing.SwingUtilities import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotSame import kotlin.test.assertTrue import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest class NovelContentOwnershipTest { @Test fun disposedParsedLinkCannotNavigateAndRemountGetsANewLink() = runTest { val f = UiFixture(this) try { f.click(f.link) assertEquals(listOf("A"), f.opened) val old = f.link f.show(false) f.click(old) assertEquals(listOf("A"), f.opened) assertTrue(f.a.owner.isActive) f.show(true) assertNotSame(old, f.link) f.click(old); f.click(f.link) assertEquals(listOf("A", "A"), f.opened) } finally { f.finish() } } @Test fun chapterReplacementRejectsThePreviousChaptersLink() = runTest { val f = UiFixture(this) try { val old = f.link f.ui { f.chapter.value = 11 }; f.pump() f.click(old); f.click(f.link) assertEquals(listOf("A"), f.opened) } finally { f.finish() } } @Test fun ownerReplacementWithTheSameChapterCannotRetargetARetainedLink() = runTest { val f = UiFixture(this) try { val old = f.link f.ui { f.content.value = f.b.content; f.target.value = "B" }; f.pump() f.click(old); f.click(f.link) assertEquals(listOf("B"), f.opened) assertTrue(f.a.owner.isActive) assertTrue(f.b.owner.isActive) } finally { f.finish() } } @Test fun backgroundLifecycleRejectsLinksImmediatelyAndResumePreservesCurrentContent() = runTest { val f = UiFixture(this) try { val current = f.link f.ui { f.registry.currentState = Lifecycle.State.CREATED } // No recomposition frame: the click checks the actual lifecycle. f.click(current); assertTrue(f.opened.isEmpty()) f.ui { f.registry.currentState = Lifecycle.State.RESUMED } f.click(current); assertEquals(listOf("A"), f.opened) } finally { f.finish() } } @Test fun replacingTheLifecycleOwnerExpiresPreviousLinksAndPublishesCurrentLinks() = runTest { val f = UiFixture(this) try { val old = f.link val replacement = object : LifecycleOwner { override val lifecycle = LifecycleRegistry.createUnsafe(this) } f.ui { replacement.lifecycle.currentState = Lifecycle.State.RESUMED f.currentLifecycle.value = replacement } f.pump() f.click(old); f.click(f.link) assertEquals(listOf("A"), f.opened) } finally { f.finish() } } @Test fun retirementAdmissionRejectsLinksBeforeJobCancellationAndSameScreenUsesLatestAction() = runTest { val f = UiFixture(this) try { val current = f.link f.ui { f.target.value = "latest" }; f.pump() f.click(current) assertEquals(listOf("latest"), f.opened) f.a.open = false f.click(current) assertEquals(listOf("latest"), f.opened) assertTrue(f.a.owner.isActive) } finally { f.finish() } } @Test fun callerCancellationJoinsABlockedLocalReadWithoutDeliveringParsedContent() = runTest { blockedReadIsJoined(retireOwner = false) } @Test fun ownerRetirementJoinsABlockedLocalReadWithoutDeliveringParsedContent() = runTest { blockedReadIsJoined(retireOwner = true) } private suspend fun TestScope.blockedReadIsJoined(retireOwner: Boolean) { val f = ProfileReaderContentTest.Fixture(this, fileDispatcher = Dispatchers.Default) val entered = CompletableDeferred() val release = CountDownLatch(1) var parsed = false f.beforeEpubChapterRead = { entered.complete(Unit) check(release.await(10, TimeUnit.SECONDS)) { "Blocked archive read was not released" } } val chapter = Chapter(10, 1, "Local", "/chapter", archivePath = "/A/book.epub#0") val request = async { f.content.novelContent(f.source, "Book", chapter) { parsed = true } } try { entered.await() val retiring = if (retireOwner) async { f.owner.cancelAndJoin() } else null if (!retireOwner) request.cancel() runCurrent() assertFalse(request.isCompleted, "extraction is still reading the captured archive") if (retiring != null) assertFalse(retiring.isCompleted, "retirement joins the blocking file read") release.countDown() if (retireOwner) { retiring?.await() assertFailsWith { request.await() } } else request.join() assertFalse(parsed) assertTrue(f.epubResourceReads.isEmpty()) assertEquals(!retireOwner, f.owner.isActive) } finally { release.countDown(); request.cancelAndJoin(); f.close() } } private class UiFixture(val test: TestScope) { val a = ProfileReaderContentTest.Fixture(test, "A") val b = ProfileReaderContentTest.Fixture(test, "B") val content = mutableStateOf(a.content) val chapter = mutableStateOf(10L) val visible = mutableStateOf(true) val target = mutableStateOf("A") val opened = mutableListOf() lateinit var link: LinkAnnotation.Url val lifecycleOwner = object : LifecycleOwner { override val lifecycle = LifecycleRegistry.createUnsafe(this) } val registry = lifecycleOwner.lifecycle as LifecycleRegistry val currentLifecycle = mutableStateOf(lifecycleOwner) val scene = ui { registry.currentState = Lifecycle.State.RESUMED ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) { CompositionLocalProvider(LocalLifecycleOwner provides currentLifecycle.value) { if (visible.value) { val currentTarget = target.value val open = rememberNovelOpenLink(content.value, chapter.value) { opened += currentTarget } val parsed = parseNovelRichContent("

Next

", onOpenLink = open) val text = assertIs(parsed.blocks.single()).text val annotation = assertIs(text.getLinkAnnotations(0, text.length).single().item) SideEffect { link = annotation } } } } } init { pump() } fun click(annotation: LinkAnnotation.Url) = ui { annotation.linkInteractionListener?.onClick(annotation) } fun show(value: Boolean) { ui { visible.value = value }; pump() } fun pump() = ui { repeat(3) { test.testScheduler.runCurrent() scene.render(test.testScheduler.currentTime * 1_000_000).close() test.testScheduler.runCurrent() } } fun ui(block: () -> T): T = onUi(block) suspend fun finish() { ui { scene.close() }; a.close(); b.close() } } private companion object { fun onUi(block: () -> T): T { if (SwingUtilities.isEventDispatchThread()) return block() val task = FutureTask(block) SwingUtilities.invokeAndWait(task) return task.get() } } }