package eu.friedcutlet.yokan.ui.navigation import androidx.lifecycle.ViewModelStore import androidx.lifecycle.viewModelScope import androidx.lifecycle.ViewModelStoreOwner import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.domain.ItemType import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import eu.friedcutlet.yokan.ui.navigation.navigationOrder as visibleSections /** One back-stack entry; its [viewModelStore] lives until the entry leaves the stack. */ class NavEntry internal constructor(val id: Long, val route: Route) : ViewModelStoreOwner { override val viewModelStore = ViewModelStore() } /** Asks the library for [itemType] to show [query] (all categories), or its default category when null. */ data class LibraryRequest(val id: Long, val itemType: ItemType, val query: String?) /** * App navigation: the selected root section, the per-section item-type cursor and the stack of * pushed [Route]s. Main-thread only. */ class Navigator(private val settings: SettingsStore, scope: CoroutineScope) { private val uiContext = scope.coroutineContext.minusKey(Job) private val ownerJob = SupervisorJob(scope.coroutineContext[Job]) private val ownerScope = CoroutineScope(scope.coroutineContext + ownerJob) private val retirementLock = Mutex() private val entries = mutableSetOf() private val pendingJobs = mutableSetOf() private val pendingCleanup = mutableSetOf() private var closed = false private var nextEntryId = 0L private var nextRequestId = 0L private val itemTypeBySection = mutableMapOf( NavSection.TrackerLibrary to ItemType.Manga, NavSection.Updates to ItemType.Manga, NavSection.History to ItemType.Manga, NavSection.Browse to ItemType.Manga, ) private val _backStack = MutableStateFlow>(emptyList()) val backStack: StateFlow> = _backStack.asStateFlow() val navigationOrder: StateFlow> val hiddenSections: StateFlow> private val _section: MutableStateFlow val section: StateFlow private val _itemType: MutableStateFlow val itemType: StateFlow private val _transitionDirection = MutableStateFlow(1) val transitionDirection: StateFlow = _transitionDirection.asStateFlow() private val _playerMinimized = MutableStateFlow(false) val playerMinimized: StateFlow = _playerMinimized.asStateFlow() private val _libraryRequest = MutableStateFlow(null) val libraryRequest: StateFlow = _libraryRequest.asStateFlow() val rootViewModelStoreOwner: ViewModelStoreOwner = object : ViewModelStoreOwner { override val viewModelStore = ViewModelStore() } init { if (settings.db.value.withNavigationOrderMigrated() != settings.db.value) { settings.updateDb { it.withNavigationOrderMigrated() } } val db = settings.db.value navigationOrder = settings.db.map { visibleSections(it) } .stateIn(ownerScope, SharingStarted.Eagerly, visibleSections(db)) hiddenSections = settings.db.map { hiddenNavigationSections(it) } .stateIn(ownerScope, SharingStarted.Eagerly, hiddenNavigationSections(db)) val initialSection = navigationOrder.value.firstOrNull() ?: NavSection.MangaLibrary _section = MutableStateFlow(initialSection) section = _section.asStateFlow() _itemType = MutableStateFlow(initialSection.itemType ?: itemTypeBySection[initialSection] ?: ItemType.Manga) itemType = _itemType.asStateFlow() // A section that is hidden (or was opened by a deep link while hidden) falls back to the first visible one. ownerScope.launch { combine(section, navigationOrder) { current, order -> current to order }.collect { (current, order) -> if (current !in order) order.firstOrNull()?.let(::select) } } } fun navigate(route: Route) { if (closed) return if (route is Route.Reader) _playerMinimized.value = false val stack = _backStack.value val entry = NavEntry(nextEntryId++, route).also { entries += it } val replaceTop = stack.lastOrNull()?.route?.destination() == route.destination() _transitionDirection.value = 1 _backStack.value = if (replaceTop) stack.dropLast(1) + entry else stack + entry } fun back() = pop(direction = -1) fun completeInteractiveBack() = pop(direction = 0) private fun pop(direction: Int) { if (closed) return val stack = _backStack.value if (stack.isEmpty()) return _transitionDirection.value = direction _backStack.value = stack.dropLast(1) } fun select(section: NavSection) { if (closed) return val popped = _backStack.value if (popped.isNotEmpty()) _transitionDirection.value = -1 _backStack.value = emptyList() // The top is still composed (exit animation); the host releases it. Nothing below is composed. popped.dropLast(1).forEach(::clearEntry) _section.value = section (section.itemType ?: itemTypeBySection[section])?.let { _itemType.value = it } section.itemType?.let { requestLibrary(it, query = null) } } /** Switches the root item type; Updates/History/Browse/Tracking remember it per section. */ fun selectItemType(type: ItemType) { if (closed) return if (_itemType.value == type) return _itemType.value = type if (_section.value in itemTypeBySection) itemTypeBySection[_section.value] = type } fun showLibrary(itemType: ItemType, query: String? = null) { select(itemType.librarySection()) requestLibrary(itemType, query) } private fun requestLibrary(itemType: ItemType, query: String?) { if (closed) return _libraryRequest.value = LibraryRequest(nextRequestId++, itemType, query) } fun minimizePlayer() { if (!closed) _playerMinimized.value = true } fun restorePlayer() { if (!closed) _playerMinimized.value = false } fun dismissPlayer() { restorePlayer() back() } /** Clears [entry]'s ViewModels once it has left the stack; true when it did. */ internal fun release(entry: NavEntry): Boolean { if (entry in _backStack.value) return false clearEntry(entry) return true } private fun clearStore(store: ViewModelStore) { // Capture scopes before clear removes references and cancels them. Retain jobs even for // entries already popped: their non-cancelable finalizers may still own profile resources. store.keys().mapNotNull(store::get).forEach { model -> model.viewModelScope.coroutineContext[Job]?.let { pendingJobs += it } (model as? AwaitedViewModelCleanup)?.let { pendingCleanup += it } } store.clear() pendingJobs.removeAll { it.isCompleted } } private fun clearEntry(entry: NavEntry) { clearStore(entry.viewModelStore) entries.remove(entry) } /** Synchronously close navigation admission and cancel every owned ViewModel and watcher. */ fun close() { closed = true ownerScope.cancel() entries.toList().forEach(::clearEntry) clearStore(rootViewModelStoreOwner.viewModelStore) } /** Call on the captured UI context, after child composition disposal and progress capture. */ suspend fun closeAndJoin() = withContext(uiContext + NonCancellable) { retirementLock.withLock { close() pendingJobs.toList().forEach { it.join(); pendingJobs.remove(it) } pendingCleanup.toList().forEach { it.awaitCleanup(); pendingCleanup.remove(it) } ownerJob.join() } } }