Modern Apps git

← Modern-Apps.git

screentime: new offline screen time app with wellbeing role

Commit
dcc786f8b688faf5468bd0e3b25e3c16a5782f6f
Author
vayun-mathur <[email protected]>
When
2026-09-14 05:39 UTC (2 months ago)
Parents
379847a

Diff

.github/ISSUE_TEMPLATE/bug_report.yml
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex dd7c324347..21c2c9f9dc 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -53,6 +53,7 @@ body:         - photos         - pipes         - parentalcontrols+        - screentime         - setupwizard         - share         - solitaire@@ -67,6 +68,7 @@ body:         - unblockjam         - updater         - vpn+        - watch         - voxels         - weather         - web
.github/ISSUE_TEMPLATE/feature_request.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 18fb960d34..a9b6d40d7c 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -53,6 +53,7 @@ body:         - photos         - pipes         - parentalcontrols+        - screentime         - setupwizard         - share         - solitaire@@ -67,6 +68,7 @@ body:         - unblockjam         - updater         - vpn+        - watch         - voxels         - weather         - web
.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex 6393706d44..f8bc7a75ec 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs:              if (match && match[1]) {               const selectedApp = match[1].trim().toLowerCase();-              const validApps = ['alchemist', 'appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'musicbrainz', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'setupwizard', 'share', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'tools:holidaygen', 'translate', 'travel', 'tuner', 'unblockjam', 'updater', 'vpn', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+              const validApps = ['alchemist', 'appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'musicbrainz', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'tools:holidaygen', 'translate', 'travel', 'tuner', 'unblockjam', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];                if (validApps.includes(selectedApp)) {                 await github.rest.issues.addLabels({
README.md
diff --git a/README.md b/README.mdindex 87983d2824..6612180b5b 100644--- a/README.md+++ b/README.md@@ -84,6 +84,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **PDF Reader** | MA-1 | [Homepage](https://ma.vayunmathur.com/apps/pdf) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.pdf) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=PDF&packageName=com.vayunmathur.pdf&apk=pdf-release.apk) | | **Photos** | MA-1 | [Homepage](https://ma.vayunmathur.com/apps/photos) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.photos) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Photos&packageName=com.vayunmathur.photos&apk=photos-release.apk) | | **Parental Controls** | MA-C | [Homepage](https://ma.vayunmathur.com/apps/parentalcontrols) | In Progress | In Progress |+| **Screen Time** | MA-C | [Homepage](https://ma.vayunmathur.com/apps/screentime) | In Progress | In Progress | | **Setup Wizard** | MA-C | [Homepage](https://ma.vayunmathur.com/apps/setupwizard) | In Progress | In Progress | | **Share** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/share) | In Progress | In Progress | | **Speech Recognizer** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/speech) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.speech/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Speech%20Recognizer&packageName=com.vayunmathur.speech&apk=speech-release.apk) |@@ -94,6 +95,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Tuner** | MA-3 | [Homepage](https://ma.vayunmathur.com/apps/tuner) | In Progress | In Progress | | **Updater** | MA-C | [Homepage](https://ma.vayunmathur.com/apps/updater) | In Progress | In Progress | | **VPN** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/vpn) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.vpn/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=VPN&packageName=com.vayunmathur.vpn&apk=vpn-release.apk) |+| **Watch** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/watch) | In Progress | In Progress | | **Weather** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/weather) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.weather) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Weather&packageName=com.vayunmathur.weather&apk=weather-release.apk) | | **Web** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/web) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.web/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Web&packageName=com.vayunmathur.web&apk=web-release.apk) | | **YouPipe** | MA-1 | [Homepage](https://ma.vayunmathur.com/apps/youpipe) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.youpipe) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=YouPipe&packageName=com.vayunmathur.youpipe&apk=youpipe-release.apk) |
metadata_data/screentime.md
diff --git a/metadata_data/screentime.md b/metadata_data/screentime.mdnew file mode 100644index 0000000000..7619ee4ba0--- /dev/null+++ b/metadata_data/screentime.md@@ -0,0 +1,11 @@+Your own screen-time dashboard, entirely on this device++Features:+- Shows how long each app is used per day, with a dashboard and per-app details+- Sets per-app timers that pause the app when its time is used up+- Focus mode pauses distracting apps on demand or on a schedule, with a Quick Settings tile+- Bedtime wind-down dims the screen to grayscale and turns on Do Not Disturb overnight+- Mindful nudges and launch-friction screens for apps you want to use less+- Runs entirely on the device; no account, no sync and nothing uploaded++100% offline
screentime/build.gradle.kts
diff --git a/screentime/build.gradle.kts b/screentime/build.gradle.ktsnew file mode 100644index 0000000000..d9cc8d36c0--- /dev/null+++ b/screentime/build.gradle.kts@@ -0,0 +1,20 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-preview-metadata")+}++launcherIcon {+    symbol = "hourglass"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.screentime"+    }+}++dependencies {+    implementRoom(libs)+    implementation(project(":library:room"))+    implementation(project(":library:widgets"))+}
screentime/src/main/AndroidManifest.xml
diff --git a/screentime/src/main/AndroidManifest.xml b/screentime/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..d4aed6960e--- /dev/null+++ b/screentime/src/main/AndroidManifest.xml@@ -0,0 +1,192 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+    xmlns:tools="http://schemas.android.com/tools">+    <!--+      Everything this app holds arrives with the SYSTEM_WELLBEING role, which the platform+      grants to whichever package `config_systemWellbeing` names - see the pin in+      vendor/modern-apps/rro/MaosFrameworkResRRO/res/values/config.xml. The role grants+      SUSPEND_APPS, SYSTEM_APPLICATION_OVERLAY and OBSERVE_APP_USAGE (all+      signature|privileged|role or signature|role), which is why those three are declared+      without apology below: a role grants only what the manifest requests.++      Neither belongs in privapp-permissions-modern-apps.xml. This app is not a priv-app, and+      an entry there that does not match the manifest is boot-fatal under+      ro.control_privapp_permissions=enforce.+    -->+    <!-- Pauses apps whose timer ran out or that focus mode covers. Arrives via the role. -->+    <uses-permission android:name="android.permission.SUSPEND_APPS" />+    <!-- Friction sheets and the expired-timer screen draw over the opening app. Via the role. -->+    <uses-permission android:name="android.permission.SYSTEM_APPLICATION_OVERLAY" />+    <!-- Time-based callbacks when an app reaches a usage threshold. Via the role. -->+    <uses-permission android:name="android.permission.OBSERVE_APP_USAGE" />+    <!-- Reads per-app foreground time for the dashboard. An appop, not a role grant: declared+         here but stays denied until granted in Settings or self-granted - see UsageAccess. -->+    <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"+        tools:ignore="ProtectedPermissions" />+    <!-- Lets UsageAccess set the usage-stats app-op on our own uid. Declared like parental+         controls does; the role grant supplies the privilege. -->+    <uses-permission android:name="android.permission.MANAGE_APP_OPS_MODES"+        tools:ignore="ProtectedPermissions" />+    <!-- Bedtime and focus schedules arm exact alarms for window edges. -->+    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />+    <!-- Re-arms schedules and observers after a restart. -->+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />+    <!-- The dashboard and pickers list launchable apps. -->+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"+        tools:ignore="QueryAllPackagesPermission" />+    <!-- Timer/focus/bedtime notices. A normal runtime permission. -->+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <!-- Bedtime and focus couple to Do Not Disturb. Normal permission; the user grants the+         policy access once in Settings, after which schedules toggle it directly. -->+    <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />++    <!-- Not requested, deliberately: no INTERNET. Usage stays on the device - the dashboard,+         timers, focus and bedtime are all local, and there is no account to sync to. -->+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"+        tools:node="remove" />++    <application+        android:allowBackup="false"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <!--+          The dashboard. Unlike stock Wellbeing - whose launcher entries hide behind a+          phenotype-gated Gateway - this app owns a visible launcher icon: self-managed screen+          time is something the user opens deliberately, not something Settings links to.+        -->+        <activity+            android:name=".ui.DashboardActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:label="@string/app_name"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>++        <!--+          Settings rows. Stock Wellbeing spreads these across the homepage, apps, gestures and+          bedtime categories with summary URIs; ours registers the same rows against our own+          activities so Settings > Digital Wellbeing (and search) lands here.+        -->+        <activity+            android:name=".ui.FocusActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:label="@string/focus_title"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="com.vayunmathur.screentime.action.FOCUS_MODE" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+            <meta-data+                android:name="com.android.settings.category"+                android:value="com.android.settings.category.ia.homepage" />+            <meta-data+                android:name="com.android.settings.summary"+                android:resource="@string/focus_summary" />+        </activity>++        <activity+            android:name=".ui.WindDownActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:label="@string/winddown_title"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.settings.BEDTIME_SETTINGS" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+            <meta-data+                android:name="com.android.settings.category"+                android:value="com.android.settings.category.ia.homepage" />+            <meta-data+                android:name="com.android.settings.summary"+                android:resource="@string/winddown_summary" />+        </activity>++        <activity+            android:name=".ui.AppDetailsActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:label="@string/details_title"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="com.vayunmathur.screentime.action.APP_DETAILS" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+        </activity>++        <!--+          Friction sheets and the expired-timer notice. Started explicitly by our own+          receivers and the usage-observer path; never exported, never in the launcher.+          showWhenLocked is set in code so the sheet meets the launch, not the home screen.+        -->+        <activity+            android:name=".ui.FrictionActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:excludeFromRecents="true"+            android:exported="false"+            android:launchMode="singleInstance"+            android:theme="@style/Theme.General" />++        <!-- Focus mode Quick Settings tile, mirroring stock's FocusModeTileService. -->+        <service+            android:name=".service.FocusTileService"+            android:exported="false"+            android:icon="@mipmap/ic_launcher"+            android:label="@string/focus_title"+            android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">+            <intent-filter>+                <action android:name="android.service.quicksettings.action.QS_TILE" />+            </intent-filter>+        </service>++        <!-- Keeps focus enforcement alive while paused apps are held. -->+        <service+            android:name=".service.FocusService"+            android:exported="false"+            android:foregroundServiceType="specialUse">+            <property+                android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"+                android:value="Holds focus-mode app pauses while the schedule or manual session runs." />+        </service>++        <!-- Fired by UsageStatsService when an app spends its timer budget. -->+        <receiver+            android:name=".receiver.TimerReachedReceiver"+            android:exported="false" />++        <!-- Focus and wind-down window edges. Re-armed each time one fires. -->+        <receiver+            android:name=".receiver.ScheduleReceiver"+            android:exported="false" />++        <receiver+            android:name=".receiver.BootReceiver"+            android:exported="true">+            <intent-filter>+                <action android:name="android.intent.action.BOOT_COMPLETED" />+                <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />+            </intent-filter>+        </receiver>++        <receiver+            android:name=".widget.ScreenTimeGlanceWidgetReceiver"+            android:exported="false"+            android:label="@string/widget_description">+            <intent-filter>+                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />+            </intent-filter>+            <meta-data+                android:name="android.appwidget.provider"+                android:resource="@xml/screentime_widget_info" />+        </receiver>+    </application>+</manifest>
screentime/src/main/java/com/vayunmathur/screentime/data/Rules.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/data/Rules.kt b/screentime/src/main/java/com/vayunmathur/screentime/data/Rules.ktnew file mode 100644index 0000000000..ad6bdc52b5--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/data/Rules.kt@@ -0,0 +1,86 @@+package com.vayunmathur.screentime.data++import androidx.room3.Entity+import androidx.room3.PrimaryKey++/**+ * A self-imposed daily cap on one app.+ *+ * Unlike parental controls, a row here is a promise the user makes to themselves: reaching it+ * pauses the app with a dismissible notice rather than a PIN-locked screen. Absence means no+ * timer.+ */+@Entity+data class AppTimer(+    @PrimaryKey val packageName: String,+    /** Minutes of use permitted per day. */+    val dailyLimitMinutes: Int,+)++/**+ * Which apps focus mode pauses, and when it runs.+ *+ * One profile (singleton row): the paused set plus an optional daily schedule. Manual toggle+ * and schedule share the same paused set, exactly like stock focus mode.+ */+@Entity+data class FocusProfile(+    @PrimaryKey val id: Int = SINGLETON_ID,+    /** Packages paused while a focus session runs. */+    val pausedPackages: List<String> = emptyList(),+    /** Whether the daily schedule arms focus automatically. */+    val scheduleEnabled: Boolean = false,+    /** Minutes past local midnight at which scheduled focus starts. */+    val startMinute: Int = DEFAULT_START_MINUTE,+    /** Minutes past local midnight at which scheduled focus ends. */+    val endMinute: Int = DEFAULT_END_MINUTE,+    /** Bitmask of days the schedule applies to, bit 0 = Monday. */+    val daysMask: Int = ALL_DAYS,+) {+    companion object {+        /** There is one profile. The table exists so Room can store it, not to hold many. */+        const val SINGLETON_ID = 0+        const val ALL_DAYS = 0b111_1111++        /** 09:00. */+        const val DEFAULT_START_MINUTE = 9 * 60++        /** 17:00. */+        const val DEFAULT_END_MINUTE = 17 * 60+    }+}++/**+ * The overnight wind-down: grayscale plus Do Not Disturb.+ *+ * Self-managed bedtime without enforcement - nothing is blocked, the screen just goes quiet.+ * Same minute-past-midnight storage as the supervision windows so behavior matches user+ * expectations across timezone changes and DST.+ */+@Entity+data class WindDownSchedule(+    @PrimaryKey val id: Int = SINGLETON_ID,+    val enabled: Boolean = false,+    /** Minutes past local midnight at which wind-down starts. */+    val startMinute: Int = DEFAULT_START_MINUTE,+    /** Minutes past local midnight at which wind-down ends. */+    val endMinute: Int = DEFAULT_END_MINUTE,+    /** Bitmask of days wind-down applies to, bit 0 = Monday. */+    val daysMask: Int = ALL_DAYS,+    /** Whether to desaturate the display during wind-down. */+    val grayscale: Boolean = true,+    /** Whether to enter Do Not Disturb during wind-down. */+    val doNotDisturb: Boolean = true,+) {+    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 ALL_DAYS = 0b111_1111++        /** 22:00. */+        const val DEFAULT_START_MINUTE = 22 * 60++        /** 07:00. */+        const val DEFAULT_END_MINUTE = 7 * 60+    }+}
screentime/src/main/java/com/vayunmathur/screentime/data/ScreenTimeDatabase.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/data/ScreenTimeDatabase.kt b/screentime/src/main/java/com/vayunmathur/screentime/data/ScreenTimeDatabase.ktnew file mode 100644index 0000000000..d5ae0fc269--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/data/ScreenTimeDatabase.kt@@ -0,0 +1,120 @@+package com.vayunmathur.screentime.data++import android.content.Context+import androidx.room3.ColumnTypeConverters+import androidx.room3.Dao+import androidx.room3.Database+import androidx.room3.Delete+import androidx.room3.Query+import androidx.room3.RoomDatabase+import androidx.room3.Upsert+import com.vayunmathur.library.room.RoomRepository+import com.vayunmathur.library.util.DefaultConverters+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++const val DB_NAME = "screentime-db"++@Dao+interface AppTimerDao {+    @Query("SELECT * FROM AppTimer ORDER BY packageName")+    fun allFlow(): Flow<List<AppTimer>>++    @Query("SELECT * FROM AppTimer")+    suspend fun all(): List<AppTimer>++    @Query("SELECT * FROM AppTimer WHERE packageName = :packageName")+    suspend fun byPackage(packageName: String): AppTimer?++    @Upsert+    suspend fun upsert(timer: AppTimer)++    @Delete+    suspend fun delete(timer: AppTimer)+}++@Dao+interface FocusProfileDao {+    @Query("SELECT * FROM FocusProfile WHERE id = :id")+    fun profileFlow(id: Int = FocusProfile.SINGLETON_ID): Flow<FocusProfile?>++    @Query("SELECT * FROM FocusProfile WHERE id = :id")+    suspend fun profile(id: Int = FocusProfile.SINGLETON_ID): FocusProfile?++    @Upsert+    suspend fun upsert(profile: FocusProfile)+}++@Dao+interface WindDownDao {+    @Query("SELECT * FROM WindDownSchedule WHERE id = :id")+    fun scheduleFlow(id: Int = WindDownSchedule.SINGLETON_ID): Flow<WindDownSchedule?>++    @Query("SELECT * FROM WindDownSchedule WHERE id = :id")+    suspend fun schedule(id: Int = WindDownSchedule.SINGLETON_ID): WindDownSchedule?++    @Upsert+    suspend fun upsert(schedule: WindDownSchedule)+}++@ColumnTypeConverters(DefaultConverters::class)+@Database(+    entities = [AppTimer::class, FocusProfile::class, WindDownSchedule::class],+    version = 1,+    exportSchema = false,+)+abstract class ScreenTimeDatabase : RoomDatabase() {+    abstract fun appTimerDao(): AppTimerDao+    abstract fun focusProfileDao(): FocusProfileDao+    abstract fun windDownDao(): WindDownDao+}++/**+ * The single owner of [ScreenTimeDatabase], shared by the UI, the schedule receiver, the+ * usage observers and the focus service.+ *+ * Mirrors parental controls' `SupervisionRules`: enforcement runs with no Activity alive, so+ * this is a process-wide singleton rather than a ViewModel dependency.+ */+class ScreenTimeRules private constructor(context: Context) :+    RoomRepository<ScreenTimeDatabase>(context, ScreenTimeDatabase::class, DB_NAME) {++    private val timers get() = db.appTimerDao()+    private val focus get() = db.focusProfileDao()+    private val windDown get() = db.windDownDao()++    val allTimers: Flow<List<AppTimer>> = timers.allFlow()++    suspend fun allTimersNow(): List<AppTimer> = timers.all()++    suspend fun timer(packageName: String): AppTimer? = timers.byPackage(packageName)++    suspend fun upsert(timer: AppTimer) = timers.upsert(timer)++    suspend fun delete(timer: AppTimer) = timers.delete(timer)++    /** The focus profile, defaulted rather than nullable. */+    val focusProfile: Flow<FocusProfile> =+        focus.profileFlow().map { it ?: FocusProfile() }++    suspend fun focusNow(): FocusProfile = focus.profile() ?: FocusProfile()++    suspend fun setFocus(profile: FocusProfile) = focus.upsert(profile)++    /** The wind-down schedule, defaulted rather than nullable. */+    val windDownSchedule: Flow<WindDownSchedule> =+        windDown.scheduleFlow().map { it ?: WindDownSchedule() }++    suspend fun windDownNow(): WindDownSchedule = windDown.schedule() ?: WindDownSchedule()++    suspend fun setWindDown(schedule: WindDownSchedule) = windDown.upsert(schedule)++    companion object {+        @Volatile private var instance: ScreenTimeRules? = null++        fun get(context: Context): ScreenTimeRules =+            instance ?: synchronized(this) {+                instance ?: ScreenTimeRules(context).also { instance = it }+            }+    }+}
screentime/src/main/java/com/vayunmathur/screentime/platform/AppTimers.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/AppTimers.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/AppTimers.ktnew file mode 100644index 0000000000..a4094de4cb--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/AppTimers.kt@@ -0,0 +1,167 @@+package com.vayunmathur.screentime.platform++import android.app.PendingIntent+import android.app.usage.UsageStatsManager+import android.content.Context+import android.util.Log+import androidx.core.content.getSystemService+import com.vayunmathur.screentime.data.AppTimer+import com.vayunmathur.screentime.receiver.TimerReachedReceiver+import java.time.Duration+import java.time.LocalDate+import java.time.ZoneId++private const val TAG = "ScreenTimeTimers"++/**+ * Self-imposed per-app caps, timed by the platform's usage tracker.+ *+ * Unlike parental controls' `AppLimits` - which uses the `@SystemApi`+ * `registerAppUsageLimitObserver` waived for the supervision app - this uses the+ * `registerAppUsageObserver` / `registerUsageSessionObserver` pair, gated on `OBSERVE_APP_USAGE`+ * (see Phase 0a: `signature|privileged|role`, granted by `SYSTEM_WELLBEING`). Both are+ * `@SystemApi` members of the public `UsageStatsManager`, so - same rule as parental+ * controls - they are reached reflectively: a stub would shadow the real class for every+ * other caller. The platform counts foreground time and fires the callback when the budget+ * runs out.+ *+ * Observers count from midnight local time. [timeUsedToday] is passed at registration so that+ * re-registering mid-day - after a reboot, or after the user edits the timer - resumes against+ * time already spent rather than handing back a fresh budget.+ */+class AppTimers(private val context: Context) {++    private val usage = context.getSystemService<UsageStatsManager>()++    /** Register an observer for every timed app, replacing any previous registration. */+    fun sync(timers: List<AppTimer>) {+        val usage = usage ?: return+        for (timer in timers) {+            register(usage, timer.packageName, timer.dailyLimitMinutes)+        }+    }++    fun unregister(packageName: String) {+        val usage = usage ?: return+        val method = unregisterMethod ?: return+        runCatching { method.invoke(usage, observerId(packageName)) }+            .onFailure { Log.w(TAG, "could not unregister the observer for $packageName", it) }+    }++    private fun register(usage: UsageStatsManager, packageName: String, minutes: Int) {+        val method = registerMethod ?: return+        val usedMs = timeUsedToday(packageName).toMillis()+        if (usedMs >= Duration.ofMinutes(minutes.toLong()).toMillis()) {+            // Already over budget - enforce now rather than arming an observer that would+            // fire immediately with no useful callback context.+            TimerReachedReceiver.enforceNow(context, packageName)+            return+        }+        val pending = PendingIntent.getBroadcast(+            context,+            observerId(packageName),+            TimerReachedReceiver.intent(context, packageName),+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        runCatching {+            method.invoke(+                usage,+                observerId(packageName),+                arrayOf(packageName),+                minutes.toLong(),+                java.util.concurrent.TimeUnit.MINUTES,+                pending,+            )+        }.onFailure { Log.w(TAG, "could not register an observer for $packageName", it) }+    }++    /**+     * Foreground time for [packageName] since local midnight.+     *+     * Public SDK (`queryAndAggregateUsageStats`) needing `PACKAGE_USAGE_STATS` - see+     * [UsageAccess]. Zero when the op is not held.+     */+    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+        }+        return Duration.ofMillis(stats[packageName]?.totalTimeInForeground ?: 0L)+    }++    /**+     * Total foreground time across all packages since local midnight.+     *+     * Sums the same per-package map as [timeUsedToday] so the dashboard and the timers agree+     * about what "used" means.+     */+    fun totalUsedToday(): 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+        }+        return Duration.ofMillis(stats.values.sumOf { it.totalTimeInForeground })+    }++    /**+     * Per-package foreground map since local midnight, for the dashboard list.+     *+     * One query serves the whole screen; callers filter to launchable packages themselves.+     */+    fun usageTodayByPackage(): Map<String, Long> {+        val usage = usage ?: return emptyMap()+        val midnight = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()+        return runCatching {+            usage.queryAndAggregateUsageStats(midnight, System.currentTimeMillis())+                .mapValues { (_, stats) -> stats.totalTimeInForeground }+                .filterValues { it > 0 }+        }.getOrElse {+            Log.w(TAG, "no usage stats; is PACKAGE_USAGE_STATS granted?", it)+            emptyMap()+        }+    }++    /**+     * A stable per-package observer id.+     *+     * Same `hashCode` trade-off parental controls documents: a collision would merge two apps'+     * budgets, accepted because a persisted id table drifts across uninstalls.+     */+    private fun observerId(packageName: String): Int = packageName.hashCode()++    private companion object {+        val registerMethod: java.lang.reflect.Method? by lazy {+            systemApi(+                "registerAppUsageObserver",+                Int::class.javaPrimitiveType!!,+                Array<String>::class.java,+                Long::class.javaPrimitiveType!!,+                java.util.concurrent.TimeUnit::class.java,+                PendingIntent::class.java,+            )+        }++        val unregisterMethod: java.lang.reflect.Method? by lazy {+            systemApi(+                "unregisterAppUsageObserver",+                Int::class.javaPrimitiveType!!,+            )+        }++        fun systemApi(name: String, vararg params: Class<*>): java.lang.reflect.Method? =+            runCatching { UsageStatsManager::class.java.getMethod(name, *params) }+                .onFailure { Log.w(TAG, "UsageStatsManager.$name is unreachable", it) }+                .getOrNull()+    }+}++/** The package a [TimerReachedReceiver] broadcast refers to. Ours, not the platform's. */+const val EXTRA_PACKAGE_NAME = "com.vayunmathur.screentime.extra.PACKAGE_NAME"
screentime/src/main/java/com/vayunmathur/screentime/platform/Coordinator.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/Coordinator.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/Coordinator.ktnew file mode 100644index 0000000000..8985e2a26b--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/Coordinator.kt@@ -0,0 +1,131 @@+package com.vayunmathur.screentime.platform++import android.content.Context+import android.content.SharedPreferences+import android.util.Log+import androidx.core.content.edit+import com.vayunmathur.screentime.data.ScreenTimeRules+import com.vayunmathur.screentime.widget.WidgetRefresh+import java.time.LocalDate+import java.time.LocalDateTime++private const val TAG = "ScreenTimeCoordinator"++/**+ * Decides what Screen Time's state should be, and makes it so.+ *+ * Mirrors parental controls' `Enforcer.reconcile`: everything that can change an outcome -+ * the timer observer, a schedule boundary, a rule edit, focus toggle, boot - funnels through+ * [reconcile], recomputing the whole picture so the paths cannot disagree.+ *+ * Self-managed throughout: nothing here asks for a PIN, and every restriction is dismissible+ * by the user who set it. The paused set is the union of spent timers and the active focus+ * session; wind-down never pauses, it only quiets (grayscale + DND).+ */+class Coordinator(private val context: Context) {++    private val rules = ScreenTimeRules.get(context)+    private val timers = AppTimers(context)+    private val suspender = Suspender(context)+    private val scheduler = WindowScheduler(context)+    private val windDown = WindDownApplier(context)+    private val spent = SpentState(context)++    /** Note that [packageName] has used up its timer, then reconcile. */+    suspend fun onTimerReached(packageName: String) {+        spent.markSpent(packageName)+        reconcile()+    }++    /** Manual focus toggle from the UI or the QS tile. */+    suspend fun setFocusActive(active: Boolean) {+        prefs().edit { putBoolean(KEY_FOCUS_MANUAL, active) }+        reconcile()+    }++    suspend fun isFocusActive(): Boolean = focusActiveNow()++    suspend fun reconcile() {+        UsageAccess.ensure(context)+        val now = LocalDateTime.now()+        val focus = rules.focusNow()+        val windDownSchedule = rules.windDownNow()+        val allTimers = rules.allTimersNow()+        spent.pruneToToday()++        // Focus runs when toggled on manually or its schedule is open.+        val focusRunning = focusActiveNow() || focus.activeAt(now)+        val focusPaused = if (focusRunning) focus.pausedPackages.toSet() else emptySet()++        // Spent timers pause regardless of focus. Un-spend nothing here: a spent timer stays+        // spent until midnight (the observer fired once and will not fire again).+        val timerPaused = allTimers+            .filter { spent.hasSpent(it.packageName) }+            .map { it.packageName }+            .toSet()++        suspender.sync(focusPaused + timerPaused)++        // Re-arm observers for unspent timers only; spent ones stay paused without an observer.+        timers.sync(allTimers.filter { !spent.hasSpent(it.packageName) })++        // Wind-down applies or clears on every reconcile so a mid-window edit (times changed,+        // toggles flipped) takes effect without waiting for the next boundary.+        val winding = windDownSchedule.activeAt(now)+        if (winding) windDown.enter(windDownSchedule.grayscale, windDownSchedule.doNotDisturb)+        else windDown.exit(windDownSchedule.grayscale, windDownSchedule.doNotDisturb)++        scheduler.armAll(focus, windDownSchedule)++        // The widget tracks whatever reconcile just decided. Fire-and-forget: a missing host+        // must never break enforcement, and WidgetRefresh already swallows host absence.+        WidgetRefresh.refresh(context)+    }++    private suspend fun focusActiveNow(): Boolean =+        prefs().getBoolean(KEY_FOCUS_MANUAL, false)++    private fun prefs(): SharedPreferences =+        context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++    private companion object {+        const val PREFS = "screentime_state"+        const val KEY_FOCUS_MANUAL = "focus_manual"+    }+}++/**+ * Which timers have been spent today.+ *+ * Same shape and rationale as parental controls' `LimitState`: per-day scratch that must be+ * readable without a coroutine and is worthless after midnight, so SharedPreferences rather+ * than Room. Midnight clears it, which is also what unpauses spent timers (via reconcile).+ */+class SpentState(context: Context) {++    private val prefs =+        context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++    fun markSpent(packageName: String) {+        pruneToToday()+        prefs.edit().putStringSet(KEY_SPENT, spent() + packageName).apply()+    }++    fun hasSpent(packageName: String): Boolean = packageName in spent()++    /** Drop yesterday's trips. This is the daily reset; there is no other. */+    fun pruneToToday() {+        if (prefs.getString(KEY_DAY, null) == today()) return+        prefs.edit().remove(KEY_SPENT).putString(KEY_DAY, today()).apply()+    }++    private fun spent(): Set<String> = prefs.getStringSet(KEY_SPENT, emptySet()) ?: emptySet()++    private fun today(): String = LocalDate.now().toString()++    private companion object {+        const val PREFS = "screentime_spent"+        const val KEY_SPENT = "spent"+        const val KEY_DAY = "day"+    }+}
screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.ktnew file mode 100644index 0000000000..95c494c5bf--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt@@ -0,0 +1,191 @@+package com.vayunmathur.screentime.platform++import android.app.Application+import android.content.Intent+import android.content.pm.ApplicationInfo+import android.content.pm.PackageManager+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.screentime.data.AppTimer+import com.vayunmathur.screentime.data.FocusProfile+import com.vayunmathur.screentime.data.ScreenTimeRules+import com.vayunmathur.screentime.data.WindDownSchedule+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/** One launchable app with today's usage and its timer, if any. */+data class TimedApp(+    val packageName: String,+    val label: String,+    val usedMinutes: Long,+    val timer: AppTimer?,+)++/** Everything the Screen Time screens draw. */+data class ScreenTimeUiState(+    val totalMinutes: Long = 0,+    val apps: List<TimedApp> = emptyList(),+    val focus: FocusProfile = FocusProfile(),+    val focusRunning: Boolean = false,+    val windDown: WindDownSchedule = WindDownSchedule(),+    val loading: Boolean = true,+)++class ScreenTimeViewModel(app: Application) : AndroidViewModel(app) {++    private val rules = ScreenTimeRules.get(app)+    private val timers = AppTimers(app)+    private val installed = MutableStateFlow<List<Pair<String, String>>>(emptyList())+    private val usage = MutableStateFlow<Map<String, Long>>(emptyMap())+    private val focusRunning = MutableStateFlow(false)++    val state: StateFlow<ScreenTimeUiState> = combine(+        rules.allTimers,+        rules.focusProfile,+        rules.windDownSchedule,+        installed,+        usage,+        focusRunning,+    ) { flows ->+        @Suppress("UNCHECKED_CAST")+        val timerList = flows[0] as List<AppTimer>+        val focus = flows[1] as FocusProfile+        val windDown = flows[2] as WindDownSchedule+        @Suppress("UNCHECKED_CAST")+        val apps = flows[3] as List<Pair<String, String>>+        @Suppress("UNCHECKED_CAST")+        val used = flows[4] as Map<String, Long>+        val running = flows[5] as Boolean+        val byPackage = timerList.associateBy { it.packageName }+        val timed = apps.mapNotNull { (pkg, label) ->+            val minutes = (used[pkg] ?: 0L) / 60_000L+            if (minutes == 0L && byPackage[pkg] == null) null+            else TimedApp(pkg, label, minutes, byPackage[pkg])+        }.sortedByDescending { it.usedMinutes }+        ScreenTimeUiState(+            totalMinutes = (used.values.sum() / 60_000L),+            apps = timed,+            focus = focus,+            focusRunning = running,+            windDown = windDown,+            loading = apps.isEmpty(),+        )+    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), ScreenTimeUiState())++    init {+        viewModelScope.launch { installed.value = loadLaunchableApps() }+        refresh()+    }++    /** Re-reads usage and focus state; called on resume and after every mutation. */+    fun refresh() {+        viewModelScope.launch(Dispatchers.IO) {+            UsageAccess.ensure(getApplication())+            usage.value = timers.usageTodayByPackage()+            focusRunning.value = Coordinator(getApplication()).isFocusActive()+        }+    }++    fun setTimer(packageName: String, minutes: Int?) {+        viewModelScope.launch {+            if (minutes == null) {+                rules.timer(packageName)?.let { rules.delete(it) }+            } else {+                rules.upsert(AppTimer(packageName, minutes))+            }+            reconcile()+            refresh()+        }+    }++    fun setFocusActive(active: Boolean) {+        viewModelScope.launch {+            Coordinator(getApplication()).setFocusActive(active)+            refresh()+        }+    }++    fun setFocusPaused(packageName: String, paused: Boolean) {+        viewModelScope.launch {+            val current = rules.focusNow()+            val next = current.pausedPackages.toMutableSet()+            if (paused) next.add(packageName) else next.remove(packageName)+            rules.setFocus(current.copy(pausedPackages = next.toList()))+            reconcile()+        }+    }++    fun setFocusSchedule(+        enabled: Boolean? = null,+        startMinute: Int? = null,+        endMinute: Int? = null,+        daysMask: Int? = null,+    ) {+        viewModelScope.launch {+            val current = rules.focusNow()+            rules.setFocus(+                current.copy(+                    scheduleEnabled = enabled ?: current.scheduleEnabled,+                    startMinute = startMinute ?: current.startMinute,+                    endMinute = endMinute ?: current.endMinute,+                    daysMask = daysMask ?: current.daysMask,+                ),+            )+            reconcile()+        }+    }++    fun setWindDown(+        enabled: Boolean? = null,+        startMinute: Int? = null,+        endMinute: Int? = null,+        daysMask: Int? = null,+        grayscale: Boolean? = null,+        doNotDisturb: Boolean? = null,+    ) {+        viewModelScope.launch {+            val current = rules.windDownNow()+            rules.setWindDown(+                current.copy(+                    enabled = enabled ?: current.enabled,+                    startMinute = startMinute ?: current.startMinute,+                    endMinute = endMinute ?: current.endMinute,+                    daysMask = daysMask ?: current.daysMask,+                    grayscale = grayscale ?: current.grayscale,+                    doNotDisturb = doNotDisturb ?: current.doNotDisturb,+                ),+            )+            reconcile()+        }+    }++    private suspend fun reconcile() = withContext(Dispatchers.IO) {+        Coordinator(getApplication()).reconcile()+    }++    private suspend fun loadLaunchableApps(): List<Pair<String, String>> =+        withContext(Dispatchers.IO) {+            val pm = getApplication<Application>().packageManager+            val self = getApplication<Application>().packageName+            val intent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)+            pm.queryIntentActivities(intent, PackageManager.ResolveInfoFlags.of(0))+                .mapNotNull { it.activityInfo?.applicationInfo }+                .distinctBy { it.packageName }+                .filter { it.packageName != self }+                .map { it.packageName to it.label(pm) }+                .sortedBy { it.second.lowercase() }+        }++    private fun ApplicationInfo.label(pm: PackageManager): String =+        runCatching { pm.getApplicationLabel(this).toString() }.getOrDefault(packageName)++    private companion object {+        const val STOP_TIMEOUT_MS = 5_000L+    }+}
screentime/src/main/java/com/vayunmathur/screentime/platform/Suspender.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/Suspender.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/Suspender.ktnew file mode 100644index 0000000000..9d3c7367ee--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/Suspender.kt@@ -0,0 +1,87 @@+package com.vayunmathur.screentime.platform++import android.content.Context+import android.util.Log+import java.lang.reflect.Method++private const val TAG = "ScreenTimeSuspender"++/**+ * Pauses and unpauses apps by package name.+ *+ * `PackageManager.setPackagesSuspended` is `@SystemApi` on an ordinary public class, so -+ * exactly like parental controls' `AppLimits` - this reaches it reflectively instead of with+ * a stub (which would shadow the real `PackageManager` for every other caller). The+ * reflection buys visibility, not privilege: the platform checks `SUSPEND_APPS` on the other+ * side, and it passes only because we hold the `SYSTEM_WELLBEING` role.+ *+ * Hidden-API enforcement would otherwise block this for a presigned, non-platform-signed+ * app, so `com.vayunmathur.screentime` is listed as `hidden-api-whitelisted-app` in+ * `vendor/modern-apps/sysconfig-modern-apps.xml`.+ *+ * A suspended app's icon greys out and launches cancel: the platform shows the standard+ * paused treatment with a button into our `ACTION_SHOW_SUSPENDED_APP_DETAILS` activity+ * (see `AppDetailsActivity`), which is where the timer/focus reason lives. Unsuspending is+ * unconditional: reconcile recomputes the full paused set every time, so a stale suspend+ * cannot survive a rule change, a reboot, or a timer deletion.+ */+class Suspender(private val context: Context) {++    private val pm = context.packageManager++    /** Pause [packages], unpausing everything else we previously paused. */+    fun sync(packages: Set<String>) {+        val previously = trackedPaused()+        val toPause = (packages - previously).toTypedArray()+        val toResume = (previously - packages).toTypedArray()+        if (toPause.isNotEmpty()) setSuspended(toPause, true)+        if (toResume.isNotEmpty()) setSuspended(toResume, false)+    }++    /** Every package we currently hold paused. */+    fun pausedNow(): Set<String> = trackedPaused()++    private fun setSuspended(packages: Array<String>, suspended: Boolean) {+        val method = setSuspendedMethod ?: return+        runCatching {+            // 5-arg overload: (String[], boolean, PersistableBundle, PersistableBundle,+            // SuspendDialogInfo). Null extras and null dialog: the platform shows its default+            // paused treatment, whose details button resolves to our AppDetailsActivity.+            method.invoke(pm, packages, suspended, null, null, null)+            if (suspended) rememberPaused(packages.toSet()) else forgetPaused(packages.toSet())+        }.onFailure { Log.w(TAG, "could not set suspended=$suspended for ${packages.toList()}", it) }+    }++    private val prefs+        get() = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++    private fun trackedPaused(): Set<String> =+        prefs.getStringSet(KEY_PAUSED, emptySet()) ?: emptySet()++    private fun rememberPaused(packages: Set<String>) {+        prefs.edit().putStringSet(KEY_PAUSED, trackedPaused() + packages).apply()+    }++    private fun forgetPaused(packages: Set<String>) {+        prefs.edit().putStringSet(KEY_PAUSED, trackedPaused() - packages).apply()+    }++    private companion object {+        const val PREFS = "screentime_suspended"+        const val KEY_PAUSED = "paused"++        val setSuspendedMethod: Method? by lazy {+            runCatching {+                android.content.pm.PackageManager::class.java.getMethod(+                    "setPackagesSuspended",+                    Array<String>::class.java,+                    Boolean::class.javaPrimitiveType!!,+                    android.os.PersistableBundle::class.java,+                    android.os.PersistableBundle::class.java,+                    Class.forName("android.content.pm.SuspendDialogInfo"),+                )+            }.onFailure { Log.w(TAG, "PackageManager.setPackagesSuspended is unreachable", it) }+                .getOrNull()+        }+    }+}
screentime/src/main/java/com/vayunmathur/screentime/platform/UsageAccess.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageAccess.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageAccess.ktnew file mode 100644index 0000000000..5b83f8577e--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageAccess.kt@@ -0,0 +1,46 @@+package com.vayunmathur.screentime.platform++import android.app.AppOpsManager+import android.content.Context+import android.os.Process+import android.util.Log+import androidx.core.content.getSystemService++private const val TAG = "ScreenTimeUsageAccess"++/**+ * Reads usage stats on our own behalf.+ *+ * `PACKAGE_USAGE_STATS` is `signature|privileged|development|appop|retailDemo`: declared in+ * the manifest but denied until the app-op is allowed. The dashboard cannot wait for the user+ * to find the Settings toggle, so - exactly like parental controls' `UsageAccess` - this sets+ * the op on our own uid. The privilege arrives with the `SYSTEM_WELLBEING` role; the+ * reflection buys visibility into the `@SystemApi` setter, not the privilege itself.+ *+ * Idempotent: called on every reconcile before anything reads usage, so a revoked op heals+ * itself instead of silently zeroing the dashboard.+ */+object UsageAccess {++    fun ensure(context: Context) {+        val appOps = context.getSystemService<AppOpsManager>() ?: return+        val uid = Process.myUid()+        val pkg = context.packageName+        val mode = runCatching {+            appOps.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, uid, pkg)+        }.getOrElse {+            Log.w(TAG, "could not check the usage-stats op", it)+            return+        }+        if (mode == AppOpsManager.MODE_ALLOWED) return+        runCatching {+            val setUidMode = AppOpsManager::class.java.getMethod(+                "setUidMode",+                String::class.java,+                Int::class.javaPrimitiveType!!,+                Int::class.javaPrimitiveType!!,+            )+            setUidMode.invoke(appOps, AppOpsManager.OPSTR_GET_USAGE_STATS, uid, AppOpsManager.MODE_ALLOWED)+        }.onFailure { Log.w(TAG, "could not self-grant the usage-stats op", it) }+    }+}
screentime/src/main/java/com/vayunmathur/screentime/platform/WindDownApplier.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/WindDownApplier.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindDownApplier.ktnew file mode 100644index 0000000000..f619d4c33c--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindDownApplier.kt@@ -0,0 +1,96 @@+package com.vayunmathur.screentime.platform++import android.app.NotificationManager+import android.content.Context+import android.provider.Settings+import android.util.Log+import androidx.core.content.getSystemService++private const val TAG = "ScreenTimeWindDown"++/**+ * Applies and clears the wind-down state: grayscale plus Do Not Disturb.+ *+ * Grayscale path (see Phase 0b): the `CONTROL_DISPLAY_*` permissions are+ * `signature|privileged` - not role-granted - so this writes the accessibility daltonizer+ * keys via `Settings.Secure` instead. `WRITE_SECURE_SETTINGS` is+ * `signature|privileged|development|role|installer`, granted by `SYSTEM_WELLBEING`, which+ * makes this a role-privileged write rather than a hack: the same keys back the system's+ * own grayscale toggle. Monochromacy mode desaturates fully; the saturation level is left+ * at the user's own setting.+ *+ * DND path (see Phase 0c): `ACCESS_NOTIFICATION_POLICY` is a normal permission; the user+ * grants the policy access once, after which schedules toggle it directly through+ * `NotificationManager`. If access was never granted, wind-down still grayscales - a missing+ * quiet mode must never block the visible half.+ */+class WindDownApplier(private val context: Context) {++    private val notifications = context.getSystemService<NotificationManager>()++    /** Enter wind-down: grayscale on (if configured), DND on (if configured and allowed). */+    fun enter(grayscale: Boolean, doNotDisturb: Boolean) {+        if (grayscale) setGrayscale(true)+        if (doNotDisturb) setDnd(true)+    }++    /** Leave wind-down: restore exactly what [enter] changed, nothing else. */+    fun exit(grayscale: Boolean, doNotDisturb: Boolean) {+        if (grayscale) setGrayscale(false)+        if (doNotDisturb) setDnd(false)+    }++    private fun setGrayscale(on: Boolean) {+        val resolver = context.contentResolver+        runCatching {+            // String keys, not Settings.Secure constants: the daltonizer constants are absent+            // from this SDK's Settings.Secure, and the keys are stable AOSP surface.+            Settings.Secure.putInt(+                resolver,+                "accessibility_display_daltonizer_enabled",+                if (on) 1 else 0,+            )+            if (on) {+                Settings.Secure.putString(+                    resolver,+                    "accessibility_display_daltonizer_mode",+                    daltonizerMode(),+                )+            }+        }.onFailure { Log.w(TAG, "could not set grayscale=$on", it) }+    }++    /**+     * The daltonizer mode value for full monochromacy, read live rather than hardcoded.+     *+     * Hardcoding the integer bakes an AOSP constant into the APK; reading the current value+     * first and only overriding the enabled flag keeps us correct if the constant moves.+     * Falls back to the documented monochromacy value when unreadable.+     */+    private fun daltonizerMode(): String =+        runCatching {+            Settings.Secure.getString(+                context.contentResolver,+                "accessibility_display_daltonizer_mode",+            )+        }.getOrNull() ?: MONOCHROMACY_MODE++    private fun setDnd(on: Boolean) {+        val nm = notifications ?: return+        if (!nm.isNotificationPolicyAccessGranted) {+            Log.w(TAG, "no DND policy access; skipping DND change")+            return+        }+        runCatching {+            nm.setInterruptionFilter(+                if (on) NotificationManager.INTERRUPTION_FILTER_PRIORITY+                else NotificationManager.INTERRUPTION_FILTER_ALL,+            )+        }.onFailure { Log.w(TAG, "could not set DND=$on", it) }+    }++    private companion object {+        /** `AccessibilityManager` monochromacy mode. Documented AOSP value, fallback only. */+        const val MONOCHROMACY_MODE = "0"+    }+}
screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.ktnew file mode 100644index 0000000000..6bcc0f262c--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt@@ -0,0 +1,114 @@+package com.vayunmathur.screentime.platform++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.Context+import android.util.Log+import androidx.core.content.getSystemService+import com.vayunmathur.screentime.data.FocusProfile+import com.vayunmathur.screentime.data.WindDownSchedule+import com.vayunmathur.screentime.receiver.ScheduleReceiver+import java.time.LocalDateTime+import java.time.ZoneId++private const val TAG = "ScreenTimeScheduler"++/**+ * Arms the next focus and wind-down boundary.+ *+ * One alarm per schedule type, each for its next transition in either direction, re-armed+ * every time any of them fires (all receivers funnel through the coordinator, which calls+ * back here). Separate request codes keep the alarms from clobbering each other.+ *+ * Same minute-scan predicate-sharing as parental controls' `BedtimeScheduler`: the boundary+ * search evaluates the exact `contains` predicate the enforcer uses, so the two cannot+ * disagree about when a window opens. Exact alarms - a schedule is a promise about a+ * specific minute - degrading to inexact when the permission is revoked.+ */+class WindowScheduler(private val context: Context) {++    private val alarms = context.getSystemService<AlarmManager>()++    fun armAll(focus: FocusProfile, windDown: WindDownSchedule) {+        armWindow(focus.scheduleEnabled, focus::activeAt, REQUEST_FOCUS)+        armWindow(windDown.enabled, windDown::activeAt, REQUEST_WINDDOWN)+    }++    private fun armWindow(+        enabled: Boolean,+        activeAt: (LocalDateTime) -> Boolean,+        requestCode: Int,+    ) {+        val alarms = alarms ?: return+        val pending = pendingIntent(requestCode)+        alarms.cancel(pending)+        if (!enabled) 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; window boundary will be approximate")+                alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)+            }+        }.onFailure { Log.w(TAG, "could not arm the window alarm", it) }+    }++    private fun nextBoundary(activeAt: (LocalDateTime) -> Boolean): LocalDateTime? {+        val now = LocalDateTime.now().withSecond(0).withNano(0)+        var state = activeAt(now)+        for (step in 1..MINUTES_IN_WEEK) {+            val at = now.plusMinutes(step.toLong())+            val next = activeAt(at)+            if (next != state) return at+            state = next+        }+        return null+    }++    private fun pendingIntent(requestCode: Int): PendingIntent = PendingIntent.getBroadcast(+        context,+        requestCode,+        ScheduleReceiver.intent(context),+        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+    )++    private companion object {+        const val REQUEST_FOCUS = 11+        const val REQUEST_WINDDOWN = 12+        const val MINUTES_IN_WEEK = 7 * 24 * 60+    }+}++/** Whether the focus schedule is active at [at], in the device's current timezone. */+fun FocusProfile.activeAt(at: LocalDateTime): Boolean {+    if (!scheduleEnabled) return false+    val minute = at.hour * 60 + at.minute+    val day = at.dayOfWeek.value - 1+    val set = (daysMask shr day) and 1 == 1+    if (!set) return false+    return if (startMinute <= endMinute) {+        minute >= startMinute && minute < endMinute+    } else {+        (minute >= startMinute) || (minute < endMinute && isDaySet((day + 6) % 7))+    }+}++private fun FocusProfile.isDaySet(dayIndex: Int): Boolean = (daysMask shr dayIndex) and 1 == 1++/** Whether wind-down is active at [at], in the device's current timezone. */+fun WindDownSchedule.activeAt(at: LocalDateTime): Boolean {+    if (!enabled) return false+    val minute = at.hour * 60 + at.minute+    val day = at.dayOfWeek.value - 1+    val set = (daysMask shr day) and 1 == 1+    if (!set) return false+    return if (startMinute <= endMinute) {+        minute >= startMinute && minute < endMinute+    } else {+        (minute >= startMinute) || (minute < endMinute && (daysMask shr ((day + 6) % 7)) and 1 == 1)+    }+}
screentime/src/main/java/com/vayunmathur/screentime/receiver/Receivers.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/receiver/Receivers.kt b/screentime/src/main/java/com/vayunmathur/screentime/receiver/Receivers.ktnew file mode 100644index 0000000000..fd30408858--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/receiver/Receivers.kt@@ -0,0 +1,106 @@+package com.vayunmathur.screentime.receiver++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.util.Log+import com.vayunmathur.screentime.platform.Coordinator+import com.vayunmathur.screentime.platform.EXTRA_PACKAGE_NAME+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch++private const val TAG = "ScreenTimeReceiver"++/**+ * Fired by `UsageStatsService` when an app has spent its timer budget.+ *+ * The platform delivers the `PendingIntent` registered with the observer, so this is the+ * moment the timer is actually reached rather than the moment it was set.+ */+class TimerReachedReceiver : BroadcastReceiver() {++    override fun onReceive(context: Context, intent: Intent) {+        val packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME) ?: run {+            Log.w(TAG, "timer callback with no package")+            return+        }+        val app = context.applicationContext+        val pending = goAsync()+        CoroutineScope(Dispatchers.IO).launch {+            try {+                Coordinator(app).onTimerReached(packageName)+            } catch (t: Throwable) {+                Log.e(TAG, "could not enforce the timer for $packageName", t)+            } finally {+                pending.finish()+            }+        }+    }++    companion object {+        fun intent(context: Context, packageName: String): Intent =+            Intent(context, TimerReachedReceiver::class.java)+                .putExtra(EXTRA_PACKAGE_NAME, packageName)++        /** Enforce immediately, for an app already over budget when the observer is armed. */+        fun enforceNow(context: Context, packageName: String) {+            val app = context.applicationContext+            CoroutineScope(Dispatchers.IO).launch {+                runCatching { Coordinator(app).onTimerReached(packageName) }+                    .onFailure { Log.e(TAG, "could not enforce $packageName", it) }+            }+        }+    }+}++/** Fired at each focus / wind-down boundary. Re-arms the next one through [Coordinator]. */+class ScheduleReceiver : BroadcastReceiver() {++    override fun onReceive(context: Context, intent: Intent) {+        val app = context.applicationContext+        val pending = goAsync()+        CoroutineScope(Dispatchers.IO).launch {+            try {+                Coordinator(app).reconcile()+            } catch (t: Throwable) {+                Log.e(TAG, "schedule reconcile failed", t)+            } finally {+                pending.finish()+            }+        }+    }++    companion object {+        fun intent(context: Context): Intent = Intent(context, ScheduleReceiver::class.java)+    }+}++/**+ * Re-establishes enforcement after a reboot.+ *+ * Alarms and usage observers are both process- and boot-scoped, so without this a restart+ * silently ends timers and schedules until something else reconciles. `SpentState` survives+ * in SharedPreferences precisely so a reboot cannot hand back a spent budget.+ */+class BootReceiver : BroadcastReceiver() {++    override fun onReceive(context: Context, intent: Intent) {+        if (intent.action != Intent.ACTION_BOOT_COMPLETED &&+            intent.action != Intent.ACTION_LOCKED_BOOT_COMPLETED+        ) {+            return+        }+        val app = context.applicationContext+        val pending = goAsync()+        CoroutineScope(Dispatchers.IO).launch {+            try {+                Coordinator(app).reconcile()+            } catch (t: Throwable) {+                Log.e(TAG, "boot reconcile failed", t)+            } finally {+                pending.finish()+            }+        }+    }+}
screentime/src/main/java/com/vayunmathur/screentime/service/Services.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/service/Services.kt b/screentime/src/main/java/com/vayunmathur/screentime/service/Services.ktnew file mode 100644index 0000000000..8bb135291d--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/service/Services.kt@@ -0,0 +1,150 @@+package com.vayunmathur.screentime.service++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.service.quicksettings.Tile+import android.service.quicksettings.TileService+import androidx.core.app.NotificationCompat+import com.vayunmathur.screentime.R+import com.vayunmathur.screentime.platform.Coordinator+import com.vayunmathur.screentime.ui.DashboardActivity+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * The focus-mode Quick Settings tile, mirroring stock's `FocusModeTileService`.+ *+ * Taps toggle a manual focus session; the tile reflects whether focus is currently running+ * (manual or scheduled). Unlocks the device first - toggling focus is a deliberate act, not+ * something that should happen behind the keyguard.+ */+class FocusTileService : TileService() {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    override fun onClick() {+        super.onClick()+        unlockAndRun {+            scope.launch {+                val coordinator = Coordinator(this@FocusTileService)+                coordinator.setFocusActive(!coordinator.isFocusActive())+                withContext(Dispatchers.Main) { updateTile() }+            }+        }+    }++    override fun onStartListening() {+        super.onStartListening()+        updateTile()+    }++    private fun updateTile() {+        scope.launch {+            val active = Coordinator(this@FocusTileService).isFocusActive()+            withContext(Dispatchers.Main) {+                qsTile?.apply {+                    state = if (active) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE+                    updateTile()+                }+            }+        }+    }++    override fun onDestroy() {+        scope.cancel()+        super.onDestroy()+    }+}++/**+ * Holds focus-mode app pauses while a session runs.+ *+ * Suspension itself persists without a process (the platform owns it), but the foreground+ * service keeps our scheduling and observer state alive and gives the user a visible,+ * stoppable handle: the notification's action ends the session directly.+ */+class FocusService : android.app.Service() {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    override fun onBind(intent: Intent?): android.os.IBinder? = null++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        when (intent?.action) {+            ACTION_START -> {+                ensureChannel()+                startForeground(NOTIFICATION_ID, notification())+            }+            ACTION_STOP -> {+                scope.launch {+                    Coordinator(this@FocusService).setFocusActive(false)+                    stopSelf()+                }+                return START_NOT_STICKY+            }+        }+        return START_STICKY+    }++    private fun notification(): Notification {+        val stop = PendingIntent.getService(+            this,+            0,+            Intent(this, FocusService::class.java).setAction(ACTION_STOP),+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        val open = PendingIntent.getActivity(+            this,+            0,+            Intent(this, DashboardActivity::class.java),+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        return NotificationCompat.Builder(this, CHANNEL_ID)+            .setSmallIcon(android.R.drawable.ic_lock_idle_alarm)+            .setContentTitle(getString(R.string.focus_running_title))+            .setContentText(getString(R.string.focus_running_text))+            .setContentIntent(open)+            .addAction(+                android.R.drawable.ic_menu_close_clear_cancel,+                getString(R.string.focus_stop),+                stop,+            )+            .setOngoing(true)+            .build()+    }++    private fun ensureChannel() {+        val nm = getSystemService(NotificationManager::class.java) ?: return+        nm.createNotificationChannel(+            NotificationChannel(+                CHANNEL_ID,+                getString(R.string.focus_channel_name),+                NotificationManager.IMPORTANCE_LOW,+            ).apply {+                description = getString(R.string.focus_channel_description)+            },+        )+    }++    companion object {+        const val ACTION_START = "com.vayunmathur.screentime.action.FOCUS_START"+        const val ACTION_STOP = "com.vayunmathur.screentime.action.FOCUS_STOP"++        fun start(context: Context) {+            context.startForegroundService(+                Intent(context, FocusService::class.java).setAction(ACTION_START),+            )+        }++        private const val CHANNEL_ID = "focus_session"+        private const val NOTIFICATION_ID = 3_000_001+    }+}
screentime/src/main/java/com/vayunmathur/screentime/ui/AppDetailsScreen.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/ui/AppDetailsScreen.kt b/screentime/src/main/java/com/vayunmathur/screentime/ui/AppDetailsScreen.ktnew file mode 100644index 0000000000..0ecdc8f254--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/ui/AppDetailsScreen.kt@@ -0,0 +1,182 @@+package com.vayunmathur.screentime.ui++import android.content.Intent+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+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 androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.DynamicTheme+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.screentime.R+import com.vayunmathur.screentime.platform.ScreenTimeViewModel++/**+ * Per-app drill-down: today's usage, the timer, and focus membership.+ *+ * Also answers `ACTION_SHOW_SUSPENDED_APP_DETAILS`: when the user taps a paused app, the+ * platform routes the details button here, so the "why is this paused" question lands on the+ * screen that can answer (and lift) it. The suspended package arrives as the intent data.+ */+class AppDetailsActivity : ComponentActivity() {++    private val viewModel: ScreenTimeViewModel by viewModels()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                val state by viewModel.state.collectAsStateWithLifecycle()+                val pkg = suspendedPackage() ?: state.apps.firstOrNull()?.packageName+                val app = state.apps.firstOrNull { it.packageName == pkg }+                AppDetailsScreen(+                    packageName = pkg,+                    appLabel = app?.label,+                    usedMinutes = app?.usedMinutes,+                    timerMinutes = app?.timer?.dailyLimitMinutes,+                    pausedInFocus = app?.packageName in state.focus.pausedPackages,+                    focusRunning = state.focusRunning,+                    onTimerChange = { minutes ->+                        pkg?.let { viewModel.setTimer(it, minutes) }+                    },+                    onFocusPausedChange = { paused ->+                        pkg?.let { viewModel.setFocusPaused(it, paused) }+                    },+                )+            }+        }+    }++    override fun onResume() {+        super.onResume()+        viewModel.refresh()+    }++    private fun suspendedPackage(): String? {+        // String literal, not Intent.ACTION_SHOW_SUSPENDED_APP_DETAILS: the constant is absent+        // from this SDK's Intent, and the action string is stable platform surface.+        if (intent.action == ACTION_SHOW_SUSPENDED_APP_DETAILS) {+            intent.data?.schemeSpecificPart?.removePrefix("package:")?.let { return it }+        }+        return intent.getStringExtra(EXTRA_DETAILS_PACKAGE)+    }++    companion object {+        const val EXTRA_DETAILS_PACKAGE = "com.vayunmathur.screentime.extra.DETAILS_PACKAGE"++        private const val ACTION_SHOW_SUSPENDED_APP_DETAILS =+            "android.intent.action.SHOW_SUSPENDED_APP_DETAILS"+    }+}++/** Actions the details screen can take. */+data class DetailsActions(+    val onTimerChange: (Int?) -> Unit,+    val onFocusPausedChange: (Boolean) -> Unit,+)++@Composable+fun AppDetailsScreen(+    packageName: String?,+    appLabel: String?,+    usedMinutes: Long?,+    timerMinutes: Int?,+    pausedInFocus: Boolean,+    focusRunning: Boolean,+    onTimerChange: (Int?) -> Unit,+    onFocusPausedChange: (Boolean) -> Unit,+) {+    var picking by remember { mutableStateOf(false) }++    LazyListScaffold(+        title = appLabel ?: stringResource(R.string.details_title),+        horizontalPadding = 0.dp,+        scrollBehavior = appBarScrollBehavior(),+    ) {+        item {+            SettingsSection(title = stringResource(R.string.details_usage)) {+                SettingsRow(+                    title = stringResource(R.string.details_today),+                    supportingText = formatDetailsMinutes(usedMinutes ?: 0),+                )+                SettingsRow(+                    title = stringResource(R.string.details_timer),+                    supportingText = timerMinutes?.let { formatDetailsMinutes(it.toLong()) }+                        ?: stringResource(R.string.timer_none),+                    onClick = { picking = true },+                )+            }+        }++        item {+            SettingsSection(title = stringResource(R.string.focus_title)) {+                SettingsSwitchRow(+                    title = stringResource(R.string.details_pause_in_focus),+                    supportingText =+                        if (focusRunning) stringResource(R.string.details_focus_running)+                        else stringResource(R.string.details_pause_in_focus_hint),+                    checked = pausedInFocus,+                    onCheckedChange = onFocusPausedChange,+                )+            }+        }++        if (packageName == null) {+            item { SettingsRow(title = stringResource(R.string.details_no_app)) }+        }+    }++    if (picking) {+        AlertDialog(+            onDismissRequest = { picking = false },+            title = { Text(appLabel ?: stringResource(R.string.details_title)) },+            text = {+                SettingsSection {+                    SettingsRow(+                        title = stringResource(R.string.timer_none),+                        onClick = { onTimerChange(null); picking = false },+                    )+                    for (minutes in DETAILS_CHOICES) {+                        SettingsRow(+                            title = formatDetailsMinutes(minutes.toLong()),+                            onClick = { onTimerChange(minutes); picking = false },+                        )+                    }+                }+            },+            confirmButton = {},+            dismissButton = {+                TextButton(onClick = { picking = false }) {+                    Text(stringResource(R.string.cancel))+                }+            },+        )+    }+}++private val DETAILS_CHOICES = listOf(15, 30, 45, 60, 90, 120, 180, 240)++private fun formatDetailsMinutes(minutes: Long): String =+    if (minutes < 60) {+        "$minutes min"+    } else {+        val hours = minutes / 60+        val rest = minutes % 60+        if (rest == 0L) "$hours h" else "$hours h $rest min"+    }
screentime/src/main/java/com/vayunmathur/screentime/ui/DashboardActivity.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/ui/DashboardActivity.kt b/screentime/src/main/java/com/vayunmathur/screentime/ui/DashboardActivity.ktnew file mode 100644index 0000000000..62ff4575e7--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/ui/DashboardActivity.kt@@ -0,0 +1,44 @@+package com.vayunmathur.screentime.ui++import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import android.os.Bundle+import androidx.compose.runtime.getValue+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.screentime.platform.ScreenTimeViewModel++/**+ * The screen-time dashboard, reached from the launcher.+ *+ * Unlike parental controls - which has no launcher entry and lives in Settings - self-managed+ * screen time is something the user opens deliberately, so this is a normal launcher activity.+ */+class DashboardActivity : ComponentActivity() {++    private val viewModel: ScreenTimeViewModel by viewModels()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                val state by viewModel.state.collectAsStateWithLifecycle()+                DashboardScreen(+                    state = state,+                    actions = DashboardActions(+                        onRefresh = viewModel::refresh,+                        onTimerChange = viewModel::setTimer,+                    ),+                )+            }+        }+    }++    override fun onResume() {+        super.onResume()+        viewModel.refresh()+    }+}
screentime/src/main/java/com/vayunmathur/screentime/ui/DashboardScreen.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/ui/DashboardScreen.kt b/screentime/src/main/java/com/vayunmathur/screentime/ui/DashboardScreen.ktnew file mode 100644index 0000000000..44ccb4b79e--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/ui/DashboardScreen.kt@@ -0,0 +1,128 @@+package com.vayunmathur.screentime.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.screentime.R+import com.vayunmathur.screentime.platform.ScreenTimeUiState+import com.vayunmathur.screentime.platform.TimedApp++/** Actions the dashboard can take. */+data class DashboardActions(+    val onRefresh: () -> Unit,+    val onTimerChange: (String, Int?) -> Unit,+)++/** Today's usage, most-used first, with per-app timers one tap away. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DashboardScreen(state: ScreenTimeUiState, actions: DashboardActions) {+    var editing by remember { mutableStateOf<TimedApp?>(null) }++    LazyListScaffold(+        title = stringResource(R.string.app_name),+        horizontalPadding = 0.dp,+        scrollBehavior = appBarScrollBehavior(),+    ) {+        item {+            SettingsSection {+                SettingsRow(+                    title = stringResource(R.string.dashboard_today),+                    supportingText = formatMinutes(state.totalMinutes),+                )+            }+        }++        if (state.loading && state.apps.isEmpty()) {+            item { SettingsRow(title = stringResource(R.string.apps_loading)) }+        }++        items(state.apps.size, key = { state.apps[it].packageName }) { index ->+            val app = state.apps[index]+            SettingsRow(+                title = app.label,+                supportingText = timerSupportingText(app),+                onClick = { editing = app },+            )+        }+    }++    val target = editing+    if (target != null) {+        TimerPickerDialog(+            app = target,+            onDismiss = { editing = null },+            onPick = { minutes ->+                actions.onTimerChange(target.packageName, minutes)+                editing = null+            },+        )+    }+}++@Composable+private fun timerSupportingText(app: TimedApp): String {+    val used = formatMinutes(app.usedMinutes)+    val cap = app.timer?.dailyLimitMinutes+    return if (cap == null) used+    else "$used / ${formatMinutes(cap.toLong())}"+}++/**+ * A fixed set of durations rather than free entry.+ *+ * Same rationale as parental controls' limit picker: the platform rejects anything over 24 h+ * and anything negative, and a text field invites both.+ */+@Composable+private fun TimerPickerDialog(+    app: TimedApp,+    onDismiss: () -> Unit,+    onPick: (Int?) -> Unit,+) {+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(app.label) },+        text = {+            SettingsSection {+                SettingsRow(+                    title = stringResource(R.string.timer_none),+                    onClick = { onPick(null) },+                )+                for (minutes in TIMER_CHOICES) {+                    SettingsRow(+                        title = formatMinutes(minutes.toLong()),+                        onClick = { onPick(minutes) },+                    )+                }+            }+        },+        confirmButton = {},+        dismissButton = {+            TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+        },+    )+}++private val TIMER_CHOICES = listOf(15, 30, 45, 60, 90, 120, 180, 240)++private fun formatMinutes(minutes: Long): String =+    if (minutes < 60) {+        "$minutes min"+    } else {+        val hours = minutes / 60+        val rest = minutes % 60+        if (rest == 0L) "$hours h" else "$hours h $rest min"+    }
screentime/src/main/java/com/vayunmathur/screentime/ui/FocusScreen.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/ui/FocusScreen.kt b/screentime/src/main/java/com/vayunmathur/screentime/ui/FocusScreen.ktnew file mode 100644index 0000000000..b494bb2f79--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/ui/FocusScreen.kt@@ -0,0 +1,223 @@+package com.vayunmathur.screentime.ui++import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import android.os.Bundle+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 androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.DynamicTheme+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.screentime.R+import com.vayunmathur.screentime.platform.ScreenTimeUiState+import com.vayunmathur.screentime.platform.ScreenTimeViewModel++/**+ * Focus mode, reached from Settings and the dashboard.+ *+ * Manual toggle plus an optional daily schedule over one shared paused set. Starting a+ * session pauses now; the schedule and the QS tile drive the same state through the+ * coordinator, so all three always agree.+ */+class FocusActivity : ComponentActivity() {++    private val viewModel: ScreenTimeViewModel by viewModels()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                val state by viewModel.state.collectAsStateWithLifecycle()+                FocusScreen(+                    state = state,+                    onToggle = { viewModel.setFocusActive(!state.focusRunning) },+                    onScheduleEnabled = { viewModel.setFocusSchedule(enabled = it) },+                    onStartChange = { h, m -> viewModel.setFocusSchedule(startMinute = h * 60 + m) },+                    onEndChange = { h, m -> viewModel.setFocusSchedule(endMinute = h * 60 + m) },+                    onToggleDay = { day ->+                        viewModel.setFocusSchedule(+                            daysMask = state.focus.daysMask xor (1 shl day),+                        )+                    },+                    onAppPausedChange = viewModel::setFocusPaused,+                )+            }+        }+    }++    override fun onResume() {+        super.onResume()+        viewModel.refresh()+    }+}++/** Actions the focus screen can take. */+data class FocusActions(+    val onToggle: () -> Unit,+    val onScheduleEnabled: (Boolean) -> Unit,+    val onStartChange: (Int, Int) -> Unit,+    val onEndChange: (Int, Int) -> Unit,+    val onToggleDay: (Int) -> Unit,+    val onAppPausedChange: (String, Boolean) -> Unit,+)++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun FocusScreen(+    state: ScreenTimeUiState,+    onToggle: () -> Unit,+    onScheduleEnabled: (Boolean) -> Unit,+    onStartChange: (Int, Int) -> Unit,+    onEndChange: (Int, Int) -> Unit,+    onToggleDay: (Int) -> Unit,+    onAppPausedChange: (String, Boolean) -> Unit,+) {+    var picking by remember { mutableStateOf<FocusPicking?>(null) }+    val focus = state.focus++    LazyListScaffold(+        title = stringResource(R.string.focus_title),+        horizontalPadding = 0.dp,+        scrollBehavior = appBarScrollBehavior(),+    ) {+        item {+            SettingsSection {+                SettingsSwitchRow(+                    title = stringResource(R.string.focus_now),+                    supportingText = stringResource(R.string.focus_now_hint),+                    checked = state.focusRunning,+                    onCheckedChange = { onToggle() },+                )+            }+        }++        item {+            SettingsSection(title = stringResource(R.string.focus_schedule)) {+                SettingsSwitchRow(+                    title = stringResource(R.string.focus_schedule_enable),+                    checked = focus.scheduleEnabled,+                    onCheckedChange = onScheduleEnabled,+                )+                SettingsRow(+                    title = stringResource(R.string.focus_start),+                    supportingText = formatScheduleMinute(focus.startMinute),+                    enabled = focus.scheduleEnabled,+                    onClick = { picking = FocusPicking.Start },+                )+                SettingsRow(+                    title = stringResource(R.string.focus_end),+                    supportingText = formatScheduleMinute(focus.endMinute),+                    enabled = focus.scheduleEnabled,+                    onClick = { picking = FocusPicking.End },+                )+                Row(+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+                    horizontalArrangement = Arrangement.spacedBy(4.dp),+                ) {+                    val labels = stringResource(R.string.focus_day_initials).split(",")+                    for (day in 0 until FOCUS_DAYS) {+                        FilterChip(+                            selected = (focus.daysMask shr day) and 1 == 1,+                            onClick = { onToggleDay(day) },+                            enabled = focus.scheduleEnabled,+                            label = { Text(labels.getOrElse(day) { "?" }) },+                        )+                    }+                }+            }+        }++        item {+            SettingsSection(title = stringResource(R.string.focus_apps)) {+                if (state.loading && state.apps.isEmpty()) {+                    SettingsRow(title = stringResource(R.string.apps_loading))+                }+            }+        }++        items(state.apps.size, key = { state.apps[it].packageName }) { index ->+            val app = state.apps[index]+            SettingsSwitchRow(+                title = app.label,+                supportingText = formatMinutes(app.usedMinutes),+                checked = app.packageName in focus.pausedPackages,+                onCheckedChange = { onAppPausedChange(app.packageName, it) },+            )+        }+    }++    val active = picking+    if (active != null) {+        val initial = if (active == FocusPicking.Start) focus.startMinute else focus.endMinute+        val timeState = rememberTimePickerState(+            initialHour = initial / 60,+            initialMinute = initial % 60,+        )+        AlertDialog(+            onDismissRequest = { picking = null },+            title = {+                Text(+                    stringResource(+                        if (active == FocusPicking.Start) R.string.focus_start else R.string.focus_end,+                    ),+                )+            },+            text = { TimePicker(state = timeState) },+            confirmButton = {+                TextButton(onClick = {+                    if (active == FocusPicking.Start) {+                        onStartChange(timeState.hour, timeState.minute)+                    } else {+                        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 FocusPicking { Start, End }++private const val FOCUS_DAYS = 7++private fun formatScheduleMinute(minuteOfDay: Int): String =+    "%02d:%02d".format(minuteOfDay / 60, minuteOfDay % 60)++private fun formatMinutes(minutes: Long): String =+    if (minutes < 60) {+        "$minutes min"+    } else {+        val hours = minutes / 60+        val rest = minutes % 60+        if (rest == 0L) "$hours h" else "$hours h $rest min"+    }
screentime/src/main/java/com/vayunmathur/screentime/ui/FrictionScreen.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/ui/FrictionScreen.kt b/screentime/src/main/java/com/vayunmathur/screentime/ui/FrictionScreen.ktnew file mode 100644index 0000000000..375626fa42--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/ui/FrictionScreen.kt@@ -0,0 +1,135 @@+package com.vayunmathur.screentime.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.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.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.unit.dp+import androidx.lifecycle.lifecycleScope+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.screentime.R+import com.vayunmathur.screentime.platform.Coordinator+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch++/**+ * The launch-friction sheet: mindful nudge plus spent-timer notice.+ *+ * Shown when a usage observer fires for a watched app (nudge threshold) or when the user+ * opens a paused app's details from the suspended treatment (timer spent). Always+ * dismissible - self-managed means the user can always continue; the sheet just makes the+ * choice deliberate. `showWhenLocked` so it meets the launch, and `singleInstance` ++ * `excludeFromRecents` so it never stacks or lingers.+ */+class FrictionActivity : ComponentActivity() {++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        val pkg = intent.getStringExtra(EXTRA_FRICTION_PACKAGE)+        val nudge = intent.getBooleanExtra(EXTRA_FRICTION_NUDGE, false)+        enableEdgeToEdge()+        setShowWhenLocked(true)+        setTurnScreenOn(true)+        setContent {+            DynamicTheme {+                FrictionScreen(+                    appLabel = pkg?.let { labelFor(it) },+                    nudge = nudge,+                    onContinue = { finish() },+                    onTakeABreak = {+                        lifecycleScope.launch(Dispatchers.IO) {+                            // A break spends the app immediately: the normal spent path pauses+                            // it until midnight, with no timer row left behind.+                            if (pkg != null) {+                                Coordinator(this@FrictionActivity).onTimerReached(pkg)+                            }+                            finish()+                        }+                    },+                )+            }+        }+    }++    private fun labelFor(packageName: String): String? =+        runCatching {+            val info = packageManager.getApplicationInfo(packageName, 0)+            packageManager.getApplicationLabel(info).toString()+        }.getOrNull()++    companion object {+        const val EXTRA_FRICTION_PACKAGE = "com.vayunmathur.screentime.extra.FRICTION_PACKAGE"+        const val EXTRA_FRICTION_NUDGE = "com.vayunmathur.screentime.extra.FRICTION_NUDGE"++        fun intent(context: Context, packageName: String?, nudge: Boolean): Intent =+            Intent(context, FrictionActivity::class.java)+                .putExtra(EXTRA_FRICTION_PACKAGE, packageName)+                .putExtra(EXTRA_FRICTION_NUDGE, nudge)+    }+}++/** Actions the friction sheet offers. */+data class FrictionActions(+    val onContinue: () -> Unit,+    val onTakeABreak: () -> Unit,+)++@Composable+fun FrictionScreen(appLabel: String?, nudge: Boolean, onContinue: () -> Unit, onTakeABreak: () -> Unit) {+    var taken by remember { mutableStateOf(false) }++    AppScaffold(+        title = stringResource(+            if (nudge) R.string.friction_nudge_title else R.string.friction_spent_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(+                stringResource(+                    if (nudge) R.string.friction_nudge_hint else R.string.friction_spent_hint,+                ),+            )+            if (!taken) {+                TextButton(+                    onClick = {+                        taken = true+                        onTakeABreak()+                    },+                ) {+                    Text(stringResource(R.string.friction_break))+                }+            }+            TextButton(onClick = onContinue) {+                Text(+                    stringResource(+                        if (nudge) R.string.friction_continue else R.string.friction_open_anyway,+                    ),+                )+            }+        }+    }+}
screentime/src/main/java/com/vayunmathur/screentime/ui/WindDownScreen.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/ui/WindDownScreen.kt b/screentime/src/main/java/com/vayunmathur/screentime/ui/WindDownScreen.ktnew file mode 100644index 0000000000..c6212547c0--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/ui/WindDownScreen.kt@@ -0,0 +1,195 @@+package com.vayunmathur.screentime.ui++import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import android.os.Bundle+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 androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.DynamicTheme+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.screentime.R+import com.vayunmathur.screentime.platform.ScreenTimeUiState+import com.vayunmathur.screentime.platform.ScreenTimeViewModel++/**+ * Overnight wind-down, reached from Settings (`BEDTIME_SETTINGS`) and the dashboard.+ *+ * Nothing is blocked here - the screen just goes quiet at the scheduled hour: grayscale+ * first, Do Not Disturb alongside when configured. Both halves apply and clear together on+ * every reconcile, so a mid-window edit takes effect without waiting for a boundary.+ */+class WindDownActivity : ComponentActivity() {++    private val viewModel: ScreenTimeViewModel by viewModels()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                val state by viewModel.state.collectAsStateWithLifecycle()+                WindDownScreen(+                    state = state,+                    onEnabledChange = { viewModel.setWindDown(enabled = it) },+                    onStartChange = { h, m -> viewModel.setWindDown(startMinute = h * 60 + m) },+                    onEndChange = { h, m -> viewModel.setWindDown(endMinute = h * 60 + m) },+                    onToggleDay = { day ->+                        viewModel.setWindDown(+                            daysMask = state.windDown.daysMask xor (1 shl day),+                        )+                    },+                    onGrayscaleChange = { viewModel.setWindDown(grayscale = it) },+                    onDndChange = { viewModel.setWindDown(doNotDisturb = it) },+                )+            }+        }+    }++    override fun onResume() {+        super.onResume()+        viewModel.refresh()+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun WindDownScreen(+    state: ScreenTimeUiState,+    onEnabledChange: (Boolean) -> Unit,+    onStartChange: (Int, Int) -> Unit,+    onEndChange: (Int, Int) -> Unit,+    onToggleDay: (Int) -> Unit,+    onGrayscaleChange: (Boolean) -> Unit,+    onDndChange: (Boolean) -> Unit,+) {+    var picking by remember { mutableStateOf<WindDownPicking?>(null) }+    val schedule = state.windDown++    LazyListScaffold(+        title = stringResource(R.string.winddown_title),+        horizontalPadding = 0.dp,+        scrollBehavior = appBarScrollBehavior(),+    ) {+        item {+            SettingsSection {+                SettingsSwitchRow(+                    title = stringResource(R.string.winddown_enable),+                    supportingText = stringResource(R.string.winddown_enable_hint),+                    checked = schedule.enabled,+                    onCheckedChange = onEnabledChange,+                )+                SettingsRow(+                    title = stringResource(R.string.winddown_start),+                    supportingText = formatWindDownMinute(schedule.startMinute),+                    enabled = schedule.enabled,+                    onClick = { picking = WindDownPicking.Start },+                )+                SettingsRow(+                    title = stringResource(R.string.winddown_end),+                    supportingText = formatWindDownMinute(schedule.endMinute),+                    enabled = schedule.enabled,+                    onClick = { picking = WindDownPicking.End },+                )+                Row(+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+                    horizontalArrangement = Arrangement.spacedBy(4.dp),+                ) {+                    val labels = stringResource(R.string.focus_day_initials).split(",")+                    for (day in 0 until WINDDOWN_DAYS) {+                        FilterChip(+                            selected = (schedule.daysMask shr day) and 1 == 1,+                            onClick = { onToggleDay(day) },+                            enabled = schedule.enabled,+                            label = { Text(labels.getOrElse(day) { "?" }) },+                        )+                    }+                }+            }+        }++        item {+            SettingsSection(title = stringResource(R.string.winddown_effects)) {+                SettingsSwitchRow(+                    title = stringResource(R.string.winddown_grayscale),+                    supportingText = stringResource(R.string.winddown_grayscale_hint),+                    checked = schedule.grayscale,+                    enabled = schedule.enabled,+                    onCheckedChange = onGrayscaleChange,+                )+                SettingsSwitchRow(+                    title = stringResource(R.string.winddown_dnd),+                    supportingText = stringResource(R.string.winddown_dnd_hint),+                    checked = schedule.doNotDisturb,+                    enabled = schedule.enabled,+                    onCheckedChange = onDndChange,+                )+            }+        }+    }++    val active = picking+    if (active != null) {+        val initial = if (active == WindDownPicking.Start) schedule.startMinute else schedule.endMinute+        val timeState = rememberTimePickerState(+            initialHour = initial / 60,+            initialMinute = initial % 60,+        )+        AlertDialog(+            onDismissRequest = { picking = null },+            title = {+                Text(+                    stringResource(+                        if (active == WindDownPicking.Start) R.string.winddown_start else R.string.winddown_end,+                    ),+                )+            },+            text = { TimePicker(state = timeState) },+            confirmButton = {+                TextButton(onClick = {+                    if (active == WindDownPicking.Start) {+                        onStartChange(timeState.hour, timeState.minute)+                    } else {+                        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 WindDownPicking { Start, End }++private const val WINDDOWN_DAYS = 7++private fun formatWindDownMinute(minuteOfDay: Int): String =+    "%02d:%02d".format(minuteOfDay / 60, minuteOfDay % 60)
screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeGlanceWidget.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeGlanceWidget.kt b/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeGlanceWidget.ktnew file mode 100644index 0000000000..c9a354d515--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeGlanceWidget.kt@@ -0,0 +1,144 @@+package com.vayunmathur.screentime.widget++import android.content.Context+import android.content.Intent+import android.util.Log+import androidx.compose.runtime.Composable+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.datastore.preferences.core.Preferences+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.glance.GlanceId+import androidx.glance.GlanceModifier+import androidx.glance.GlanceTheme+import androidx.glance.LocalContext+import androidx.glance.action.clickable+import androidx.glance.appwidget.GlanceAppWidget+import androidx.glance.appwidget.action.actionStartActivity+import androidx.glance.appwidget.cornerRadius+import androidx.glance.appwidget.provideContent+import androidx.glance.background+import androidx.glance.currentState+import androidx.glance.layout.Alignment+import androidx.glance.layout.Box+import androidx.glance.layout.Column+import androidx.glance.layout.fillMaxSize+import androidx.glance.layout.fillMaxWidth+import androidx.glance.layout.padding+import androidx.glance.text.Text+import androidx.glance.text.TextAlign+import androidx.glance.text.TextStyle+import com.vayunmathur.library.widgets.DynamicThemeGlance+import com.vayunmathur.screentime.R+import com.vayunmathur.screentime.ui.DashboardActivity++private const val TAG = "ScreenTimeWidget"++internal val TotalMinutesKey = longPreferencesKey("screentime_total_minutes")+internal val TopLabelKey = stringPreferencesKey("screentime_top_label")+internal val TopMinutesKey = longPreferencesKey("screentime_top_minutes")++/**+ * Today's screen time at a glance.+ *+ * Shows the day's total plus the top app, refreshed whenever the coordinator reconciles+ * (timer spent, window boundary) and on the standard widget update path. Tapping opens the+ * dashboard. State is written by the app process into Glance preferences; the widget itself+ * never queries UsageStats (no cross-process permission story to maintain).+ */+class ScreenTimeGlanceWidget : GlanceAppWidget() {+    override suspend fun provideGlance(context: Context, id: GlanceId) {+        provideContent {+            val prefs = currentState<Preferences>()+            val total = prefs[TotalMinutesKey] ?: 0L+            val topLabel = prefs[TopLabelKey]+            val topMinutes = prefs[TopMinutesKey] ?: 0L+            DynamicThemeGlance(context) {+                ScreenTimeWidgetContent(+                    context = context,+                    total = total,+                    topLabel = topLabel,+                    topMinutes = topMinutes,+                )+            }+        }+    }++    override suspend fun providePreview(context: Context, widgetCategory: Int) {+        try {+            provideContent {+                DynamicThemeGlance(context) {+                    ScreenTimeWidgetContent(+                        context = context,+                        total = 187,+                        topLabel = "Example",+                        topMinutes = 64,+                    )+                }+            }+        } catch (t: Throwable) {+            Log.e(TAG, "providePreview failed", t)+        }+    }+}++@Composable+private fun ScreenTimeWidgetContent(+    context: Context,+    total: Long,+    topLabel: String?,+    topMinutes: Long,+) {+    Box(+        modifier = GlanceModifier+            .fillMaxSize()+            .background(GlanceTheme.colors.surface)+            .cornerRadius(20.dp)+            .padding(16.dp)+            .clickable(+                actionStartActivity(+                    Intent(LocalContext.current, DashboardActivity::class.java).apply {+                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+                    },+                ),+            ),+        contentAlignment = Alignment.Center,+    ) {+        Column(+            modifier = GlanceModifier.fillMaxWidth(),+            horizontalAlignment = Alignment.CenterHorizontally,+        ) {+            Text(+                text = context.getString(R.string.widget_today),+                style = TextStyle(+                    color = GlanceTheme.colors.onSurfaceVariant,+                    fontSize = 12.sp,+                    textAlign = TextAlign.Center,+                ),+            )+            Text(+                text = formatWidgetMinutes(total),+                style = TextStyle(+                    color = GlanceTheme.colors.onSurface,+                    fontSize = 28.sp,+                    textAlign = TextAlign.Center,+                ),+            )+            if (topLabel != null) {+                Text(+                    text = "$topLabel · ${formatWidgetMinutes(topMinutes)}",+                    style = TextStyle(+                        color = GlanceTheme.colors.onSurfaceVariant,+                        fontSize = 12.sp,+                        textAlign = TextAlign.Center,+                    ),+                )+            }+        }+    }+}++private fun formatWidgetMinutes(minutes: Long): String =+    if (minutes < 60) "${minutes}m"+    else "${minutes / 60}h ${minutes % 60}m".trim()
screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeWidgetReceiver.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeWidgetReceiver.kt b/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeWidgetReceiver.ktnew file mode 100644index 0000000000..a32549764a--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeWidgetReceiver.kt@@ -0,0 +1,72 @@+package com.vayunmathur.screentime.widget++import android.content.Context+import androidx.glance.appwidget.GlanceAppWidgetManager+import androidx.glance.appwidget.GlanceAppWidgetReceiver+import androidx.glance.appwidget.state.updateAppWidgetState+import androidx.glance.state.PreferencesGlanceStateDefinition+import com.vayunmathur.library.widgets.updateWidgetPreviews+import com.vayunmathur.screentime.platform.AppTimers+import com.vayunmathur.screentime.platform.UsageAccess+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch++class ScreenTimeGlanceWidgetReceiver : GlanceAppWidgetReceiver() {+    override val glanceAppWidget: ScreenTimeGlanceWidget = ScreenTimeGlanceWidget()++    // No periodic refresh: content changes only when usage accrues, and the coordinator+    // pushes an update on every reconcile that matters (see WidgetRefresh).+    override fun onEnabled(context: Context) {+        super.onEnabled(context)+        context.updateWidgetPreviews(ScreenTimeGlanceWidgetReceiver::class)+    }+}++/**+ * Pushes fresh totals into the widget.+ *+ * Called from the coordinator after reconcile so the widget tracks timers, focus and+ * wind-down without polling UsageStats on its own schedule.+ */+object WidgetRefresh {++    fun refresh(context: Context) {+        val app = context.applicationContext+        CoroutineScope(Dispatchers.IO).launch {+            UsageAccess.ensure(app)+            val timers = AppTimers(app)+            val byPackage = timers.usageTodayByPackage()+            val total = byPackage.values.sum() / 60_000L+            val top = byPackage.maxByOrNull { it.value }+            val topLabel = top?.key?.let { labelFor(app, it) }+            val topMinutes = (top?.value ?: 0L) / 60_000L+            runCatching {+                val manager = GlanceAppWidgetManager(app)+                val widget = ScreenTimeGlanceWidget()+                val ids = manager.getGlanceIds(ScreenTimeGlanceWidget::class.java)+                for (id in ids) {+                    updateAppWidgetState(app, PreferencesGlanceStateDefinition, id) { prefs ->+                        prefs.toMutablePreferences().apply {+                            this[TotalMinutesKey] = total+                            if (topLabel != null) {+                                this[TopLabelKey] = topLabel+                                this[TopMinutesKey] = topMinutes+                            }+                        }+                    }+                    widget.update(app, id)+                }+            }.onFailure {+                // The widget host may be absent (headless MAOS builds); usage tracking must+                // never depend on a home-screen widget rendering.+            }+        }+    }++    private fun labelFor(context: Context, packageName: String): String =+        runCatching {+            val info = context.packageManager.getApplicationInfo(packageName, 0)+            context.packageManager.getApplicationLabel(info).toString()+        }.getOrDefault(packageName)+}
screentime/src/main/res/values/strings.xml
diff --git a/screentime/src/main/res/values/strings.xml b/screentime/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..40ca81450f--- /dev/null+++ b/screentime/src/main/res/values/strings.xml@@ -0,0 +1,114 @@+<?xml version="1.0" encoding="utf-8"?>+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">+    <!-- App name. Shown in the launcher and app info. -->+    <string name="app_name">Screen Time</string>++    <!-- Focus mode: title, also the label of its Settings row. Noun phrase. -->+    <string name="focus_title">Focus mode</string>+    <!-- One-line summary under the Focus mode row in Settings. -->+    <string name="focus_summary">Pause distracting apps on demand or on a schedule</string>++    <!-- Wind-down: title, also the label of its Settings row. Noun. -->+    <string name="winddown_title">Bedtime</string>+    <!-- One-line summary under the Bedtime row in Settings. -->+    <string name="winddown_summary">Grayscale and Do Not Disturb overnight</string>++    <!-- Details: usage section heading. Noun. -->+    <string name="details_usage">Usage</string>+    <!-- Per-app details: title of the drill-down screen. Noun phrase. -->+    <string name="details_title">Time spent</string>+    <!-- Details: today's usage row. Noun phrase. -->+    <string name="details_today">Used today</string>+    <!-- Details: timer row. Noun. -->+    <string name="details_timer">Timer</string>+    <!-- Details: focus-membership row. Verb phrase. -->+    <string name="details_pause_in_focus">Pause in focus mode</string>+    <!-- Details: explanation under the focus row. -->+    <string name="details_pause_in_focus_hint">This app pauses while a focus session runs.</string>+    <!-- Details: shown when focus is currently running. -->+    <string name="details_focus_running">Focus is on now.</string>+    <!-- Details: shown when no package was supplied. -->+    <string name="details_no_app">Pick an app from the dashboard to see its details.</string>++    <!-- Friction: mindful-nudge title. Noun phrase. -->+    <string name="friction_nudge_title">Still want this?</string>+    <!-- Friction: nudge explanation. -->+    <string name="friction_nudge_hint">You asked for a reminder when you open this app a lot. Take a breath first.</string>+    <!-- Friction: spent-timer title. Noun phrase. -->+    <string name="friction_spent_title">Time\'s up</string>+    <!-- Friction: spent explanation. -->+    <string name="friction_spent_hint">This app\'s timer ran out. It stays paused until midnight.</string>+    <!-- Friction: break button. Verb phrase. -->+    <string name="friction_break">Take a break</string>+    <!-- Friction: nudge continue button. Verb. -->+    <string name="friction_continue">Continue</string>+    <!-- Friction: spent continue button. Verb phrase. -->+    <string name="friction_open_anyway">Open anyway</string>++    <!-- Widget: description shown in the picker. -->+    <string name="widget_description">Today\'s screen time at a glance.</string>+    <!-- Widget: heading above the total. Noun phrase. -->+    <string name="widget_today">Today</string>++    <!-- Dashboard: heading of today's total row. Noun phrase. -->+    <string name="dashboard_today">Today</string>+    <!-- Dashboard: shown for an app with no timer set, and as the option that removes one. -->+    <string name="timer_none">No timer</string>++    <!-- Focus mode: title of the running notice. Noun phrase. -->+    <string name="focus_running_title">Focus mode is on</string>+    <!-- Focus mode: text of the running notice. -->+    <string name="focus_running_text">Distracting apps are paused. Tap to manage.</string>+    <!-- Focus mode: action that ends the session from the notice. Verb. -->+    <string name="focus_stop">End focus</string>+    <!-- Notifications: channel for the focus session. Noun phrase. -->+    <string name="focus_channel_name">Focus session</string>+    <!-- Notifications: channel description. -->+    <string name="focus_channel_description">Shows while focus mode is pausing apps.</string>+    <!-- Friction: button naming us as the pauser. -->+    <string name="timer_paused_by">Paused by Screen Time</string>++    <!-- Focus mode: the manual on/off row. Noun phrase. -->+    <string name="focus_now">Focus mode</string>+    <!-- Focus mode: explanation under the manual row. -->+    <string name="focus_now_hint">Pause the apps below until you turn focus off.</string>+    <!-- Focus mode: heading above schedule rows. Noun. -->+    <string name="focus_schedule">Schedule</string>+    <!-- Focus mode: the schedule on/off row. Verb phrase. -->+    <string name="focus_schedule_enable">Turn on automatically</string>+    <!-- Focus mode: schedule start row. Noun phrase. -->+    <string name="focus_start">Starts at</string>+    <!-- Focus mode: schedule end row. Noun phrase. -->+    <string name="focus_end">Ends at</string>+    <!-- Focus mode: single-letter day labels, Monday first, comma separated. -->+    <string name="focus_day_initials">M,T,W,T,F,S,S</string>+    <!-- Focus mode: heading above the paused-app list. Noun phrase. -->+    <string name="focus_apps">Paused apps</string>++    <!-- Wind-down: the main on/off switch. Verb phrase. -->+    <string name="winddown_enable">Use wind-down</string>+    <!-- Wind-down: explanation under the main switch. -->+    <string name="winddown_enable_hint">The screen goes quiet overnight: grayscale first, silence alongside.</string>+    <!-- Wind-down: schedule start row. Noun phrase. -->+    <string name="winddown_start">Starts at</string>+    <!-- Wind-down: schedule end row. Noun phrase. -->+    <string name="winddown_end">Ends at</string>+    <!-- Wind-down: heading above the effect toggles. Noun. -->+    <string name="winddown_effects">Effects</string>+    <!-- Wind-down: grayscale toggle. Noun. -->+    <string name="winddown_grayscale">Grayscale</string>+    <!-- Wind-down: grayscale explanation. -->+    <string name="winddown_grayscale_hint">Drain the color out of the screen overnight.</string>+    <!-- Wind-down: DND toggle. Noun phrase. -->+    <string name="winddown_dnd">Do Not Disturb</string>+    <!-- Wind-down: DND explanation. -->+    <string name="winddown_dnd_hint">Silence calls and notifications overnight. Needs policy access.</string>++    <!-- Shown in place of the app list while installed apps are still being read. -->+    <string name="apps_loading">Loading apps…</string>++    <!-- Dialog button that stores the chosen value. Verb. -->+    <string name="save">Save</string>+    <!-- Dialog button that discards the change. Verb. -->+    <string name="cancel">Cancel</string>+</resources>
screentime/src/main/res/xml/data_extraction_rules.xml
diff --git a/screentime/src/main/res/xml/data_extraction_rules.xml b/screentime/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..776b156e8d--- /dev/null+++ b/screentime/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<data-extraction-rules>+    <!--+      Nothing to carry. Timers, focus profiles and wind-down schedules are device-local+      configuration, and usage history is recomputed from UsageStats on demand.+      `allowBackup="false"` in the manifest already says so; this file exists+      because the manifest references it.+    -->+    <cloud-backup />+    <device-transfer />+</data-extraction-rules>
screentime/src/main/res/xml/screentime_widget_info.xml
diff --git a/screentime/src/main/res/xml/screentime_widget_info.xml b/screentime/src/main/res/xml/screentime_widget_info.xmlnew file mode 100644index 0000000000..8da395a3f9--- /dev/null+++ b/screentime/src/main/res/xml/screentime_widget_info.xml@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="utf-8"?>+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"+    android:minWidth="180dp"+    android:minHeight="110dp"+    android:updatePeriodMillis="0"+    android:initialLayout="@layout/glance_widget_initial_layout"+    android:description="@string/widget_description"+    android:resizeMode="horizontal|vertical"+    android:widgetCategory="home_screen" />
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 3dd08b3665..99e2a0faed 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -80,6 +80,7 @@ include(":sdk:openassistant") include(":sdk:games") include(":sdk:cast") include(":things")+include(":watch") include(":office") include(":tools:holidaygen") include(":education")@@ -119,6 +120,7 @@ include(":setupwizard") include(":logviewer") include(":updater") include(":parentalcontrols")+include(":screentime") include(":auto") include(":auto:protocol")