Modern Apps git

← Modern-Apps.git

launcher: home screen built to Launcher3 parity

Commit
ee13f0600232fa8d50c59e0cba55761023448c57
Author
vayun-mathur <[email protected]>
When
2026-08-18 22:21 UTC (3 months ago)
Parents
39c4f4d
A paged workspace with drag-and-drop reordering, folders, an all-apps drawer
with a fast scroller, hosted app widgets with a resize frame, and long-press
popups on both items and bare wallpaper.

Interaction constants come from the AOSP Launcher3 source rather than being
tuned by eye, each named at its use site next to the symbol it came from: the
650ms reorder dwell (Workspace.REORDER_TIMEOUT), the 0.5 all-apps commit
threshold (LauncherAnimUtils.SUCCESS_TRANSITION_PROGRESS), the 1dp/ms fling
release velocity (base_swift_detector_fling_release_velocity), the folder
creation radius (CellLayout.getFolderCreationRadius), the 600/300ms drawer
durations (config_allAppsOpen/CloseDuration) and the reorder preview
oscillation (ReorderPreviewAnimation).

The entire home hierarchy has a single pointerInput owner, so the pager, page
drags, long presses and the drawer swipe arbitrate in one place rather than
competing for touches. The two exceptions - the widget resize handles and the
popup, which lives in its own window - are documented where they are.

Icon loading is bounded and off the main thread, as is the app list. Both were
measured with dumpsys gfxinfo, which is also what identified callable
references defeating Compose skipping as the dominant frame cost.

83 unit tests cover the pure grid, reorder, merge and placement logic.

Diff

README.md
diff --git a/README.md b/README.mdindex adea60db3b..df29aca42d 100644--- a/README.md+++ b/README.md@@ -54,6 +54,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Food Delivery (US only)** | [Homepage](https://ma.vayunmathur.com/apps/fooddelivery) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.fooddelivery/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Food%20Delivery&packageName=com.vayunmathur.fooddelivery&apk=fooddelivery-release.apk) | | **Health** | [Homepage](https://ma.vayunmathur.com/apps/health) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.health/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Health&packageName=com.vayunmathur.health&apk=health-release.apk) | | **Keyboard** | [Homepage](https://ma.vayunmathur.com/apps/keyboard) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.keyboard/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Keyboard&packageName=com.vayunmathur.keyboard&apk=keyboard-release.apk) |+| **Launcher** | [Homepage](https://ma.vayunmathur.com/apps/launcher) | In Progress | In Progress | | **Maps** | [Homepage](https://ma.vayunmathur.com/apps/maps) | In Progress | In Progress | | **Measure** | [Homepage](https://ma.vayunmathur.com/apps/measure) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://ma.vayunmathur.com/fdroid) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Measure&packageName=com.vayunmathur.measure&apk=measure-release.apk) | | **Messages** | [Homepage](https://ma.vayunmathur.com/apps/messages) | In Progress | In Progress |
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex b18e51fde9..dad2c542a4 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -177,6 +177,8 @@ androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "u # Supplies @PreviewTest, which is what actually marks a @Preview as a screenshot test. screenshot-validation-api = { group = "com.android.tools.screenshot", name = "screenshot-validation-api", version.ref = "composeScreenshot" } androidx-compose-foundation = { group = "androidx.compose.foundation", name = "foundation", version.ref = "foundation" }+# Only a transitive dependency otherwise; :launcher declares it directly for animateBounds and Animatable.+androidx-compose-animation = { group = "androidx.compose.animation", name = "animation" } androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" } androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" } androidx-compose-material3-adaptive-navigation-suite = { group = "androidx.compose.material3", name = "material3-adaptive-navigation-suite", version.ref = "material3AdaptiveNavigationSuite" }
launcher/build.gradle.kts
diff --git a/launcher/build.gradle.kts b/launcher/build.gradle.ktsnew file mode 100644index 0000000000..5232068ade--- /dev/null+++ b/launcher/build.gradle.kts@@ -0,0 +1,26 @@+plugins {+    id("common-conventions-app")+    // Listing screenshots come from Compose previews (src/screenshotTest), not from an+    // instrumented test on a device. Same `:launcher:metadata` task name either way.+    id("common-conventions-preview-metadata")+    alias(libs.plugins.ksp)+}++launcherIcon {+    symbol = "apps"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.launcher"+    }+}++dependencies {+    implementRoom(libs)+    implementation(project(":library:room"))+    implementation(libs.androidx.datastore.preferences)+    // Declared rather than relied on transitively: a launcher is mostly motion, so `Animatable`,+    // `animateBounds` and the animation specs are load-bearing here rather than incidental.+    implementation(libs.androidx.compose.animation)+}
launcher/src/main/AndroidManifest.xml
diff --git a/launcher/src/main/AndroidManifest.xml b/launcher/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..a5a5f53821--- /dev/null+++ b/launcher/src/main/AndroidManifest.xml@@ -0,0 +1,83 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+    xmlns:tools="http://schemas.android.com/tools">++    <uses-permission android:name="android.permission.SET_WALLPAPER" />+    <!-- Read the current wallpaper to preview it in the picker. Ignored on API 33+, where+         WallpaperManager.getDrawable() is restricted to the default home app regardless. -->+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"+        android:maxSdkVersion="32" />++    <!--+        Privileged permissions, declared so a build that *is* on the system image gets the+        features they unlock. On an ordinary device none of them is granted, every probe in+        `platform/LauncherPrivilege.kt` answers false, and the app behaves exactly as it would+        without this block. Only `<uses-permission>` appears here on purpose: a `<permission>`,+        a `sharedUserId` or a `<uses-feature>` would stop the APK installing on a stock device.++        `ProtectedPermissions` is suppressed rather than fixed because it is telling us the truth -+        these are granted to system apps only - and that is exactly the arrangement intended. The+        declaration is harmless on a device that will not grant it; requesting it is not possible.+    -->+    <!-- Uninstall without the system confirmation dialog, from the drop bar. -->+    <uses-permission android:name="android.permission.DELETE_PACKAGES"+        tools:ignore="ProtectedPermissions" />+    <!-- Pause and resume the work profile from the drawer's Work tab. -->+    <uses-permission android:name="android.permission.MODIFY_QUIET_MODE"+        tools:ignore="ProtectedPermissions" />+    <!-- Pull the notification shade down by swiping down on the workspace. -->+    <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />++    <!--+        The app drawer lists launchable activities, so it needs to see them. This is the+        narrow form of package visibility rather than QUERY_ALL_PACKAGES: it resolves+        exactly the MAIN/LAUNCHER activities a drawer shows and nothing else, and it is+        what makes LauncherApps.getActivityList return a full list before we hold the+        HOME role.+    -->+    <queries>+        <intent>+            <action android:name="android.intent.action.MAIN" />+            <category android:name="android.intent.category.LAUNCHER" />+        </intent>+        <intent>+            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />+        </intent>+    </queries>++    <application+        android:allowBackup="true"+        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.Launcher">+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:launchMode="singleTask"+            android:resizeableActivity="true"+            android:stateNotNeeded="true"+            android:theme="@style/Theme.Launcher">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+                <!--+                    HOME plus DEFAULT is what makes this eligible to be the home app; without+                    DEFAULT the system will not offer it in the chooser. LAUNCHER stays so the+                    app is still reachable from whatever launcher is currently in charge,+                    which matters while it is not yet the default.+                -->+                <category android:name="android.intent.category.HOME" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+            <!-- Surfaces an in-app settings entry on the system App Info page. -->+            <intent-filter>+                <action android:name="android.intent.action.APPLICATION_PREFERENCES" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+        </activity>+    </application>+</manifest>
launcher/src/main/java/com/vayunmathur/launcher/MainActivity.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/MainActivity.kt b/launcher/src/main/java/com/vayunmathur/launcher/MainActivity.ktnew file mode 100644index 0000000000..5d2dc2404e--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/MainActivity.kt@@ -0,0 +1,237 @@+package com.vayunmathur.launcher++import android.app.Activity+import android.app.ActivityOptions+import android.app.PendingIntent+import android.app.role.RoleManager+import android.appwidget.AppWidgetManager+import android.content.ComponentName+import android.content.Intent+import android.net.Uri+import android.content.pm.PackageManager+import android.os.Bundle+import android.provider.Settings+import android.view.WindowManager+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.result.contract.ActivityResultContracts+import androidx.activity.viewModels+import androidx.compose.runtime.SideEffect+import com.vayunmathur.launcher.platform.ActivityBridge+import com.vayunmathur.launcher.platform.LauncherPrivilege+import com.vayunmathur.launcher.platform.LauncherViewModel+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.rememberNavBackStack++/**+ * The home screen activity, and the [ActivityBridge] the Compose tree talks to.+ *+ * `singleTask` plus `stateNotNeeded` in the manifest are what make it behave like a home+ * app: HOME delivers a new intent to the existing instance rather than stacking another+ * copy, and the system may kill it without saving state because the workspace is in the+ * database, not in a `Bundle`.+ */+class MainActivity : ComponentActivity(), ActivityBridge {++    private val viewModel: LauncherViewModel by viewModels()+    private var backStack: NavBackStack<Route>? = null++    /** Asked before anything a stock device cannot do is offered. See [LauncherPrivilege]. */+    private val privilege get() = viewModel.privilege++    /**+     * The bind consent dialog is a plain intent, so it goes through the Activity Result API.+     *+     * The configure step cannot: `AppWidgetHost.startAppWidgetConfigureActivityForResult` starts+     * the activity itself via the legacy call, so its result can only arrive through+     * [onActivityResult]. One pending callback per flow is enough - both are modal to the user.+     */+    private var pendingBindResult: ((Boolean) -> Unit)? = null+    private var pendingConfigureResult: ((Boolean) -> Unit)? = null++    private val bindWidgetLauncher =+        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->+            val callback = pendingBindResult+            pendingBindResult = null+            callback?.invoke(result.resultCode == Activity.RESULT_OK)+        }++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        viewModel.bridge = this+        setContent {+            DynamicTheme {+                val stack = rememberNavBackStack<Route>(Route.Home)+                SideEffect { backStack = stack }+                Navigation(viewModel, this, stack)+            }+        }+    }++    override fun onStart() {+        super.onStart()+        viewModel.onStart()+        viewModel.refreshDefaultHome()+    }++    override fun onResume() {+        super.onResume()+        // Cheap enough to redo every time we come back: an app may have been installed or+        // uninstalled while we were away without us being alive to hear the callback.+        viewModel.reconcileNow()+    }++    override fun onStop() {+        viewModel.onStop()+        super.onStop()+    }++    override fun onDestroy() {+        viewModel.bridge = null+        super.onDestroy()+    }++    /**+     * Pressing HOME from inside another app, or from a folder we left open, comes back here.+     * Resetting to the first page is what makes HOME feel like HOME rather than a no-op.+     */+    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        setIntent(intent)+        backStack?.reset(Route.Home)+    }++    // ------------------------------------------------------------------+    // ActivityBridge+    // ------------------------------------------------------------------++    override fun requestBindWidget(+        appWidgetId: Int,+        provider: ComponentName,+        profileSerial: Long,+        onResult: (Boolean) -> Unit,+    ) {+        val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_BIND).apply {+            putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)+            putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, provider)+            putExtra(+                AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE,+                viewModel.appsMonitor.userFor(profileSerial),+            )+        }+        pendingBindResult = onResult+        val started = runCatching { bindWidgetLauncher.launch(intent) }.isSuccess+        if (!started) {+            pendingBindResult = null+            // Reporting failure rather than leaving the flow hanging is what triggers the+            // caller's deleteAppWidgetId; a silent drop here leaks the allocated id.+            onResult(false)+        }+    }++    override fun startWidgetConfigure(appWidgetId: Int, onResult: (Boolean) -> Unit) {+        pendingConfigureResult = onResult+        val started = runCatching {+            viewModel.widgetHost.startAppWidgetConfigureActivityForResult(+                this,+                appWidgetId,+                0,+                REQUEST_CONFIGURE_WIDGET,+                null,+            )+        }.isSuccess+        if (!started) {+            pendingConfigureResult = null+            onResult(false)+        }+    }++    @Deprecated("AppWidgetHost only offers startActivityForResult for the configure step.")+    @Suppress("DEPRECATION")+    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {+        super.onActivityResult(requestCode, resultCode, data)+        if (requestCode != REQUEST_CONFIGURE_WIDGET) return+        val callback = pendingConfigureResult ?: return+        pendingConfigureResult = null+        callback(resultCode == Activity.RESULT_OK)+    }++    override fun pickWallpaper() {+        val chooser = Intent.createChooser(+            Intent(Intent.ACTION_SET_WALLPAPER),+            getString(R.string.app_name),+        )+        if (!startSafely(chooser)) AppMessages.show("No wallpaper picker available")+    }++    override fun requestHomeRole() {+        val roleManager = getSystemService(RoleManager::class.java)+        val intent = if (roleManager?.isRoleAvailable(RoleManager.ROLE_HOME) == true) {+            roleManager.createRequestRoleIntent(RoleManager.ROLE_HOME)+        } else {+            // Without the role available there is no direct prompt, so the honest fallback is+            // the settings page where the choice actually lives.+            Intent(Settings.ACTION_HOME_SETTINGS)+        }+        if (!startSafely(intent)) AppMessages.show("Could not open home app settings")+    }++    override fun isDefaultHome(): Boolean {+        val intent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)+        val resolved = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)+        return resolved?.activityInfo?.packageName == packageName+    }++    override fun requestUninstall(packageName: String) {+        // Silently when the ROM has granted DELETE_PACKAGES, which only a system build has; on an+        // ordinary device this is false and the user gets the system confirmation they expect.+        if (privilege.canUninstallSilently() && uninstallSilently(packageName)) return+        // ACTION_DELETE rather than the package installer session API: it needs no+        // permission and shows the system confirmation the user expects.+        val intent = Intent(Intent.ACTION_DELETE, Uri.fromParts("package", packageName, null))+        if (!startSafely(intent)) AppMessages.show("Could not open the uninstaller")+    }++    private fun uninstallSilently(packageName: String): Boolean = runCatching {+        val intent = Intent(this, MainActivity::class.java)+        val sender = PendingIntent.getActivity(+            this,+            REQUEST_SILENT_UNINSTALL,+            intent,+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        packageManager.packageInstaller.uninstall(packageName, sender.intentSender)+        true+    }.getOrDefault(false)++    override fun setWallpaperBlurRadius(radiusPx: Int) {+        // Off on some devices and in battery saver, where asking for a blur is silently ignored -+        // so the drawer's own translucent fill has to be enough on its own, and is.+        val manager = getSystemService(WindowManager::class.java)+        if (manager?.isCrossWindowBlurEnabled != true) return+        runCatching { window.setBackgroundBlurRadius(radiusPx) }+    }++    override fun launchAnimationOptions(left: Int, top: Int, right: Int, bottom: Int): Bundle? =+        runCatching {+            // Clip reveal from the icon's own rect, which is as close to the system launcher's app+            // open as an unprivileged app gets; the real shared-element handoff needs SystemUI.+            ActivityOptions+                .makeClipRevealAnimation(window.decorView, left, top, right - left, bottom - top)+                .toBundle()+        }.getOrNull()++    private fun startSafely(intent: Intent): Boolean = runCatching {+        startActivity(intent)+        true+    }.getOrDefault(false)++    private companion object {+        const val REQUEST_CONFIGURE_WIDGET = 1002+        const val REQUEST_SILENT_UNINSTALL = 1003+    }+}
launcher/src/main/java/com/vayunmathur/launcher/Navigation.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/Navigation.kt b/launcher/src/main/java/com/vayunmathur/launcher/Navigation.ktnew file mode 100644index 0000000000..8e443f5db8--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/Navigation.kt@@ -0,0 +1,45 @@+package com.vayunmathur.launcher++import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.Color+import com.vayunmathur.launcher.platform.ActivityBridge+import com.vayunmathur.launcher.platform.LauncherViewModel+import com.vayunmathur.launcher.platform.LocalActivityBridge+import com.vayunmathur.launcher.platform.LocalIconLoader+import com.vayunmathur.launcher.ui.HomePage+import com.vayunmathur.launcher.ui.SettingsPage+import com.vayunmathur.launcher.ui.components.LauncherDragController+import com.vayunmathur.launcher.ui.components.LocalLauncherDrag+import com.vayunmathur.library.util.DialogPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.openSettingsIfRequested++@Composable+fun Navigation(+    viewModel: LauncherViewModel,+    bridge: ActivityBridge,+    backStack: NavBackStack<Route>,+) {+    backStack.openSettingsIfRequested(Route.Settings)++    // One controller for the whole app, above the nav host, so it outlives anything opening over+    // the home screen while a drag is in flight.+    val dragController = remember { LauncherDragController() }++    CompositionLocalProvider(+        LocalActivityBridge provides bridge,+        LocalIconLoader provides viewModel,+        LocalLauncherDrag provides dragController,+    ) {+        // Transparent, so the wallpaper that Theme.Launcher's window exposes is actually visible.+        // The Scaffold inside MainNavigation otherwise paints an opaque colorScheme.background+        // straight over it.+        MainNavigation(backStack, containerColor = Color.Transparent) {+            entry<Route.Home> { HomePage(backStack, viewModel) }+            entry<Route.Settings>(metadata = DialogPage()) { SettingsPage(backStack, viewModel) }+        }+    }+}
launcher/src/main/java/com/vayunmathur/launcher/Route.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/Route.kt b/launcher/src/main/java/com/vayunmathur/launcher/Route.ktnew file mode 100644index 0000000000..fd3741129a--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/Route.kt@@ -0,0 +1,23 @@+package com.vayunmathur.launcher++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++/**+ * The nav graph is deliberately small.+ *+ * The app drawer, an open folder, the long-press item menu and the widget picker sheet are **not**+ * routes: they are overlays inside [com.vayunmathur.launcher.ui.HomeContent], because a drag has to+ * be able to cross from the drawer onto the grid, out of a folder onto the grid, and out of an+ * item's menu onto the grid, and it can only do that while everything stays inside the home+ * screen's single gesture owner. Only the screens a drag never touches are destinations.+ */+@Serializable+sealed interface Route : NavKey {+    /** The paged home screen, with the drawer, folders and item menus layered over it. */+    @Serializable+    data object Home : Route++    @Serializable+    data object Settings : Route+}
launcher/src/main/java/com/vayunmathur/launcher/data/LauncherDatabase.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherDatabase.kt b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherDatabase.ktnew file mode 100644index 0000000000..dbd5837b3c--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherDatabase.kt@@ -0,0 +1,90 @@+package com.vayunmathur.launcher.data++import androidx.room.Dao+import androidx.room.Database+import androidx.room.Delete+import androidx.room.Query+import androidx.room.RoomDatabase+import androidx.room.TypeConverters+import androidx.room.Upsert+import androidx.room.migration.Migration+import com.vayunmathur.launcher.domain.CONTAINER_DESKTOP+import com.vayunmathur.launcher.domain.CONTAINER_HOTSEAT+import com.vayunmathur.library.util.DatabaseMigrations+import com.vayunmathur.library.util.DefaultConverters+import kotlinx.coroutines.flow.Flow++@Dao+interface LauncherItemDao {++    /**+     * The whole workspace as one flow.+     *+     * One query for everything rather than one per container: the home screen renders all+     * of them together, and Room's invalidation tracker fires per table anyway, so+     * separate flows would all re-emit on every write regardless.+     */+    @Query("SELECT * FROM launcher_items")+    fun getAllFlow(): Flow<List<LauncherItemEntity>>++    @Query("SELECT * FROM launcher_items")+    suspend fun getAll(): List<LauncherItemEntity>++    @Query("SELECT * FROM launcher_items WHERE id = :id")+    suspend fun get(id: Long): LauncherItemEntity?++    @Query("SELECT * FROM launcher_items WHERE containerId = $CONTAINER_DESKTOP")+    suspend fun getDesktopItems(): List<LauncherItemEntity>++    @Query("SELECT * FROM launcher_items WHERE containerId = $CONTAINER_HOTSEAT ORDER BY rank")+    suspend fun getHotseatItems(): List<LauncherItemEntity>++    @Query("SELECT * FROM launcher_items WHERE containerId = :folderId ORDER BY rank")+    suspend fun getFolderChildren(folderId: Long): List<LauncherItemEntity>++    @Query("SELECT COUNT(*) FROM launcher_items WHERE containerId = :folderId")+    suspend fun countFolderChildren(folderId: Long): Int++    @Query("SELECT COUNT(*) FROM launcher_items")+    suspend fun count(): Int++    @Query("SELECT appWidgetId FROM launcher_items WHERE appWidgetId IS NOT NULL")+    suspend fun getUsedWidgetIds(): List<Int>++    @Upsert+    suspend fun upsert(item: LauncherItemEntity): Long++    @Upsert+    suspend fun upsertAll(items: List<LauncherItemEntity>)++    @Delete+    suspend fun delete(item: LauncherItemEntity): Int++    @Query("DELETE FROM launcher_items WHERE id = :id")+    suspend fun deleteById(id: Long)++    @Query("UPDATE launcher_items SET hidden = :hidden WHERE id = :id")+    suspend fun setHidden(id: Long, hidden: Boolean)++    @Query("UPDATE launcher_items SET containerId = :containerId, screen = :screen, cellX = :cellX, cellY = :cellY, rank = :rank WHERE id = :id")+    suspend fun move(id: Long, containerId: Long, screen: Int, cellX: Int, cellY: Int, rank: Int)++    @Query("UPDATE launcher_items SET cellX = :cellX, cellY = :cellY, spanX = :spanX, spanY = :spanY WHERE id = :id")+    suspend fun resizeTo(id: Long, cellX: Int, cellY: Int, spanX: Int, spanY: Int)++    @Query("UPDATE launcher_items SET title = :title WHERE id = :id")+    suspend fun setTitle(id: Long, title: String?)++    @Query("UPDATE launcher_items SET rank = :rank WHERE id = :id")+    suspend fun setRank(id: Long, rank: Int)+}++@TypeConverters(DefaultConverters::class, LauncherConverters::class)+@Database(entities = [LauncherItemEntity::class], version = 1, exportSchema = false)+abstract class LauncherDatabase : RoomDatabase() {+    abstract fun itemDao(): LauncherItemDao++    companion object : DatabaseMigrations {+        override val migrations: List<Migration> = emptyList()+    }+}
launcher/src/main/java/com/vayunmathur/launcher/data/LauncherItemEntity.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherItemEntity.kt b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherItemEntity.ktnew file mode 100644index 0000000000..c446904ae7--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherItemEntity.kt@@ -0,0 +1,129 @@+package com.vayunmathur.launcher.data++import androidx.room.ColumnInfo+import androidx.room.Entity+import androidx.room.Index+import androidx.room.PrimaryKey+import androidx.room.TypeConverter+import com.vayunmathur.launcher.domain.CellRect+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.GridItem+import com.vayunmathur.launcher.domain.LauncherItemType+import com.vayunmathur.launcher.domain.PackageKey+import com.vayunmathur.launcher.domain.ReconcileUseCase+import com.vayunmathur.launcher.domain.containerRefOf+import com.vayunmathur.library.util.DatabaseItem++/**+ * Every icon, folder, widget and pinned shortcut on the home screen, in one table.+ *+ * Deliberately polymorphic, mirroring Launcher3's `favorites`, rather than a table per+ * type. Items of all four kinds share a container/screen/cell/span identity, so every+ * placement query is type-agnostic; and drag-and-drop converts between types constantly+ * (an app becomes a folder child, a shortcut becomes a home item). Separate tables would+ * put a union in front of every read and a cross-table move behind every drop.+ *+ * The target is stored as [packageName] + [className] + [profileSerial] rather than a+ * serialized Intent URI. That makes it queryable — orphan cleanup and reconciliation are+ * `WHERE` clauses instead of a full scan and parse of every row — and it round-trips+ * through `LauncherApps`/`UserManager` without losing the user. [profileSerial] is the+ * `UserManager` serial number because a `UserHandle` is not stable across reboots.+ */+@Entity(+    tableName = "launcher_items",+    indices = [+        // Every workspace read is "the items in this container on this page".+        Index("containerId", "screen"),+        // Reconciliation and package events both look items up by target.+        Index("packageName", "profileSerial"),+        // Widget id lookups on host GC. Unique because two rows sharing an id would make+        // deleting one silently break the other's hosted view.+        Index(value = ["appWidgetId"], unique = true),+    ],+)+data class LauncherItemEntity(+    val itemType: LauncherItemType,++    /** Raw container sentinel. Read through [container], never directly. */+    val containerId: Long,++    /** Page index, for [ContainerRef.Desktop] only. Zero elsewhere. */+    val screen: Int = 0,++    val cellX: Int = 0,+    val cellY: Int = 0,+    val spanX: Int = 1,+    val spanY: Int = 1,++    /** Order within a folder or the hotseat. Unused on the desktop, where cells order. */+    val rank: Int = 0,++    /** Folder name, or a user-overridden label. Null means "use the app's own label". */+    val title: String? = null,++    val packageName: String? = null,+    val className: String? = null,++    /** `UserManager` serial number of the owning profile. 0 is the primary user. */+    val profileSerial: Long = 0,++    /** For [LauncherItemType.DEEP_SHORTCUT]. */+    val shortcutId: String? = null,++    /** Allocated by `AppWidgetHost`. Null for everything that is not a widget. */+    val appWidgetId: Int? = null,++    /** Flattened `ComponentName` of the widget provider. */+    val appWidgetProvider: String? = null,++    /**+     * Target exists but cannot be launched right now — a paused work profile, an app on+     * unmounted storage. Hidden rather than deleted so it comes back; see+     * [ReconcileUseCase].+     */+    @ColumnInfo(defaultValue = "0")+    val hidden: Boolean = false,++    @PrimaryKey(autoGenerate = true)+    override var id: Long = 0,+) : DatabaseItem {++    val container: ContainerRef get() = containerRefOf(containerId)++    val rect: CellRect get() = CellRect(cellX, cellY, spanX, spanY)++    val packageKey: PackageKey? get() = packageName?.let { PackageKey(it, profileSerial) }++    fun withRect(screen: Int, rect: CellRect): LauncherItemEntity = copy(+        screen = screen,+        cellX = rect.cellX,+        cellY = rect.cellY,+        spanX = rect.spanX,+        spanY = rect.spanY,+    )++    fun toGridItem(): GridItem = GridItem(id, screen, rect)++    fun toReconcileItem(): ReconcileUseCase.Item = ReconcileUseCase.Item(+        id = id,+        type = itemType,+        packageName = packageName,+        profileSerial = profileSerial,+        appWidgetId = appWidgetId,+        hidden = hidden,+    )+}++/**+ * Stores [LauncherItemType] as its name.+ *+ * The name rather than the ordinal: a column of readable strings survives someone+ * reordering the enum, which an ordinal column does not.+ */+class LauncherConverters {+    @TypeConverter+    fun fromItemType(value: LauncherItemType): String = value.name++    @TypeConverter+    fun toItemType(value: String): LauncherItemType = LauncherItemType.valueOf(value)+}
launcher/src/main/java/com/vayunmathur/launcher/data/LauncherRepository.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherRepository.kt b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherRepository.ktnew file mode 100644index 0000000000..0e3da0b3aa--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/data/LauncherRepository.kt@@ -0,0 +1,400 @@+package com.vayunmathur.launcher.data++import android.content.Context+import androidx.room.withTransaction+import com.vayunmathur.launcher.domain.AutoPlacer+import com.vayunmathur.launcher.domain.CellRect+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.FolderRules+import com.vayunmathur.launcher.domain.GridSpec+import com.vayunmathur.launcher.domain.HotseatArrange+import com.vayunmathur.launcher.domain.LauncherItemType+import com.vayunmathur.launcher.domain.PackageKey+import com.vayunmathur.launcher.domain.PagedRect+import com.vayunmathur.launcher.domain.ReconcileUseCase+import com.vayunmathur.launcher.domain.toRaw+import com.vayunmathur.library.room.RoomRepository+import kotlinx.coroutines.flow.Flow++/**+ * Single owner of the workspace layout.+ *+ * Everything above this — the ViewModel, the drag controller's commit, the package+ * receiver, the widget host's garbage collection — reads and writes through here, so the+ * grid invariants (no two items in one cell, no folder with one child, no widget row+ * without a bound id) are enforced in one place.+ *+ * Writes that must not be seen half-done are wrapped in [withTransaction]: creating a+ * folder moves two items and inserts a third, and the workspace flow re-emits promptly+ * enough that an intermediate state would render.+ */+class LauncherRepository private constructor(context: Context) :+    RoomRepository<LauncherDatabase>(context, LauncherDatabase::class, DB_NAME) {++    private val dao: LauncherItemDao get() = db.itemDao()++    val items: Flow<List<LauncherItemEntity>> get() = dao.getAllFlow()++    suspend fun isEmpty(): Boolean = dao.count() == 0++    suspend fun get(id: Long): LauncherItemEntity? = dao.get(id)++    suspend fun getAll(): List<LauncherItemEntity> = dao.getAll()++    suspend fun getFolderChildren(folderId: Long): List<LauncherItemEntity> =+        dao.getFolderChildren(folderId)++    suspend fun usedWidgetIds(): Set<Int> = dao.getUsedWidgetIds().toSet()++    suspend fun setTitle(id: Long, title: String?) = dao.setTitle(id, title)++    /**+     * Writes a new span and origin together, with any neighbours the resize shoved aside.+     *+     * One transaction rather than several, because dragging a widget's left or top edge changes both+     * its origin and its span, and a workspace re-emit between the writes would render the widget+     * half-resized, or resized on top of a neighbour that has not moved yet.+     */+    suspend fun resizeTo(id: Long, rect: CellRect, displaced: Map<Long, CellRect> = emptyMap()) {+        if (displaced.isEmpty()) {+            dao.resizeTo(id, rect.cellX, rect.cellY, rect.spanX, rect.spanY)+            return+        }+        val screen = dao.get(id)?.screen ?: 0+        db.withTransaction {+            displaced.forEach { (other, to) ->+                dao.move(other, ContainerRef.Desktop.toRaw(), screen, to.cellX, to.cellY, 0)+            }+            dao.resizeTo(id, rect.cellX, rect.cellY, rect.spanX, rect.spanY)+        }+    }++    // ------------------------------------------------------------------+    // Adding+    // ------------------------------------------------------------------++    /** Inserts [item] at the first free desktop cell that fits its span. */+    suspend fun addToFirstVacantCell(spec: GridSpec, item: LauncherItemEntity): Long {+        val existing = dao.getDesktopItems().map { PagedRect(it.screen, it.rect) }+        val target = AutoPlacer.place(spec, existing, item.rect)+        return dao.upsert(+            item.copy(containerId = ContainerRef.Desktop.toRaw()).withRect(target.screen, target.rect),+        )+    }++    suspend fun upsert(item: LauncherItemEntity): Long = dao.upsert(item)++    /**+     * Seeds the first run.+     *+     * Called only when the table is empty, so a user who deliberately empties their home+     * screen does not get it refilled on the next launch.+     */+    suspend fun seed(spec: GridSpec, apps: List<LauncherItemEntity>, hotseat: List<LauncherItemEntity>) {+        db.withTransaction {+            if (dao.count() > 0) return@withTransaction+            val placements = AutoPlacer.placeAll(spec, emptyList(), apps.map { it.rect })+            dao.upsertAll(+                apps.mapIndexed { index, app ->+                    val at = placements[index]+                    app.copy(containerId = ContainerRef.Desktop.toRaw()).withRect(at.screen, at.rect)+                },+            )+            dao.upsertAll(+                hotseat.take(spec.hotseatSlots).mapIndexed { index, app ->+                    app.copy(containerId = ContainerRef.Hotseat.toRaw(), rank = index)+                },+            )+        }+    }++    // ------------------------------------------------------------------+    // Moving+    // ------------------------------------------------------------------++    /**+     * Commits a finished drag, together with any neighbours the drop pushed aside.+     *+     * One statement when nothing was displaced, so the workspace flow emits once; a transaction+     * when something was, so it still emits once and never with the item moved but its neighbours+     * left behind — which the page would render as a jump.+     */+    suspend fun moveTo(+        id: Long,+        container: ContainerRef,+        screen: Int,+        rect: CellRect,+        rank: Int = 0,+        displaced: Map<Long, CellRect> = emptyMap(),+    ) {+        if (displaced.isEmpty()) {+            dao.move(id, container.toRaw(), screen, rect.cellX, rect.cellY, rank)+            return+        }+        db.withTransaction {+            // Displaced items are neighbours on the same page, so only their cell changes.+            displaced.forEach { (other, to) ->+                dao.move(other, ContainerRef.Desktop.toRaw(), screen, to.cellX, to.cellY, 0)+            }+            dao.move(id, container.toRaw(), screen, rect.cellX, rect.cellY, rank)+        }+    }++    /**+     * Moves [id] into the hotseat at [slot].+     *+     * The hotseat is a rank list rather than a cell grid, so an insert renumbers instead of finding+     * a hole — and once the row is full, something has to give. [HotseatArrange] decides what;+     * whatever it is goes back onto the desktop rather than nowhere, because the alternative is a+     * row the database still holds and the screen never draws.+     */+    suspend fun moveToHotseat(id: Long, slot: Int, spec: GridSpec) {+        db.withTransaction {+            val plan = HotseatArrange.arrange(+                current = dao.getHotseatItems().map { it.id },+                id = id,+                toRank = slot,+                slots = spec.hotseatSlots,+            )+            plan.evicted?.let { evicted ->+                val occupied = dao.getDesktopItems().map { PagedRect(it.screen, it.rect) }+                val at = AutoPlacer.place(spec, occupied, CellRect(0, 0))+                dao.move(+                    evicted,+                    ContainerRef.Desktop.toRaw(),+                    at.screen,+                    at.rect.cellX,+                    at.rect.cellY,+                    0,+                )+            }+            plan.ranks.forEach { (item, rank) ->+                if (item == id) {+                    dao.move(id, ContainerRef.Hotseat.toRaw(), 0, 0, 0, rank)+                } else {+                    dao.setRank(item, rank)+                }+            }+        }+    }++    // ------------------------------------------------------------------+    // Folders+    // ------------------------------------------------------------------++    /**+     * Turns two items into a folder in [target]'s cell.+     *+     * The folder takes the target's exact placement so the icon does not appear to jump,+     * and both items become children ranked in drop order — target first, since it was+     * already there.+     */+    suspend fun createFolder(targetId: Long, draggedId: Long): Long? = db.withTransaction {+        val target = dao.get(targetId) ?: return@withTransaction null+        val dragged = dao.get(draggedId) ?: return@withTransaction null+        if (!FolderRules.canMerge(dragged.itemType, target.itemType)) return@withTransaction null++        val folderId = dao.upsert(+            LauncherItemEntity(+                itemType = LauncherItemType.FOLDER,+                containerId = target.containerId,+                screen = target.screen,+                cellX = target.cellX,+                cellY = target.cellY,+                rank = target.rank,+                title = FolderRules.DEFAULT_FOLDER_TITLE,+            ),+        )+        dao.move(target.id, folderId, 0, 0, 0, 0)+        dao.move(dragged.id, folderId, 0, 0, 0, 1)+        folderId+    }++    /** Appends [itemId] to an existing folder. */+    suspend fun addToFolder(folderId: Long, itemId: Long) {+        db.withTransaction {+            val ranks = dao.getFolderChildren(folderId).map { it.rank }+            dao.move(itemId, folderId, 0, 0, 0, FolderRules.nextRank(ranks))+        }+    }++    /** Moves [itemId] to [rank] within its folder, shifting the siblings it passes. */+    suspend fun reorderInFolder(folderId: Long, itemId: Long, rank: Int) {+        db.withTransaction {+            val others = dao.getFolderChildren(folderId).filter { it.id != itemId }+            val reordered = others.toMutableList()+            val index = rank.coerceIn(0, reordered.size)+            dao.setRank(itemId, index)+            reordered.forEachIndexed { position, child ->+                val next = if (position >= index) position + 1 else position+                if (child.rank != next) dao.setRank(child.id, next)+            }+        }+    }++    /**+     * Renumbers a folder's children to dense ranks, and collapses the folder if too few are left.+     *+     * Called *after* whatever removed a child — a delete, or a move out onto the grid — so it+     * simply reads what remains rather than being told what went. The last child inherits the+     * folder's own cell rather than being auto-placed, which is what makes dragging one of two+     * apps out of a folder look like the folder turning back into the other app.+     */+    suspend fun collapseFolderIfNeeded(folderId: Long) {+        db.withTransaction {+            val remaining = dao.getFolderChildren(folderId)+            FolderRules.denseRanks(remaining.map { it.id }).forEach { (id, rank) ->+                dao.setRank(id, rank)+            }+            if (!FolderRules.shouldCollapse(remaining.size)) return@withTransaction++            val folder = dao.get(folderId) ?: return@withTransaction+            remaining.singleOrNull()?.let { survivor ->+                dao.move(+                    survivor.id,+                    folder.containerId,+                    folder.screen,+                    folder.cellX,+                    folder.cellY,+                    folder.rank,+                )+            }+            dao.deleteById(folderId)+        }+    }++    // ------------------------------------------------------------------+    // Removal+    // ------------------------------------------------------------------++    /**+     * Deletes an item, and the folder that contained it if that leaves it too small.+     *+     * Returns the widget id the caller must hand back to `AppWidgetHost`; the repository+     * cannot call `deleteAppWidgetId` itself without dragging a platform dependency into+     * the data layer, and leaking the id means the provider keeps being updated for a+     * widget nobody can see.+     */+    suspend fun remove(id: Long): Int? = db.withTransaction {+        val item = dao.get(id) ?: return@withTransaction null+        val container = item.container+        // Deleting a folder takes its children with it - they have no cell of their own to+        // fall back to, so leaving them would strand rows nothing can reach.+        if (item.itemType == LauncherItemType.FOLDER) {+            dao.getFolderChildren(id).forEach { dao.deleteById(it.id) }+        }+        dao.deleteById(id)+        if (container is ContainerRef.Folder) {+            collapseFolderIfNeeded(container.id)+        }+        item.appWidgetId+    }++    // ------------------------------------------------------------------+    // Reconciliation and regrid+    // ------------------------------------------------------------------++    /**+     * Applies [ReconcileUseCase] to the saved rows, and returns the widget ids of any rows+     * it deleted so the caller can release them on the host.+     */+    suspend fun reconcile(+        installed: Set<PackageKey>,+        unavailable: Set<PackageKey>,+        boundWidgetIds: Set<Int>,+    ): List<Int> = db.withTransaction {+        val all = dao.getAll()+        val actions = ReconcileUseCase.reconcile(+            items = all.map { it.toReconcileItem() },+            installed = installed,+            unavailable = unavailable,+            boundWidgetIds = boundWidgetIds,+        )+        val byId = all.associateBy { it.id }+        val orphanedWidgetIds = mutableListOf<Int>()+        for (action in actions) {+            when (action) {+                is ReconcileUseCase.Action.Delete -> {+                    byId[action.id]?.appWidgetId?.let(orphanedWidgetIds::add)+                    dao.deleteById(action.id)+                }+                is ReconcileUseCase.Action.SetHidden -> dao.setHidden(action.id, action.hidden)+            }+        }+        // Folders can be emptied by the deletions above, so they are swept afterwards+        // rather than judged alongside their children.+        collapseEmptyFolders()+        orphanedWidgetIds+    }++    /** Re-lays out the desktop for a new grid shape. */+    suspend fun regrid(to: GridSpec) {+        db.withTransaction {+            val desktop = dao.getDesktopItems()+            val moved = AutoPlacer.regrid(desktop.map { it.toGridItem() }, to)+            val before = desktop.associateBy { it.id }+            for (item in moved) {+                val original = before[item.id] ?: continue+                if (original.screen == item.screen && original.rect == item.rect) continue+                dao.move(+                    item.id,+                    original.containerId,+                    item.screen,+                    item.rect.cellX,+                    item.rect.cellY,+                    original.rank,+                )+                if (original.rect.spanX != item.rect.spanX || original.rect.spanY != item.rect.spanY) {+                    dao.resizeTo(item.id, item.rect.cellX, item.rect.cellY, item.rect.spanX, item.rect.spanY)+                }+            }+            // The hotseat is a rank list, so a narrower one drops the tail back onto the+            // desktop rather than renumbering into slots that no longer exist.+            val hotseat = dao.getHotseatItems()+            if (hotseat.size > to.hotseatSlots) {+                val overflow = hotseat.drop(to.hotseatSlots)+                val occupied = dao.getDesktopItems().map { PagedRect(it.screen, it.rect) }.toMutableList()+                for (item in overflow) {+                    val at = AutoPlacer.place(to, occupied, CellRect(0, 0))+                    occupied.add(at)+                    dao.move(item.id, ContainerRef.Desktop.toRaw(), at.screen, at.rect.cellX, at.rect.cellY, 0)+                }+            }+        }+    }++    private suspend fun collapseEmptyFolders() {+        val folders = dao.getAll().filter { it.itemType == LauncherItemType.FOLDER }+        for (folder in folders) {+            val children = dao.getFolderChildren(folder.id)+            if (!FolderRules.shouldCollapse(children.size)) continue+            children.singleOrNull()?.let { survivor ->+                dao.move(+                    survivor.id,+                    folder.containerId,+                    folder.screen,+                    folder.cellX,+                    folder.cellY,+                    folder.rank,+                )+            }+            dao.deleteById(folder.id)+        }+    }++    companion object {+        /**+         * Explicit, because [RoomRepository]'s default is `"passwords-db"` — a default that+         * predates it being shared and that `clock` still inherits by accident.+         */+        private const val DB_NAME = "launcher-db"++        @Volatile+        private var instance: LauncherRepository? = null++        fun get(context: Context): LauncherRepository =+            instance ?: synchronized(this) {+                instance ?: LauncherRepository(context).also { instance = it }+            }+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/AutoPlacer.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/AutoPlacer.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/AutoPlacer.ktnew file mode 100644index 0000000000..dcd9040668--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/AutoPlacer.kt@@ -0,0 +1,66 @@+package com.vayunmathur.launcher.domain++/**+ * Places items across pages without being told where to put them: first-run seeding, a+ * widget added from the picker, an item promoted out of a collapsing folder, and every+ * item after a grid-size change.+ *+ * The rule throughout is **never drop an item**. Running out of room adds a page; a span+ * too large for the new grid is clamped. Silently discarding something the user placed is+ * the one outcome worse than an ugly layout.+ */+object AutoPlacer {++    /**+     * First page (in ascending order, including a brand new one) with room for [span].+     *+     * [existing] is every item already on the desktop. Pages need not be contiguous — a+     * gap is simply an empty page that everything fits on.+     */+    fun place(spec: GridSpec, existing: List<PagedRect>, span: CellRect): PagedRect {+        val clamped = spec.clampSpan(span)+        val byScreen = existing.groupBy { it.screen }+        val lastScreen = byScreen.keys.maxOrNull() ?: -1+        for (screen in 0..(lastScreen + 1)) {+            val occupancy = CellOccupancy.of(spec, byScreen[screen]?.map { it.rect } ?: emptyList())+            val found = GridPlacer.findFirstVacant(occupancy, clamped.spanX, clamped.spanY)+            if (found != null) return PagedRect(screen, found)+        }+        // Unreachable for any span the grid can hold, since screen lastScreen+1 is empty.+        // A span wider than the grid is impossible even so, and clampSpan has already+        // ruled that out.+        error("no room for span ${clamped.spanX}x${clamped.spanY} on a ${spec.columns}x${spec.rows} grid")+    }++    /**+     * Places [spans] in order, each seeing the ones before it. Returned in the same order+     * as the input.+     */+    fun placeAll(spec: GridSpec, existing: List<PagedRect>, spans: List<CellRect>): List<PagedRect> {+        val placed = existing.toMutableList()+        return spans.map { span ->+            place(spec, placed, span).also { placed.add(it) }+        }+    }++    /**+     * Re-lays out every desktop item for a new grid shape.+     *+     * Reading order is preserved (page, then row, then column) and items are re-placed+     * first-fit, so growing the grid pulls items forward and **shrinking it spills the+     * overflow onto new pages** rather than dropping it. Ranks and containers are not this+     * function's business; only desktop items need regridding, since the hotseat is one+     * row of ranks and folder children have no cell coordinates.+     */+    fun regrid(items: List<GridItem>, to: GridSpec): List<GridItem> {+        val ordered = items.sortedWith(+            compareBy({ it.screen }, { it.rect.cellY }, { it.rect.cellX }),+        )+        val placed = mutableListOf<PagedRect>()+        return ordered.map { item ->+            val target = place(to, placed, item.rect)+            placed.add(target)+            GridItem(item.id, target.screen, target.rect)+        }+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/CellOccupancy.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/CellOccupancy.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/CellOccupancy.ktnew file mode 100644index 0000000000..a0212b3467--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/CellOccupancy.kt@@ -0,0 +1,44 @@+package com.vayunmathur.launcher.domain++/**+ * Which cells of one page are taken.+ *+ * A plain bitmap rather than a list of rects: every placement question ("does this fit",+ * "what is the nearest hole") is asked many times per drag frame, and scanning a+ * `BooleanArray` is both simpler and faster than pairwise rectangle intersection.+ *+ * Out-of-bounds is treated as occupied, so callers never need a separate bounds check+ * before asking whether something fits.+ */+class CellOccupancy(val columns: Int, val rows: Int) {+    private val cells = BooleanArray(columns * rows)++    constructor(spec: GridSpec) : this(spec.columns, spec.rows)++    fun isFree(rect: CellRect): Boolean {+        if (rect.cellX < 0 || rect.cellY < 0 || rect.right > columns || rect.bottom > rows) {+            return false+        }+        for (y in rect.cellY until rect.bottom) {+            for (x in rect.cellX until rect.right) {+                if (cells[y * columns + x]) return false+            }+        }+        return true+    }++    fun mark(rect: CellRect, occupied: Boolean = true) {+        for (y in rect.cellY.coerceAtLeast(0) until rect.bottom.coerceAtMost(rows)) {+            for (x in rect.cellX.coerceAtLeast(0) until rect.right.coerceAtMost(columns)) {+                cells[y * columns + x] = occupied+            }+        }+    }++    val freeCellCount: Int get() = cells.count { !it }++    companion object {+        fun of(spec: GridSpec, rects: Iterable<CellRect>): CellOccupancy =+            CellOccupancy(spec).apply { rects.forEach { mark(it) } }+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/CellRect.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/CellRect.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/CellRect.ktnew file mode 100644index 0000000000..4c92041ac7--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/CellRect.kt@@ -0,0 +1,44 @@+package com.vayunmathur.launcher.domain++/**+ * A rectangle of grid cells, in cell units.+ *+ * The grid is the launcher's coordinate system: an icon is 1x1, a widget is whatever+ * span it was given. Everything about placement is expressed in these rather than in+ * pixels, so all of it is testable without a device.+ */+data class CellRect(val cellX: Int, val cellY: Int, val spanX: Int = 1, val spanY: Int = 1) {+    /** Exclusive right edge. */+    val right: Int get() = cellX + spanX++    /** Exclusive bottom edge. */+    val bottom: Int get() = cellY + spanY++    val area: Int get() = spanX * spanY++    fun movedTo(x: Int, y: Int): CellRect = copy(cellX = x, cellY = y)++    fun overlaps(other: CellRect): Boolean =+        cellX < other.right && other.cellX < right && cellY < other.bottom && other.cellY < bottom+}++/** The shape of one grid. [hotseatSlots] is the number of columns in the bottom row. */+data class GridSpec(val columns: Int, val rows: Int, val hotseatSlots: Int = columns) {+    val cellsPerPage: Int get() = columns * rows++    /**+     * Shrinks a span so it can actually be placed on this grid. A widget declaring 4x2+     * cannot go on a 3-column grid, and providers' min/max span metadata is unreliable+     * enough that clamping is the only safe response.+     */+    fun clampSpan(rect: CellRect): CellRect = rect.copy(+        spanX = rect.spanX.coerceIn(1, columns),+        spanY = rect.spanY.coerceIn(1, rows),+    )+}++/** A [CellRect] together with the page it sits on. */+data class PagedRect(val screen: Int, val rect: CellRect)++/** An item reduced to just its identity and placement, which is all the grid logic needs. */+data class GridItem(val id: Long, val screen: Int, val rect: CellRect)
launcher/src/main/java/com/vayunmathur/launcher/domain/ContainerRef.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/ContainerRef.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/ContainerRef.ktnew file mode 100644index 0000000000..afbd639a45--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/ContainerRef.kt@@ -0,0 +1,36 @@+package com.vayunmathur.launcher.domain++/**+ * Where an item lives.+ *+ * Persisted as a single `Long` using Launcher3's sentinel scheme (see [toRaw]) because+ * one column keeps every placement query type-agnostic, and drag-and-drop routinely+ * moves an item between the three kinds of container. This sealed type exists so no+ * code above the DAO ever handles the magic numbers.+ */+sealed interface ContainerRef {+    /** The paged home screen. Items also carry a `screen` (page) index. */+    data object Desktop : ContainerRef++    /** The fixed row at the bottom, present on every page. `screen` is unused. */+    data object Hotseat : ContainerRef++    /** Inside the folder with this row id. `screen` is unused; `rank` orders children. */+    data class Folder(val id: Long) : ContainerRef+}++/** Sentinel container ids. Negative, so they cannot collide with an autogenerated row id. */+const val CONTAINER_DESKTOP = -100L+const val CONTAINER_HOTSEAT = -101L++fun ContainerRef.toRaw(): Long = when (this) {+    ContainerRef.Desktop -> CONTAINER_DESKTOP+    ContainerRef.Hotseat -> CONTAINER_HOTSEAT+    is ContainerRef.Folder -> id+}++fun containerRefOf(raw: Long): ContainerRef = when (raw) {+    CONTAINER_DESKTOP -> ContainerRef.Desktop+    CONTAINER_HOTSEAT -> ContainerRef.Hotseat+    else -> ContainerRef.Folder(raw)+}
launcher/src/main/java/com/vayunmathur/launcher/domain/DropBarTargets.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/DropBarTargets.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/DropBarTargets.ktnew file mode 100644index 0000000000..1dd53d24bc--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/DropBarTargets.kt@@ -0,0 +1,34 @@+package com.vayunmathur.launcher.domain++/** The second thing a drag can be dropped on, beside Remove. */+enum class DropBarSecondary { Uninstall, AppInfo }++/**+ * What the drop bar offers besides Remove.+ *+ * Launcher3 shows a *bar* of targets during a drag, not a single one, and the second target changes+ * with what is in the air: an app the user installed can be uninstalled from here, while a system+ * app cannot be, so it offers App info instead. A target that silently does nothing for half the+ * icons dropped on it is worse than no target, which is why this returns null rather than a+ * disabled Uninstall for the types that have nothing to offer.+ *+ * Pure, so the bar's contents are decided in one testable place rather than by a chain of `when`s+ * inside a composable.+ */+object DropBarTargets {++    /**+     * [canUninstall] is the same test the item menu applies: a user app in this profile.+     * Cross-profile uninstall is not permitted, and a system app cannot be removed at all.+     */+    fun secondaryFor(type: LauncherItemType, canUninstall: Boolean): DropBarSecondary? =+        when (type) {+            LauncherItemType.APPLICATION ->+                if (canUninstall) DropBarSecondary.Uninstall else DropBarSecondary.AppInfo+            // A pinned shortcut belongs to an app that is staying, so App info is the honest+            // second target: uninstalling from here would remove far more than was dragged.+            LauncherItemType.DEEP_SHORTCUT -> DropBarSecondary.AppInfo+            // A folder is not one app, and a widget is not an app at all.+            LauncherItemType.FOLDER, LauncherItemType.APPWIDGET -> null+        }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/FastScroll.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/FastScroll.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/FastScroll.ktnew file mode 100644index 0000000000..6a8cc6bffd--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/FastScroll.kt@@ -0,0 +1,27 @@+package com.vayunmathur.launcher.domain++/**+ * Turning a finger's position on the A-Z strip into a section, and back again.+ *+ * The arithmetic of a fast scroller, which is easy to get subtly wrong and impossible to test on a+ * device: the strip's ends have to be reachable, so the first and last sections must be selectable+ * at fraction 0 and 1 exactly, and a finger dragged past either end must clamp rather than wrap.+ */+object FastScroll {++    /** The section [fraction] of the way down a strip of [sections], or null when there are none. */+    fun sectionAt(fraction: Float, sections: Int): Int? {+        if (sections <= 0) return null+        // Scaled by the count rather than by count-1, so every section owns an equal band of the+        // strip; the last band would otherwise be unreachable except at exactly 1.0.+        val index = (fraction.coerceIn(0f, 1f) * sections).toInt()+        return index.coerceIn(0, sections - 1)+    }++    /** Where section [index] sits along the strip, as the centre of its band. */+    fun fractionOf(index: Int, sections: Int): Float {+        if (sections <= 0) return 0f+        val clamped = index.coerceIn(0, sections - 1)+        return (clamped + 0.5f) / sections+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/FolderMerge.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/FolderMerge.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/FolderMerge.ktnew file mode 100644index 0000000000..5962203173--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/FolderMerge.kt@@ -0,0 +1,67 @@+package com.vayunmathur.launcher.domain++import kotlin.math.min+import kotlin.math.sqrt++/**+ * Whether a drag is close enough to an icon to fold into it, rather than to reorder past it.+ *+ * The distinction the grid otherwise cannot draw: a cell is not one target but two. Its middle is a+ * folder and the rest of it is a hole in the grid.+ *+ * Launcher3's radius, from `CellLayout.getFolderCreationRadius`, is the mean of two things:+ *+ * ```+ * iconVisibleRadius = ICON_VISIBLE_AREA_FACTOR * iconSizePx / 2   // 0.92, so 0.46 * iconSizePx+ * folderRadius      = (reorderRadius + iconVisibleRadius) / 2+ * ```+ *+ * where `reorderRadius` for a 1x1 cell that could accept a folder is the distance from the icon's+ * centre to the *nearest edge of its cell* — "halfway between the reorder radius and the icon", as+ * the AOSP comment puts it. So the threshold is not a fixed fraction of the icon: it grows with the+ * cell, which matters on a three-column grid where cells are much wider than icons.+ *+ * Distances arrive as a component pair rather than as a point, so this stays free of+ * `androidx.compose` and therefore testable: [dx] and [dy] are the drag position minus the icon's+ * centre, in pixels.+ */+object FolderMerge {++    fun willCreateFolder(+        dx: Float,+        dy: Float,+        iconSizePx: Float,+        cellWidthPx: Float,+        cellHeightPx: Float,+    ): Boolean = mergeProgress(dx, dy, iconSizePx, cellWidthPx, cellHeightPx) > 0f++    /**+     * How far into the merge zone the drag is: 0 on or outside the threshold, 1 dead centre.+     *+     * Exposed separately from [willCreateFolder] because Launcher3 does not just decide — it+     * *shows* the decision coming, growing a ring around the icon as the drag closes in. A boolean+     * alone would make folder creation feel like it happened by accident.+     */+    fun mergeProgress(+        dx: Float,+        dy: Float,+        iconSizePx: Float,+        cellWidthPx: Float,+        cellHeightPx: Float,+    ): Float {+        val radius = radius(iconSizePx, cellWidthPx, cellHeightPx)+        if (radius <= 0f) return 0f+        // Squared, so no square root is taken until it is known to be needed.+        val distanceSquared = dx * dx + dy * dy+        if (distanceSquared >= radius * radius) return 0f+        return 1f - sqrt(distanceSquared) / radius+    }++    /** The merge radius in pixels, which is what the growing ring is drawn against. */+    fun radius(iconSizePx: Float, cellWidthPx: Float, cellHeightPx: Float): Float {+        // The icon sits centred in its cell, so the nearest cell edge is half the smaller dimension.+        val reorderRadius = min(cellWidthPx, cellHeightPx) / 2f+        val iconVisibleRadius = LauncherTuning.IconVisibleAreaFactor * iconSizePx / 2f+        return (reorderRadius + iconVisibleRadius) / 2f+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/FolderRules.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/FolderRules.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/FolderRules.ktnew file mode 100644index 0000000000..5b3853d641--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/FolderRules.kt@@ -0,0 +1,52 @@+package com.vayunmathur.launcher.domain++/**+ * When one item dropped onto another becomes a folder, and when a folder stops being+ * worth keeping.+ *+ * Pure predicates rather than logic inlined into the drop handler, because "can these+ * merge" is asked twice per drag — once to draw the highlight under the finger, once to+ * commit — and the two answers must never disagree.+ */+object FolderRules {++    /** Below this, a folder is just an icon with extra taps, so it collapses. */+    const val MIN_CHILDREN = 2++    /**+     * Whether dropping [dragged] onto [target] should produce or grow a folder.+     *+     * Widgets are excluded in both directions: they have a span, and a folder child has no+     * cell coordinates to give one. A folder dropped onto another item is a move, not a+     * merge — nesting folders is a maze, and Launcher3 does not allow it either.+     */+    fun canMerge(dragged: LauncherItemType, target: LauncherItemType): Boolean {+        if (dragged == LauncherItemType.APPWIDGET || target == LauncherItemType.APPWIDGET) return false+        if (dragged == LauncherItemType.FOLDER) return false+        return true+    }++    /**+     * Whether [childCount] children left in a folder means it should go away, promoting the+     * remaining child (if any) into the folder's own cell.+     */+    fun shouldCollapse(childCount: Int): Boolean = childCount < MIN_CHILDREN++    /**+     * Default name for a folder created by a drop.+     *+     * Deliberately empty rather than "Folder": an unnamed folder renders as just its+     * children, and a placeholder name is something the user then has to clear.+     */+    const val DEFAULT_FOLDER_TITLE = ""++    /** Ranks are dense and zero-based, so the next child goes after the current highest. */+    fun nextRank(existingRanks: Collection<Int>): Int = (existingRanks.maxOrNull() ?: -1) + 1++    /**+     * Re-numbers [orderedIds] to dense ranks. Called after a removal so a folder that has+     * lost its second child does not leave a hole that the next insert falls into.+     */+    fun denseRanks(orderedIds: List<Long>): Map<Long, Int> =+        orderedIds.withIndex().associate { (index, id) -> id to index }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/GridPlacer.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/GridPlacer.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/GridPlacer.ktnew file mode 100644index 0000000000..f993c31e69--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/GridPlacer.kt@@ -0,0 +1,51 @@+package com.vayunmathur.launcher.domain++/**+ * Finds somewhere on a single page to put something.+ *+ * Used while dragging: the finger names a preferred cell every frame, and the drop+ * preview has to land on a real vacancy rather than wherever the finger happens to be.+ */+object GridPlacer {++    /**+     * The vacant position closest to [preferred], or null when the page cannot hold the+     * span at all.+     *+     * Distance is measured between rectangle origins, and ties break towards the smaller+     * row then column so the result is stable frame to frame — a preview that flickers+     * between two equidistant holes is worse than one that picks the wrong one+     * consistently.+     */+    fun findNearestVacant(occupancy: CellOccupancy, preferred: CellRect): CellRect? {+        if (occupancy.isFree(preferred)) return preferred++        var best: CellRect? = null+        var bestDistance = Int.MAX_VALUE+        for (y in 0..(occupancy.rows - preferred.spanY)) {+            for (x in 0..(occupancy.columns - preferred.spanX)) {+                val candidate = preferred.movedTo(x, y)+                if (!occupancy.isFree(candidate)) continue+                val dx = x - preferred.cellX+                val dy = y - preferred.cellY+                val distance = dx * dx + dy * dy+                if (distance < bestDistance) {+                    bestDistance = distance+                    best = candidate+                }+            }+        }+        return best+    }++    /** Top-left-most vacancy that fits the span, or null when the page is too full. */+    fun findFirstVacant(occupancy: CellOccupancy, spanX: Int, spanY: Int): CellRect? {+        for (y in 0..(occupancy.rows - spanY)) {+            for (x in 0..(occupancy.columns - spanX)) {+                val candidate = CellRect(x, y, spanX, spanY)+                if (occupancy.isFree(candidate)) return candidate+            }+        }+        return null+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/GridPreview.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/GridPreview.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/GridPreview.ktnew file mode 100644index 0000000000..4973b50bdc--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/GridPreview.kt@@ -0,0 +1,96 @@+package com.vayunmathur.launcher.domain++/**+ * Where everything on a page goes if a drag is released at a particular cell.+ *+ * [target] is where the dragged item lands. [displaced] is every *other* item that has to move to+ * make room, as `id` to its new rect; items absent from it stay where they are.+ *+ * One value for both the live preview and the commit, which is the point: the page renders the+ * plan while the finger is down and the drop writes the same plan, so nothing jumps at the end.+ */+data class DropPlan(val target: CellRect, val displaced: Map<Long, CellRect> = emptyMap())++/**+ * Works out what a drop would do to a page, without touching the page.+ *+ * Separate from [GridPlacer] because the question is different. `GridPlacer` answers "where is+ * there a hole", which is what an install or a regrid needs. This answers "what if the user+ * insists on *this* cell" — the dragged item takes the cell under the finger and its neighbours+ * slide out of the way, which is what makes a launcher grid feel like it is being rearranged+ * rather than being told where there is room. Launcher3 calls the same idea a reorder.+ *+ * Pure, and therefore the part of dragging that can be tested without a device.+ */+object GridPreview {++    /**+ * The plan for dropping [draggedId] with span and position [wanted], or null when the page+     * cannot take it at all.+     *+     * Four outcomes, in the order they are tried:+     *+     *  1. [wanted] is free — nothing else moves.+     *  2. [direction] is known and the occupants can be pushed that way — [GridReorder.pushAlong],+     *     which is what makes a reorder read as the row shuffling along under the finger.+     *  3. They cannot, but every occupant has *somewhere* to go — they are pushed there. This is+     *     Launcher3's own fallback, and it is also the whole answer when the direction is unknown,+     *     which is the case for a drop that never moved.+     *  4. An occupant has nowhere to go — the push is abandoned *whole* rather than in part, and+     *     the item falls back to the nearest hole. Half a push would leave the page rearranged+     *     for no reason, or worse, leave an item with no cell at all.+     */+    fun plan(+        spec: GridSpec,+        placed: Map<Long, CellRect>,+        draggedId: Long?,+        wanted: CellRect,+        direction: PushDirection? = null,+    ): DropPlan? {+        val others = placed.filterKeys { it != draggedId }++        val settled = CellOccupancy.of(spec, others.values)+        if (settled.isFree(wanted)) return DropPlan(wanted)++        if (direction != null) {+            GridReorder.pushAlong(spec, others, wanted, direction)?.let {+                return DropPlan(wanted, it)+            }+        }++        pushAside(spec, others, wanted)?.let { return DropPlan(wanted, it) }++        return GridPlacer.findNearestVacant(settled, wanted)?.let { DropPlan(it) }+    }++    /**+     * Where each occupant of [wanted] goes, or null if any of them has nowhere to go.+     *+     * Occupants are moved in reading order, and each one's new cell is marked before the next is+     * placed, so two items pushed out of the same widget-sized hole cannot be sent to the same+     * cell. That ordering is also what makes the result stable frame to frame while the finger+     * hovers, which a preview has to be.+     */+    private fun pushAside(+        spec: GridSpec,+        others: Map<Long, CellRect>,+        wanted: CellRect,+    ): Map<Long, CellRect>? {+        val occupants = others.entries+            .filter { it.value.overlaps(wanted) }+            .sortedWith(compareBy({ it.value.cellY }, { it.value.cellX }))++        val occupancy = CellOccupancy(spec)+        others.forEach { (id, rect) -> if (occupants.none { it.key == id }) occupancy.mark(rect) }+        // The dragged item is taking this, so nothing may be pushed into it.+        occupancy.mark(wanted)++        val moves = mutableMapOf<Long, CellRect>()+        occupants.forEach { (id, rect) ->+            val to = GridPlacer.findNearestVacant(occupancy, rect) ?: return null+            occupancy.mark(to)+            moves[id] = to+        }+        return moves+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/GridReorder.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/GridReorder.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/GridReorder.ktnew file mode 100644index 0000000000..3ef4385681--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/GridReorder.kt@@ -0,0 +1,95 @@+package com.vayunmathur.launcher.domain++import kotlin.math.abs++/** One of the four ways a drag can push its neighbours. */+enum class PushDirection { Left, Up, Right, Down }++/**+ * Pushing a page's items *along* a drag rather than into the nearest hole.+ *+ * The difference is the whole feel of a reorder. [GridPlacer.findNearestVacant] answers "where is+ * there room", which is right for an install but wrong under a finger: dragging an icon leftwards+ * across a row makes each icon it passes jump to whatever gap happens to be closest, which reads+ * as the page scattering. Launcher3 instead shoves the occupant one cell further in the direction+ * the finger is already travelling, and shoves whatever *that* lands on, and so on — so a row+ * shuffles along like beads on a wire.+ *+ * All-or-nothing on purpose. A cascade that runs out of grid halfway would leave the page+ * rearranged for a move that then does not happen, or worse, two items in one cell. When it cannot+ * be done, [pushAlong] says so and the caller falls back.+ */+object GridReorder {++    /**+     * The direction [to] lies in from [from], or null when the two are the same cell.+     *+     * Quantised to the dominant axis, ties going horizontal, because a cascade needs one direction+     * rather than a vector: pushing diagonally would mean moving each occupant twice. The caller is+     * expected to keep the last non-null answer while the finger holds still, which is what stops+     * the cascade flip-flopping between two directions frame to frame.+     */+    fun directionOf(from: CellRect, to: CellRect): PushDirection? {+        val dx = to.cellX - from.cellX+        val dy = to.cellY - from.cellY+        if (dx == 0 && dy == 0) return null+        return if (abs(dx) >= abs(dy)) {+            if (dx > 0) PushDirection.Right else PushDirection.Left+        } else {+            if (dy > 0) PushDirection.Down else PushDirection.Up+        }+    }++    /**+     * Where each item has to go for [wanted] to be free, pushing along [direction], or null when+     * some item in the chain would end up off the grid.+     *+     * Breadth-first over the chain rather than recursive descent, so the cascade is bounded by the+     * number of items on the page: each one may move at most once, and a second push of the same+     * item aborts the whole plan. Without that, two items shoved into each other's paths would+     * loop.+     */+    fun pushAlong(+        spec: GridSpec,+        others: Map<Long, CellRect>,+        wanted: CellRect,+        direction: PushDirection,+    ): Map<Long, CellRect>? {+        if (!fits(spec, wanted)) return null++        val layout = others.toMutableMap()+        val moved = LinkedHashMap<Long, CellRect>()+        // The item now sitting in each region, so a region does not count as blocking itself.+        val pending = ArrayDeque<Pair<Long?, CellRect>>()+        pending += null to wanted++        while (pending.isNotEmpty()) {+            val (owner, region) = pending.removeFirst()+            val blocking = layout+                .filter { it.key != owner && it.value.overlaps(region) }+                .map { it.key to it.value }+            for ((id, rect) in blocking) {+                if (id in moved) return null+                val to = shiftedClear(rect, region, direction)+                if (!fits(spec, to)) return null+                layout[id] = to+                moved[id] = to+                pending += id to to+            }+        }+        return moved+    }++    /** [rect] moved the fewest whole cells along [direction] that takes it clear of [region]. */+    private fun shiftedClear(rect: CellRect, region: CellRect, direction: PushDirection): CellRect =+        when (direction) {+            PushDirection.Right -> rect.movedTo(region.right, rect.cellY)+            PushDirection.Left -> rect.movedTo(region.cellX - rect.spanX, rect.cellY)+            PushDirection.Down -> rect.movedTo(rect.cellX, region.bottom)+            PushDirection.Up -> rect.movedTo(rect.cellX, region.cellY - rect.spanY)+        }++    private fun fits(spec: GridSpec, rect: CellRect): Boolean =+        rect.cellX >= 0 && rect.cellY >= 0 &&+            rect.right <= spec.columns && rect.bottom <= spec.rows+}
launcher/src/main/java/com/vayunmathur/launcher/domain/HotseatArrange.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/HotseatArrange.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/HotseatArrange.ktnew file mode 100644index 0000000000..fb84043d50--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/HotseatArrange.kt@@ -0,0 +1,46 @@+package com.vayunmathur.launcher.domain++/**+ * The new hotseat order after an insert, and whoever it pushed out.+ *+ * [ranks] is every id that stays, with the rank it stays at. [evicted] is the id that no longer+ * fits, or null when the row had room.+ */+data class HotseatPlan(val ranks: Map<Long, Int>, val evicted: Long? = null)++/**+ * Arranging the one row that is on every page.+ *+ * A rank list rather than a cell grid: the hotseat has fixed slots, so an insert shifts its+ * neighbours along instead of looking for a hole.+ *+ * The eviction is the part that was missing. Renumbering alone leaves more items than there are+ * slots, and the row draws exactly `hotseatSlots` of them — so the overflow was still in the+ * database, still counted as being in the hotseat, and simply never rendered anywhere. An item the+ * user can neither see nor get back is worse than one they watched being pushed out.+ */+object HotseatArrange {++    /**+     * Puts [id] at [toRank], returning where everything ends up.+     *+     * [current] is the row in rank order, and may or may not already contain [id] — reordering+     * within the row and moving in from the workspace are the same operation with the same answer,+     * so both go through here.+     *+     * The tail is what gives way, being the item furthest from the slot the user aimed at.+     */+    fun arrange(current: List<Long>, id: Long, toRank: Int, slots: Int): HotseatPlan {+        val limit = slots.coerceAtLeast(1)+        val without = current.filter { it != id }+        val index = toRank.coerceIn(0, minOf(without.size, limit - 1))+        val inserted = without.toMutableList().apply { add(index, id) }++        val evicted = inserted.lastOrNull()?.takeIf { inserted.size > limit }+        val kept = if (evicted == null) inserted else inserted.dropLast(1)+        return HotseatPlan(+            ranks = kept.withIndex().associate { (rank, item) -> item to rank },+            evicted = evicted,+        )+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/LauncherItemType.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/LauncherItemType.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/LauncherItemType.ktnew file mode 100644index 0000000000..93f0b425bd--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/LauncherItemType.kt@@ -0,0 +1,32 @@+package com.vayunmathur.launcher.domain++/**+ * The kinds of thing that can sit on the home screen.+ *+ * One flat table holds all of them (see `LauncherItemEntity`), so this is the+ * discriminator. Kept in `domain/` because the placement and folder rules branch on it+ * and must not depend on the persistence layer.+ */+enum class LauncherItemType {+    /** A launchable activity, addressed by package + class + user. */+    APPLICATION,++    /** A container for other items. Its own children reference it by row id. */+    FOLDER,++    /** A hosted `AppWidgetHostView`, addressed by an allocated `appWidgetId`. */+    APPWIDGET,++    /** A `ShortcutInfo` pinned from an app's static, dynamic or pinned shortcuts. */+    DEEP_SHORTCUT,+}++/**+ * Identity of an app for a given user.+ *+ * Two profiles can have the same package installed, and they are different items with+ * different icons, so the profile is part of the key everywhere. The value is the+ * `UserManager` serial number, which is the only handle for a user that survives a+ * reboot.+ */+data class PackageKey(val packageName: String, val profileSerial: Long)
launcher/src/main/java/com/vayunmathur/launcher/domain/LauncherTuning.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/LauncherTuning.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/LauncherTuning.ktnew file mode 100644index 0000000000..ccd667ea30--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/LauncherTuning.kt@@ -0,0 +1,64 @@+package com.vayunmathur.launcher.domain++/**+ * Launcher3's unitless constants.+ *+ * The ones that are neither a duration nor a dp, and therefore have nowhere in+ * [com.vayunmathur.library.ui.Motion] or [com.vayunmathur.library.ui.Spacing] to live. They are+ * here rather than as literals at their call sites because each is a *tuning* decision copied+ * from a specific place in AOSP, and a bare `0.55f` three files away from any explanation is the+ * thing that gets "simplified" to `0.5f` by the next reader.+ *+ * A `domain` object with no logic in it, which is unusual — but these are read from `ui` and from+ * pure code alike, and a second copy in either place is what this prevents.+ */+object LauncherTuning {++    /**+     * How much of an adaptive icon's bitmap is actually visible once it is masked.+     *+     * `IconNormalizer.ICON_VISIBLE_AREA_FACTOR`. Used to size the folder-merge radius against the+     * icon a drag is being folded into rather than against its whole bitmap - see [FolderMerge].+     */+    const val IconVisibleAreaFactor = 0.92f++    /**+     * How much of a page's width counts as its edge, where a dwelling drag flips to the next page.+     * Launcher3 uses a fixed dp region; a fraction travels better across screen widths.+     */+    const val PageEdgeZone = 0.08f++    /**+     * How much bigger a dragged item is than the same item in its cell, in dp added to its edge.+     *+     * Launcher3's `pre_drag_view_scale`, and it really is a dp rather than a factor: the drag view+     * grows by a fixed amount so a large icon is not magnified more than a small one.+     */+    const val DragLiftDp = 6f++    /**+     * What is left of an item in its cell while the drag layer draws a copy of it: nothing.+     *+     * Launcher3 calls `setVisibility(INVISIBLE)` on the dragged child. A dimmed ghost instead reads+     * as two copies of one icon, which is exactly what the drag view already is.+     */+    const val DraggedAlpha = 0f++    /** How far the workspace shrinks behind a fully open drawer, as Launcher3's does. */+    const val WorkspaceScaleBehindDrawer = 0.92f++    /**+     * How far an item provisionally displaced by a drag pulses back towards where it came from, as a+     * fraction of the icon size. `CellLayout.REORDER_PREVIEW_MAGNITUDE`.+     */+    const val ReorderPreviewMagnitude = 0.12f++    /** One period of that pulse. `ReorderPreviewAnimation.PREVIEW_DURATION`. */+    const val ReorderPreviewMillis = 300++    /**+     * How much narrower a pulsing item gets, in pixels off its width.+     * `ReorderPreviewAnimation.CHILD_DIVIDEND`, which AOSP divides by the child's width.+     */+    const val ReorderPreviewShrinkPx = 4f+}
launcher/src/main/java/com/vayunmathur/launcher/domain/PageCount.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/PageCount.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/PageCount.ktnew file mode 100644index 0000000000..9972079b30--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/PageCount.kt@@ -0,0 +1,19 @@+package com.vayunmathur.launcher.domain++/**+ * How many pages the workspace has.+ *+ * One line, and it exists only to pin the behaviour: the trailing empty page is there **for the+ * duration of a drag and no longer**. Launcher3 adds it when a drag starts and takes it away when+ * the drag ends, because its purpose is to be somewhere to drag *to*. Kept permanently, it is an+ * empty page the user can page onto for no reason and cannot get rid of.+ */+object PageCount {++    /** [maxOccupied] is the highest page index holding anything, or -1 for an empty workspace. */+    fun pageCount(maxOccupied: Int, isDragging: Boolean): Int {+        val occupied = maxOccupied + 1+        val spare = if (isDragging) 1 else 0+        return (occupied + spare).coerceAtLeast(1)+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/ReconcileUseCase.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/ReconcileUseCase.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/ReconcileUseCase.ktnew file mode 100644index 0000000000..88b14f1caf--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/ReconcileUseCase.kt@@ -0,0 +1,73 @@+package com.vayunmathur.launcher.domain++/**+ * Decides what to do with saved items whose target may no longer be there.+ *+ * Run on cold start and on every package/profile event. The distinction that matters is+ * **uninstalled** versus **unavailable**: a work profile turned off, or an app on+ * unmounted storage, reports as gone but comes back. Deleting on unavailable is the+ * classic launcher bug where pausing a work profile permanently wipes half the home+ * screen, so those items are hidden and restored instead.+ *+ * Pure, and returns actions rather than performing them, so the whole matrix of+ * installed/unavailable/missing against already-hidden is unit-testable.+ */+object ReconcileUseCase {++    /** An item reduced to what reconciliation needs to judge it. */+    data class Item(+        val id: Long,+        val type: LauncherItemType,+        val packageName: String?,+        val profileSerial: Long,+        val appWidgetId: Int?,+        val hidden: Boolean,+    ) {+        val key: PackageKey? get() = packageName?.let { PackageKey(it, profileSerial) }+    }++    sealed interface Action {+        /** The target is gone for good. Drop the row. */+        data class Delete(val id: Long) : Action++        /** The target is temporarily absent, or has come back. Keep the row, change visibility. */+        data class SetHidden(val id: Long, val hidden: Boolean) : Action+    }++    /**+     * @param installed packages present and usable right now.+     * @param unavailable packages that exist but cannot be launched at the moment — a+     *   paused or quiet work profile, an app on ejected storage. Callers must not fold+     *   these into [installed] or the icon disappears; nor omit them, or it is deleted.+     * @param boundWidgetIds ids `AppWidgetHost.getAppWidgetIds()` still recognises. An id+     *   the host has forgotten can never be rendered, so its row is dead weight.+     */+    fun reconcile(+        items: List<Item>,+        installed: Set<PackageKey>,+        unavailable: Set<PackageKey>,+        boundWidgetIds: Set<Int>,+    ): List<Action> = items.mapNotNull { item ->+        when (item.type) {+            // A folder's existence depends on its children, which FolderRules owns.+            LauncherItemType.FOLDER -> null++            LauncherItemType.APPWIDGET ->+                if (item.appWidgetId == null || item.appWidgetId !in boundWidgetIds) {+                    Action.Delete(item.id)+                } else {+                    null+                }++            LauncherItemType.APPLICATION, LauncherItemType.DEEP_SHORTCUT -> {+                val key = item.key+                when {+                    key == null -> Action.Delete(item.id)+                    key in unavailable -> Action.SetHidden(item.id, true).takeUnless { item.hidden }+                    key in installed -> Action.SetHidden(item.id, false).takeIf { item.hidden }+                    else -> Action.Delete(item.id)+                }+            }+        }+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/ReorderDwell.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/ReorderDwell.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/ReorderDwell.ktnew file mode 100644index 0000000000..908c338c02--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/ReorderDwell.kt@@ -0,0 +1,62 @@+package com.vayunmathur.launcher.domain++/**+ * The 650ms a drag has to hold still before the rearrangement it implies is committed.+ *+ * Why a dwell exists at all: a drag from one corner of the page to another passes over every cell+ * on the way, and reordering on each of them would rearrange the whole page in transit and then+ * rearrange it back. Launcher3 gates the reorder on `CellLayout.REORDER_TIMEOUT` for exactly that+ * reason.+ *+ * Why it lives in its own object rather than inside [GridPreview]: `plan` is the single currency+ * for both the live preview and the commit, and it stays pure and clockless so it can go on being+ * that. The clock belongs here, fed from the pointer stream.+ *+ * The consequence, and the reason this is a correctness fix rather than tidiness: **with a dwell+ * the release point is no longer necessarily the dwelt point.** A drop must therefore commit+ * [committed] — what the user actually watched happen — and not a plan recomputed at whatever cell+ * the finger happened to be over when it lifted.+ */+class ReorderDwell(private val timeoutMillis: Long) {++    /**+     * The rearrangement the page is showing, and the one a drop must write. Null until something+     * has been dwelt on, and kept afterwards even as the finger moves on — which is what makes a+     * release somewhere else still commit what was previewed.+     */+    var committed: DropPlan? = null+        private set++    private var candidate: DropPlan? = null+    private var since = 0L++    /**+     * Feeds one frame of the pointer stream, and returns whether this call is the one that+     * committed.+     *+     * A [candidate] that displaces nothing commits on arrival rather than waiting: there is no+     * rearrangement to be careful about, and making a move into an empty cell wait 650ms would+     * make the whole grid feel unresponsive.+     */+    fun update(nowMillis: Long, candidate: DropPlan?): Boolean {+        if (candidate == null) {+            this.candidate = null+            return false+        }+        if (candidate != this.candidate) {+            this.candidate = candidate+            since = nowMillis+        }+        if (candidate == committed) return false+        if (candidate.displaced.isNotEmpty() && nowMillis - since < timeoutMillis) return false+        committed = candidate+        return true+    }++    /** Forgets everything, for the start of the next drag. */+    fun reset() {+        committed = null+        candidate = null+        since = 0L+    }+}
launcher/src/main/java/com/vayunmathur/launcher/domain/WidgetResize.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/WidgetResize.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/WidgetResize.ktnew file mode 100644index 0000000000..9e658e9aad--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/WidgetResize.kt@@ -0,0 +1,87 @@+package com.vayunmathur.launcher.domain++/**+ * Turning a drag on one edge of a widget into a new cell rectangle.+ *+ * Pure, because the interesting part is not the gesture but the arithmetic: dragging the+ * **left** edge left has to grow the span *and* move the origin, so the right edge stays put.+ * Getting that backwards makes a widget appear to slide rather than resize, and it is much+ * easier to pin down in a test than on a device.+ */+object WidgetResize {++    enum class Edge { Left, Top, Right, Bottom }++    /** Which way a resize on [edge] shoves whatever is in the way. */+    fun pushDirection(edge: Edge): PushDirection = when (edge) {+        Edge.Left -> PushDirection.Left+        Edge.Top -> PushDirection.Up+        Edge.Right -> PushDirection.Right+        Edge.Bottom -> PushDirection.Down+    }++    /**+     * [rect] adjusted by [steps] whole cells on [edge], or null when the result would be+     * degenerate (a zero-width span, or an origin off the top or left of the grid).+     *+     * Positive [steps] means right or down for every edge, so a caller can hand over the raw+     * sign of the drag without knowing which edge it is on.+     *+     * Bounds against the right and bottom of the grid are **not** checked here; that is the+     * occupancy check's job, and it has to be done against the page anyway.+     */+    fun resized(rect: CellRect, edge: Edge, steps: Int): CellRect? {+        if (steps == 0) return null+        val next = when (edge) {+            Edge.Right -> rect.copy(spanX = rect.spanX + steps)+            Edge.Bottom -> rect.copy(spanY = rect.spanY + steps)+            // The origin moves with the edge, so the opposite edge does not shift.+            Edge.Left -> rect.copy(cellX = rect.cellX + steps, spanX = rect.spanX - steps)+            Edge.Top -> rect.copy(cellY = rect.cellY + steps, spanY = rect.spanY - steps)+        }+        if (next.spanX < 1 || next.spanY < 1) return null+        if (next.cellX < 0 || next.cellY < 0) return null+        return next+    }++    /**+     * Whether [candidate] can replace [current] on a page holding [others].+     *+     * [others] must exclude the widget being resized: measuring it against its own cells would+     * refuse every enlargement, since a growing rectangle always overlaps where it already is.+     */+    fun canPlace(+        candidate: CellRect,+        current: CellRect,+        others: List<CellRect>,+        spec: GridSpec,+    ): Boolean {+        if (candidate == current) return false+        val occupancy = CellOccupancy.of(spec, others)+        return occupancy.isFree(candidate)+    }++    /**+     * The neighbours a resize to [candidate] has to shove aside, or null when it cannot be done.+     *+     * This replaces refusing the step. Launcher3 does not stop a widget growing into its+     * neighbours; it pushes them, on the same cascade a drag uses, and only gives up at a wall. A+     * refusal instead reads as the handle being stuck, with nothing on screen saying why.+     *+     * An empty map means the space was already clear — which is also the answer for every shrink.+     */+    fun resizeWithPush(+        spec: GridSpec,+        candidate: CellRect,+        others: Map<Long, CellRect>,+        direction: PushDirection,+    ): Map<Long, CellRect>? {+        val occupancy = CellOccupancy.of(spec, others.values)+        // Off the grid is refused here rather than by the cascade: with nothing in the way, an+        // out-of-bounds candidate would otherwise come back as "nothing to push".+        if (candidate.cellX < 0 || candidate.cellY < 0) return null+        if (candidate.right > spec.columns || candidate.bottom > spec.rows) return null+        if (occupancy.isFree(candidate)) return emptyMap()+        return GridReorder.pushAlong(spec, others, candidate, direction)+    }+}
launcher/src/main/java/com/vayunmathur/launcher/platform/ActivityBridge.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/platform/ActivityBridge.kt b/launcher/src/main/java/com/vayunmathur/launcher/platform/ActivityBridge.ktnew file mode 100644index 0000000000..f19cf48b01--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/platform/ActivityBridge.kt@@ -0,0 +1,74 @@+package com.vayunmathur.launcher.platform++import android.content.ComponentName+import android.os.Bundle+import androidx.compose.runtime.staticCompositionLocalOf++/**+ * The Activity-only capabilities the Compose tree needs.+ *+ * Binding a widget, running its configure activity and claiming the HOME role all need a+ * real Activity to start something for a result. There is no DI framework here, and+ * threading four callbacks down through the page tree would put Activity plumbing in every+ * signature — so `MainActivity` implements this and provides it through+ * [LocalActivityBridge].+ *+ * Deliberately narrow: only things that genuinely cannot be done from a `Context`.+ * Launching apps and reading shortcuts go through [LauncherAppsMonitor] instead.+ */+interface ActivityBridge {++    /**+     * Asks the user to allow binding [appWidgetId] to [provider].+     *+     * Only called after `bindAppWidgetIdIfAllowed` has already refused, which it does for+     * every third-party launcher — `BIND_APPWIDGET` is signature/privileged-only, so this+     * consent dialog is the only way in.+     */+    fun requestBindWidget(+        appWidgetId: Int,+        provider: ComponentName,+        profileSerial: Long,+        onResult: (Boolean) -> Unit,+    )++    /** Runs the provider's configure activity, if it declared one. */+    fun startWidgetConfigure(appWidgetId: Int, onResult: (Boolean) -> Unit)++    /** Opens the system wallpaper chooser. */+    fun pickWallpaper()++    /** Prompts to make this app the default home app. */+    fun requestHomeRole()++    /** Whether we currently hold the HOME role. Gates the features that require it. */+    fun isDefaultHome(): Boolean++    /** Opens the system uninstall confirmation for [packageName]. */+    fun requestUninstall(packageName: String)++    /**+     * Blurs whatever is behind this window, which on a home screen is the wallpaper.+     *+     * `Window.setBackgroundBlurRadius` is a window-level call, so nothing inside the Compose tree+     * can make it — and it is the only way to blur the wallpaper from here, since the drawer shares+     * this window rather than having one of its own. Degrades to nothing when the device has+     * cross-window blur disabled, which is a battery-saver setting as well as a hardware one.+     */+    fun setWallpaperBlurRadius(radiusPx: Int)++    /**+     * The launch animation options for an app opening out of the icon at these bounds, or null when+     * there is nothing to animate from.+     *+     * `ActivityOptions.makeClipRevealAnimation` needs a `View` to reveal *from*, which is the one+     * thing the Compose tree cannot hand over — a composable is not a View, and the only real one is+     * this Activity's decor view. Without this, every launch used null options and the app appeared+     * with the system's default cross-fade rather than growing out of the icon that was tapped.+     */+    fun launchAnimationOptions(left: Int, top: Int, right: Int, bottom: Int): Bundle?+}++val LocalActivityBridge = staticCompositionLocalOf<ActivityBridge> {+    error("No ActivityBridge provided - MainActivity must provide LocalActivityBridge")+}
launcher/src/main/java/com/vayunmathur/launcher/platform/IconCache.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/platform/IconCache.kt b/launcher/src/main/java/com/vayunmathur/launcher/platform/IconCache.ktnew file mode 100644index 0000000000..f59c996861--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/platform/IconCache.kt@@ -0,0 +1,66 @@+package com.vayunmathur.launcher.platform++import android.content.ComponentName+import android.content.pm.LauncherApps+import android.graphics.drawable.Drawable+import android.util.LruCache+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.core.graphics.drawable.toBitmap++/** An activity for a given profile. Two profiles' copies of an app are different icons. */+data class ComponentKey(val componentName: ComponentName, val profileSerial: Long)++/**+ * App icons, rasterised once and kept.+ *+ * `Icon()` and `painterResource` are unavailable here and would not help anyway: an icon+ * from [LauncherApps] is an arbitrary [Drawable] — adaptive, sometimes animated,+ * sometimes badged for a work profile — and neither `ImageVector` nor `Painter` can+ * represent one. So icons are drawn with `Image(bitmap = ...)`, which means rasterising,+ * which means caching: a page of 20 icons re-rasterised on every recomposition is+ * visible jank, and a drag recomposes constantly.+ *+ * (This is not a hole in the "all icons come from `Icons.kt`" rule. That rule governs+ * semantic UI glyphs — the settings cog, the back arrow — which still all come from+ * there. These are third-party app artwork.)+ *+ * Bounded by count rather than bytes because every entry is rasterised to the same+ * [iconSizePx], so entries are all the same size.+ */+class IconCache(private val iconSizePx: Int) {++    private val bitmaps = object : LruCache<ComponentKey, ImageBitmap>(MAX_ENTRIES) {}++    /**+     * The cached bitmap, rasterising through [load] on a miss.+     *+     * [load] is called on the caller's thread, so callers must not invoke this from+     * composition directly — go through `LauncherAppIcon`, which does it in a+     * `produceState`.+     */+    fun get(key: ComponentKey, load: () -> Drawable?): ImageBitmap? {+        bitmaps.get(key)?.let { return it }+        val drawable = runCatching(load).getOrNull() ?: return null+        // A zero-intrinsic-size drawable (some adaptive icons report -1) would produce a+        // 0x0 bitmap and throw, so the target size is always explicit.+        val bitmap = drawable.toBitmap(iconSizePx, iconSizePx).asImageBitmap()+        bitmaps.put(key, bitmap)+        return bitmap+    }++    /** Drops everything. Called on a locale change, which relabels and re-themes icons. */+    fun clear() = bitmaps.evictAll()++    /** Drops one app's entries, so a package update shows its new icon. */+    fun evictPackage(packageName: String, profileSerial: Long) {+        bitmaps.snapshot().keys+            .filter { it.componentName.packageName == packageName && it.profileSerial == profileSerial }+            .forEach { bitmaps.remove(it) }+    }++    private companion object {+        /** Comfortably more than two pages plus a full drawer viewport. */+        const val MAX_ENTRIES = 512+    }+}
launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherAppsMonitor.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherAppsMonitor.kt b/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherAppsMonitor.ktnew file mode 100644index 0000000000..293c208fdc--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherAppsMonitor.kt@@ -0,0 +1,265 @@+package com.vayunmathur.launcher.platform++import android.content.ComponentName+import android.content.Context+import android.content.pm.LauncherApps+import android.content.pm.ShortcutInfo+import android.graphics.Rect+import android.graphics.drawable.Drawable+import android.os.Bundle+import android.os.Process+import android.os.UserHandle+import android.os.UserManager+import com.vayunmathur.launcher.domain.PackageKey+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/** One launchable activity, as the drawer and the home screen see it. */+data class AppEntry(+    val componentName: ComponentName,+    val label: String,+    val user: UserHandle,+    val profileSerial: Long,+    /** True for anything outside the primary user, which cannot be uninstalled from here. */+    val isWorkProfile: Boolean,+) {+    val key: ComponentKey get() = ComponentKey(componentName, profileSerial)+    val packageKey: PackageKey get() = PackageKey(componentName.packageName, profileSerial)+}++/**+ * The one registration with [LauncherApps], feeding both the app drawer and+ * reconciliation.+ *+ * [LauncherApps] rather than a `PackageManager` query plus a broadcast receiver: it is+ * the only API that reports work-profile events and `onShortcutsChanged`, and its+ * `getActivityList` already spans every profile. Two separate sources would also mean two+ * lists that can disagree about what is installed, which is exactly the disagreement that+ * makes a launcher lose icons.+ *+ * Availability is tracked separately from installation. A paused work profile or an app on+ * unmounted storage reports as absent from `getActivityList` but is not uninstalled, and+ * only the callback can tell the two apart — so [unavailable] accumulates from+ * `onPackagesUnavailable` and drains on `onPackagesAvailable`, and+ * `ReconcileUseCase` uses it to hide rather than delete.+ */+class LauncherAppsMonitor(context: Context, private val scope: CoroutineScope) {++    private val appContext = context.applicationContext+    private val launcherApps = appContext.getSystemService(LauncherApps::class.java)+    private val userManager = appContext.getSystemService(UserManager::class.java)++    private val _apps = MutableStateFlow<List<AppEntry>>(emptyList())+    val apps: StateFlow<List<AppEntry>> = _apps++    private val _unavailable = MutableStateFlow<Set<PackageKey>>(emptySet())+    val unavailable: StateFlow<Set<PackageKey>> = _unavailable++    /**+     * Notified whenever the app list changes.+     *+     * The argument names the package whose *artwork* is now stale — an update, rather than an+     * install or removal. Null means "the list changed but no icon needs re-rasterising", which+     * spares the icon cache from being thrown away on every package event.+     */+    private var onChanged: ((PackageKey?) -> Unit)? = null++    private val callback = object : LauncherApps.Callback() {+        override fun onPackageRemoved(packageName: String, user: UserHandle) {+            markAvailable(packageName, user)+            refresh()+        }++        override fun onPackageAdded(packageName: String, user: UserHandle) {+            markAvailable(packageName, user)+            refresh()+        }++        override fun onPackageChanged(packageName: String, user: UserHandle) =+            refresh(PackageKey(packageName, serialFor(user)))++        override fun onPackagesAvailable(+            packageNames: Array<out String>,+            user: UserHandle,+            replacing: Boolean,+        ) {+            packageNames.forEach { markAvailable(it, user) }+            refresh()+        }++        override fun onPackagesUnavailable(+            packageNames: Array<out String>,+            user: UserHandle,+            replacing: Boolean,+        ) {+            // `replacing` means an update is in flight and the package is about to be back,+            // so it is not really unavailable and must not be recorded as such.+            if (!replacing) {+                val serial = serialFor(user)+                _unavailable.value = _unavailable.value + packageNames.map { PackageKey(it, serial) }+            }+            refresh()+        }++        override fun onPackagesSuspended(packageNames: Array<out String>, user: UserHandle) = refresh()++        override fun onPackagesUnsuspended(packageNames: Array<out String>, user: UserHandle) = refresh()++        override fun onShortcutsChanged(+            packageName: String,+            shortcuts: MutableList<ShortcutInfo>,+            user: UserHandle,+        ) = refresh()+    }++    /**+     * Registers the callback and starts loading the initial list. Tied to the Activity lifecycle.+     *+     * The load is asynchronous, so the first frame does not wait for it. Until it arrives [apps] is+     * empty, which every consumer already handles: the drawer shows its loading state and+     * `ReconcileUseCase` refuses to run against an empty list precisely so that it cannot mistake+     * "not loaded yet" for "everything was uninstalled".+     */+    fun start(onChanged: (PackageKey?) -> Unit) {+        this.onChanged = onChanged+        launcherApps.registerCallback(callback)+        refresh()+    }++    fun stop() {+        launcherApps.unregisterCallback(callback)+        onChanged = null+    }++    /**+     * Reloads the app list off the main thread, then publishes it.+     *+     * **The load must not be synchronous.** `getActivityList` is a binder call returning every+     * launchable activity on the device, and reading `info.label` for each one opens that app's+     * resources - a few hundred of those is tens of milliseconds at best. This runs from `onStart`,+     * so on the main thread it delayed the first frame after every HOME press, and it runs again for+     * *every* package event, so a Play Store update session stuttered the whole launcher.+     *+     * Launcher3 does the same work on its `LauncherModel` worker thread for the same reason.+     */+    fun refresh(stale: PackageKey? = null) {+        scope.launch {+            val loaded = withContext(Dispatchers.IO) { loadApps() }+            _apps.value = loaded+            // Back on the caller's dispatcher - consumers update UI state from here.+            onChanged?.invoke(stale)+        }+    }++    private fun loadApps(): List<AppEntry> {+        val profiles = launcherApps.profiles.ifEmpty { listOf(Process.myUserHandle()) }+        val primary = Process.myUserHandle()+        return profiles.flatMap { user ->+            val serial = serialFor(user)+            // Null package means "every package for this user".+            runCatching { launcherApps.getActivityList(null, user) }.getOrDefault(emptyList())+                .map { info ->+                    AppEntry(+                        componentName = info.componentName,+                        label = info.label?.toString().orEmpty(),+                        user = user,+                        profileSerial = serial,+                        isWorkProfile = user != primary,+                    )+                }+        }.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.label })+    }++    /** Packages present and usable right now, for reconciliation. */+    fun installedKeys(): Set<PackageKey> = _apps.value.map { it.packageKey }.toSet()++    fun icon(entry: AppEntry, densityDpi: Int): Drawable? = runCatching {+        val info = launcherApps.resolveActivity(+            android.content.Intent().setComponent(entry.componentName),+            entry.user,+        )+        // Badged, so a work-profile copy is visibly distinct from the personal one.+        info?.getBadgedIcon(densityDpi)+    }.getOrNull()++    fun icon(componentName: ComponentName, profileSerial: Long, densityDpi: Int): Drawable? {+        val entry = _apps.value.firstOrNull {+            it.componentName == componentName && it.profileSerial == profileSerial+        } ?: return null+        return icon(entry, densityDpi)+    }++    fun entryFor(componentName: ComponentName, profileSerial: Long): AppEntry? =+        _apps.value.firstOrNull {+            it.componentName == componentName && it.profileSerial == profileSerial+        }++    fun userFor(profileSerial: Long): UserHandle =+        userManager.getUserForSerialNumber(profileSerial) ?: Process.myUserHandle()++    /**+     * Launches an activity, animating out of [sourceBounds] with [options].+     *+     * [options] comes from [ActivityBridge.launchAnimationOptions] and carries a clip reveal from the+     * icon's rect, which is as close to the system launcher's app-open transition as an+     * unprivileged app can get; the real shared-element handoff needs SystemUI-signed integration.+     * Null is accepted and means the system's default transition.+     */+    fun launch(entry: AppEntry, sourceBounds: Rect?, options: Bundle? = null): Boolean = runCatching {+        launcherApps.startMainActivity(entry.componentName, entry.user, sourceBounds, options)+        true+    }.getOrDefault(false)++    /**+     * The app's static, dynamic and pinned shortcuts.+     *+     * Empty rather than throwing when we are not the default home app: `getShortcuts` is+     * gated on holding that role, and a long-press menu with no shortcuts in it is a much+     * better outcome than a crash on the home screen.+     */+    @Suppress("DEPRECATION")+    fun shortcuts(packageName: String, user: UserHandle): List<ShortcutInfo> = runCatching {+        val query = LauncherApps.ShortcutQuery()+            .setPackage(packageName)+            .setQueryFlags(+                LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST or+                    LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC or+                    LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED,+            )+        launcherApps.getShortcuts(query, user).orEmpty()+    }.getOrDefault(emptyList())++    fun shortcutIcon(shortcut: ShortcutInfo, densityDpi: Int): Drawable? = runCatching {+        launcherApps.getShortcutBadgedIconDrawable(shortcut, densityDpi)+    }.getOrNull()++    fun pinShortcut(shortcut: ShortcutInfo): Boolean = runCatching {+        val pinned = shortcuts(shortcut.`package`, shortcut.userHandle)+            .filter { it.isPinned }+            .map { it.id }+        launcherApps.pinShortcuts(shortcut.`package`, pinned + shortcut.id, shortcut.userHandle)+        true+    }.getOrDefault(false)++    fun startShortcut(shortcut: ShortcutInfo, sourceBounds: Rect?, options: Bundle? = null): Boolean =+        runCatching {+            launcherApps.startShortcut(shortcut, sourceBounds, options)+            true+        }.getOrDefault(false)++    fun startAppDetails(entry: AppEntry, sourceBounds: Rect?): Boolean = runCatching {+        launcherApps.startAppDetailsActivity(entry.componentName, entry.user, sourceBounds, null)+        true+    }.getOrDefault(false)++    private fun markAvailable(packageName: String, user: UserHandle) {+        val key = PackageKey(packageName, serialFor(user))+        if (key in _unavailable.value) _unavailable.value = _unavailable.value - key+    }++    private fun serialFor(user: UserHandle): Long = userManager.getSerialNumberForUser(user)+}
launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherPrivilege.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherPrivilege.kt b/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherPrivilege.ktnew file mode 100644index 0000000000..36c3a2fedf--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherPrivilege.kt@@ -0,0 +1,88 @@+package com.vayunmathur.launcher.platform++import android.content.Context+import android.content.pm.PackageManager+import android.os.UserHandle+import android.os.UserManager++/**+ * What this build is actually allowed to do, asked at runtime.+ *+ * The system launcher does several things a third-party one cannot: uninstall without a+ * confirmation dialog, pause a work profile, pull the notification shade down from the workspace.+ * Each is worth having *if* the app happens to be built into a ROM, and each must be invisible+ * otherwise — a menu item that always fails is worse than no menu item.+ *+ * So every probe here follows the shape [com.vayunmathur.library.ui.SpecialAccess] uses, with two+ * rules that matter more than the individual answers:+ *+ *  - **`runCatching`-guarded, defaulting to false.** These call into APIs that a stock device may+ *    not expose at all, and a launcher that crashes on the way up leaves the user with no home+ *    screen. Failing to answer therefore means "no".+ *  - **Nothing here grants anything.** A privileged permission is granted by being on the system+ *    image, not by asking. There are no `request*()` counterparts because there is nothing to+ *    request: the answer is fixed at install time.+ *+ * The consequence to hold onto: on an ordinary device every one of these is false, and the app+ * behaves exactly as it does without this file.+ */+class LauncherPrivilege(context: Context, private val bridge: () -> ActivityBridge?) {++    private val appContext = context.applicationContext++    /** Whether we hold the HOME role, which gates shortcuts, widgets and the wallpaper. */+    fun hasHomeRole(): Boolean = runCatching { bridge()?.isDefaultHome() == true }.getOrDefault(false)++    /**+     * Whether an app can be removed without the system's confirmation dialog.+     *+     * `DELETE_PACKAGES` is privileged, so this is false on a stock device and the uninstall goes+     * through `ACTION_DELETE` — which is the right behaviour there anyway.+     */+    fun canUninstallSilently(): Boolean = holds("android.permission.DELETE_PACKAGES")++    /**+     * Whether the work profile can be paused and resumed from the drawer's Work tab.+     *+     * `UserManager.requestQuietModeEnabled` is public API but needs `MODIFY_QUIET_MODE`, which is+     * not.+     */+    fun canToggleQuietMode(): Boolean = holds("android.permission.MODIFY_QUIET_MODE")++    /**+     * Whether a downward swipe on the workspace can pull the notification shade down, as it does on+     * the system launcher.+     *+     * Needs `EXPAND_STATUS_BAR`, and the call itself is not public API — see+     * [expandNotificationShade], which is why this is the probe rather than the feature.+     */+    fun canExpandNotificationShade(): Boolean = holds("android.permission.EXPAND_STATUS_BAR")++    /**+     * Pulls the notification shade down, and reports whether it worked.+     *+     * `StatusBarManager.expandNotificationsPanel` has never been public API, so this is reflection —+     * which is exactly why it is guarded twice over: by [canExpandNotificationShade] before it is+     * offered at all, and by `runCatching` here in case a release has renamed or removed it.+     */+    fun expandNotificationShade(): Boolean = runCatching {+        val service = appContext.getSystemService("statusbar") ?: return false+        service.javaClass.getMethod("expandNotificationsPanel").invoke(service)+        true+    }.getOrDefault(false)++    /** Pauses or resumes [user]'s profile, and reports whether it worked. */+    fun setQuietMode(user: UserHandle, quiet: Boolean): Boolean = runCatching {+        val manager = appContext.getSystemService(UserManager::class.java) ?: return false+        manager.requestQuietModeEnabled(quiet, user)+    }.getOrDefault(false)++    /** Whether [user]'s profile is currently paused. */+    fun isQuietModeEnabled(user: UserHandle): Boolean = runCatching {+        appContext.getSystemService(UserManager::class.java)?.isQuietModeEnabled(user) == true+    }.getOrDefault(false)++    private fun holds(permission: String): Boolean = runCatching {+        appContext.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED+    }.getOrDefault(false)+}
launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherUiContract.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherUiContract.kt b/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherUiContract.ktnew file mode 100644index 0000000000..f8cfc79341--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherUiContract.kt@@ -0,0 +1,357 @@+package com.vayunmathur.launcher.platform++import androidx.compose.runtime.staticCompositionLocalOf+import androidx.compose.ui.graphics.ImageBitmap+import com.vayunmathur.launcher.domain.CellRect+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.GridSpec+import com.vayunmathur.launcher.domain.LauncherItemType++/**+ * The UI contract between [LauncherViewModel] and the pages in `ui`.+ *+ * Pages take a state value plus an actions interface rather than the ViewModel itself, so+ * they can be rendered by a `@Preview` — which is what the store listing images are+ * generated from (see `src/screenshotTest`). It lives beside the ViewModel rather than in+ * `ui` so the dependency runs one way.+ *+ * Every actions method has a no-op default body, so `HomeActions.Noop` and friends are the+ * whole implementation a preview needs.+ *+ * Note what these models deliberately do *not* contain: no `UserHandle`, no `ShortcutInfo`,+ * no `AppWidgetProviderInfo`. Those cannot be constructed outside a real device, and a+ * state model that cannot be written as a literal cannot be previewed. Profiles are carried+ * as the `UserManager` serial number and resolved back in the ViewModel.+ */++/** The default grid. Overridable in settings; a regrid follows any change. */+val DefaultGrid = GridSpec(columns = 5, rows = 5, hotseatSlots = 5)++/** One thing drawn in a cell, on the desktop, in the hotseat, or inside a folder. */+data class WorkspaceItem(+    val id: Long,+    val type: LauncherItemType,+    val label: String,+    val screen: Int = 0,+    val container: ContainerRef = ContainerRef.Desktop,+    val rect: CellRect = CellRect(0, 0),+    val rank: Int = 0,+    val key: ComponentKey? = null,+    val shortcutId: String? = null,+    val appWidgetId: Int? = null,+    /** Flattened provider `ComponentName`, so the hosted view can be recreated after a restart. */+    val appWidgetProvider: String? = null,+    /** Target exists but is not launchable right now. Drawn dimmed and not clickable. */+    val hidden: Boolean = false,+    /**+     * Whether the user could uninstall this, which is what decides the drop bar's second target.+     *+     * False for a system app and for anything in another profile: cross-profile uninstall is not+     * permitted, and offering a target that always fails is worse than not offering it.+     */+    val canUninstall: Boolean = false,+    /** A folder's children, ordered by rank. Empty for every other type. */+    val children: List<WorkspaceItem> = emptyList(),+)++/**+ * Supplies third-party artwork to the icon composables.+ *+ * A composition local rather than a state field: icons are loaded lazily per item and+ * cached, so putting them in the state would mean rebuilding the whole workspace state+ * every time one resolved. Previews get [Noop] and fall back to a placeholder, which is+ * also what the real loader does for an app whose icon fails to rasterise.+ */+interface IconLoader {+    fun appIcon(key: ComponentKey): ImageBitmap? = null+    fun shortcutIcon(packageName: String, shortcutId: String, profileSerial: Long): ImageBitmap? = null+    fun widgetPreview(provider: String, profileSerial: Long): ImageBitmap? = null++    companion object {+        val Noop: IconLoader = object : IconLoader {}+    }+}++val LocalIconLoader = staticCompositionLocalOf { IconLoader.Noop }++// ------------------------------------------------------------------+// Home+// ------------------------------------------------------------------++/**+ * The home screen.+ *+ * [loading] renders wallpaper and chrome with an empty grid. The database is+ * SQLCipher-encrypted and opening it sits on the cold-start critical path — the launcher is+ * the first thing drawn after a boot — so there is a real window before the layout is+ * known, and it must not be a blank screen.+ */+data class HomeUiState(+    val loading: Boolean = true,+    val grid: GridSpec = DefaultGrid,+    /** Desktop items by page index. Pages with nothing on them are absent. */+    val pages: Map<Int, List<WorkspaceItem>> = emptyMap(),+    val hotseat: List<WorkspaceItem> = emptyList(),+    val showLabels: Boolean = true,+    val iconScale: Float = 1f,+    /**+     * Whether a downward swipe on the workspace can pull the notification shade down, as it does on+     * the system launcher. False on every ordinary device — the swipe is then simply not claimed.+     */+    val canExpandShade: Boolean = false,+)++interface HomeActions {+    /** [boundsInWindow] is the icon's on-screen rect, used for the launch animation. */+    fun launch(item: WorkspaceItem, left: Int, top: Int, right: Int, bottom: Int) {}++    /**+     * Commits a finished drag.+     *+     * [displaced] carries the neighbours the drop pushed aside, as id to new cell, so they are+     * written in the same commit as the move. They are already drawn at those cells - the page+     * previews the whole rearrangement while the finger is down - and committing them separately+     * would let the workspace re-emit with the item moved but its neighbours not, which reads as a+     * jump at the very end of the gesture.+     */+    fun commitMove(+        id: Long,+        container: ContainerRef,+        screen: Int,+        rect: CellRect,+        rank: Int,+        displaced: Map<Long, CellRect> = emptyMap(),+    ) {}++    fun mergeIntoFolder(targetId: Long, draggedId: Long) {}++    /** The drop bar's second target, for an app the user installed. */+    fun uninstallItem(id: Long) {}++    /** The drop bar's second target, for one they cannot uninstall. */+    fun openItemInfo(id: Long) {}++    /**+     * Inserts an app that was dragged in from the drawer, at the cell it was dropped on.+     *+     * Separate from [commitMove] because there is no row to move yet — the drawer deals in apps,+     * not workspace items, and the row is created by the drop. [displaced] means the same thing it+     * does there.+     */+    fun addPendingToHome(+        key: ComponentKey,+        screen: Int,+        rect: CellRect,+        displaced: Map<Long, CellRect> = emptyMap(),+    ) {}++    /** The same insert, into a hotseat slot. */+    fun addPendingToHotseat(key: ComponentKey, slot: Int) {}++    /**+     * Pins a shortcut dragged out of an item's menu, at the cell it was dropped on.+     *+     * Separate from [ItemMenuActions.pinShortcutToHome], which puts it in the first free cell,+     * because a drag names the cell itself — and may have pushed neighbours aside to get it.+     */+    fun addPendingShortcutToHome(+        shortcut: ShortcutEntry,+        screen: Int,+        rect: CellRect,+        displaced: Map<Long, CellRect> = emptyMap(),+    ) {}++    fun remove(id: Long) {}++    /**+     * Blurs the wallpaper behind the whole window, which is how Launcher3 separates the drawer from+     * the workspace. Only the Activity can do it, so it goes through the actions rather than being+     * reached for from the composable.+     */+    fun setWallpaperBlurred(blurred: Boolean) {}++    /** Pulls the notification shade down. Only called when [HomeUiState.canExpandShade]. */+    fun expandNotificationShade() {}++    /**+     * Both the span and the origin, since dragging a left or top edge moves both — plus the+     * neighbours the resize shoved aside, so they are written in the same commit as the widget and+     * the page never renders half of a rearrangement it already previewed.+     */+    fun resizeItem(id: Long, rect: CellRect, displaced: Map<Long, CellRect> = emptyMap()) {}++    companion object {+        val Noop: HomeActions = object : HomeActions {}+    }+}++// ------------------------------------------------------------------+// App drawer+// ------------------------------------------------------------------++/** One row of the drawer. Free of `UserHandle` so it can be written as a literal. */+data class DrawerApp(+    val key: ComponentKey,+    val label: String,+    val isWorkProfile: Boolean = false,+)++data class DrawerUiState(+    val query: String = "",+    /** Already filtered by [query] and sorted case-insensitively by label. */+    val apps: List<DrawerApp> = emptyList(),+    /**+     * The handful of apps most likely to be wanted next, shown along the top of an unfiltered+     * drawer. From a local launch count, not from the system predictor, which is system-only.+     */+    val predictions: List<DrawerApp> = emptyList(),+    val loading: Boolean = false,+    val showLabels: Boolean = true,+    val iconScale: Float = 1f,+    /**+     * Whether the work profile is paused, or null when this build cannot pause it.+     *+     * Null on every ordinary device: pausing needs `MODIFY_QUIET_MODE`, which is privileged, so t

Diff truncated.