parentalcontrols: convert activity-per-screen to Route host (#nav)
- Commit
c5ca00a4c69c016ffe46d3a5e8e056a32331e920- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 19:48 UTC (20 days ago)
- Parents
2696bb7
Dashboard, DailyLimit, AppLimits, Bedtime, Downtime, SchoolTime and WebFilters each had a PinGatedActivity subclass (or, for the dashboard, activity-result gates launched at PinGateActivity and PinSetupActivity), so which screen was showing lived in the activity stack and every Settings entry rebuilt a gated activity shell. Selection-as-activities is exactly the implicit navigation the owner directive bans. Add Route (Dashboard / DailyLimit / AppLimits / Bedtime / Downtime / SchoolTime / WebFilters / PinSetup / PinGate(target)) and a single MainActivity host rendering Navigation.kt over a rememberNavBackStack. The dashboard rows push gated destinations; each editor binds the same SupervisionViewModel state and actions its activity used to wire. PIN semantics are unchanged, judged as follows. Route.PinGate is a full-screen DetailPage destination (not DialogPage: a dialog scene needs a destination underneath, which a direct Settings entry does not have, and it must never sit over gated content). The gated destination is never on the stack below its gate - verification replaces the gate with the destination (PinGateTarget.editorRoute), cancel pops it or finishes the host when the gate is the only entry, and leaving the gate unverified drops the pending master-switch value. No PIN yet routes through Route.PinSetup first and then hands over to the gate for the same target, as PinGatedActivity did. Backgrounding after verified content re-challenges on resume by swapping a gated top destination back to its gate, mirroring PinGatedActivity.onResume, and a gated entry that finds itself unverified (e.g. after recreation) swaps itself back to its gate instead of rendering. PinGateActivity is kept as an activity, deliberately: the five lock activities (Bedtime/Downtime/SchoolTime/DailyLimit/AppLimit, kept as OS surfaces) start it for a result and grant bonus time on RESULT_VERIFIED, a contract a route inside another activity cannot answer. It renders the same PinGateScreen as Route.PinGate. The lock activities, SetupActivity (no-UI supervision-install handoff; it now starts the host at Route.PinSetup before the platform flow) and PinGateActivity are the only activities besides the host. Entry behaviour is preserved through activity-aliases: the old component names keep their labels, exported flags, MANAGE_SUPERVISION permissions, intent-filters and Settings supervision category/summary meta-data and point at the host, which is singleTask; ManageAlias now targets the host, whose routeFor maps MANAGE_SUPERVISION_APP_SETTINGS to Bedtime as before. MainActivity.routeFor maps each Settings action to its gated destination, so a Settings row starts at the PIN gate, never at the editor. WebFilters had no intent-filter and remains dashboard-only. Tests: ParentalActivitiesTest drives the host - dashboard rows and Settings actions go through the on-screen PIN gate into their editors (including Web filters from the dashboard), the gate-cancel case finishes the host, PIN setup renders as a route and cancels back to the dashboard, and seedDatabase force-opens the seeded in-memory database because a closed activity scenario can drop its tables. Lock-activity, PinGateActivity result and SetupActivity handoff tests are unchanged. Verified: ./gradlew :parentalcontrols:compileDevKotlin :parentalcontrols:testDevUnitTest green (65 tests).
Diff
parentalcontrols/AGENTS.md
diff --git a/parentalcontrols/AGENTS.md b/parentalcontrols/AGENTS.mdindex 3d5da2386b..3ab3c12574 100644--- a/parentalcontrols/AGENTS.md+++ b/parentalcontrols/AGENTS.md@@ -6,7 +6,7 @@ _Install: ./install parentalcontrols (dev by default)._ <!-- last-reviewed: 2026-10-16 --> - Gradle: :parentalcontrols / dir: parentalcontrols/ - Package roots present: ui, data, domain, platform, service, notifications, auth-- Entry files: ui/DashboardActivity.kt + ui/SetupActivity.kt (activity-per-surface OS module; no MainActivity/Route)+- Entry files: MainActivity.kt + Route.kt + Navigation.kt (single host) + ui/SetupActivity.kt and ui/PinActivities.kt (PinGateActivity, kept for lock-screen activity-result) + ui/LockActivities.kt (kept OS lock surfaces) - Deps: :library:room, :library:aosp-stubs - Metadata: metadata_data/parentalcontrols.md (present) - Rust: no / screenshotTest: no@@ -14,7 +14,7 @@ _Install: ./install parentalcontrols (dev by default)._ ## Overview **Purpose:** On-device parental controls over Android's supervision APIs — screen-time/bedtime/app-limits, web filters, install restrictions, all PIN-gated (`auth/ParentPin`). No account, nothing uploaded. **Key features:** `platform/SupervisionMaster` + `SupervisionPolicies`/`Apis`/`Caller` enforce `data/` rules + `domain/TimeWindow`; `platform/Enforcer` + `AppLimits` + `BedtimeScheduler` apply limits; `service/` supervision messengers bridge the system.-**Entry points:** `ui/SetupActivity.kt` → `ui/DashboardActivity.kt` → `platform/SupervisionViewModel.kt` → `platform/SupervisionMaster.kt` → `data/Rules.kt`.+**Entry points:** `MainActivity.kt` → `Navigation.kt` (`Route.Dashboard/DailyLimit/AppLimits/Bedtime/Downtime/SchoolTime/WebFilters/PinSetup/PinGate`) → `platform/SupervisionViewModel.kt`; `ui/SetupActivity.kt` hands off to the host's PinSetup route then the platform setup flow → `platform/SupervisionMaster.kt` → `data/Rules.kt`. **Gotchas:** - `receiver/` is NOT a closed package root — pending migration; don't add more files there - Enforcement is system-mediated (supervision APIs) — sideloaded builds can't enforce; PIN loss locks parents out by design, no backdoor@@ -45,23 +45,21 @@ _Install: ./install parentalcontrols (dev by default)._ - com/vayunmathur/parentalcontrols/service/SupervisionMessengerService.kt - com/vayunmathur/parentalcontrols/notifications/LockNotifier.kt ### ui/ — PIN-gated activities (the entries)-- com/vayunmathur/parentalcontrols/ui/DashboardActivity.kt+- com/vayunmathur/parentalcontrols/MainActivity.kt+- com/vayunmathur/parentalcontrols/Route.kt+- com/vayunmathur/parentalcontrols/Navigation.kt - com/vayunmathur/parentalcontrols/ui/DashboardScreen.kt - com/vayunmathur/parentalcontrols/ui/SetupActivity.kt - com/vayunmathur/parentalcontrols/ui/PinSetupScreen.kt - com/vayunmathur/parentalcontrols/ui/PinGateScreen.kt-- com/vayunmathur/parentalcontrols/ui/PinGatedActivity.kt - com/vayunmathur/parentalcontrols/ui/PinActivities.kt - com/vayunmathur/parentalcontrols/ui/LockScreen.kt - com/vayunmathur/parentalcontrols/ui/LockActivities.kt-- com/vayunmathur/parentalcontrols/ui/AppLimitsActivity.kt - com/vayunmathur/parentalcontrols/ui/AppLimitsScreen.kt - com/vayunmathur/parentalcontrols/ui/DailyLimitScreen.kt-- com/vayunmathur/parentalcontrols/ui/BedtimeActivity.kt - com/vayunmathur/parentalcontrols/ui/BedtimeScreen.kt-- com/vayunmathur/parentalcontrols/ui/WindowActivities.kt - com/vayunmathur/parentalcontrols/ui/WindowScheduleScreen.kt-- com/vayunmathur/parentalcontrols/ui/WebContentFiltersActivity.kt+- com/vayunmathur/parentalcontrols/ui/WebContentFiltersScreen.kt ## Verify (this module only) ```
parentalcontrols/src/main/AndroidManifest.xml
diff --git a/parentalcontrols/src/main/AndroidManifest.xml b/parentalcontrols/src/main/AndroidManifest.xmlindex 1185790386..8093c170f4 100644--- a/parentalcontrols/src/main/AndroidManifest.xml+++ b/parentalcontrols/src/main/AndroidManifest.xml@@ -114,13 +114,27 @@ supervision dashboard - is what the user sees. Exported because Settings launches it from another process; the page is read-only and every change is behind the parent PIN. -->+ <!--+ The single navigation host. Every former editor activity below is an alias+ onto this host, keeping its own label, permission, intent-filter and Settings+ meta-data, so Settings rows land exactly where they did; MainActivity.routeFor+ turns the arriving intent into the start route (gated editors start at their+ PIN gate). singleTask so a second Settings tap re-routes via onNewIntent.+ --> <activity- android:name=".ui.DashboardActivity"+ android:name=".MainActivity" android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:exported="true" android:label="@string/dashboard_title" android:launchMode="singleTask"- android:theme="@style/Theme.General">+ android:theme="@style/Theme.General" />++ <!-- The top-level "Parental controls" page (was DashboardActivity). -->+ <activity-alias+ android:name=".ui.DashboardActivity"+ android:exported="true"+ android:label="@string/dashboard_title"+ android:targetActivity=".MainActivity"> <intent-filter> <action android:name="com.vayunmathur.parentalcontrols.action.DASHBOARD" /> <category android:name="android.intent.category.DEFAULT" />@@ -129,19 +143,15 @@ <action android:name="android.app.supervision.action.INTERSTITIAL_SCREEN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>- </activity>+ </activity-alias> - <!--- Web content filters, opened from the dashboard. Not exported: launched explicitly by- our own dashboard, and guarded by MANAGE_SUPERVISION like the other editors.- -->- <activity+ <!-- Web content filters: dashboard-only, so no intent-filter (was WebContentFiltersActivity). -->+ <activity-alias android:name=".ui.WebContentFiltersActivity"- android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:exported="false" android:label="@string/web_filters_title" android:permission="android.permission.MANAGE_SUPERVISION"- android:theme="@style/Theme.General" />+ android:targetActivity=".MainActivity" /> <!-- The parental-control features themselves.@@ -155,13 +165,12 @@ Still no launcher entry: these are reached from Settings, and an icon would be a second route to a screen that only makes sense in that context. -->- <activity+ <activity-alias android:name=".ui.BedtimeActivity"- android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:exported="true" android:label="@string/bedtime_title" android:permission="android.permission.MANAGE_SUPERVISION"- android:theme="@style/Theme.General">+ android:targetActivity=".MainActivity"> <intent-filter> <action android:name="com.vayunmathur.parentalcontrols.action.BEDTIME" /> <category android:name="android.intent.category.DEFAULT" />@@ -172,15 +181,14 @@ <meta-data android:name="com.android.settings.summary" android:resource="@string/bedtime_summary" />- </activity>+ </activity-alias> - <activity+ <activity-alias android:name=".ui.AppLimitsActivity"- android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:exported="true" android:label="@string/limits_title" android:permission="android.permission.MANAGE_SUPERVISION"- android:theme="@style/Theme.General">+ android:targetActivity=".MainActivity"> <intent-filter> <action android:name="com.vayunmathur.parentalcontrols.action.APP_LIMITS" /> <category android:name="android.intent.category.DEFAULT" />@@ -191,22 +199,21 @@ <meta-data android:name="com.android.settings.summary" android:resource="@string/limits_summary" />- </activity>+ </activity-alias> <!-- The Family Link set: downtime, school time and the device-wide daily limit. Same Settings-dashboard integration as bedtime and app limits - one row each, filled only- because of the supervision category tags. All three are parent-gated in code (see- PinGatedActivity); the MANAGE_SUPERVISION permission here keeps other apps from+ because of the supervision category tags. All three are parent-gated in the host+ (Route.PinGate); the MANAGE_SUPERVISION permission here keeps other apps from opening them directly. -->- <activity+ <activity-alias android:name=".ui.DowntimeActivity"- android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:exported="true" android:label="@string/downtime_title" android:permission="android.permission.MANAGE_SUPERVISION"- android:theme="@style/Theme.General">+ android:targetActivity=".MainActivity"> <intent-filter> <action android:name="com.vayunmathur.parentalcontrols.action.DOWNTIME" /> <category android:name="android.intent.category.DEFAULT" />@@ -217,15 +224,14 @@ <meta-data android:name="com.android.settings.summary" android:resource="@string/downtime_summary" />- </activity>+ </activity-alias> - <activity+ <activity-alias android:name=".ui.SchoolTimeActivity"- android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:exported="true" android:label="@string/school_title" android:permission="android.permission.MANAGE_SUPERVISION"- android:theme="@style/Theme.General">+ android:targetActivity=".MainActivity"> <intent-filter> <action android:name="com.vayunmathur.parentalcontrols.action.SCHOOL_TIME" /> <category android:name="android.intent.category.DEFAULT" />@@ -236,15 +242,14 @@ <meta-data android:name="com.android.settings.summary" android:resource="@string/school_summary" />- </activity>+ </activity-alias> - <activity+ <activity-alias android:name=".ui.DailyLimitActivity"- android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:exported="true" android:label="@string/daily_title" android:permission="android.permission.MANAGE_SUPERVISION"- android:theme="@style/Theme.General">+ android:targetActivity=".MainActivity"> <intent-filter> <action android:name="com.vayunmathur.parentalcontrols.action.DAILY_LIMIT" /> <category android:name="android.intent.category.DEFAULT" />@@ -255,7 +260,7 @@ <meta-data android:name="com.android.settings.summary" android:resource="@string/daily_summary" />- </activity>+ </activity-alias> <!-- Where Settings sends the user for "app settings" of a supervision app. Without an@@ -268,7 +273,7 @@ android:exported="true" android:label="@string/app_name" android:permission="android.permission.MANAGE_SUPERVISION"- android:targetActivity=".ui.BedtimeActivity">+ android:targetActivity=".MainActivity"> <intent-filter> <action android:name="android.settings.MANAGE_SUPERVISION_APP_SETTINGS" /> <category android:name="android.intent.category.DEFAULT" />@@ -316,10 +321,12 @@ </activity> <!--- The parent-PIN challenge and its first-run setup. Neither is exported: both are- started explicitly by our own editors and lock screens, and the PIN must never be- reachable - or even visible - to another app. Both are guarded by MANAGE_SUPERVISION- as well, so even an explicit intent from elsewhere cannot open them.+ The parent-PIN challenge as an activity, kept for the lock screens: they run+ outside the navigation host and start it for a result (RESULT_VERIFIED grants+ bonus time), a contract a route cannot answer. Inside the host the same+ PinGateScreen is Route.PinGate. Not exported and guarded by MANAGE_SUPERVISION,+ so even an explicit intent from elsewhere cannot open it. (PIN setup is now+ Route.PinSetup in the host, so its former activity is gone.) --> <activity android:name=".ui.PinGateActivity"@@ -327,12 +334,6 @@ android:exported="false" android:permission="android.permission.MANAGE_SUPERVISION" android:theme="@style/Theme.General" />- <activity- android:name=".ui.PinSetupActivity"- android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"- android:exported="false"- android:permission="android.permission.MANAGE_SUPERVISION"- android:theme="@style/Theme.General" /> <!-- Full-screen restriction notices, one per block reason. None exported: started
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/MainActivity.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/MainActivity.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/MainActivity.ktnew file mode 100644index 0000000000..0d8812d60d--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/MainActivity.kt@@ -0,0 +1,91 @@+package com.vayunmathur.parentalcontrols++import android.content.Context+import android.content.Intent+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import com.vayunmathur.library.ui.MaActivity+import com.vayunmathur.parentalcontrols.platform.SupervisionViewModel++/**+ * The single Parental Controls host, launched from Settings (MAOS redirects+ * the platform supervision entry here - see the Settings patch in+ * vendor/modern-apps).+ *+ * Every former editor activity is an alias onto this host (see the+ * manifest): the Settings supervision rows for bedtime, app limits,+ * downtime, school time and the daily limit keep their own labels,+ * permissions, intent-filters and summary meta-data and point here, and+ * [routeFor] turns the arriving intent into the start destination (a gated+ * editor starts at its PIN gate, never at the editor). Intents that arrive+ * while the host is running are re-routed through [pendingRoute].+ * SetupActivity, PinGateActivity and the five lock activities stay+ * activities: they are system-facing surfaces with activity-result or+ * no-UI contracts outside this navigation graph.+ */+class MainActivity : MaActivity() {++ private val viewModel: SupervisionViewModel by viewModels()++ private var initialRoute: Route = Route.Dashboard+ private var pendingRoute by mutableStateOf<Route?>(null)++ override fun onCreateBeforeContent() {+ initialRoute = routeFor(intent)+ }++ @Composable+ override fun Content() {+ Navigation(+ viewModel = viewModel,+ initialRoute = initialRoute,+ externalRoute = pendingRoute,+ onExternalRouteConsumed = { pendingRoute = null },+ onFinish = { finish() },+ )+ }++ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ setIntent(intent)+ pendingRoute = routeFor(intent)+ }++ companion object {+ const val ACTION_DASHBOARD = "com.vayunmathur.parentalcontrols.action.DASHBOARD"+ const val ACTION_BEDTIME = "com.vayunmathur.parentalcontrols.action.BEDTIME"+ const val ACTION_APP_LIMITS = "com.vayunmathur.parentalcontrols.action.APP_LIMITS"+ const val ACTION_DOWNTIME = "com.vayunmathur.parentalcontrols.action.DOWNTIME"+ const val ACTION_SCHOOL_TIME = "com.vayunmathur.parentalcontrols.action.SCHOOL_TIME"+ const val ACTION_DAILY_LIMIT = "com.vayunmathur.parentalcontrols.action.DAILY_LIMIT"++ private const val ACTION_INTERSTITIAL_SCREEN =+ "android.app.supervision.action.INTERSTITIAL_SCREEN"+ private const val ACTION_MANAGE_SUPERVISION_APP_SETTINGS =+ "android.settings.MANAGE_SUPERVISION_APP_SETTINGS"++ /** An explicit intent to the host at the PIN-setup destination. */+ fun pinSetupIntent(context: Context): Intent =+ Intent(context, MainActivity::class.java)+ .putExtra(EXTRA_PIN_SETUP, true)++ private const val EXTRA_PIN_SETUP = "com.vayunmathur.parentalcontrols.extra.PIN_SETUP"++ /** The route an entry intent names; the dashboard is the default landing. */+ fun routeFor(intent: Intent?): Route = when (intent?.action) {+ ACTION_BEDTIME, ACTION_MANAGE_SUPERVISION_APP_SETTINGS -> Route.Bedtime+ ACTION_APP_LIMITS -> Route.AppLimits+ ACTION_DOWNTIME -> Route.Downtime+ ACTION_SCHOOL_TIME -> Route.SchoolTime+ ACTION_DAILY_LIMIT -> Route.DailyLimit+ else -> if (intent?.getBooleanExtra(EXTRA_PIN_SETUP, false) == true) {+ Route.PinSetup+ } else {+ Route.Dashboard+ }+ }+ }+}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/Navigation.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/Navigation.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/Navigation.ktnew file mode 100644index 0000000000..af759a1bf7--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/Navigation.kt@@ -0,0 +1,328 @@+package com.vayunmathur.parentalcontrols++import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.util.DetailPage+import com.vayunmathur.library.util.ListPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.parentalcontrols.auth.ParentPin+import com.vayunmathur.parentalcontrols.platform.SupervisionViewModel+import com.vayunmathur.parentalcontrols.ui.AppLimitsActions+import com.vayunmathur.parentalcontrols.ui.AppLimitsScreen+import com.vayunmathur.parentalcontrols.ui.BedtimeActions+import com.vayunmathur.parentalcontrols.ui.BedtimeScreen+import com.vayunmathur.parentalcontrols.ui.DailyLimitActions+import com.vayunmathur.parentalcontrols.ui.DailyLimitScreen+import com.vayunmathur.parentalcontrols.ui.DashboardActions+import com.vayunmathur.parentalcontrols.ui.DashboardScreen+import com.vayunmathur.parentalcontrols.ui.PinGateActions+import com.vayunmathur.parentalcontrols.ui.PinGateScreen+import com.vayunmathur.parentalcontrols.ui.PinSetupActions+import com.vayunmathur.parentalcontrols.ui.PinSetupScreen+import com.vayunmathur.parentalcontrols.ui.WebContentFiltersScreen+import com.vayunmathur.parentalcontrols.ui.WindowScheduleActions+import com.vayunmathur.parentalcontrols.ui.WindowScheduleScreen+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+++/**+ * Navigation host for Parental Controls, with the PIN gate as a destination.+ *+ * Gate semantics carry over from the activity-per-screen design unchanged:+ * a gated editor is never on the stack under its gate (verification+ * replaces [Route.PinGate] with the destination, cancel pops or finishes),+ * a fresh install goes through [Route.PinSetup] first and only then the+ * gate, and backgrounding the host after content was verified re-challenges+ * on resume (see the lifecycle observer below). PinGateActivity remains a+ * separate activity for the lock screens, which start it for a result from+ * outside this host; it renders the same [PinGateScreen].+ */+@Composable+fun Navigation(+ viewModel: SupervisionViewModel,+ initialRoute: Route = Route.Dashboard,+ externalRoute: Route? = null,+ onExternalRouteConsumed: () -> Unit = {},+ onFinish: () -> Unit = {},+) {+ val context = LocalContext.current+ val pin = remember(context) { ParentPin.get(context) }+ val scope = rememberCoroutineScope()++ val initialTarget = PinGateTarget.forRoute(initialRoute)+ val backStack = when {+ initialTarget != null && pin.isSet() ->+ rememberNavBackStack<Route>(Route.PinGate(initialTarget))+ initialTarget != null ->+ rememberNavBackStack<Route>(Route.PinSetup)+ initialRoute == Route.PinSetup ->+ rememberNavBackStack<Route>(Route.Dashboard, Route.PinSetup)+ initialRoute == Route.Dashboard ->+ rememberNavBackStack<Route>(Route.Dashboard)+ else -> rememberNavBackStack<Route>(Route.Dashboard, initialRoute)+ }++ // Non-screen continuations for the gate/setup destinations: what a passed+ // gate applies (the pending master-switch value) and which gate a finished+ // setup hands over to. Neither chooses a screen; the routes above do.+ var pinVerified by remember { mutableStateOf(false) }+ var pendingControls by remember { mutableStateOf<Boolean?>(null) }+ var pendingAfterSetup by remember { mutableStateOf(initialTarget) }+ var backgroundedAfterContent by remember { mutableStateOf(false) }++ fun requestGated(target: PinGateTarget) {+ pinVerified = false+ if (pin.isSet()) {+ backStack.add(Route.PinGate(target))+ } else {+ pendingAfterSetup = target+ backStack.add(Route.PinSetup)+ }+ }++ fun requestSetup(after: PinGateTarget?) {+ pendingAfterSetup = after+ backStack.add(Route.PinSetup)+ }++ fun leaveGate() {+ if (backStack.backStack.size <= 1) onFinish() else backStack.pop()+ }++ // Re-challenge on return, mirroring the former PinGatedActivity: backgrounding after+ // verified content was shown revokes the verification, and a gated top+ // destination is swapped back to its gate before it can render again.+ val lifecycleOwner = LocalLifecycleOwner.current+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ when (event) {+ Lifecycle.Event.ON_PAUSE -> if (pinVerified) backgroundedAfterContent = true+ Lifecycle.Event.ON_RESUME -> if (backgroundedAfterContent) {+ backgroundedAfterContent = false+ pinVerified = false+ val top = backStack.last()+ PinGateTarget.forRoute(top)?.let { backStack.setLast(Route.PinGate(it)) }+ }+ else -> Unit+ }+ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+ }++ LaunchedEffect(externalRoute) {+ val route = externalRoute ?: return@LaunchedEffect+ when {+ route == Route.Dashboard -> backStack.reset(Route.Dashboard)+ PinGateTarget.forRoute(route) != null ->+ requestGated(PinGateTarget.forRoute(route)!!)+ route == Route.PinSetup -> requestSetup(null)+ else -> backStack.add(route)+ }+ onExternalRouteConsumed()+ }++ MainNavigation(backStack) {+ entry<Route.Dashboard>(metadata = ListPage()) {+ val state by viewModel.state.collectAsStateWithLifecycle()+ DashboardScreen(+ state = state,+ actions = DashboardActions(+ onSetControls = { desired ->+ if (!pin.isSet()) {+ requestSetup(null)+ } else {+ pendingControls = desired+ backStack.add(Route.PinGate(PinGateTarget.Controls))+ }+ },+ onOpenDailyLimit = { requestGated(PinGateTarget.DailyLimit) },+ onOpenAppLimits = { requestGated(PinGateTarget.AppLimits) },+ onOpenDowntime = { requestGated(PinGateTarget.Downtime) },+ onOpenWebFilters = { requestGated(PinGateTarget.WebFilters) },+ onOpenPin = {+ if (!pin.isSet()) {+ requestSetup(null)+ } else {+ backStack.add(Route.PinGate(PinGateTarget.ManagePin))+ }+ },+ ),+ )+ }+ entry<Route.DailyLimit>(metadata = DetailPage()) {+ if (!pinVerified) { LaunchedEffect(Unit) { backStack.setLast(Route.PinGate(PinGateTarget.DailyLimit)) }; return@entry }+ val state by viewModel.state.collectAsStateWithLifecycle()+ DailyLimitScreen(+ currentMinutes = state.dailyLimitMinutes,+ actions = DailyLimitActions(onLimitChange = viewModel::setDeviceDailyLimit),+ )+ }+ entry<Route.AppLimits>(metadata = DetailPage()) {+ if (!pinVerified) { LaunchedEffect(Unit) { backStack.setLast(Route.PinGate(PinGateTarget.AppLimits)) }; return@entry }+ val state by viewModel.state.collectAsStateWithLifecycle()+ AppLimitsScreen(+ state = state,+ actions = AppLimitsActions(onLimitChange = viewModel::setDailyLimit),+ )+ }+ entry<Route.Bedtime>(metadata = DetailPage()) {+ if (!pinVerified) { LaunchedEffect(Unit) { backStack.setLast(Route.PinGate(PinGateTarget.Bedtime)) }; return@entry }+ val state by viewModel.state.collectAsStateWithLifecycle()+ BedtimeScreen(+ state = state,+ actions = BedtimeActions(+ onEnabledChange = viewModel::setScheduleEnabled,+ onStartChange = viewModel::setStart,+ onEndChange = viewModel::setEnd,+ onToggleDay = viewModel::toggleDay,+ onAppBedtimeChange = viewModel::setBedtimeBlocked,+ ),+ )+ }+ entry<Route.Downtime>(metadata = DetailPage()) {+ if (!pinVerified) { LaunchedEffect(Unit) { backStack.setLast(Route.PinGate(PinGateTarget.Downtime)) }; return@entry }+ val state by viewModel.state.collectAsStateWithLifecycle()+ WindowScheduleScreen(+ title = stringResource(R.string.downtime_title),+ enableLabel = stringResource(R.string.downtime_enable),+ enableHint = stringResource(R.string.downtime_enable_hint),+ startLabel = stringResource(R.string.schedule_start),+ endLabel = stringResource(R.string.schedule_end),+ daysLabel = stringResource(R.string.schedule_days),+ appsLabel = stringResource(R.string.downtime_apps),+ dayInitials = stringResource(R.string.bedtime_day_initials),+ enabled = state.downtime.enabled,+ startMinute = state.downtime.startMinute,+ endMinute = state.downtime.endMinute,+ daysMask = state.downtime.daysMask,+ apps = state.apps,+ loading = state.loading,+ actions = WindowScheduleActions(+ onEnabledChange = viewModel::setDowntimeEnabled,+ onStartChange = viewModel::setDowntimeStart,+ onEndChange = viewModel::setDowntimeEnd,+ onToggleDay = viewModel::toggleDowntimeDay,+ onAppAllowChange = viewModel::setAllowedInDowntime,+ ),+ )+ }+ entry<Route.SchoolTime>(metadata = DetailPage()) {+ if (!pinVerified) { LaunchedEffect(Unit) { backStack.setLast(Route.PinGate(PinGateTarget.SchoolTime)) }; return@entry }+ val state by viewModel.state.collectAsStateWithLifecycle()+ WindowScheduleScreen(+ title = stringResource(R.string.school_title),+ enableLabel = stringResource(R.string.school_enable),+ enableHint = stringResource(R.string.school_enable_hint),+ startLabel = stringResource(R.string.schedule_start),+ endLabel = stringResource(R.string.schedule_end),+ daysLabel = stringResource(R.string.schedule_days),+ appsLabel = stringResource(R.string.school_apps),+ dayInitials = stringResource(R.string.bedtime_day_initials),+ enabled = state.schoolTime.enabled,+ startMinute = state.schoolTime.startMinute,+ endMinute = state.schoolTime.endMinute,+ daysMask = state.schoolTime.daysMask,+ apps = state.apps,+ loading = state.loading,+ actions = WindowScheduleActions(+ onEnabledChange = viewModel::setSchoolTimeEnabled,+ onStartChange = viewModel::setSchoolTimeStart,+ onEndChange = viewModel::setSchoolTimeEnd,+ onToggleDay = viewModel::toggleSchoolTimeDay,+ onAppAllowChange = viewModel::setAllowedInDowntime,+ ),+ )+ }+ entry<Route.WebFilters>(metadata = DetailPage()) {+ if (!pinVerified) { LaunchedEffect(Unit) { backStack.setLast(Route.PinGate(PinGateTarget.WebFilters)) }; return@entry }+ WebContentFiltersScreen()+ }+ entry<Route.PinSetup>(metadata = DetailPage()) {+ PinSetupScreen(+ actions = PinSetupActions(+ onSet = { entry ->+ val after = pendingAfterSetup+ pendingAfterSetup = null+ scope.launch {+ withContext(Dispatchers.IO) { pin.set(entry) }+ if (after != null) {+ backStack.setLast(Route.PinGate(after))+ } else if (backStack.backStack.size <= 1) {+ backStack.reset(Route.Dashboard)+ } else {+ backStack.pop()+ }+ }+ true+ },+ onCancel = { leaveGate() },+ ),+ )+ }+ entry<Route.PinGate>(metadata = DetailPage()) { route ->+ var error by remember(route) { mutableStateOf<String?>(null) }+ var lockedOut by remember(route) { mutableStateOf(pin.isLockedOut()) }+ val wrongPin = stringResource(R.string.pin_wrong)+ val lockedOutText = stringResource(R.string.pin_locked_out)+ DisposableEffect(route) {+ onDispose {+ // Leaving without verifying (cancel, system back) drops the+ // pending gated action; a later gate must not apply it.+ if (!pinVerified) pendingControls = null+ }+ }+ PinGateScreen(+ error = error,+ lockedOut = lockedOut,+ actions = PinGateActions(+ onVerify = { entry ->+ scope.launch {+ val ok = withContext(Dispatchers.IO) { pin.verify(entry) }+ if (ok) {+ pinVerified = true+ when (route.target) {+ PinGateTarget.Controls -> {+ pendingControls?.let { viewModel.setControlsEnabled(it) }+ pendingControls = null+ if (backStack.backStack.size <= 1) {+ backStack.reset(Route.Dashboard)+ } else {+ backStack.pop()+ }+ }+ PinGateTarget.ManagePin -> {+ pendingAfterSetup = null+ backStack.setLast(Route.PinSetup)+ }+ else -> backStack.setLast(route.target.editorRoute()!!)+ }+ } else {+ lockedOut = pin.isLockedOut()+ error = if (lockedOut) lockedOutText else wrongPin+ }+ }+ // The real answer arrives asynchronously; false keeps the entry.+ false+ },+ onCancel = { leaveGate() },+ ),+ )+ }+ }+}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/Route.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/Route.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/Route.ktnew file mode 100644index 0000000000..bf57401a0a--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/Route.kt@@ -0,0 +1,89 @@+package com.vayunmathur.parentalcontrols++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+/** Navigation destinations for Parental Controls. */+sealed interface Route : NavKey {+ @Serializable+ /** The top-level parental-controls page from Settings. Read-only without the PIN. */+ data object Dashboard : Route++ @Serializable+ /** The device-wide daily screen-time budget. Parent-gated. */+ data object DailyLimit : Route++ @Serializable+ /** Per-app daily caps. Parent-gated. */+ data object AppLimits : Route++ @Serializable+ /** The nightly bedtime window. Parent-gated. */+ data object Bedtime : Route++ @Serializable+ /** The daytime downtime window. Parent-gated. */+ data object Downtime : Route++ @Serializable+ /** The school-hours window. Parent-gated. */+ data object SchoolTime : Route++ @Serializable+ /** Web content filters. Parent-gated. */+ data object WebFilters : Route++ @Serializable+ /** First-run PIN creation, and PIN change after the gate passes. */+ data object PinSetup : Route++ @Serializable+ /**+ * The parent-PIN challenge for [target]. The gated destination itself is+ * never on the stack below this route: verification replaces the gate+ * with the destination, and cancel pops it (finishing the host when the+ * gate is the only entry), so back can never expose gated content.+ */+ data class PinGate(val target: PinGateTarget) : Route+}++/** What a passed [Route.PinGate] unlocks. */+@Serializable+enum class PinGateTarget {+ /** Applying the dashboard master switch. */+ Controls,++ /** Replacing the PIN: the gate is followed by [Route.PinSetup]. */+ ManagePin,+ DailyLimit,+ AppLimits,+ Bedtime,+ Downtime,+ SchoolTime,+ WebFilters;++ /** The editor route this target unlocks; null when it unlocks an action, not a screen. */+ fun editorRoute(): Route? = when (this) {+ Controls, ManagePin -> null+ DailyLimit -> Route.DailyLimit+ AppLimits -> Route.AppLimits+ Bedtime -> Route.Bedtime+ Downtime -> Route.Downtime+ SchoolTime -> Route.SchoolTime+ WebFilters -> Route.WebFilters+ }++ companion object {+ /** The gate target guarding [route], or null for ungated destinations. */+ fun forRoute(route: Route): PinGateTarget? = when (route) {+ Route.DailyLimit -> DailyLimit+ Route.AppLimits -> AppLimits+ Route.Bedtime -> Bedtime+ Route.Downtime -> Downtime+ Route.SchoolTime -> SchoolTime+ Route.WebFilters -> WebFilters+ else -> null+ }+ }+}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/AppLimitsActivity.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/AppLimitsActivity.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/AppLimitsActivity.ktdeleted file mode 100644index 48f7112d42..0000000000--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/AppLimitsActivity.kt+++ /dev/null@@ -1,28 +0,0 @@-package com.vayunmathur.parentalcontrols.ui--import androidx.activity.compose.setContent-import androidx.activity.enableEdgeToEdge-import androidx.activity.viewModels-import androidx.compose.runtime.getValue-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.parentalcontrols.platform.SupervisionViewModel--/** Per-app daily caps, reached from Settings > Parental controls. Parent-gated. */-class AppLimitsActivity : PinGatedActivity() {-- private val viewModel: SupervisionViewModel by viewModels()-- override fun onPinVerifiedContent() {- enableEdgeToEdge()- setContent {- DynamicTheme {- val state by viewModel.state.collectAsStateWithLifecycle()- AppLimitsScreen(- state = state,- actions = AppLimitsActions(onLimitChange = viewModel::setDailyLimit),- )- }- }- }-}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/BedtimeActivity.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/BedtimeActivity.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/BedtimeActivity.ktdeleted file mode 100644index 9c9caa7a04..0000000000--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/BedtimeActivity.kt+++ /dev/null@@ -1,40 +0,0 @@-package com.vayunmathur.parentalcontrols.ui--import androidx.activity.compose.setContent-import androidx.activity.enableEdgeToEdge-import androidx.activity.viewModels-import androidx.compose.runtime.getValue-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.parentalcontrols.platform.SupervisionViewModel--/**- * The bedtime schedule, reached from Settings > Parental controls.- *- * Launched by a dashboard tile rather than a launcher icon - see the manifest. This app still- * has no entry in the launcher, and these screens are the only UI it owns. Parent-gated: only- * a verified parent may see or change the schedule.- */-class BedtimeActivity : PinGatedActivity() {-- private val viewModel: SupervisionViewModel by viewModels()-- override fun onPinVerifiedContent() {- enableEdgeToEdge()- setContent {- DynamicTheme {- val state by viewModel.state.collectAsStateWithLifecycle()- BedtimeScreen(- state = state,- actions = BedtimeActions(- onEnabledChange = viewModel::setScheduleEnabled,- onStartChange = viewModel::setStart,- onEndChange = viewModel::setEnd,- onToggleDay = viewModel::toggleDay,- onAppBedtimeChange = viewModel::setBedtimeBlocked,- ),- )- }- }- }-}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DashboardActivity.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DashboardActivity.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DashboardActivity.ktdeleted file mode 100644index 2d5cd78725..0000000000--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DashboardActivity.kt+++ /dev/null@@ -1,86 +0,0 @@-package com.vayunmathur.parentalcontrols.ui--import android.content.Intent-import android.os.Bundle-import androidx.activity.ComponentActivity-import androidx.activity.compose.setContent-import androidx.activity.enableEdgeToEdge-import androidx.activity.result.contract.ActivityResultContracts-import androidx.activity.viewModels-import androidx.compose.runtime.getValue-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.parentalcontrols.auth.ParentPin-import com.vayunmathur.parentalcontrols.platform.SupervisionViewModel--/**- * The top-level "Parental controls" page, launched from Settings (MAOS redirects the platform- * supervision entry here - see the Settings patch in vendor/modern-apps).- *- * The page itself is read-only, so a child may see the current setup, but every change is behind- * the parent PIN: flipping the master switch, managing the PIN, and each control's own editor- * (which re-gate themselves via [PinGatedActivity]).- */-class DashboardActivity : ComponentActivity() {-- private val viewModel: SupervisionViewModel by viewModels()- private var pendingControls: Boolean? = null-- /** Master-switch change: verify the PIN, then apply the pending value. */- private val controlsGate =- registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->- if (result.resultCode == PinGateActivity.RESULT_VERIFIED) {- pendingControls?.let { viewModel.setControlsEnabled(it) }- }- pendingControls = null- }-- /** "Manage your PIN": verify the current PIN before allowing it to be replaced. */- private val pinManageGate =- registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->- if (result.resultCode == PinGateActivity.RESULT_VERIFIED) {- startActivity(Intent(this, PinSetupActivity::class.java))- }- }-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- enableEdgeToEdge()- setContent {- DynamicTheme {- val state by viewModel.state.collectAsStateWithLifecycle()- DashboardScreen(- state = state,- actions = DashboardActions(- onSetControls = ::requestControls,- onOpenDailyLimit = { open(DailyLimitActivity::class.java) },- onOpenAppLimits = { open(AppLimitsActivity::class.java) },- onOpenDowntime = { open(DowntimeActivity::class.java) },- onOpenWebFilters = { open(WebContentFiltersActivity::class.java) },- onOpenPin = ::requestManagePin,- ),- )- }- }- }-- private fun open(activity: Class<*>) = startActivity(Intent(this, activity))-- private fun requestControls(desired: Boolean) {- if (!ParentPin.get(this).isSet()) {- // No PIN yet: send the parent to create one first; they can toggle afterwards.- startActivity(Intent(this, PinSetupActivity::class.java))- return- }- pendingControls = desired- controlsGate.launch(Intent(this, PinGateActivity::class.java))- }-- private fun requestManagePin() {- if (!ParentPin.get(this).isSet()) {- startActivity(Intent(this, PinSetupActivity::class.java))- } else {- pinManageGate.launch(Intent(this, PinGateActivity::class.java))- }- }-}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinActivities.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinActivities.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinActivities.ktindex 497dfb2422..a3c9372659 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinActivities.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinActivities.kt@@ -71,32 +71,3 @@ class PinGateActivity : ComponentActivity() { const val RESULT_VERIFIED = RESULT_FIRST_USER + 1 } }--/**- * First-run PIN creation, and later PIN change (after [PinGateActivity] passes).- *- * Nothing else in the app opens until a PIN exists: the setup flow lands here when- * [ParentPin.isSet] is false, so imposed enforcement always has a gatekeeper.- */-class PinSetupActivity : ComponentActivity() {- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- val pin = ParentPin.get(this)- enableEdgeToEdge()- setContent {- DynamicTheme {- PinSetupScreen(- actions = PinSetupActions(- onSet = { entry ->- lifecycleScope.launch(Dispatchers.IO) { pin.set(entry) }- setResult(RESULT_OK)- finish()- true- },- onCancel = { finish() },- ),- )- }- }- }-}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinGatedActivity.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinGatedActivity.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinGatedActivity.ktdeleted file mode 100644index b22af74ff2..0000000000--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinGatedActivity.kt+++ /dev/null@@ -1,88 +0,0 @@-package com.vayunmathur.parentalcontrols.ui--import android.content.Intent-import android.os.Bundle-import androidx.activity.ComponentActivity-import androidx.activity.result.contract.ActivityResultContracts-import com.vayunmathur.parentalcontrols.auth.ParentPin--/**- * An editor that only a parent may see.- *- * Settings launches editor activities directly, so each one verifies the parent PIN on every- * resume - not just on create - because the activity can sit in the back stack while the- * child does something else. When no PIN exists yet (fresh install), the setup screen runs- * instead so first run always creates the gatekeeper.- *- * Subclasses implement [onPinVerifiedContent]: it runs only after verification (or when no- * PIN is set, which cannot happen post-setup but is tolerated). The content is set exactly- * once per verification; a failed or canceled challenge finishes the activity.- */-abstract class PinGatedActivity : ComponentActivity() {-- private var verified = false-- /**- * Whether the activity was backgrounded after content was shown.- *- * Guards the re-challenge in [onResume]: returning from the PIN gate itself also resumes- * us, and that resume must not re-challenge or verification could never complete.- */- private var backgroundedAfterContent = false-- private val gate =- registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->- if (result.resultCode == PinGateActivity.RESULT_VERIFIED) {- verified = true- onPinVerifiedContent()- } else {- finish()- }- }-- private val setup =- registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->- if (result.resultCode == RESULT_OK && ParentPin.get(this).isSet()) {- verified = false- checkGate()- } else {- finish()- }- }-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- checkGate()- }-- override fun onPause() {- super.onPause()- if (verified) backgroundedAfterContent = true- }-- override fun onResume() {- super.onResume()- // Re-challenge on return: the activity may have been backgrounded while the child- // held the device. Content from a previous verification stays visible only while- // this resume's check passes again. The resume that follows the gate itself is- // exempt - that is the verification completing, not a backgrounding.- if (backgroundedAfterContent) {- backgroundedAfterContent = false- verified = false- checkGate()- }- }-- private fun checkGate() {- when {- !ParentPin.get(this).isSet() ->- setup.launch(Intent(this, PinSetupActivity::class.java))- !verified ->- gate.launch(Intent(this, PinGateActivity::class.java))- else -> onPinVerifiedContent()- }- }-- /** Sets the activity content. Runs only with a verified (or absent) PIN. */- protected abstract fun onPinVerifiedContent()-}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/SetupActivity.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/SetupActivity.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/SetupActivity.ktindex 3da43195d0..8775bc8545 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/SetupActivity.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/SetupActivity.kt@@ -5,13 +5,13 @@ import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import com.vayunmathur.library.log.Log+import com.vayunmathur.parentalcontrols.MainActivity import com.vayunmathur.parentalcontrols.auth.ParentPin private const val TAG = "ParentalControlsSetup" /**- * Where `android.app.supervision.action.INSTALL_SUPERVISION_APP` lands, and the only activity- * this app has.+ * Where `android.app.supervision.action.INSTALL_SUPERVISION_APP` lands. * * **It draws nothing.** Settings looks for an activity answering that action so it can show the * Parental controls entry on a device where the supervision app still needs installing, and it is@@ -21,8 +21,9 @@ private const val TAG = "ParentalControlsSetup" * to hand straight to the platform's own setup flow. * * A screen here would be a dead end. Every control - the PIN, schedules, app limits, content- * filters - belongs to Settings, so anything drawn in this app could only tell the user to go- * back to where they already were.+ * filters - lives in the navigation host, so anything drawn in this activity could only tell+ * the user to go back to where they already were. When no PIN exists yet, the host is+ * started at its PIN-setup destination first (behind the platform flow started below). */ class SetupActivity : Activity() { @@ -32,7 +33,7 @@ class SetupActivity : Activity() { // make sure a parent PIN exists. First run lands on PIN creation; afterwards the // platform flow proceeds as before. if (!ParentPin.get(this).isSet()) {- startActivity(Intent(this, PinSetupActivity::class.java))+ startActivity(MainActivity.pinSetupIntent(this)) } val enable = Intent(ACTION_ENABLE_SUPERVISION).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WebContentFiltersScreen.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WebContentFiltersActivity.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WebContentFiltersScreen.ktsimilarity index 74%rename from parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WebContentFiltersActivity.ktrename to parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WebContentFiltersScreen.ktindex 723adca5ec..314ffb0952 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WebContentFiltersActivity.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WebContentFiltersScreen.kt@@ -1,7 +1,5 @@ package com.vayunmathur.parentalcontrols.ui -import androidx.activity.compose.setContent-import androidx.activity.enableEdgeToEdge import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -10,7 +8,6 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.LazyListScaffold import com.vayunmathur.library.ui.SettingsSection import com.vayunmathur.library.ui.SettingsSwitchRow@@ -18,29 +15,12 @@ import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.parentalcontrols.R import com.vayunmathur.parentalcontrols.platform.WebContentFilters -/**- * Web content filters, reached from the parental-controls dashboard. Parent-gated like every- * other control. A single "filter explicit sites" preference; see [WebContentFilters] for the- * note on enforcement.- */-class WebContentFiltersActivity : PinGatedActivity() {-- override fun onPinVerifiedContent() {- enableEdgeToEdge()- setContent {- DynamicTheme {- WebContentFiltersScreen()- }- }- }-}- /** * The single-toggle web-filter editor. * * [enabled]/[onEnabledChange] are hoisted so screenshot previews can drive the screen with * literals; when left null the screen owns its state and persists it via [WebContentFilters],- * which is how the activity uses it.+ * which is how the host route uses it. */ @Composable fun WebContentFiltersScreen(
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WindowActivities.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WindowActivities.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WindowActivities.ktdeleted file mode 100644index fd54795cc7..0000000000--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WindowActivities.kt+++ /dev/null@@ -1,120 +0,0 @@-package com.vayunmathur.parentalcontrols.ui--import androidx.activity.compose.setContent-import androidx.activity.enableEdgeToEdge-import androidx.activity.viewModels-import androidx.compose.runtime.getValue-import androidx.compose.ui.res.stringResource-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.parentalcontrols.R-import com.vayunmathur.parentalcontrols.platform.SupervisionViewModel--/**- * The daytime downtime window, reached from Settings > Parental controls.- *- * Inside the window only allow-listed apps open; everything else waits it out. Parent-gated- * like every other imposed-enforcement surface.- */-class DowntimeActivity : PinGatedActivity() {-- private val viewModel: SupervisionViewModel by viewModels()-- override fun onPinVerifiedContent() {- enableEdgeToEdge()- setContent {- DynamicTheme {- val state by viewModel.state.collectAsStateWithLifecycle()- WindowScheduleScreen(- title = stringResource(R.string.downtime_title),- enableLabel = stringResource(R.string.downtime_enable),- enableHint = stringResource(R.string.downtime_enable_hint),- startLabel = stringResource(R.string.schedule_start),- endLabel = stringResource(R.string.schedule_end),- daysLabel = stringResource(R.string.schedule_days),- appsLabel = stringResource(R.string.downtime_apps),- dayInitials = stringResource(R.string.bedtime_day_initials),- enabled = state.downtime.enabled,- startMinute = state.downtime.startMinute,- endMinute = state.downtime.endMinute,- daysMask = state.downtime.daysMask,- apps = state.apps,- loading = state.loading,- actions = WindowScheduleActions(- onEnabledChange = viewModel::setDowntimeEnabled,- onStartChange = viewModel::setDowntimeStart,- onEndChange = viewModel::setDowntimeEnd,- onToggleDay = viewModel::toggleDowntimeDay,- onAppAllowChange = viewModel::setAllowedInDowntime,- ),- )- }- }- }-}--/**- * The school-hours window, reached from Settings > Parental controls.- *- * Same mechanics as downtime with school-friendly defaults (weekdays 08:00-15:00); the- * allow-list is shared, so approving a learning app covers both windows. Parent-gated.- */-class SchoolTimeActivity : PinGatedActivity() {-- private val viewModel: SupervisionViewModel by viewModels()-- override fun onPinVerifiedContent() {- enableEdgeToEdge()- setContent {- DynamicTheme {- val state by viewModel.state.collectAsStateWithLifecycle()- WindowScheduleScreen(- title = stringResource(R.string.school_title),- enableLabel = stringResource(R.string.school_enable),- enableHint = stringResource(R.string.school_enable_hint),- startLabel = stringResource(R.string.schedule_start),- endLabel = stringResource(R.string.schedule_end),- daysLabel = stringResource(R.string.schedule_days),- appsLabel = stringResource(R.string.school_apps),- dayInitials = stringResource(R.string.bedtime_day_initials),- enabled = state.schoolTime.enabled,- startMinute = state.schoolTime.startMinute,- endMinute = state.schoolTime.endMinute,- daysMask = state.schoolTime.daysMask,- apps = state.apps,- loading = state.loading,- actions = WindowScheduleActions(- onEnabledChange = viewModel::setSchoolTimeEnabled,- onStartChange = viewModel::setSchoolTimeStart,- onEndChange = viewModel::setSchoolTimeEnd,- onToggleDay = viewModel::toggleSchoolTimeDay,- onAppAllowChange = viewModel::setAllowedInDowntime,- ),- )- }- }- }-}--/**- * The device-wide daily budget, reached from Settings > Parental controls.- *- * One cap for the whole device on top of the per-app caps in AppLimitsActivity. Parent-gated.- */-class DailyLimitActivity : PinGatedActivity() {-- private val viewModel: SupervisionViewModel by viewModels()-- override fun onPinVerifiedContent() {- enableEdgeToEdge()- setContent {- DynamicTheme {- val state by viewModel.state.collectAsStateWithLifecycle()- DailyLimitScreen(- currentMinutes = state.dailyLimitMinutes,- actions = DailyLimitActions(onLimitChange = viewModel::setDeviceDailyLimit),- )- }- }- }-}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.ktindex e46f0342f7..18416416d5 100644--- a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt@@ -37,23 +37,52 @@ class ParentalActivitiesTest { .setSingleConnectionPool() .allowMainThreadQueries().build().also { sharedDb = it } synchronized(databases) { databases[ParentalControlsDatabase::class] = mem }+ // Force the database open: closing a prior activity scenario can drop an+ // in-memory database's tables, and the first query re-creates them.+ runCatching { kotlinx.coroutines.runBlocking { mem.appRuleDao().all() } } } @Test- fun dashboardActivityShowsDashboardAndOpensEditors() {+ fun dashboardShowsDashboardAndOpensEditorsThroughGate() { seedDatabase()- ActivityScenario.launch(DashboardActivity::class.java).use { scenario ->+ com.vayunmathur.parentalcontrols.platform.FakeAndroidKeyStore.install()+ com.vayunmathur.parentalcontrols.auth.ParentPin.get(+ ApplicationProvider.getApplicationContext(),+ ).set("1234")+ ActivityScenario.launch(com.vayunmathur.parentalcontrols.MainActivity::class.java).use { scenario -> composeRule.onNodeWithText("Parental controls").assertIsDisplayed() composeRule.onNodeWithText("Controls for this phone").assertIsDisplayed()- var started: Intent? = null- scenario.onActivity { started = shadowOf(it).nextStartedActivity } composeRule.onNodeWithText("Daily limit").performClick()- scenario.onActivity { started = shadowOf(it).peekNextStartedActivity() }- assertEquals(DailyLimitActivity::class.java.name, started?.component?.className)+ composeRule.onNodeWithText("Parent PIN").assertIsDisplayed()+ composeRule.onNodeWithText("PIN").performTextInput("1234")+ composeRule.onNodeWithText("Unlock").performClick()+ waitForText("Daily limit")+ composeRule.onNodeWithText("Daily limit").assertIsDisplayed()+ scenario.onActivity { it.onBackPressedDispatcher.onBackPressed() } composeRule.onNodeWithText("App limits").performClick()- scenario.onActivity { started = shadowOf(it).peekNextStartedActivity() }- assertEquals(AppLimitsActivity::class.java.name, started?.component?.className)+ composeRule.onNodeWithText("PIN").performTextInput("1234")+ composeRule.onNodeWithText("Unlock").performClick()+ waitForText("App limits")+ composeRule.onNodeWithText("App limits").assertIsDisplayed()+ scenario.onActivity { it.onBackPressedDispatcher.onBackPressed() }+ composeRule.onNodeWithText("Web content filters").performClick()+ composeRule.onNodeWithText("PIN").performTextInput("1234")+ composeRule.onNodeWithText("Unlock").performClick()+ waitForText("Web content filters")+ composeRule.onNodeWithText("Web content filters").assertIsDisplayed()+ }+ }++ private fun waitForText(text: String) {+ val deadline = System.currentTimeMillis() + 10_000+ while (System.currentTimeMillis() < deadline) {+ val found = runCatching {+ composeRule.onNodeWithText(text).assertIsDisplayed(); true+ }.getOrDefault(false)+ if (found) return+ Thread.sleep(50) }+ composeRule.onNodeWithText(text).assertIsDisplayed() } @Test@@ -67,12 +96,17 @@ class ParentalActivitiesTest { } @Test- fun pinSetupActivityRendersAndCancels() {- ActivityScenario.launch(PinSetupActivity::class.java).use {+ fun pinSetupRouteRendersAndCancelsToDashboard() {+ seedDatabase()+ ActivityScenario.launch<com.vayunmathur.parentalcontrols.MainActivity>(+ com.vayunmathur.parentalcontrols.MainActivity.pinSetupIntent(+ ApplicationProvider.getApplicationContext(),+ ),+ ).use { composeRule.onNodeWithText("Set parent PIN").assertIsDisplayed() composeRule.onNodeWithText("New PIN").assertIsDisplayed() composeRule.onNodeWithText("Cancel").performClick()- it.onActivity { activity -> assertTrue(activity.isFinishing) }+ composeRule.onNodeWithText("Parental controls").assertIsDisplayed() } } @@ -100,50 +134,49 @@ class ParentalActivitiesTest { } @Test- fun pinGatedActivitiesShowContentAfterVerification() {+ fun gatedRoutesShowContentAfterVerification() { seedDatabase() com.vayunmathur.parentalcontrols.platform.FakeAndroidKeyStore.install() com.vayunmathur.parentalcontrols.auth.ParentPin.get( ApplicationProvider.getApplicationContext(), ).set("1234") val cases = listOf(- BedtimeActivity::class.java to "Child bedtime",- AppLimitsActivity::class.java to "App limits",- DailyLimitActivity::class.java to "Daily limit",- DowntimeActivity::class.java to "Downtime",- SchoolTimeActivity::class.java to "School time",- WebContentFiltersActivity::class.java to "Web content filters",+ com.vayunmathur.parentalcontrols.MainActivity.ACTION_BEDTIME to "Child bedtime",+ com.vayunmathur.parentalcontrols.MainActivity.ACTION_APP_LIMITS to "App limits",+ com.vayunmathur.parentalcontrols.MainActivity.ACTION_DAILY_LIMIT to "Daily limit",+ com.vayunmathur.parentalcontrols.MainActivity.ACTION_DOWNTIME to "Downtime",+ com.vayunmathur.parentalcontrols.MainActivity.ACTION_SCHOOL_TIME to "School time", )- for ((activity, title) in cases) {- ActivityScenario.launch<android.app.Activity>(Intent(ApplicationProvider.getApplicationContext(), activity)).use { scenario ->- var delivered = false- scenario.onActivity { launched ->- val shadow = shadowOf(launched)- val forResult = shadow.nextStartedActivityForResult- if (forResult != null) {- shadow.receiveResult(forResult.intent, PinGateActivity.RESULT_VERIFIED, null)- delivered = true- }- }- assertTrue(delivered, "no gate launched for $activity")+ for ((action, title) in cases) {+ val intent = Intent(action)+ .setClass(+ ApplicationProvider.getApplicationContext(),+ com.vayunmathur.parentalcontrols.MainActivity::class.java,+ )+ ActivityScenario.launch<android.app.Activity>(intent).use {+ composeRule.onNodeWithText("Parent PIN").assertIsDisplayed()+ composeRule.onNodeWithText("PIN").performTextInput("1234")+ composeRule.onNodeWithText("Unlock").performClick()+ waitForText(title) composeRule.onNodeWithText(title).assertIsDisplayed() } } } @Test- fun pinGatedActivityFinishesWhenGateCancelled() {+ fun gatedHostFinishesWhenGateCancelled() { seedDatabase() com.vayunmathur.parentalcontrols.platform.FakeAndroidKeyStore.install() com.vayunmathur.parentalcontrols.auth.ParentPin.get( ApplicationProvider.getApplicationContext(), ).set("1234")- ActivityScenario.launch(BedtimeActivity::class.java).use { scenario ->- scenario.onActivity { launched ->- val shadow = shadowOf(launched)- val forResult = shadow.nextStartedActivityForResult- shadow.receiveResult(forResult.intent, android.app.Activity.RESULT_CANCELED, null)- }+ val intent = Intent(com.vayunmathur.parentalcontrols.MainActivity.ACTION_BEDTIME)+ .setClass(+ ApplicationProvider.getApplicationContext(),+ com.vayunmathur.parentalcontrols.MainActivity::class.java,+ )+ ActivityScenario.launch<android.app.Activity>(intent).use { scenario ->+ composeRule.onNodeWithText("Cancel").performClick() scenario.onActivity { launched -> assertTrue(launched.isFinishing) } } }