Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<activity
android:name=".app.presentation.MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/Theme.KeyGoV2">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@ package de.davis.keygo.app.presentation
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.deeplink.DeepLinkRequest
import de.davis.keygo.app.presentation.navigation.DeepLink
import de.davis.keygo.app.presentation.navigation.match
import de.davis.keygo.core.identity.domain.repository.AccountRepository
import de.davis.keygo.core.security.domain.Session
import de.davis.keygo.core.ui.navigation.LinkMatcher
import de.davis.keygo.core.ui.navigation.PendingLink
import de.davis.keygo.feature.password_health.domain.PasswordHealthAttention
import de.davis.keygo.legacy_migration.domain.usecase.HasMainPasswordUseCase
import kotlinx.coroutines.flow.MutableStateFlow
Expand All @@ -20,6 +25,7 @@ internal class AppViewModel(
private val hasV1Password: HasMainPasswordUseCase,
session: Session,
passwordHealthAttention: PasswordHealthAttention,
private val linkMatchers: List<LinkMatcher>,
) : ViewModel() {

private val _isReturningUser = MutableStateFlow<Boolean?>(null)
Expand All @@ -36,6 +42,21 @@ internal class AppViewModel(
private val _requestedTopLevelRoute = MutableStateFlow<NavKey?>(null)
val requestedTopLevelRoute = _requestedTopLevelRoute.asStateFlow()

private val _incomingDeepLink = MutableStateFlow<DeepLink?>(null)

/** A link that arrived while the app was running, until the navigation has taken it. */
val incomingDeepLink = _incomingDeepLink.asStateFlow()

/** The readable link this Activity was started with, which its launch stack opens. */
var launchLink: DeepLink? = null
private set
private var isLaunchLinkChecked = false

private val _rejectedLink = MutableStateFlow<RejectedLink?>(null)

/** A link that could not be read, until the user has dismissed the report. */
val rejectedLink = _rejectedLink.asStateFlow()

init {
viewModelScope.launch {
_isReturningUser.update { accountRepository.getOrNull() != null || hasV1Password() }
Expand All @@ -50,4 +71,47 @@ internal class AppViewModel(
fun onTopLevelRouteRequestHandled() {
_requestedTopLevelRoute.value = null
}

/**
* Checks the link the Activity was started with. Only the first call counts: a recreated
* Activity hands in the same intent, and its navigation is restored rather than relaunched.
*/
fun onLaunchLink(request: DeepLinkRequest?) {
if (isLaunchLinkChecked) return
isLaunchLinkChecked = true

matchLink(request, closesApp = true) { launchLink = it }
}

fun onDeepLink(request: DeepLinkRequest?) {
matchLink(request, closesApp = false) { _incomingDeepLink.value = it }
}

/**
* Hands a link the app accepts to [onAccepted] if it could be read, and reports it otherwise.
* A request no feature recognises is not a link at all and is ignored.
*/
private inline fun matchLink(
request: DeepLinkRequest?,
closesApp: Boolean,
onAccepted: (DeepLink) -> Unit,
) {
val match = request?.let(linkMatchers::match) ?: return
if (match.isReadable) onAccepted(DeepLink(match.key, match.kind))
else _rejectedLink.value = RejectedLink(match.kind, closesApp)
}

fun onRejectedLinkDismissed() {
_rejectedLink.value = null
}

fun onDeepLinkHandled() {
_incomingDeepLink.value = null
}
}

/**
* A link that could not be read. [closesApp] when the Activity was started only to take it: there
* is nothing else to show, so dismissing the report hands back to the app that sent it.
*/
internal data class RejectedLink(val pending: PendingLink, val closesApp: Boolean)
61 changes: 38 additions & 23 deletions app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,16 @@ import androidx.compose.runtime.setValue
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.fragment.app.FragmentActivity
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.deeplink.DeepLinkRequest
import androidx.navigation3.scene.DialogSceneStrategy
import de.davis.keygo.app.presentation.component.KeyGoNavigationWrapper
import de.davis.keygo.app.presentation.navigation.AppNavigator
import de.davis.keygo.app.presentation.navigation.DeepLink
import de.davis.keygo.app.presentation.navigation.RejectedLinkDialog
import de.davis.keygo.app.presentation.navigation.keyGoEntryProvider
import de.davis.keygo.app.presentation.navigation.launchStack
import de.davis.keygo.app.presentation.navigation.rememberAppNavigationState
import de.davis.keygo.app.presentation.navigation.resolveAppShell
import de.davis.keygo.app.presentation.navigation.toDeepLinkRequest
import de.davis.keygo.core.presentation.model.RouteDestination
import de.davis.keygo.core.sync.domain.stepup.StepUpPrompter
import de.davis.keygo.core.ui.composition.LocalIsInSinglePaneMode
Expand All @@ -38,10 +41,6 @@ import de.davis.keygo.core.util.domain.snackbar.SnackbarManager
import de.davis.keygo.core.util.presentation.snackbar.LocalSnackbarManager
import de.davis.keygo.core.util.presentation.snackbar.SnackbarHandler
import de.davis.keygo.core.sync.presentation.stepup.StepUpDialogHost
import de.davis.keygo.feature.auth.presentation.AuthRoute
import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute
import de.davis.keygo.feature.totp.presentation.TotpImportDeepLinkMatcher
import de.davis.keygo.feature.totp.presentation.TotpImportRedirect
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.compose.koinInject

Expand All @@ -56,6 +55,7 @@ class MainActivity : FragmentActivity() {

// A recreated Activity already restored the tab the request selected.
if (savedInstanceState == null) viewModel.onIntentAction(intent.action)
viewModel.onLaunchLink(intent.toDeepLinkRequest())

splashScreen.setKeepOnScreenCondition {
viewModel.isReturningUser.value == null
Expand All @@ -68,20 +68,36 @@ class MainActivity : FragmentActivity() {
val isSessionActive by viewModel.isSessionActive.collectAsState()
val needsAttentionCount by viewModel.needsAttentionCount.collectAsState()
val requestedTopLevelRoute by viewModel.requestedTopLevelRoute.collectAsState()
val incomingDeepLink by viewModel.incomingDeepLink.collectAsState()
val rejectedLink by viewModel.rejectedLink.collectAsState()
// Only read when the navigation state is first created; after that the saved stack wins.
val launchStack = remember { launchStack(viewModel.launchLink, hasAccess, isSessionActive) }

KeyGoTheme {
val snackbarManager = koinInject<SnackbarManager>()
CompositionLocalProvider(
LocalSnackbarManager provides snackbarManager,
) {
App(
hasAccess = hasAccess,
launchRoute = launchRoute(hasAccess),
// Started only to take a link that cannot be read: no gate, just the report.
if (rejectedLink?.closesApp != true) App(
launchStack = launchStack,
isSessionActive = isSessionActive,
needsAttentionCount = needsAttentionCount,
requestedTopLevelRoute = requestedTopLevelRoute,
onTopLevelRouteRequestHandled = viewModel::onTopLevelRouteRequestHandled,
incomingDeepLink = incomingDeepLink,
onDeepLinkHandled = viewModel::onDeepLinkHandled,
)

rejectedLink?.let { rejected ->
RejectedLinkDialog(
pending = rejected.pending,
onDismiss = {
if (rejected.closesApp) finish()
else viewModel.onRejectedLinkDismissed()
},
)
}
}
}
}
Expand All @@ -90,30 +106,23 @@ class MainActivity : FragmentActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
viewModel.onIntentAction(intent.action)
viewModel.onDeepLink(intent.toDeepLinkRequest())
}

private fun launchRoute(hasAccess: Boolean): NavKey =
intent.totpImportRedirect() ?: if (hasAccess) AuthRoute() else OnboardingRoute()
}

private fun Intent.totpImportRedirect(): TotpImportRedirect? {
// A DeepLinkRequest with neither a uri nor extras throws, and the launcher intent has no data.
val uri = data ?: return null
return TotpImportDeepLinkMatcher.match(DeepLinkRequest(uri))?.key
}

@OptIn(ExperimentalMaterial3AdaptiveApi::class)
@Composable
private fun App(
hasAccess: Boolean,
launchRoute: NavKey,
launchStack: List<NavKey>,
isSessionActive: Boolean,
needsAttentionCount: Int,
requestedTopLevelRoute: NavKey?,
onTopLevelRouteRequestHandled: () -> Unit,
incomingDeepLink: DeepLink?,
onDeepLinkHandled: () -> Unit,
) {
val navigationState = rememberAppNavigationState(
launchRoute = launchRoute,
launchStack = launchStack,
startRoute = RouteDestination.Home,
topLevelRoutes = TopLevelRoutes,
)
Expand All @@ -128,6 +137,12 @@ private fun App(
onTopLevelRouteRequestHandled()
}

LaunchedEffect(incomingDeepLink) {
if (incomingDeepLink == null) return@LaunchedEffect
navigator.openDeepLink(incomingDeepLink, isSessionActive)
onDeepLinkHandled()
}

val windowAdaptiveInfo = currentWindowAdaptiveInfoV2()
val directive = remember(windowAdaptiveInfo) {
calculatePaneScaffoldDirective(windowAdaptiveInfo)
Expand All @@ -136,7 +151,7 @@ private fun App(

DropAutoSelectedDetailWhenListLeaves(listPaneVisible, navigator)

val entries = navigationState.toDecoratedEntries(keyGoEntryProvider(navigator, hasAccess))
val entries = navigationState.toDecoratedEntries(keyGoEntryProvider(navigator))
val shell = entries.resolveAppShell(listPaneVisible)

val listDetailStrategy = rememberListDetailSceneStrategy<NavKey>(directive = directive)
Expand Down Expand Up @@ -174,8 +189,8 @@ private fun App(
/**
* No ARK means the user has to authenticate again, so the session's own state is the whole rule -
* a session that just ended and a restored process that never had one are the same thing here.
* [AppNavigator.lock] is what knows when a gate would be wrong, so onboarding and the deep link
* redirect need no special case. Keyed on what the overlay is showing as well, so it re-decides
* [AppNavigator.lock] is what knows when a gate would be wrong, so onboarding and a link waiting
* under a gate need no special case. Keyed on what the overlay is showing as well, so it re-decides
* when that changes under a session that is still ended.
*/
@Composable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,21 @@ import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.runtime.serialization.NavKeySerializer
import androidx.savedstate.compose.serialization.serializers.MutableStateSerializer
import de.davis.keygo.core.presentation.model.RouteDestination
import de.davis.keygo.feature.auth.presentation.AuthRoute
import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute
import de.davis.keygo.core.ui.navigation.rememberNavEntryDecorators

/**
* Creates the app's navigation state. It survives configuration changes and process death.
*
* @param launchRoute what the overlay starts on. Only used the first time the state is created;
* after that the saved stack wins.
* @param launchStack what the overlay starts as, bottom first. Only used the first time the state
* is created; after that the saved stack wins.
* @param startRoute the top level route the app opens on. Must be one of [topLevelRoutes].
* @param topLevelRoutes the navigation bar's destinations, one back stack each.
*/
@Composable
fun rememberAppNavigationState(
launchRoute: NavKey,
launchStack: List<NavKey>,
startRoute: NavKey,
topLevelRoutes: Set<NavKey>,
): AppNavigationState {
Expand All @@ -38,7 +40,7 @@ fun rememberAppNavigationState(
mutableStateOf(startRoute)
}

val overlayStack = rememberNavBackStack(launchRoute)
val overlayStack = rememberNavBackStack(*launchStack.toTypedArray())
val backStacks = topLevelRoutes.associateWith { key -> rememberNavBackStack(key) }

return remember(startRoute, topLevelRoutes) {
Expand All @@ -53,8 +55,8 @@ fun rememberAppNavigationState(
/**
* The app's navigation state, modified through [AppNavigator]. It holds two things:
*
* - The **overlay stack**: the unlock gate, first run, or an incoming `otpauth://` link. While it
* holds anything it is all that shows.
* - The **overlay stack**: the unlock gate, first run, and a deep link's destination, which waits
* under the gate until it goes. While it holds anything it is all that shows.
* - One **back stack per top level route**, each keeping its own history. Only the selected one is
* shown, with nothing underneath it, so back out of its base leaves the app.
*/
Expand All @@ -70,6 +72,24 @@ class AppNavigationState(
/** Whether the overlay owns the window, hiding the app proper underneath. */
val isOverlaid: Boolean get() = overlayStack.isNotEmpty()

/**
* True while the unlock gate is the overlay's top entry. Derived, so a restored gate reports
* itself. The type is what decides it: deep link destinations share this stack, so neither
* emptiness nor depth tells a gate from a screen back may legitimately pop.
*/
val isGated: Boolean get() = overlayStack.lastOrNull() is AuthRoute

/**
* True while the overlay's top entry is one a deep link can wait under: the gate, or first run
* for a user with no account yet. Both run before there is a session, and both hide what is
* under them completely - nothing under them is displayed, and back never pops them to it.
*/
val isCovered: Boolean
get() = when (overlayStack.lastOrNull()) {
is AuthRoute, is OnboardingRoute -> true
else -> false
}

/** The stack destinations are currently pushed onto and popped from. */
val currentStack: NavBackStack<NavKey>
get() = if (isOverlaid) overlayStack else backStacks.getValue(topLevelRoute)
Expand Down Expand Up @@ -97,8 +117,20 @@ class AppNavigationState(
rememberDecoratedEntries(stack, entryProvider)
}

return if (isOverlaid) overlayEntries
else topLevelEntries.getValue(topLevelRoute)
return visible(overlayEntries, topLevelEntries)
}

/**
* Picks what the display is handed. While the gate or first run is up that is it alone: everything
* under it stays decorated, holding its state, but the display never learns it exists. It
* would otherwise draw it on its own - a back gesture previews the entry under the top one -
* showing a screen the lock was meant to hide. With a single entry, back on the gate exits the
* app, the same as on a cold start.
*/
fun <T> visible(overlay: List<T>, tabs: Map<NavKey, List<T>>): List<T> = when {
isCovered -> listOf(overlay.last())
isOverlaid -> overlay
else -> tabs.getValue(topLevelRoute)
}
}

Expand Down
Loading