Modern Apps git

← Modern-Apps.git

parentalcontrols: downtime, school time, daily limit, bonus, parent PIN

Commit
db4a16541aac839318825985a7b0aa841e028de9
Author
vayun-mathur <[email protected]>
When
2026-09-14 04:52 UTC (2 months ago)
Parents
f9436ac

Diff

parentalcontrols/src/main/AndroidManifest.xml
diff --git a/parentalcontrols/src/main/AndroidManifest.xml b/parentalcontrols/src/main/AndroidManifest.xmlindex 75297a7135..8545954fdc 100644--- a/parentalcontrols/src/main/AndroidManifest.xml+++ b/parentalcontrols/src/main/AndroidManifest.xml@@ -37,6 +37,8 @@     <!-- The app-limits and bedtime screens list launchable apps to choose between. -->     <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"         tools:ignore="QueryAllPackagesPermission" />+    <!-- Restriction notices (limit spent, window opened) tap through to the lock screens. -->+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />      <!-- Not requested, deliberately: no INTERNET. Nothing here leaves the device - the schedule,          the caps and which apps they cover are all local, and there is no account to sync to. -->@@ -151,6 +153,70 @@                 android:resource="@string/limits_summary" />         </activity> +        <!--+          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+          opening them directly.+        -->+        <activity+            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">+            <intent-filter>+                <action android:name="com.vayunmathur.parentalcontrols.action.DOWNTIME" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+            <meta-data+                android:name="com.android.settings.category"+                android:value="com.android.settings.category.ia.supervision" />+            <meta-data+                android:name="com.android.settings.summary"+                android:resource="@string/downtime_summary" />+        </activity>++        <activity+            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">+            <intent-filter>+                <action android:name="com.vayunmathur.parentalcontrols.action.SCHOOL_TIME" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+            <meta-data+                android:name="com.android.settings.category"+                android:value="com.android.settings.category.ia.supervision" />+            <meta-data+                android:name="com.android.settings.summary"+                android:resource="@string/school_summary" />+        </activity>++        <activity+            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">+            <intent-filter>+                <action android:name="com.vayunmathur.parentalcontrols.action.DAILY_LIMIT" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+            <meta-data+                android:name="com.android.settings.category"+                android:value="com.android.settings.category.ia.supervision" />+            <meta-data+                android:name="com.android.settings.summary"+                android:resource="@string/daily_summary" />+        </activity>+         <!--           Where Settings sends the user for "app settings" of a supervision app. Without an           activity answering this, `createSupervisionAppPreference` throws IllegalStateException@@ -208,5 +274,55 @@                 <category android:name="android.intent.category.DEFAULT" />             </intent-filter>         </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.+        -->+        <activity+            android:name=".ui.PinGateActivity"+            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" />+        <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+          explicitly by our own receivers and notifications. showWhenLocked is set in code so+          the child meets the reason over the keyguard, not a home screen.+        -->+        <activity+            android:name=".ui.BedtimeLockActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="false"+            android:theme="@style/Theme.General" />+        <activity+            android:name=".ui.DowntimeLockActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="false"+            android:theme="@style/Theme.General" />+        <activity+            android:name=".ui.SchoolTimeLockActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="false"+            android:theme="@style/Theme.General" />+        <activity+            android:name=".ui.DailyLimitLockActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="false"+            android:theme="@style/Theme.General" />+        <activity+            android:name=".ui.AppLimitLockActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="false"+            android:theme="@style/Theme.General" />     </application> </manifest>
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/auth/ParentPin.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/auth/ParentPin.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/auth/ParentPin.ktnew file mode 100644index 0000000000..c5f9a20383--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/auth/ParentPin.kt@@ -0,0 +1,126 @@+package com.vayunmathur.parentalcontrols.auth++import android.content.Context+import android.util.Base64+import androidx.core.content.edit+import com.vayunmathur.library.util.DatabaseHelper+import java.security.MessageDigest+import java.security.SecureRandom++/**+ * The parent PIN that gates every imposed-enforcement surface.+ *+ * Family Link verifies the parent through their Google account on another device; there is no+ * account here, so the parent proves themselves with a PIN entered on this device. The PIN+ * itself is never stored: a random salt plus SHA-256(salt + PIN) is kept keystore-wrapped via+ * [DatabaseHelper], so the verifier is bound to this device's hardware and unreadable off it.+ *+ * Only UI flows touch this class - setup, editor opens, mutations, lock-screen unlock, bonus+ * grants. Enforcement ([Enforcer.reconcile] and everything it calls) never needs the PIN, so+ * boot-time and background enforcement work with no credential available. That is also why+ * credential-protected storage is fine here: nothing on the boot path reads the verifier.+ *+ * Brute force is throttled: 5 wrong attempts lock verification for a minute, doubling each+ * subsequent failure up to 30 minutes. The counter lives beside the verifier so clearing app+ * data (which wipes both) also wipes the rules database - there is nothing left to protect.+ */+class ParentPin(context: Context) : DatabaseHelper(context) {++    override val keyStoreAlias = "parentalcontrols_parent_pin"+    override val sharedPrefsName = PREFS+    override val passphraseKey = "pin_verifier"+    override val ivKey = "pin_verifier_iv"++    /** Whether a parent PIN has been set. */+    fun isSet(): Boolean = isKeyGenerated()++    /**+     * Sets (or resets) the PIN. The caller must have verified the old PIN first when one+     * exists - this function does not check it.+     */+    fun set(pin: String) {+        require(pin.length >= MIN_LENGTH) { "PIN too short" }+        val salt = ByteArray(SALT_BYTES).also { SecureRandom().nextBytes(it) }+        storePassphrase(verifierFor(salt, pin))+        prefs().edit {+            putString(KEY_SALT_B64, Base64.encodeToString(salt, Base64.NO_WRAP))+            remove(KEY_ATTEMPTS)+            remove(KEY_LOCKOUT_UNTIL)+        }+    }++    /** Clears the PIN entirely. Supervision stays configured; editors just stop asking. */+    fun clear() = deleteKey()++    /**+     * Verifies [pin], honoring the brute-force lockout.+     *+     * Returns true only on a correct, non-locked-out attempt. A correct attempt resets the+     * failure counter; a wrong one increments it and may start a lockout.+     */+    fun verify(pin: String): Boolean {+        if (!isSet()) return false+        if (isLockedOut()) return false+        val saltB64 = prefs().getString(KEY_SALT_B64, null) ?: return false+        val salt = Base64.decode(saltB64, Base64.NO_WRAP)+        val expected = runCatching { getPassphrase() }.getOrNull() ?: return false+        val actual = verifierFor(salt, pin)+        return if (MessageDigest.isEqual(expected.toByteArray(), actual.toByteArray())) {+            prefs().edit { remove(KEY_ATTEMPTS); remove(KEY_LOCKOUT_UNTIL) }+            true+        } else {+            recordFailure()+            false+        }+    }++    /** Milliseconds until verification is allowed again, or 0 when not locked out. */+    fun lockoutRemainingMillis(): Long {+        val until = prefs().getLong(KEY_LOCKOUT_UNTIL, 0)+        return (until - System.currentTimeMillis()).coerceAtLeast(0)+    }++    fun isLockedOut(): Boolean = lockoutRemainingMillis() > 0++    private fun recordFailure() {+        val attempts = prefs().getInt(KEY_ATTEMPTS, 0) + 1+        val editor = prefs().edit().putInt(KEY_ATTEMPTS, attempts)+        if (attempts >= FREE_ATTEMPTS) {+            val shift = (attempts - FREE_ATTEMPTS).coerceAtMost(MAX_DOUBLINGS)+            val lockout = BASE_LOCKOUT_MILLIS shl shift+            editor.putLong(KEY_LOCKOUT_UNTIL, System.currentTimeMillis() + lockout)+        }+        editor.apply()+    }++    private fun verifierFor(salt: ByteArray, pin: String): String {+        val digest = MessageDigest.getInstance("SHA-256")+        digest.update(salt)+        digest.update(pin.toByteArray(Charsets.UTF_8))+        return Base64.encodeToString(digest.digest(), Base64.NO_WRAP)+    }++    private fun prefs() =+        context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++    companion object {+        const val PREFS = "parentalcontrols_pin"+        const val MIN_LENGTH = 4++        private const val KEY_SALT_B64 = "salt_b64"+        private const val KEY_ATTEMPTS = "attempts"+        private const val KEY_LOCKOUT_UNTIL = "lockout_until"++        private const val SALT_BYTES = 16+        private const val FREE_ATTEMPTS = 5+        private const val BASE_LOCKOUT_MILLIS = 60_000L+        private const val MAX_DOUBLINGS = 4++        @Volatile private var instance: ParentPin? = null++        fun get(context: Context): ParentPin =+            instance ?: synchronized(this) {+                instance ?: ParentPin(context).also { instance = it }+            }+    }+}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/Migrations.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/Migrations.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/Migrations.ktnew file mode 100644index 0000000000..f764852a65--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/Migrations.kt@@ -0,0 +1,50 @@+package com.vayunmathur.parentalcontrols.data++import androidx.room3.migration.Migration+import androidx.sqlite.SQLiteConnection+import androidx.sqlite.execSQL++/**+ * Version 1 held bedtime + per-app caps. Version 2 adds the Family Link set: downtime and+ * school-time windows, the device-wide daily limit, one-shot bonus grants, and the+ * downtime allow-list column on [AppRule].+ *+ * All new tables start empty (every new feature defaults to off) and the new column defaults+ * to blocked-everywhere, so existing installs keep exactly the behavior they had.+ */+val MIGRATION_1_2: Migration =+    object : Migration(1, 2) {+        override suspend fun migrate(connection: SQLiteConnection) {+            connection.execSQL(+                "CREATE TABLE IF NOT EXISTS DowntimeSchedule (" ++                    "id INTEGER NOT NULL PRIMARY KEY, " ++                    "enabled INTEGER NOT NULL DEFAULT 0, " ++                    "startMinute INTEGER NOT NULL DEFAULT 720, " ++                    "endMinute INTEGER NOT NULL DEFAULT 840, " ++                    "daysMask INTEGER NOT NULL DEFAULT 127)",+            )+            connection.execSQL(+                "CREATE TABLE IF NOT EXISTS SchoolTimeSchedule (" ++                    "id INTEGER NOT NULL PRIMARY KEY, " ++                    "enabled INTEGER NOT NULL DEFAULT 0, " ++                    "startMinute INTEGER NOT NULL DEFAULT 480, " ++                    "endMinute INTEGER NOT NULL DEFAULT 900, " ++                    "daysMask INTEGER NOT NULL DEFAULT 31)",+            )+            connection.execSQL(+                "CREATE TABLE IF NOT EXISTS DailyLimit (" ++                    "id INTEGER NOT NULL PRIMARY KEY, " ++                    "dailyLimitMinutes INTEGER)",+            )+            connection.execSQL(+                "CREATE TABLE IF NOT EXISTS BonusGrant (" ++                    "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " ++                    "packageName TEXT, " ++                    "bonusMinutes INTEGER NOT NULL DEFAULT 0, " ++                    "day TEXT NOT NULL DEFAULT '')",+            )+            connection.execSQL(+                "ALTER TABLE AppRule ADD COLUMN allowedInDowntime INTEGER NOT NULL DEFAULT 0",+            )+        }+    }
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/ParentalControlsDatabase.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/ParentalControlsDatabase.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/ParentalControlsDatabase.ktindex 353553ba14..1c4c719c0d 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/ParentalControlsDatabase.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/ParentalControlsDatabase.kt@@ -40,8 +40,71 @@ interface BedtimeDao {     suspend fun upsert(schedule: BedtimeSchedule) } -@Database(entities = [AppRule::class, BedtimeSchedule::class], version = 1, exportSchema = false)+@Dao+interface DowntimeDao {+    @Query("SELECT * FROM DowntimeSchedule WHERE id = :id")+    fun scheduleFlow(id: Int = DowntimeSchedule.SINGLETON_ID): Flow<DowntimeSchedule?>++    @Query("SELECT * FROM DowntimeSchedule WHERE id = :id")+    suspend fun schedule(id: Int = DowntimeSchedule.SINGLETON_ID): DowntimeSchedule?++    @Upsert+    suspend fun upsert(schedule: DowntimeSchedule)+}++@Dao+interface SchoolTimeDao {+    @Query("SELECT * FROM SchoolTimeSchedule WHERE id = :id")+    fun scheduleFlow(id: Int = SchoolTimeSchedule.SINGLETON_ID): Flow<SchoolTimeSchedule?>++    @Query("SELECT * FROM SchoolTimeSchedule WHERE id = :id")+    suspend fun schedule(id: Int = SchoolTimeSchedule.SINGLETON_ID): SchoolTimeSchedule?++    @Upsert+    suspend fun upsert(schedule: SchoolTimeSchedule)+}++@Dao+interface DailyLimitDao {+    @Query("SELECT * FROM DailyLimit WHERE id = :id")+    fun limitFlow(id: Int = DailyLimit.SINGLETON_ID): Flow<DailyLimit?>++    @Query("SELECT * FROM DailyLimit WHERE id = :id")+    suspend fun limit(id: Int = DailyLimit.SINGLETON_ID): DailyLimit?++    @Upsert+    suspend fun upsert(limit: DailyLimit)+}++@Dao+interface BonusGrantDao {+    @Query("SELECT * FROM BonusGrant WHERE day = :day")+    suspend fun forDay(day: String): List<BonusGrant>++    @Upsert+    suspend fun upsert(grant: BonusGrant)++    @Query("DELETE FROM BonusGrant WHERE day != :day")+    suspend fun pruneForeignDays(day: String)+}++@Database(+    entities = [+        AppRule::class,+        BedtimeSchedule::class,+        DowntimeSchedule::class,+        SchoolTimeSchedule::class,+        DailyLimit::class,+        BonusGrant::class,+    ],+    version = 2,+    exportSchema = false,+) abstract class ParentalControlsDatabase : RoomDatabase() {     abstract fun appRuleDao(): AppRuleDao     abstract fun bedtimeDao(): BedtimeDao+    abstract fun downtimeDao(): DowntimeDao+    abstract fun schoolTimeDao(): SchoolTimeDao+    abstract fun dailyLimitDao(): DailyLimitDao+    abstract fun bonusGrantDao(): BonusGrantDao }
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/Rules.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/Rules.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/Rules.ktindex 7f69bbfb6d..cdd64a6888 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/Rules.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/Rules.kt@@ -2,6 +2,7 @@ package com.vayunmathur.parentalcontrols.data  import androidx.room3.Entity import androidx.room3.PrimaryKey+import com.vayunmathur.parentalcontrols.domain.TimeWindow  /**  * What supervision does to one app.@@ -26,6 +27,13 @@ data class AppRule(     val dailyLimitMinutes: Int? = null,     /** Whether this app is blocked during the bedtime window. */     val blockedAtBedtime: Boolean = false,+    /**+     * Whether this app stays usable during downtime and school time.+     *+     * During those windows everything else is blocked, so this is the allow-list. Defaults to+     * false: a newly restricted app is blocked everywhere until the parent approves it.+     */+    val allowedInDowntime: Boolean = false, )  /**@@ -49,28 +57,25 @@ data class BedtimeSchedule(     val daysMask: Int = ALL_DAYS, ) {     /** Whether [minuteOfDay] on [dayIndex] (0 = Monday) falls inside the window. */-    fun contains(dayIndex: Int, minuteOfDay: Int): Boolean {-        if (!enabled) return false-        return if (startMinute <= endMinute) {-            // Same-day window.-            isDaySet(dayIndex) && minuteOfDay >= startMinute && minuteOfDay < endMinute-        } else {-            // Crosses midnight. The evening half belongs to `dayIndex`; the morning half belongs-            // to the *previous* day's window, so that "Fri 21:00-07:00" still applies at 02:00-            // on Saturday.-            (isDaySet(dayIndex) && minuteOfDay >= startMinute) ||-                (isDaySet((dayIndex + 6) % DAYS_IN_WEEK) && minuteOfDay < endMinute)-        }-    }+    fun contains(dayIndex: Int, minuteOfDay: Int): Boolean =+        asWindow().contains(dayIndex, minuteOfDay)      fun isDaySet(dayIndex: Int): Boolean = (daysMask shr dayIndex) and 1 == 1 +    private fun asWindow(): TimeWindow =+        TimeWindow(+            enabled = enabled,+            startMinute = startMinute,+            endMinute = endMinute,+            daysMask = daysMask,+        )+     companion object {         /** There is one schedule. The table exists so Room can store it, not to hold many. */         const val SINGLETON_ID = 0-        const val DAYS_IN_WEEK = 7-        const val ALL_DAYS = 0b111_1111-        const val MINUTES_PER_DAY = 24 * 60+        const val DAYS_IN_WEEK = TimeWindow.DAYS_IN_WEEK+        const val ALL_DAYS = TimeWindow.ALL_DAYS+        const val MINUTES_PER_DAY = TimeWindow.MINUTES_PER_DAY          /** 21:00. */         const val DEFAULT_START_MINUTE = 21 * 60@@ -79,3 +84,127 @@ data class BedtimeSchedule(         const val DEFAULT_END_MINUTE = 7 * 60     } }++/**+ * The daytime window during which only parent-approved apps are available.+ *+ * Same shape as [BedtimeSchedule] with its own on/off, times and days, so the two windows can+ * overlap or sit apart without interfering. Defaults to off; when on, everything not explicitly+ * allowed is blocked. The allow-list lives on [AppRule]: an app usable during downtime carries+ * `allowedInDowntime = true`.+ */+@Entity+data class DowntimeSchedule(+    @PrimaryKey val id: Int = SINGLETON_ID,+    val enabled: Boolean = false,+    /** Minutes past local midnight at which the window opens. */+    val startMinute: Int = DEFAULT_START_MINUTE,+    /** Minutes past local midnight at which it closes. */+    val endMinute: Int = DEFAULT_END_MINUTE,+    /** Bitmask of days the window applies to, bit 0 = Monday. */+    val daysMask: Int = TimeWindow.ALL_DAYS,+) {+    /** Whether [minuteOfDay] on [dayIndex] (0 = Monday) falls inside the window. */+    fun contains(dayIndex: Int, minuteOfDay: Int): Boolean =+        asWindow().contains(dayIndex, minuteOfDay)++    private fun asWindow(): TimeWindow =+        TimeWindow(+            enabled = enabled,+            startMinute = startMinute,+            endMinute = endMinute,+            daysMask = daysMask,+        )++    companion object {+        /** There is one schedule. The table exists so Room can store it, not to hold many. */+        const val SINGLETON_ID = 0++        /** 12:00. */+        const val DEFAULT_START_MINUTE = 12 * 60++        /** 14:00. */+        const val DEFAULT_END_MINUTE = 14 * 60+    }+}++/**+ * The school-hours window during which only learning apps are available.+ *+ * Same shape as [BedtimeSchedule] with its own on/off, times and days. Defaults to 08:00-15:00+ * on weekdays, off until the parent enables it. The allow-list is shared with downtime: an app+ * usable during school carries `allowedInDowntime = true`.+ */+@Entity+data class SchoolTimeSchedule(+    @PrimaryKey val id: Int = SINGLETON_ID,+    val enabled: Boolean = false,+    /** Minutes past local midnight at which the window opens. */+    val startMinute: Int = DEFAULT_START_MINUTE,+    /** Minutes past local midnight at which it closes. */+    val endMinute: Int = DEFAULT_END_MINUTE,+    /** Bitmask of days the window applies to, bit 0 = Monday. */+    val daysMask: Int = TimeWindow.WEEKDAYS,+) {+    /** Whether [minuteOfDay] on [dayIndex] (0 = Monday) falls inside the window. */+    fun contains(dayIndex: Int, minuteOfDay: Int): Boolean =+        asWindow().contains(dayIndex, minuteOfDay)++    private fun asWindow(): TimeWindow =+        TimeWindow(+            enabled = enabled,+            startMinute = startMinute,+            endMinute = endMinute,+            daysMask = daysMask,+        )++    companion object {+        /** There is one schedule. The table exists so Room can store it, not to hold many. */+        const val SINGLETON_ID = 0++        /** 08:00. */+        const val DEFAULT_START_MINUTE = 8 * 60++        /** 15:00. */+        const val DEFAULT_END_MINUTE = 15 * 60+    }+}++/**+ * The device-wide daily screen-time budget, mirroring Family Link's daily limit.+ *+ * Null means no device-wide cap; per-app caps still live on [AppRule.dailyLimitMinutes]. When+ * the budget is spent, everything except calls and parent-approved apps locks until midnight,+ * with the same lock-screen UX as an app limit. Stored as minutes so the UI offers the same+ * fixed choices as per-app limits.+ */+@Entity+data class DailyLimit(+    @PrimaryKey val id: Int = SINGLETON_ID,+    /** Minutes of screen time permitted per day, or null for no device-wide limit. */+    val dailyLimitMinutes: Int? = null,+) {+    companion object {+        /** There is one limit. The table exists so Room can store it, not to hold many. */+        const val SINGLETON_ID = 0+    }+}++/**+ * A one-shot grant of extra minutes, given on-device by the parent from a lock screen.+ *+ * Family Link's bonus time, without the cloud: the child taps "ask for more time", the parent+ * enters the PIN on the same device, and the grant extends today's budget. Rows are stamped+ * with the day they belong to so a grant can never leak into tomorrow; the enforcer prunes+ * foreign-day rows on reconcile.+ */+@Entity+data class BonusGrant(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    /** Package the grant applies to, or null for a device-wide (daily-limit) grant. */+    val packageName: String? = null,+    /** Extra minutes added to today's budget for [packageName]. */+    val bonusMinutes: Int = 0,+    /** Local date the grant belongs to, ISO-8601 (yyyy-MM-dd). */+    val day: String = "",+)
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/SupervisionRules.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/SupervisionRules.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/SupervisionRules.ktindex 77cc16a99f..5d9d87eeb5 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/SupervisionRules.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/data/SupervisionRules.kt@@ -13,10 +13,19 @@ import kotlinx.coroutines.flow.map  * dependency: enforcement runs with no Activity alive.  */ class SupervisionRules private constructor(context: Context) :-    RoomRepository<ParentalControlsDatabase>(context, ParentalControlsDatabase::class, DB_NAME) {+    RoomRepository<ParentalControlsDatabase>(+        context,+        ParentalControlsDatabase::class,+        DB_NAME,+        migrations = listOf(MIGRATION_1_2),+    ) {      private val rules get() = db.appRuleDao()     private val bedtime get() = db.bedtimeDao()+    private val downtime get() = db.downtimeDao()+    private val schoolTime get() = db.schoolTimeDao()+    private val dailyLimit get() = db.dailyLimitDao()+    private val bonus get() = db.bonusGrantDao()      val allRules: Flow<List<AppRule>> = rules.allFlow() @@ -45,6 +54,46 @@ class SupervisionRules private constructor(context: Context) :      suspend fun setSchedule(schedule: BedtimeSchedule) = bedtime.upsert(schedule) +    /**+     * The downtime window, defaulted rather than nullable.+     *+     * Same collapsing as [schedule]: a missing row and a disabled window mean the same thing+     * to every caller.+     */+    val downtimeSchedule: Flow<DowntimeSchedule> =+        downtime.scheduleFlow().map { it ?: DowntimeSchedule() }++    suspend fun downtimeNow(): DowntimeSchedule = downtime.schedule() ?: DowntimeSchedule()++    suspend fun setDowntime(schedule: DowntimeSchedule) = downtime.upsert(schedule)++    /** The school-time window, defaulted rather than nullable. */+    val schoolTimeSchedule: Flow<SchoolTimeSchedule> =+        schoolTime.scheduleFlow().map { it ?: SchoolTimeSchedule() }++    suspend fun schoolTimeNow(): SchoolTimeSchedule =+        schoolTime.schedule() ?: SchoolTimeSchedule()++    suspend fun setSchoolTime(schedule: SchoolTimeSchedule) = schoolTime.upsert(schedule)++    /** The device-wide daily budget in minutes, or null for no device-wide cap. */+    val dailyLimitMinutes: Flow<Int?> = dailyLimit.limitFlow().map { it?.dailyLimitMinutes }++    suspend fun dailyLimitNow(): Int? = dailyLimit.limit()?.dailyLimitMinutes++    suspend fun setDailyLimit(minutes: Int?) = dailyLimit.upsert(DailyLimit(dailyLimitMinutes = minutes))++    /**+     * Today's bonus grants, with foreign-day rows pruned first so a grant can never leak into+     * tomorrow.+     */+    suspend fun bonusesToday(day: String): List<BonusGrant> {+        bonus.pruneForeignDays(day)+        return bonus.forDay(day)+    }++    suspend fun grantBonus(grant: BonusGrant) = bonus.upsert(grant)+     companion object {         @Volatile private var instance: SupervisionRules? = null 
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/domain/TimeWindow.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/domain/TimeWindow.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/domain/TimeWindow.ktnew file mode 100644index 0000000000..ccf6cee233--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/domain/TimeWindow.kt@@ -0,0 +1,45 @@+package com.vayunmathur.parentalcontrols.domain++/**+ * A recurring daily window stored as minutes past local midnight.+ *+ * Minutes-past-midnight (rather than a timestamp) survives timezone changes and DST the way a+ * user expects: "9pm" means 9pm wherever the device is. [startMinute] greater than [endMinute]+ * is the normal case, not an error - a window that crosses midnight.+ *+ * Bedtime, downtime and school time are three answers to one question - when may apps be used -+ * so they share this predicate while keeping separate rows (separate on/off, times and days).+ */+data class TimeWindow(+    val enabled: Boolean = false,+    /** Minutes past local midnight at which the window opens. */+    val startMinute: Int = 0,+    /** Minutes past local midnight at which it closes. */+    val endMinute: Int = 0,+    /** Bitmask of days the window applies to, bit 0 = Monday. */+    val daysMask: Int = ALL_DAYS,+) {+    /** Whether [minuteOfDay] on [dayIndex] (0 = Monday) falls inside the window. */+    fun contains(dayIndex: Int, minuteOfDay: Int): Boolean {+        if (!enabled) return false+        return if (startMinute <= endMinute) {+            // Same-day window.+            isDaySet(dayIndex) && minuteOfDay >= startMinute && minuteOfDay < endMinute+        } else {+            // Crosses midnight. The evening half belongs to `dayIndex`; the morning half belongs+            // to the *previous* day's window, so that "Fri 21:00-07:00" still applies at 02:00+            // on Saturday.+            (isDaySet(dayIndex) && minuteOfDay >= startMinute) ||+                (isDaySet((dayIndex + 6) % DAYS_IN_WEEK) && minuteOfDay < endMinute)+        }+    }++    fun isDaySet(dayIndex: Int): Boolean = (daysMask shr dayIndex) and 1 == 1++    companion object {+        const val DAYS_IN_WEEK = 7+        const val ALL_DAYS = 0b111_1111+        const val WEEKDAYS = 0b001_1111+        const val MINUTES_PER_DAY = 24 * 60+    }+}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/notifications/LockNotifier.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/notifications/LockNotifier.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/notifications/LockNotifier.ktnew file mode 100644index 0000000000..6345d31b75--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/notifications/LockNotifier.kt@@ -0,0 +1,110 @@+package com.vayunmathur.parentalcontrols.notifications++import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import androidx.core.app.NotificationCompat+import com.vayunmathur.parentalcontrols.R+import com.vayunmathur.parentalcontrols.platform.Enforcer+import com.vayunmathur.parentalcontrols.ui.AppLimitLockActivity+import com.vayunmathur.parentalcontrols.ui.BaseLockActivity+import com.vayunmathur.parentalcontrols.ui.BedtimeLockActivity+import com.vayunmathur.parentalcontrols.ui.DailyLimitLockActivity+import com.vayunmathur.parentalcontrols.ui.DowntimeLockActivity+import com.vayunmathur.parentalcontrols.ui.SchoolTimeLockActivity++/**+ * Tells the child a restriction has bitten, with a tap target that explains it.+ *+ * Blocking itself is silent - the platform just refuses the launch - so without this the+ * child meets a dead icon and no reason. Each notification carries a full-screen intent to+ * the matching lock activity (which shows over the keyguard per the 0d mechanism) and a+ * content intent to the same place for the tap, so both the heads-up and the shade row land+ * on the reason, the unlock path and - for budgets - the bonus flow.+ *+ * Posted from receivers after [Enforcer.reconcile]: limit trips from `LimitReachedReceiver`,+ * window entries from `BedtimeReceiver`. Deduplicated by notification id per reason, so a+ * flapping boundary updates one row instead of stacking.+ */+object LockNotifier {++    fun notifyLocked(context: Context, reason: Enforcer.BlockReason, blockedPackage: String?) {+        val app = context.applicationContext+        ensureChannel(app)+        val activity = activityFor(reason)+        val intent = BaseLockActivity.intent(app, activity, blockedPackage).apply {+            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+        }+        val pending = PendingIntent.getActivity(+            app,+            reason.ordinal,+            intent,+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        val notification = NotificationCompat.Builder(app, CHANNEL_ID)+            .setSmallIcon(android.R.drawable.ic_lock_lock)+            .setContentTitle(app.getString(titleFor(reason)))+            .setContentText(app.getString(hintFor(reason)))+            .setPriority(NotificationCompat.PRIORITY_HIGH)+            .setCategory(NotificationCompat.CATEGORY_REMINDER)+            .setFullScreenIntent(pending, true)+            .setContentIntent(pending)+            .setAutoCancel(true)+            .build()+        val nm = app.getSystemService(NotificationManager::class.java) ?: return+        // POST_NOTIFICATIONS is a runtime permission; without it this throws, and a missing+        // notice must never break enforcement - the block itself already happened.+        runCatching { nm.notify(NOTIFICATION_ID_BASE + reason.ordinal, notification) }+    }++    fun cancel(context: Context, reason: Enforcer.BlockReason) {+        val nm = context.applicationContext.getSystemService(NotificationManager::class.java)+            ?: return+        runCatching { nm.cancel(NOTIFICATION_ID_BASE + reason.ordinal) }+    }++    private fun activityFor(reason: Enforcer.BlockReason): Class<out BaseLockActivity> =+        when (reason) {+            Enforcer.BlockReason.Bedtime -> BedtimeLockActivity::class.java+            Enforcer.BlockReason.Downtime -> DowntimeLockActivity::class.java+            Enforcer.BlockReason.SchoolTime -> SchoolTimeLockActivity::class.java+            Enforcer.BlockReason.DailyLimit -> DailyLimitLockActivity::class.java+            Enforcer.BlockReason.AppLimit -> AppLimitLockActivity::class.java+        }++    private fun titleFor(reason: Enforcer.BlockReason): Int =+        when (reason) {+            Enforcer.BlockReason.Bedtime -> R.string.lock_bedtime_title+            Enforcer.BlockReason.Downtime -> R.string.lock_downtime_title+            Enforcer.BlockReason.SchoolTime -> R.string.lock_school_title+            Enforcer.BlockReason.DailyLimit -> R.string.lock_daily_title+            Enforcer.BlockReason.AppLimit -> R.string.lock_applimit_title+        }++    private fun hintFor(reason: Enforcer.BlockReason): Int =+        when (reason) {+            Enforcer.BlockReason.Bedtime -> R.string.lock_bedtime_hint+            Enforcer.BlockReason.Downtime -> R.string.lock_downtime_hint+            Enforcer.BlockReason.SchoolTime -> R.string.lock_school_hint+            Enforcer.BlockReason.DailyLimit -> R.string.lock_daily_hint+            Enforcer.BlockReason.AppLimit -> R.string.lock_applimit_hint+        }++    private fun ensureChannel(context: Context) {+        val nm = context.getSystemService(NotificationManager::class.java) ?: return+        nm.createNotificationChannel(+            NotificationChannel(+                CHANNEL_ID,+                context.getString(R.string.lock_channel_name),+                NotificationManager.IMPORTANCE_HIGH,+            ).apply {+                description = context.getString(R.string.lock_channel_description)+            },+        )+    }++    private const val CHANNEL_ID = "restriction_locks"+    private const val NOTIFICATION_ID_BASE = 2_000_000+}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.ktindex 04409af49b..6ccbd85b99 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.kt@@ -6,6 +6,7 @@ import android.content.Context import android.util.Log import androidx.core.content.getSystemService import com.vayunmathur.parentalcontrols.data.AppRule+import com.vayunmathur.parentalcontrols.data.BonusGrant import com.vayunmathur.parentalcontrols.receiver.LimitReachedReceiver import java.lang.reflect.Method import java.time.Duration@@ -49,13 +50,66 @@ class AppLimits(private val context: Context) {      /** Register an observer for every capped app, replacing any previous registration. */     fun sync(rules: List<AppRule>) {+        sync(rules, emptyList())+    }++    /**+     * Register an observer for every capped app, with today's bonus grants extending budgets.+     *+     * A grant for [BonusGrant.packageName] adds [BonusGrant.bonusMinutes] to that app's cap; a+     * grant with null package is device-wide and handled by the daily-limit path, not here.+     */+    fun sync(rules: List<AppRule>, bonuses: List<BonusGrant>) {         val usage = usage ?: return+        val bonusByPackage = bonuses.filter { it.packageName != null }+            .groupBy { it.packageName!! }+            .mapValues { (_, grants) -> grants.sumOf { it.bonusMinutes } }         for (rule in rules) {             val minutes = rule.dailyLimitMinutes ?: continue-            register(usage, rule.packageName, minutes)+            val budget = minutes + (bonusByPackage[rule.packageName] ?: 0)+            register(usage, rule.packageName, budget)+        }+    }++    /**+     * Foreground time for [packageName] since local midnight.+     *+     * `queryAndAggregateUsageStats` is public SDK and needs `PACKAGE_USAGE_STATS`, which is an+     * app-op rather than a role grant - see the manifest note. If it is not held this returns+     * zero, and a cap then measures from the moment it was armed instead of from midnight.+     */+    fun timeUsedToday(packageName: String): Duration {+        val usage = usage ?: return Duration.ZERO+        val stats = runCatching {+            usage.queryAndAggregateUsageStats(midnightMillis(), System.currentTimeMillis())+        }.getOrElse {+            Log.w(TAG, "no usage stats; is PACKAGE_USAGE_STATS granted?", it)+            return Duration.ZERO         }+        val millis = stats[packageName]?.totalTimeInForeground ?: 0L+        return Duration.ofMillis(millis)     } +    /**+     * Total foreground time across all packages since local midnight.+     *+     * Used for the device-wide daily limit. Sums the same per-package map as [timeUsedToday],+     * so both paths agree about what "used" means.+     */+    fun totalUsedToday(): Duration {+        val usage = usage ?: return Duration.ZERO+        val stats = runCatching {+            usage.queryAndAggregateUsageStats(midnightMillis(), System.currentTimeMillis())+        }.getOrElse {+            Log.w(TAG, "no usage stats; is PACKAGE_USAGE_STATS granted?", it)+            return Duration.ZERO+        }+        return Duration.ofMillis(stats.values.sumOf { it.totalTimeInForeground })+    }++    private fun midnightMillis(): Long =+        LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()+     fun unregister(packageName: String) {         val usage = usage ?: return         val method = unregisterMethod ?: return@@ -91,26 +145,6 @@ class AppLimits(private val context: Context) {         }.onFailure { Log.w(TAG, "could not register an observer for $packageName", it) }     } -    /**-     * Foreground time for [packageName] since local midnight.-     *-     * `queryAndAggregateUsageStats` is public SDK and needs `PACKAGE_USAGE_STATS`, which is an-     * app-op rather than a role grant - see the manifest note. If it is not held this returns-     * zero, and a cap then measures from the moment it was armed instead of from midnight.-     */-    private fun timeUsedToday(packageName: String): Duration {-        val usage = usage ?: return Duration.ZERO-        val midnight = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()-        val stats = runCatching {-            usage.queryAndAggregateUsageStats(midnight, System.currentTimeMillis())-        }.getOrElse {-            Log.w(TAG, "no usage stats; is PACKAGE_USAGE_STATS granted?", it)-            return Duration.ZERO-        }-        val millis = stats[packageName]?.totalTimeInForeground ?: 0L-        return Duration.ofMillis(millis)-    }-     /**      * A stable per-package observer id.      *
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.ktindex 504cc96a4e..e90b68104e 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt@@ -6,6 +6,8 @@ import android.content.Context import android.util.Log import androidx.core.content.getSystemService import com.vayunmathur.parentalcontrols.data.BedtimeSchedule+import com.vayunmathur.parentalcontrols.data.DowntimeSchedule+import com.vayunmathur.parentalcontrols.data.SchoolTimeSchedule import com.vayunmathur.parentalcontrols.receiver.BedtimeReceiver import java.time.LocalDateTime import java.time.ZoneId@@ -28,54 +30,81 @@ class BedtimeScheduler(private val context: Context) {     private val alarms = context.getSystemService<AlarmManager>()      fun arm(schedule: BedtimeSchedule) {+        armWindow(schedule.enabled, schedule::activeAt, REQUEST_BEDTIME)+    }++    /**+     * Arms the next boundary of every supervised window.+     *+     * One alarm per window type, each for its next transition in either direction, re-armed+     * every time any of them fires (all receivers funnel through `Enforcer.reconcile`, which+     * calls here). Separate request codes keep the three alarms from clobbering each other.+     */+    fun armAll(+        bedtime: BedtimeSchedule,+        downtime: DowntimeSchedule,+        schoolTime: SchoolTimeSchedule,+    ) {+        armWindow(bedtime.enabled, bedtime::activeAt, REQUEST_BEDTIME)+        armWindow(downtime.enabled, downtime::activeAt, REQUEST_DOWNTIME)+        armWindow(schoolTime.enabled, schoolTime::activeAt, REQUEST_SCHOOLTIME)+    }++    private fun armWindow(+        enabled: Boolean,+        activeAt: (LocalDateTime) -> Boolean,+        requestCode: Int,+    ) {         val alarms = alarms ?: return-        val pending = pendingIntent()+        val pending = pendingIntent(requestCode)         alarms.cancel(pending)-        if (!schedule.enabled) return+        if (!enabled) return -        val next = nextBoundary(schedule) ?: return+        val next = nextBoundary(activeAt) ?: return         val at = next.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()         val canExact = alarms.canScheduleExactAlarms()         runCatching {             if (canExact) {                 alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)             } else {-                Log.w(TAG, "no exact-alarm permission; bedtime will be approximate")+                Log.w(TAG, "no exact-alarm permission; window boundary will be approximate")                 alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)             }-        }.onFailure { Log.w(TAG, "could not arm the bedtime alarm", it) }+        }.onFailure { Log.w(TAG, "could not arm the window alarm", it) }     }      /**      * The next minute at which the window's state changes, searched forward a week.      *-     * Evaluating [BedtimeSchedule.contains] minute by minute rather than deriving the boundary+     * Evaluating the window predicate minute by minute rather than deriving the boundary      * arithmetically is deliberate: the day mask, the midnight wrap and the "evening belongs to      * today, morning to yesterday" rule interact, and one predicate that the enforcer also uses      * cannot disagree with itself. A week of minutes is 10,080 cheap comparisons, run at most-     * twice a day.+     * a few times a day.      */-    private fun nextBoundary(schedule: BedtimeSchedule): LocalDateTime? {+    private fun nextBoundary(activeAt: (LocalDateTime) -> Boolean): LocalDateTime? {         val now = LocalDateTime.now().withSecond(0).withNano(0)-        var state = schedule.activeAt(now)+        var state = activeAt(now)         for (step in 1..MINUTES_IN_WEEK) {             val at = now.plusMinutes(step.toLong())-            val next = schedule.activeAt(at)+            val next = activeAt(at)             if (next != state) return at             state = next         }         return null     } -    private fun pendingIntent(): PendingIntent = PendingIntent.getBroadcast(+    private fun pendingIntent(requestCode: Int): PendingIntent = PendingIntent.getBroadcast(         context,-        REQUEST_CODE,+        requestCode,         BedtimeReceiver.intent(context),         PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,     )      private companion object {-        const val REQUEST_CODE = 1+        const val REQUEST_BEDTIME = 1+        const val REQUEST_DOWNTIME = 2+        const val REQUEST_SCHOOLTIME = 3         const val MINUTES_IN_WEEK = 7 * 24 * 60     } }@@ -83,3 +112,11 @@ class BedtimeScheduler(private val context: Context) { /** Whether the window is open at [at], in the device's current timezone. */ fun BedtimeSchedule.activeAt(at: LocalDateTime): Boolean =     contains(at.dayOfWeek.value - 1, at.hour * 60 + at.minute)++/** Whether the window is open at [at], in the device's current timezone. */+fun DowntimeSchedule.activeAt(at: LocalDateTime): Boolean =+    contains(at.dayOfWeek.value - 1, at.hour * 60 + at.minute)++/** Whether the window is open at [at], in the device's current timezone. */+fun SchoolTimeSchedule.activeAt(at: LocalDateTime): Boolean =+    contains(at.dayOfWeek.value - 1, at.hour * 60 + at.minute)
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.ktindex bd5ceec108..f2ef40a08d 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.kt@@ -3,7 +3,9 @@ package com.vayunmathur.parentalcontrols.platform import android.content.Context import android.util.Log import com.vayunmathur.parentalcontrols.data.AppRule+import com.vayunmathur.parentalcontrols.data.BonusGrant import com.vayunmathur.parentalcontrols.data.SupervisionRules+import com.vayunmathur.parentalcontrols.notifications.LockNotifier import java.time.LocalDate import java.time.LocalDateTime @@ -20,9 +22,9 @@ private const val TAG = "ParentalControlsEnforcer"  *  * ## Precedence  *- * Bedtime wins over a daily limit. Both are reasons to block and neither is a reason to unblock- * while the other holds, so the state is simply the OR of them; the ordering only matters for- * the *reason* shown to the user.+ * Bedtime > downtime > school time > device-wide daily limit > per-app limit. All are reasons+ * to block and none is a reason to unblock while another holds, so the state is simply the OR+ * of them; the ordering only matters for the *reason* shown to the user.  *  * ## Why a limit trip is remembered  *@@ -43,6 +45,61 @@ class Enforcer(private val context: Context) {     suspend fun onLimitReached(packageName: String) {         limitState.markReached(packageName)         reconcile()+        // The observer fires exactly once per trip, so this notifies exactly once: the child+        // learns why the app just died. Window entries are notified by onWindowBoundary.+        LockNotifier.notifyLocked(context, BlockReason.AppLimit, packageName)+    }++    /**+     * Called from the window-boundary receiver after [reconcile].+     *+     * Notifies only for windows that just *opened* (closed a minute ago, open now), and only+     * the apps that window blocks - so a boundary that ends a window stays silent, and an+     * already-crying child is not re-notified for apps blocked all along by another reason.+     */+    suspend fun onWindowBoundary() {+        reconcile()+        val now = LocalDateTime.now()+        val minuteAgo = now.minusMinutes(1)+        val bedtime = rules.scheduleNow()+        val downtime = rules.downtimeNow()+        val school = rules.schoolTimeNow()+        val all = rules.allRulesNow()+        val day = LocalDate.now().toString()+        val deviceOverBudget = deviceOverBudgetNow(rules.bonusesToday(day))+        if (bedtime.activeAt(now) && !bedtime.activeAt(minuteAgo)) {+            for (rule in all) {+                if (rule.blockedAtBedtime) {+                    LockNotifier.notifyLocked(context, BlockReason.Bedtime, rule.packageName)+                }+            }+        }+        if (downtime.activeAt(now) && !downtime.activeAt(minuteAgo)) {+            for (rule in all) {+                if (!rule.allowedInDowntime &&+                    !(rule.blockedAtBedtime && bedtime.activeAt(now))+                ) {+                    LockNotifier.notifyLocked(context, BlockReason.Downtime, rule.packageName)+                }+            }+        }+        if (school.activeAt(now) && !school.activeAt(minuteAgo)) {+            for (rule in all) {+                if (!rule.allowedInDowntime &&+                    !(rule.blockedAtBedtime && bedtime.activeAt(now)) &&+                    !(downtime.activeAt(now))+                ) {+                    LockNotifier.notifyLocked(context, BlockReason.SchoolTime, rule.packageName)+                }+            }+        }+        // Device-wide budget crossing is detected here rather than by an observer (the+        // platform has no device-total primitive): if the last minute pushed the total over,+        // the child gets one notice. Per-app trips already notified via onLimitReached.+        if (!deviceOverBudget) {+            val overNow = deviceOverBudgetNow(rules.bonusesToday(LocalDate.now().toString()))+            if (overNow) LockNotifier.notifyLocked(context, BlockReason.DailyLimit, null)+        }     }      /**@@ -56,17 +113,33 @@ class Enforcer(private val context: Context) {             Log.w(TAG, "no supervision policy channel; nothing will be enforced")             return         }-        val schedule = rules.scheduleNow()+        val now = LocalDateTime.now()+        val bedtimeSchedule = rules.scheduleNow()+        val downtimeSchedule = rules.downtimeNow()+        val schoolSchedule = rules.schoolTimeNow()         val all = rules.allRulesNow()-        val nightNow = schedule.activeAt(LocalDateTime.now())+        val bedtimeNow = bedtimeSchedule.activeAt(now)+        val downtimeNow = downtimeSchedule.activeAt(now)+        val schoolNow = schoolSchedule.activeAt(now)+        val day = LocalDate.now().toString()+        val bonuses = rules.bonusesToday(day)         limitState.pruneToToday()         // Cheap and idempotent, and it has to happen before AppLimits.sync below: without the         // usage-stats op an observer is armed with timeUsed = 0.         UsageAccess.ensure(context) +        val deviceOverBudget = deviceOverBudgetNow(bonuses)+         for (rule in all) {-            val blocked = shouldBlock(rule, nightNow)-            if (blocked) policies.block(rule.packageName) else policies.allow(rule.packageName)+            val reason = blockReason(+                rule = rule,+                bedtimeNow = bedtimeNow,+                downtimeNow = downtimeNow,+                schoolNow = schoolNow,+                deviceOverBudget = deviceOverBudget,+            )+            if (reason != null) policies.block(rule.packageName)+            else policies.allow(rule.packageName)         }          // Record the parent's caps in the platform's own policy store. Does not enforce - see@@ -76,12 +149,56 @@ class Enforcer(private val context: Context) {             rule.dailyLimitMinutes?.let { policies.limit(rule.packageName, it) }         } -        limits.sync(all.filter { !shouldBlock(it, nightNow) })-        bedtime.arm(schedule)+        limits.sync(all.filter { blockReason(+            rule = it,+            bedtimeNow = bedtimeNow,+            downtimeNow = downtimeNow,+            schoolNow = schoolNow,+            deviceOverBudget = deviceOverBudget,+        ) == null }, bonuses)+        bedtime.armAll(bedtimeSchedule, downtimeSchedule, schoolSchedule)     } -    private fun shouldBlock(rule: AppRule, nightNow: Boolean): Boolean =-        (rule.blockedAtBedtime && nightNow) || limitState.hasReached(rule.packageName)+    /**+     * Why [rule]'s app is currently blocked, or null when it may run.+     *+     * Order is bedtime > downtime > school time > device daily limit > per-app limit; the first+     * holding reason wins so the lock screen can name it.+     */+    private fun blockReason(+        rule: AppRule,+        bedtimeNow: Boolean,+        downtimeNow: Boolean,+        schoolNow: Boolean,+        deviceOverBudget: Boolean,+    ): BlockReason? {+        if (rule.blockedAtBedtime && bedtimeNow) return BlockReason.Bedtime+        if (downtimeNow && !rule.allowedInDowntime) return BlockReason.Downtime+        if (schoolNow && !rule.allowedInDowntime) return BlockReason.SchoolTime+        if (deviceOverBudget) return BlockReason.DailyLimit+        if (limitState.hasReached(rule.packageName)) return BlockReason.AppLimit+        return null+    }++    /** The user-facing reason an app is blocked. Ordering matches [blockReason] precedence. */+    enum class BlockReason {+        Bedtime,+        Downtime,+        SchoolTime,+        DailyLimit,+        AppLimit,+    }++    /**+     * Whether the device-wide budget (cap plus today's device-wide bonuses) is spent.+     *+     * Takes the already-loaded bonuses so [reconcile] does not read the table twice.+     */+    private suspend fun deviceOverBudgetNow(bonuses: List<BonusGrant>): Boolean {+        val deviceBonus = bonuses.filter { it.packageName == null }.sumOf { it.bonusMinutes }+        val deviceLimit = rules.dailyLimitNow()?.let { it + deviceBonus } ?: return false+        return limits.totalUsedToday() >= java.time.Duration.ofMinutes(deviceLimit.toLong())+    } }  /**
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.ktindex 7a2b048de9..e4b832fe84 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.kt@@ -7,6 +7,8 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.parentalcontrols.data.AppRule import com.vayunmathur.parentalcontrols.data.BedtimeSchedule+import com.vayunmathur.parentalcontrols.data.DowntimeSchedule+import com.vayunmathur.parentalcontrols.data.SchoolTimeSchedule import com.vayunmathur.parentalcontrols.data.SupervisionRules import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow@@ -26,9 +28,12 @@ data class SupervisableApp(     val isSupervised: Boolean get() = rule != null } -/** Everything the bedtime and app-limit screens draw. */+/** Everything the supervision screens draw. */ data class SupervisionUiState(     val schedule: BedtimeSchedule = BedtimeSchedule(),+    val downtime: DowntimeSchedule = DowntimeSchedule(),+    val schoolTime: SchoolTimeSchedule = SchoolTimeSchedule(),+    val dailyLimitMinutes: Int? = null,     val apps: List<SupervisableApp> = emptyList(),     val loading: Boolean = true, )@@ -40,12 +45,26 @@ class SupervisionViewModel(app: Application) : AndroidViewModel(app) {      val state: StateFlow<SupervisionUiState> = combine(         rules.schedule,+        rules.downtimeSchedule,+        rules.schoolTimeSchedule,+        rules.dailyLimitMinutes,         rules.allRules,         installed,-    ) { schedule, ruleList, apps ->+    ) { flows ->+        @Suppress("UNCHECKED_CAST")+        val schedule = flows[0] as BedtimeSchedule+        val downtime = flows[1] as DowntimeSchedule+        val schoolTime = flows[2] as SchoolTimeSchedule+        val dailyLimit = flows[3] as Int?+        val ruleList = flows[4] as List<AppRule>+        @Suppress("UNCHECKED_CAST")+        val apps = flows[5] as List<Pair<String, String>>         val byPackage = ruleList.associateBy { it.packageName }         SupervisionUiState(             schedule = schedule,+            downtime = downtime,+            schoolTime = schoolTime,+            dailyLimitMinutes = dailyLimit,             apps = apps.map { (pkg, label) -> SupervisableApp(pkg, label, byPackage[pkg]) },             loading = apps.isEmpty(),         )@@ -73,6 +92,41 @@ class SupervisionViewModel(app: Application) : AndroidViewModel(app) {         it.copy(dailyLimitMinutes = minutes)     } +    fun setAllowedInDowntime(packageName: String, allowed: Boolean) = editRule(packageName) {+        it.copy(allowedInDowntime = allowed)+    }++    fun setDowntimeEnabled(enabled: Boolean) = editDowntime { it.copy(enabled = enabled) }++    fun setDowntimeStart(hour: Int, minute: Int) =+        editDowntime { it.copy(startMinute = hour * 60 + minute) }++    fun setDowntimeEnd(hour: Int, minute: Int) =+        editDowntime { it.copy(endMinute = hour * 60 + minute) }++    fun toggleDowntimeDay(dayIndex: Int) = editDowntime {+        it.copy(daysMask = it.daysMask xor (1 shl dayIndex))+    }++    fun setSchoolTimeEnabled(enabled: Boolean) = editSchoolTime { it.copy(enabled = enabled) }++    fun setSchoolTimeStart(hour: Int, minute: Int) =+        editSchoolTime { it.copy(startMinute = hour * 60 + minute) }++    fun setSchoolTimeEnd(hour: Int, minute: Int) =+        editSchoolTime { it.copy(endMinute = hour * 60 + minute) }++    fun toggleSchoolTimeDay(dayIndex: Int) = editSchoolTime {+        it.copy(daysMask = it.daysMask xor (1 shl dayIndex))+    }++    fun setDeviceDailyLimit(minutes: Int?) {+        viewModelScope.launch {+            rules.setDailyLimit(minutes)+            reconcile()+        }+    }+     private fun edit(transform: (BedtimeSchedule) -> BedtimeSchedule) {         viewModelScope.launch {             rules.setSchedule(transform(rules.scheduleNow()))@@ -80,6 +134,20 @@ class SupervisionViewModel(app: Application) : AndroidViewModel(app) {         }     } +    private fun editDowntime(transform: (DowntimeSchedule) -> DowntimeSchedule) {+        viewModelScope.launch {+            rules.setDowntime(transform(rules.downtimeNow()))+            reconcile()+        }+    }++    private fun editSchoolTime(transform: (SchoolTimeSchedule) -> SchoolTimeSchedule) {+        viewModelScope.launch {+            rules.setSchoolTime(transform(rules.schoolTimeNow()))+            reconcile()+        }+    }+     /**      * Applies [transform] to the app's rule, creating one if absent and deleting it once it      * carries no restriction. A row that restricts nothing is indistinguishable from no row, and@@ -89,7 +157,7 @@ class SupervisionViewModel(app: Application) : AndroidViewModel(app) {         viewModelScope.launch {             val existing = rules.rule(packageName) ?: AppRule(packageName)             val next = transform(existing)-            if (next.dailyLimitMinutes == null && !next.blockedAtBedtime) {+            if (next.dailyLimitMinutes == null && !next.blockedAtBedtime && !next.allowedInDowntime) {                 rules.delete(next)             } else {                 rules.upsert(next)
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/receiver/Receivers.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/receiver/Receivers.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/receiver/Receivers.ktindex 7002359f26..d411f1f38d 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/receiver/Receivers.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/receiver/Receivers.kt@@ -55,7 +55,7 @@ class LimitReachedReceiver : BroadcastReceiver() {     } } -/** Fired at each bedtime boundary. Re-arms the next one through [Enforcer.reconcile]. */+/** Fired at each supervised-window boundary. Re-arms the next one through [Enforcer]. */ class BedtimeReceiver : BroadcastReceiver() {      override fun onReceive(context: Context, intent: Intent) {@@ -63,9 +63,11 @@ class BedtimeReceiver : BroadcastReceiver() {         val pending = goAsync()         CoroutineScope(Dispatchers.IO).launch {             try {-                Enforcer(app).reconcile()+                // reconcile plus entry notifications for windows that just opened - not a bare+                // reconcile, or the child would never learn why apps just closed.+                Enforcer(app).onWindowBoundary()             } catch (t: Throwable) {-                Log.e(TAG, "bedtime reconcile failed", t)+                Log.e(TAG, "window boundary failed", t)             } finally {                 pending.finish()             }
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.ktindex 2e24f54c6d..48f7112d42 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/AppLimitsActivity.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/AppLimitsActivity.kt@@ -1,7 +1,5 @@ package com.vayunmathur.parentalcontrols.ui -import android.os.Bundle-import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels@@ -10,13 +8,12 @@ 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. */-class AppLimitsActivity : ComponentActivity() {+/** Per-app daily caps, reached from Settings > Parental controls. Parent-gated. */+class AppLimitsActivity : PinGatedActivity() {      private val viewModel: SupervisionViewModel by viewModels() -    override fun onCreate(savedInstanceState: Bundle?) {-        super.onCreate(savedInstanceState)+    override fun onPinVerifiedContent() {         enableEdgeToEdge()         setContent {             DynamicTheme {
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.ktindex e3ee32bf3b..9c9caa7a04 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/BedtimeActivity.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/BedtimeActivity.kt@@ -1,7 +1,5 @@ package com.vayunmathur.parentalcontrols.ui -import android.os.Bundle-import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels@@ -14,14 +12,14 @@ 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.+ * 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 : ComponentActivity() {+class BedtimeActivity : PinGatedActivity() {      private val viewModel: SupervisionViewModel by viewModels() -    override fun onCreate(savedInstanceState: Bundle?) {-        super.onCreate(savedInstanceState)+    override fun onPinVerifiedContent() {         enableEdgeToEdge()         setContent {             DynamicTheme {
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DailyLimitScreen.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DailyLimitScreen.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DailyLimitScreen.ktnew file mode 100644index 0000000000..57fd4a6d1f--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DailyLimitScreen.kt@@ -0,0 +1,95 @@+package com.vayunmathur.parentalcontrols.ui++import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.LazyListScaffold+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.parentalcontrols.R++/** Actions the device-wide daily-limit screen can take. */+data class DailyLimitActions(+    val onLimitChange: (Int?) -> Unit,+)++/**+ * The device-wide daily screen-time budget.+ *+ * One row, one dialog: when the budget is spent, everything except calls locks until midnight+ * (per-app caps keep working underneath). Same fixed choices as per-app limits, plus No limit.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DailyLimitScreen(currentMinutes: Int?, actions: DailyLimitActions) {+    var picking by remember { mutableStateOf(false) }++    LazyListScaffold(+        title = stringResource(R.string.daily_title),+        horizontalPadding = 0.dp,+        scrollBehavior = appBarScrollBehavior(),+    ) {+        item {+            SettingsSection {+                SettingsRow(+                    title = stringResource(R.string.daily_explainer),+                    supportingText = stringResource(R.string.daily_explainer_hint),+                )+                SettingsRow(+                    title = stringResource(R.string.daily_budget),+                    supportingText = currentMinutes?.let { formatDailyLimit(it) }+                        ?: stringResource(R.string.limits_none),+                    onClick = { picking = true },+                )+            }+        }+    }++    if (picking) {+        AlertDialog(+            onDismissRequest = { picking = false },+            title = { Text(stringResource(R.string.daily_budget)) },+            text = {+                SettingsSection {+                    SettingsRow(+                        title = stringResource(R.string.limits_none),+                        onClick = { actions.onLimitChange(null); picking = false },+                    )+                    for (minutes in DAILY_CHOICES) {+                        SettingsRow(+                            title = formatDailyLimit(minutes),+                            onClick = { actions.onLimitChange(minutes); picking = false },+                        )+                    }+                }+            },+            confirmButton = {},+            dismissButton = {+                TextButton(onClick = { picking = false }) {+                    Text(stringResource(R.string.cancel))+                }+            },+        )+    }+}++/** Generous steps for a whole-device budget; per-app caps use the finer [CHOICES] scale. */+private val DAILY_CHOICES = listOf(60, 120, 180, 240, 300, 360, 480)++private fun formatDailyLimit(minutes: Int): String =+    if (minutes < 60) {+        "$minutes min"+    } else {+        val hours = minutes / 60+        val rest = minutes % 60+        if (rest == 0) "$hours h" else "$hours h $rest min"+    }
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockActivities.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockActivities.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockActivities.ktnew file mode 100644index 0000000000..6f2363771b--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockActivities.kt@@ -0,0 +1,131 @@+package com.vayunmathur.parentalcontrols.ui++import android.content.Context+import android.content.Intent+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.lifecycle.lifecycleScope+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.parentalcontrols.data.BonusGrant+import com.vayunmathur.parentalcontrols.data.SupervisionRules+import com.vayunmathur.parentalcontrols.platform.Enforcer+import java.time.LocalDate+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch++/**+ * Full-screen restriction notices, one per block reason.+ *+ * Reached from the "why is this blocked" entry point and from limit-spent notifications - not+ * auto-shown on window entry, which would interrupt whatever allowed app the child is using.+ * Bedtime, downtime and school-time locks explain and wait out the window; daily and per-app+ * limit locks additionally offer bonus time, granted on-device by the parent's PIN.+ *+ * None of these is exported: they are started explicitly by our own receivers and+ * notifications. The bonus path reuses [PinGateActivity] rather than taking a PIN here, so+ * the secret is entered in exactly one place.+ */+abstract class BaseLockActivity : ComponentActivity() {++    protected abstract val reason: Enforcer.BlockReason++    /** Null for device-wide (daily-limit) locks. */+    protected open val blockedPackage: String? = null++    private val bonusGate =+        registerForActivityResult(+            androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult(),+        ) { result ->+            if (result.resultCode == PinGateActivity.RESULT_VERIFIED) grantBonus()+        }++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        val label = blockedPackage?.let { pkg -> packageLabel(pkg) }+        enableEdgeToEdge()+        // Lock screens show over the keyguard: the child meets the reason, not a home screen.+        setShowWhenLocked(true)+        setTurnScreenOn(true)+        setContent {+            DynamicTheme {+                LockScreen(+                    reason = reason,+                    appLabel = label,+                    actions = LockActions(+                        onAskParent = {+                            bonusGate.launch(Intent(this, PinGateActivity::class.java))+                        },+                        onClose = { finish() },+                    ),+                )+            }+        }+    }++    private fun packageLabel(blockedPackage: String): String? =+        runCatching {+            val info = packageManager.getApplicationInfo(blockedPackage, 0)+            packageManager.getApplicationLabel(info).toString()+        }.getOrNull()++    private fun grantBonus() {+        lifecycleScope.launch(Dispatchers.IO) {+            val rules = SupervisionRules.get(this@BaseLockActivity)+            rules.grantBonus(+                BonusGrant(+                    packageName = blockedPackage,+                    bonusMinutes = BONUS_MINUTES,+                    day = LocalDate.now().toString(),+                ),+            )+            Enforcer(this@BaseLockActivity).reconcile()+            finish()+        }+    }++    companion object {+        /** Minutes each on-device bonus grant adds. Matches the smallest fixed limit choice. */+        const val BONUS_MINUTES = 15++        const val EXTRA_PACKAGE = "com.vayunmathur.parentalcontrols.extra.BLOCKED_PACKAGE"++        fun intent(context: Context, activity: Class<out BaseLockActivity>, blockedPackage: String?): Intent =+            Intent(context, activity).putExtra(EXTRA_PACKAGE, blockedPackage)+    }+}++/** Shown for bedtime-blocked apps. The window ends on its own schedule; no bonus offered. */+class BedtimeLockActivity : BaseLockActivity() {+    override val reason = Enforcer.BlockReason.Bedtime+    override val blockedPackage: String?+        get() = intent.getStringExtra(EXTRA_PACKAGE)+}++/** Shown for downtime-blocked apps. Allowed-list apps never land here. */+class DowntimeLockActivity : BaseLockActivity() {+    override val reason = Enforcer.BlockReason.Downtime+    override val blockedPackage: String?+        get() = intent.getStringExtra(EXTRA_PACKAGE)+}++/** Shown for school-time-blocked apps. Allowed learning apps never land here. */+class SchoolTimeLockActivity : BaseLockActivity() {+    override val reason = Enforcer.BlockReason.SchoolTime+    override val blockedPackage: String?+        get() = intent.getStringExtra(EXTRA_PACKAGE)+}++/** Shown when the device-wide daily budget is spent. Bonus extends today for everything. */+class DailyLimitLockActivity : BaseLockActivity() {+    override val reason = Enforcer.BlockReason.DailyLimit+    override val blockedPackage: String? = null+}++/** Shown when a single app's daily cap is spent. Bonus extends today for that app. */+class AppLimitLockActivity : BaseLockActivity() {+    override val reason = Enforcer.BlockReason.AppLimit+    override val blockedPackage: String?+        get() = intent.getStringExtra(EXTRA_PACKAGE)+}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockScreen.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockScreen.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockScreen.ktnew file mode 100644index 0000000000..141f9ee2f1--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockScreen.kt@@ -0,0 +1,74 @@+package com.vayunmathur.parentalcontrols.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.parentalcontrols.R+import com.vayunmathur.parentalcontrols.platform.Enforcer++/** Actions a restriction lock screen offers. */+data class LockActions(+    val onAskParent: () -> Unit,+    val onClose: () -> Unit,+)++/**+ * The full-screen reason shown for a blocked app.+ *+ * One screen serves all four restriction types; [reason] picks the title, explanation and+ * whether bonus time can be requested (daily and per-app limits only - bedtime, downtime and+ * school time end on their own schedule, so extra minutes would be meaningless).+ */+@Composable+fun LockScreen(reason: Enforcer.BlockReason, appLabel: String?, actions: LockActions) {+    val title =+        when (reason) {+            Enforcer.BlockReason.Bedtime -> stringResource(R.string.lock_bedtime_title)+            Enforcer.BlockReason.Downtime -> stringResource(R.string.lock_downtime_title)+            Enforcer.BlockReason.SchoolTime -> stringResource(R.string.lock_school_title)+            Enforcer.BlockReason.DailyLimit -> stringResource(R.string.lock_daily_title)+            Enforcer.BlockReason.AppLimit -> stringResource(R.string.lock_applimit_title)+        }+    val hint =+        when (reason) {+            Enforcer.BlockReason.Bedtime -> stringResource(R.string.lock_bedtime_hint)+            Enforcer.BlockReason.Downtime -> stringResource(R.string.lock_downtime_hint)+            Enforcer.BlockReason.SchoolTime -> stringResource(R.string.lock_school_hint)+            Enforcer.BlockReason.DailyLimit -> stringResource(R.string.lock_daily_hint)+            Enforcer.BlockReason.AppLimit -> stringResource(R.string.lock_applimit_hint)+        }+    val bonusable =+        reason == Enforcer.BlockReason.DailyLimit || reason == Enforcer.BlockReason.AppLimit++    AppScaffold(+        title = title,+        scrollBehavior = appBarScrollBehavior(),+    ) {+        Column(+            modifier = Modifier.fillMaxSize().padding(24.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),+        ) {+            if (appLabel != null) Text(appLabel)+            Text(hint)+            if (bonusable) {+                TextButton(onClick = actions.onAskParent) {+                    Text(stringResource(R.string.lock_ask_parent))+                }+            }+            TextButton(onClick = actions.onClose) {+                Text(stringResource(R.string.lock_close))+            }+        }+    }+}
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.ktnew file mode 100644index 0000000000..497dfb2422--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinActivities.kt@@ -0,0 +1,102 @@+package com.vayunmathur.parentalcontrols.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.lifecycleScope+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.parentalcontrols.auth.ParentPin+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch++/**+ * The parent-PIN challenge, reached before any imposed-enforcement surface.+ *+ * Started for a result: the caller passes what unlocking means via the result code -+ * [RESULT_VERIFIED] when the entered PIN checks out, [RESULT_CANCELED] otherwise. The PIN+ * itself never leaves this activity.+ */+class PinGateActivity : ComponentActivity() {++    private var error by mutableStateOf<String?>(null)+    private var lockedOut by mutableStateOf(false)++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        val pin = ParentPin.get(this)+        lockedOut = pin.isLockedOut()+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                PinGateScreen(+                    error = error,+                    lockedOut = lockedOut,+                    actions = PinGateActions(+                        onVerify = { entry -> verify(pin, entry) },+                        onCancel = { finish() },+                    ),+                )+            }+        }+    }++    private fun verify(pin: ParentPin, entry: String): Boolean {+        lifecycleScope.launch(Dispatchers.IO) {+            val ok = pin.verify(entry)+            launch(Dispatchers.Main) {+                if (ok) {+                    setResult(RESULT_VERIFIED)+                    finish()+                } else {+                    lockedOut = pin.isLockedOut()+                    error = if (lockedOut) {+                        getString(+                            com.vayunmathur.parentalcontrols.R.string.pin_locked_out,+                        )+                    } else {+                        getString(com.vayunmathur.parentalcontrols.R.string.pin_wrong)+                    }+                }+            }+        }+        // The real answer arrives asynchronously; returning false keeps the entry until then.+        return false+    }++    companion object {+        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/PinGateScreen.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinGateScreen.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinGateScreen.ktnew file mode 100644index 0000000000..c3c814da1a--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinGateScreen.kt@@ -0,0 +1,79 @@+package com.vayunmathur.parentalcontrols.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.OutlinedTextField+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.input.PasswordVisualTransformation+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.parentalcontrols.R++/** Actions the PIN challenge screen can take. */+data class PinGateActions(+    val onVerify: (String) -> Boolean,+    val onCancel: () -> Unit,+)++/**+ * The challenge shown before any imposed-enforcement surface.+ *+ * Stateless except for the in-progress entry: verification itself lives in the host, which+ * owns the [ParentPin] and decides what unlocking means (open an editor, grant a bonus,+ * dismiss a lock screen). Wrong entries show the remaining-attempts hint via [error]; a+ * lockout disables the field until it lapses.+ */+@Composable+fun PinGateScreen(error: String?, lockedOut: Boolean, actions: PinGateActions) {+    var entry by remember { mutableStateOf("") }++    AppScaffold(+        title = stringResource(R.string.pin_title),+        scrollBehavior = appBarScrollBehavior(),+    ) {+        Column(+            modifier = Modifier.fillMaxSize().padding(24.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),+        ) {+            Text(stringResource(R.string.pin_challenge_hint))+            OutlinedTextField(+                value = entry,+                onValueChange = { entry = it.filter(Char::isDigit).take(MAX_PIN_LENGTH) },+                label = { Text(stringResource(R.string.pin_label)) },+                visualTransformation = PasswordVisualTransformation(),+                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),+                enabled = !lockedOut,+                isError = error != null,+                supportingText = error?.let { { Text(it) } },+                singleLine = true,+            )+            TextButton(+                onClick = { if (actions.onVerify(entry)) entry = "" },+                enabled = entry.length >= MIN_PIN_LENGTH && !lockedOut,+            ) {+                Text(stringResource(R.string.pin_unlock))+            }+            TextButton(onClick = actions.onCancel) {+                Text(stringResource(R.string.cancel))+            }+        }+    }+}++private const val MIN_PIN_LENGTH = 4+private const val MAX_PIN_LENGTH = 16
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.ktnew file mode 100644index 0000000000..9c79340bf1--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinGatedActivity.kt@@ -0,0 +1,85 @@+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()) {+            // Either way the PIN now exists or the user declined; re-run the normal gate.+            verified = false+            checkGate()+        }++    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/PinSetupScreen.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinSetupScreen.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinSetupScreen.ktnew file mode 100644index 0000000000..4ffebafeea--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/PinSetupScreen.kt@@ -0,0 +1,92 @@+package com.vayunmathur.parentalcontrols.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.OutlinedTextField+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.input.PasswordVisualTransformation+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.parentalcontrols.R++/** Actions the PIN setup screen can take. */+data class PinSetupActions(+    val onSet: (String) -> Boolean,+    val onCancel: () -> Unit,+)++/**+ * First-run PIN creation (and later PIN change, after the old PIN passes [PinGateScreen]).+ *+ * Asks twice and only enables saving when both entries match and meet the length floor, so a+ * typo cannot lock the parent out of their own controls.+ */+@Composable+fun PinSetupScreen(actions: PinSetupActions) {+    var first by remember { mutableStateOf("") }+    var second by remember { mutableStateOf("") }+    val mismatch = second.isNotEmpty() && first != second+    val ready = first.length >= SETUP_MIN_LENGTH && first == second++    AppScaffold(+        title = stringResource(R.string.pin_setup_title),+        scrollBehavior = appBarScrollBehavior(),+    ) {+        Column(+            modifier = Modifier.fillMaxSize().padding(24.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),+        ) {+            Text(stringResource(R.string.pin_setup_hint))+            OutlinedTextField(+                value = first,+                onValueChange = { first = it.filter(Char::isDigit).take(SETUP_MAX_LENGTH) },+                label = { Text(stringResource(R.string.pin_new_label)) },+                visualTransformation = PasswordVisualTransformation(),+                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),+                singleLine = true,+            )+            OutlinedTextField(+                value = second,+                onValueChange = { second = it.filter(Char::isDigit).take(SETUP_MAX_LENGTH) },+                label = { Text(stringResource(R.string.pin_confirm_label)) },+                visualTransformation = PasswordVisualTransformation(),+                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),+                isError = mismatch,+                supportingText =+                    if (mismatch) {+                        { Text(stringResource(R.string.pin_mismatch)) }+                    } else {+                        null+                    },+                singleLine = true,+            )+            TextButton(+                onClick = { if (actions.onSet(first)) { first = ""; second = "" } },+                enabled = ready,+            ) {+                Text(stringResource(R.string.save))+            }+            TextButton(onClick = actions.onCancel) {+                Text(stringResource(R.string.cancel))+            }+        }+    }+}++private const val SETUP_MIN_LENGTH = 4+private const val SETUP_MAX_LENGTH = 16
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 061ecd8a58..18d7b0b410 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/SetupActivity.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/SetupActivity.kt@@ -5,6 +5,7 @@ import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.util.Log+import com.vayunmathur.parentalcontrols.auth.ParentPin  private const val TAG = "ParentalControlsSetup" @@ -27,6 +28,12 @@ class SetupActivity : Activity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        // Imposed enforcement always has a gatekeeper: before the platform setup flow runs,+        // 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))+        }         val enable = Intent(ACTION_ENABLE_SUPERVISION).apply {             addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)         }
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.ktnew file mode 100644index 0000000000..bb59b051b4--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WindowActivities.kt@@ -0,0 +1,120 @@+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.downtime_start),+                    endLabel = stringResource(R.string.downtime_end),+                    daysLabel = stringResource(R.string.downtime_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.school_start),+                    endLabel = stringResource(R.string.school_end),+                    daysLabel = stringResource(R.string.school_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/main/java/com/vayunmathur/parentalcontrols/ui/WindowScheduleScreen.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WindowScheduleScreen.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WindowScheduleScreen.ktnew file mode 100644index 0000000000..3d451dffd9--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/WindowScheduleScreen.kt@@ -0,0 +1,170 @@+package com.vayunmathur.parentalcontrols.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.FilterChip+import androidx.compose.material3.TimePicker+import androidx.compose.material3.rememberTimePickerState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.LazyListScaffold+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.parentalcontrols.R+import com.vayunmathur.parentalcontrols.domain.TimeWindow+import com.vayunmathur.parentalcontrols.platform.SupervisableApp++/** Actions any supervised window screen can take. */+data class WindowScheduleActions(+    val onEnabledChange: (Boolean) -> Unit,+    val onStartChange: (Int, Int) -> Unit,+    val onEndChange: (Int, Int) -> Unit,+    val onToggleDay: (Int) -> Unit,+    val onAppAllowChange: (String, Boolean) -> Unit,+)++/**+ * A supervised window editor shared by downtime and school time.+ *+ * Same shape as the bedtime screen with different labels: master switch, start/end pickers,+ * day chips, and the per-app allow-list (apps that stay usable inside the window). Bedtime+ * keeps its own screen because it predates this one and uses block-list semantics.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun WindowScheduleScreen(+    title: String,+    enableLabel: String,+    enableHint: String,+    startLabel: String,+    endLabel: String,+    daysLabel: String,+    appsLabel: String,+    dayInitials: String,+    enabled: Boolean,+    startMinute: Int,+    endMinute: Int,+    daysMask: Int,+    apps: List<SupervisableApp>,+    loading: Boolean,+    actions: WindowScheduleActions,+) {+    var picking by remember { mutableStateOf<WindowPicking?>(null) }++    LazyListScaffold(+        title = title,+        horizontalPadding = 0.dp,+        scrollBehavior = appBarScrollBehavior(),+    ) {+        item {+            SettingsSection {+                SettingsSwitchRow(+                    title = enableLabel,+                    supportingText = enableHint,+                    checked = enabled,+                    onCheckedChange = actions.onEnabledChange,+                )+                SettingsRow(+                    title = startLabel,+                    supportingText = formatWindowMinute(startMinute),+                    enabled = enabled,+                    onClick = { picking = WindowPicking.Start },+                )+                SettingsRow(+                    title = endLabel,+                    supportingText = formatWindowMinute(endMinute),+                    enabled = enabled,+                    onClick = { picking = WindowPicking.End },+                )+            }+        }++        item {+            SettingsSection(title = daysLabel) {+                Row(+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+                    horizontalArrangement = Arrangement.spacedBy(4.dp),+                ) {+                    val labels = dayInitials.split(",")+                    for (day in 0 until TimeWindow.DAYS_IN_WEEK) {+                        val set = (daysMask shr day) and 1 == 1+                        FilterChip(+                            selected = set,+                            onClick = { actions.onToggleDay(day) },+                            enabled = enabled,+                            label = { Text(labels.getOrElse(day) { "?" }) },+                        )+                    }+                }+            }+        }++        item {+            SettingsSection(title = appsLabel) {+                if (loading && apps.isEmpty()) {+                    SettingsRow(title = "")+                }+            }+        }++        items(apps.size, key = { apps[it].packageName }) { index ->+            val app = apps[index]+            SettingsSwitchRow(+                title = app.label,+                checked = app.rule?.allowedInDowntime == true,+                enabled = enabled,+                onCheckedChange = { actions.onAppAllowChange(app.packageName, it) },+            )+        }+    }++    val active = picking+    if (active != null) {+        val initial = if (active == WindowPicking.Start) startMinute else endMinute+        val timeState = rememberTimePickerState(+            initialHour = initial / 60,+            initialMinute = initial % 60,+        )+        AlertDialog(+            onDismissRequest = { picking = null },+            title = {+                Text(if (active == WindowPicking.Start) startLabel else endLabel)+            },+            text = { TimePicker(state = timeState) },+            confirmButton = {+                TextButton(onClick = {+                    if (active == WindowPicking.Start) {+                        actions.onStartChange(timeState.hour, timeState.minute)+                    } else {+                        actions.onEndChange(timeState.hour, timeState.minute)+                    }+                    picking = null+                }) { Text(stringResource(R.string.save)) }+            },+            dismissButton = {+                TextButton(onClick = { picking = null }) {+                    Text(stringResource(R.string.cancel))+                }+            },+        )+    }+}++private enum class WindowPicking { Start, End }++private fun formatWindowMinute(minuteOfDay: Int): String =+    "%02d:%02d".format(minuteOfDay / 60, minuteOfDay % 60)
parentalcontrols/src/main/res/values/strings.xml
diff --git a/parentalcontrols/src/main/res/values/strings.xml b/parentalcontrols/src/main/res/values/strings.xmlindex b9ce47dfd5..70e3b84c44 100644--- a/parentalcontrols/src/main/res/values/strings.xml+++ b/parentalcontrols/src/main/res/values/strings.xml@@ -36,6 +36,98 @@     <!-- Shown in place of the app list while installed apps are still being read. -->     <string name="apps_loading">Loading apps…</string> +    <!-- PIN challenge: title of the gate shown before any parent-only surface. Noun phrase. -->+    <string name="pin_title">Parent PIN</string>+    <!-- PIN challenge: explanation of why the PIN is asked. -->+    <string name="pin_challenge_hint">Enter the parent PIN to change these settings.</string>+    <!-- PIN challenge: label of the PIN entry field. Noun. -->+    <string name="pin_label">PIN</string>+    <!-- PIN challenge: button that submits the entered PIN. Verb. -->+    <string name="pin_unlock">Unlock</string>+    <!-- PIN challenge: shown after a wrong entry while attempts remain. -->+    <string name="pin_wrong">Wrong PIN. Try again.</string>+    <!-- PIN challenge: shown while brute-force lockout is active. -->+    <string name="pin_locked_out">Too many tries. Try again later.</string>++    <!-- PIN setup: title of first-run creation and later change. Noun phrase. -->+    <string name="pin_setup_title">Set parent PIN</string>+    <!-- PIN setup: explanation shown above the two entry fields. -->+    <string name="pin_setup_hint">Choose a PIN only a parent knows. It protects every limit, schedule and bonus.</string>+    <!-- PIN setup: label of the first entry field. Noun phrase. -->+    <string name="pin_new_label">New PIN</string>+    <!-- PIN setup: label of the repeat field. Noun phrase. -->+    <string name="pin_confirm_label">Repeat PIN</string>+    <!-- PIN setup: shown under the repeat field when the two entries differ. -->+    <string name="pin_mismatch">PINs do not match.</string>+    <!-- PIN setup: confirmation shown after the PIN is stored. -->+    <string name="pin_saved">Parent PIN saved.</string>++    <!-- Lock screens: title shown for each block reason. Noun phrases. -->+    <string name="lock_bedtime_title">Bedtime</string>+    <string name="lock_downtime_title">Downtime</string>+    <string name="lock_school_title">School time</string>+    <string name="lock_daily_title">Daily limit reached</string>+    <string name="lock_applimit_title">App limit reached</string>+    <!-- Lock screens: explanation under each title. -->+    <string name="lock_bedtime_hint">This app is unavailable during bedtime hours.</string>+    <string name="lock_downtime_hint">This app is unavailable during downtime. Only approved apps can be opened.</string>+    <string name="lock_school_hint">This app is unavailable during school hours. Only learning apps can be opened.</string>+    <string name="lock_daily_hint">Today\'s screen-time budget is used up. Everything unlocks again at midnight.</string>+    <string name="lock_applimit_hint">This app\'s time for today is used up. It unlocks again at midnight.</string>+    <!-- Lock screens: button that starts the parent-PIN bonus flow. Verb phrase. -->+    <string name="lock_ask_parent">Ask a parent for more time</string>+    <!-- Lock screens: button that dismisses the notice. Verb. -->+    <string name="lock_close">OK</string>+    <!-- Notifications: channel for restriction notices. Noun phrase. -->+    <string name="lock_channel_name">Restrictions</string>+    <!-- Notifications: channel description. -->+    <string name="lock_channel_description">Notices when bedtime, downtime, school time or a limit blocks an app.</string>++    <!-- Downtime screen: title, also the label of its row in Settings > Parental controls. Noun. -->+    <string name="downtime_title">Downtime</string>+    <!-- One-line summary under the Downtime row in Settings. -->+    <string name="downtime_summary">Choose hours when only approved apps open</string>+    <!-- Downtime screen: the main on/off switch. Verb phrase. -->+    <string name="downtime_enable">Use a downtime schedule</string>+    <!-- Downtime screen: explanation under the main switch. -->+    <string name="downtime_enable_hint">Everything except the apps you approve below stays closed during the hours you set.</string>+    <!-- Downtime screen: row for the time the window opens. Noun phrase. -->+    <string name="downtime_start">Starts at</string>+    <!-- Downtime screen: row for the time the window closes. Noun phrase. -->+    <string name="downtime_end">Ends at</string>+    <!-- Downtime screen: heading above the day-of-week chips. Noun. -->+    <string name="downtime_days">Days</string>+    <!-- Downtime screen: heading above the list of apps that stay available. Noun phrase. -->+    <string name="downtime_apps">Approved apps</string>++    <!-- School time screen: title, also the label of its row in Settings > Parental controls. Noun phrase. -->+    <string name="school_title">School time</string>+    <!-- One-line summary under the School time row in Settings. -->+    <string name="school_summary">Limit the device to learning apps during school</string>+    <!-- School time screen: the main on/off switch. Verb phrase. -->+    <string name="school_enable">Use a school time schedule</string>+    <!-- School time screen: explanation under the main switch. -->+    <string name="school_enable_hint">Only the learning apps you approve below can be opened during school hours.</string>+    <!-- School time screen: row for the time the window opens. Noun phrase. -->+    <string name="school_start">Starts at</string>+    <!-- School time screen: row for the time the window closes. Noun phrase. -->+    <string name="school_end">Ends at</string>+    <!-- School time screen: heading above the day-of-week chips. Noun. -->+    <string name="school_days">Days</string>+    <!-- School time screen: heading above the list of learning apps. Noun phrase. -->+    <string name="school_apps">Learning apps</string>++    <!-- Daily limit screen: title, also the label of its row in Settings > Parental controls. Noun phrase. -->+    <string name="daily_title">Daily limit</string>+    <!-- One-line summary under the Daily limit row in Settings. -->+    <string name="daily_summary">Set total screen time allowed per day</string>+    <!-- Daily limit screen: heading of the explanatory row. Noun phrase. -->+    <string name="daily_explainer">Whole-device time budget</string>+    <!-- Daily limit screen: explanation of when the budget takes effect and resets. -->+    <string name="daily_explainer_hint">Everything locks once the day\'s budget is used up, and unlocks again at midnight.</string>+    <!-- Daily limit screen: row showing the current budget. Noun phrase. -->+    <string name="daily_budget">Daily budget</string>+     <!-- Dialog button that stores the chosen value. Verb. -->     <string name="save">Save</string>     <!-- Dialog button that discards the change. Verb. -->