diff --git a/flexera/res/values/flexera_strings.xml b/flexera/res/values/flexera_strings.xml
index 9f9b6b7804..84fd54e409 100644
--- a/flexera/res/values/flexera_strings.xml
+++ b/flexera/res/values/flexera_strings.xml
@@ -27,6 +27,38 @@
Lawnchair
Flexera Launcher is a modified version of Lawnchair, the open-source launcher made by the Lawnchair team. Lawnchair is itself based on Launcher3 from the Android Open Source Project.
Lawnchair source code
+
+ Import from Smart Launcher
+ Home screens, folders and widgets from a Smart Launcher backup file (.slbk)
+ In this backup
+ Home screens
+ %1$d, on a grid of %2$d by %3$d
+ Apps on the home screens
+ Folders
+
+ - %1$d, holding %2$d app
+ - %1$d, holding %2$d apps
+
+ Widgets
+ %1$d. Each arrives in its place as “tap to set up”: Android asks you to allow it again, and its own settings start fresh.
+ Left out
+ Widgets of Smart Launcher itself
+
+ - %1$d. It exists only inside Smart Launcher, so its place stays empty.
+ - %1$d. They exist only inside Smart Launcher, so their places stay empty.
+
+ Other items
+
+ - %1$d that this launcher cannot show or place
+ - %1$d that this launcher cannot show or place
+
+ What importing does
+ Replaces your current home screens
+ The home screens you have now are removed. The grid takes the size it has in the backup and the dock is switched off, because Smart Launcher has none; both can be changed again in Settings. Icons of apps that are not installed on this phone are dropped. Make a backup first if you want to be able to go back.
+ Import
+ Imported
+ The import failed
+ This is not a Smart Launcher backup that can be read
Share
Scan to get Flexera Launcher
QR code that opens the download page
diff --git a/flexera/src/app/flexera/backup/SmartLauncherBackupConverter.kt b/flexera/src/app/flexera/backup/SmartLauncherBackupConverter.kt
new file mode 100644
index 0000000000..c2057075ae
--- /dev/null
+++ b/flexera/src/app/flexera/backup/SmartLauncherBackupConverter.kt
@@ -0,0 +1,619 @@
+package app.flexera.backup
+
+import android.content.ComponentName
+import android.content.ContentValues
+import android.content.Context
+import android.content.Intent
+import android.content.pm.LauncherApps
+import android.database.sqlite.SQLiteDatabase
+import android.net.Uri
+import android.os.Process
+import android.util.Log
+import app.lawnchair.DeviceProfileOverrides
+import app.lawnchair.backup.LawnchairBackup
+import app.lawnchair.preferences.PreferenceManager
+import app.lawnchair.preferences2.PreferenceManager2
+import com.android.launcher3.GridType
+import com.android.launcher3.InvariantDeviceProfile
+import com.android.launcher3.LauncherSettings.Favorites
+import com.android.launcher3.model.DatabaseHelper
+import com.android.launcher3.model.DeviceGridState
+import com.android.launcher3.model.ModelDbController
+import com.android.launcher3.pm.UserCache
+import com.android.launcher3.provider.RestoreDbTask
+import com.android.launcher3.shortcuts.ShortcutKey
+import com.android.launcher3.shortcuts.ShortcutRequest
+import java.io.File
+import java.io.FileInputStream
+import java.io.FileOutputStream
+import java.net.URISyntaxException
+import java.util.UUID
+import java.util.zip.ZipInputStream
+import javax.xml.parsers.DocumentBuilderFactory
+import kotlin.math.max
+import kotlin.math.roundToInt
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import org.json.JSONObject
+
+/**
+ * Imports the home screens of a Smart Launcher backup: icons, folders and widgets, each in the
+ * place it had, on a grid of the same size and, like Smart Launcher, without a dock.
+ *
+ * A backup (a .slbk file) is a zip of Smart Launcher's own files. Two of them matter here:
+ * - `databases/ginlemon.flower.db`, a SQLite database. Its table `HomeItem` has one row per
+ * thing on a home screen (screen, cell, size) that points either at a `Launchable`, which
+ * `Action` describes with an ordinary Android intent, or at a `Widget` with its provider.
+ * A folder is a launchable too; its members are the launchables that name it as their parent.
+ * - the preferences file under `shared_prefs/`, where `launcher_profile_#0` holds the grid.
+ *
+ * The format is not documented. This follows one real backup, of Smart Launcher's data
+ * version 64, and refuses a file in which it does not find these tables.
+ *
+ * What cannot come along is said to the owner before the import ([Info]): Smart Launcher's own
+ * widgets, which exist only inside Smart Launcher, and items of other profiles. A widget that
+ * does come along arrives as "tap to set up": Android has every launcher ask for its widgets
+ * itself, and keeps a widget's settings with the launcher that made it.
+ *
+ * The layout is handed to Launcher3 the way Lawnchair's Nova import hands over its own
+ * (see [app.lawnchair.backup.NovaBackupConverter]): as a database of Launcher3's own shape,
+ * which Launcher3's restore code then takes in.
+ */
+class SmartLauncherBackupConverter(
+ private val context: Context,
+ private val uri: Uri,
+) {
+
+ /** What a backup holds, for the owner to see before agreeing to the import. */
+ data class Info(
+ val columns: Int,
+ val rows: Int,
+ val screens: Int,
+ val apps: Int,
+ val folders: Int,
+ val appsInFolders: Int,
+ val widgets: Int,
+ /** Smart Launcher's own widgets, which stay behind. */
+ val ownWidgets: Int,
+ /** Other things that stay behind: no usable target, another profile, or no free cells. */
+ val skipped: Int,
+ )
+
+ /** Where a thing sits on the home screens, in whole cells. */
+ private data class Place(val screen: Int, val x: Int, val y: Int, val width: Int, val height: Int)
+
+ /** An icon: an app, or a shortcut into an app ([shortcutId] with [packageName]). */
+ private data class Icon(
+ val title: String?,
+ val intentUri: String,
+ val packageName: String?,
+ val shortcutId: String?,
+ )
+
+ private sealed interface HomeThing {
+ val place: Place
+ }
+
+ private data class HomeIcon(override val place: Place, val icon: Icon) : HomeThing
+ private data class HomeFolder(override val place: Place, val title: String?, val icons: List) : HomeThing
+ private data class HomeWidget(override val place: Place, val provider: String) : HomeThing
+
+ private data class Layout(
+ val columns: Int,
+ val rows: Int,
+ val showLabels: Boolean?,
+ val things: List,
+ val ownWidgets: Int,
+ val skipped: Int,
+ ) {
+ val info: Info
+ get() = Info(
+ columns = columns,
+ rows = rows,
+ screens = things.map { it.place.screen }.distinct().size,
+ apps = things.count { it is HomeIcon },
+ folders = things.count { it is HomeFolder },
+ appsInFolders = things.sumOf { (it as? HomeFolder)?.icons?.size ?: 0 },
+ widgets = things.count { it is HomeWidget },
+ ownWidgets = ownWidgets,
+ skipped = skipped,
+ )
+ }
+
+ /** Reads the backup and says what is in it. Throws if it is not a backup this can read. */
+ suspend fun parseInfo(): Info = withContext(Dispatchers.IO) {
+ withUnpackedBackup { dir -> readLayout(dir).info }
+ }
+
+ /**
+ * Replaces the home screens with the backup's. The launcher has to be restarted afterwards
+ * to show them.
+ */
+ suspend fun convertAndRestore() {
+ val layout = withContext(Dispatchers.IO) { withUnpackedBackup { dir -> readLayout(dir) } }
+
+ withContext(Dispatchers.IO) {
+ val tempDir = newTempDir()
+ try {
+ val staged = File(tempDir, STAGED_DB)
+ val shortcuts = writeLauncherDb(layout, staged)
+ applyGrid(layout)
+
+ val restored = context.getDatabasePath(LawnchairBackup.RESTORED_DB_FILE_NAME)
+ restored.parentFile?.mkdirs()
+ staged.copyTo(restored, overwrite = true)
+ // Opening the controller moves the restored file into place; the restore task
+ // then marks every item as freshly restored, which is what makes Launcher3 ask
+ // for the widgets anew and drop icons of apps that are not installed.
+ check(RestoreDbTask.performRestore(context, ModelDbController(context))) {
+ "Launcher3 did not accept the converted layout"
+ }
+ pinShortcuts(shortcuts)
+ } finally {
+ tempDir.deleteRecursively()
+ }
+ }
+
+ // Settings that make the result match the source: no dock, because Smart Launcher has
+ // none, and labels as they were. Last, so that a failed import changes nothing.
+ val prefs2 = PreferenceManager2.getInstance(context)
+ prefs2.isHotseatEnabled.set(false)
+ layout.showLabels?.let { prefs2.showIconLabelsOnHomeScreen.set(it) }
+ }
+
+ // ---- Reading the backup ------------------------------------------------------------------
+
+ private fun withUnpackedBackup(block: (File) -> T): T {
+ val dir = newTempDir()
+ try {
+ unpack(dir)
+ return block(dir)
+ } finally {
+ dir.deleteRecursively()
+ }
+ }
+
+ private fun newTempDir(): File =
+ File(context.cacheDir, "$TEMP_DIR_PREFIX${UUID.randomUUID()}").apply { mkdirs() }
+
+ /**
+ * Unpacks the database and the preference files, and nothing else, into [dir]. Entry names
+ * come from the file and are not trusted: only the two known places are accepted, each file
+ * lands under its bare name, and a file of unreasonable size ends the import.
+ */
+ private fun unpack(dir: File) {
+ val descriptor = context.contentResolver.openFileDescriptor(uri, "r")
+ ?: error("Cannot open the backup file")
+ descriptor.use {
+ ZipInputStream(FileInputStream(it.fileDescriptor)).use { zip ->
+ var entry = zip.nextEntry
+ while (entry != null) {
+ val name = entry.name
+ val target = when {
+ entry.isDirectory -> null
+ name == SL_DB_ENTRY -> File(dir, SL_DB)
+ name.startsWith(SL_PREFS_DIR) && name.endsWith(".xml") ->
+ File(dir, PREFS_PREFIX + File(name).name)
+ else -> null
+ }
+ if (target != null) {
+ require(target.canonicalPath.startsWith(dir.canonicalPath + File.separator)) {
+ "Backup entry outside the import folder: $name"
+ }
+ FileOutputStream(target).use { out ->
+ val buffer = ByteArray(64 * 1024)
+ var total = 0L
+ while (true) {
+ val read = zip.read(buffer)
+ if (read < 0) break
+ total += read
+ require(total <= MAX_ENTRY_BYTES) { "Backup entry too large: $name" }
+ out.write(buffer, 0, read)
+ }
+ }
+ }
+ entry = zip.nextEntry
+ }
+ }
+ }
+ }
+
+ private fun readLayout(dir: File): Layout {
+ val dbFile = File(dir, SL_DB)
+ require(dbFile.exists()) { "No Smart Launcher database in this file" }
+ val grid = readGrid(dir)
+
+ SQLiteDatabase.openDatabase(dbFile.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { db ->
+ for (table in listOf(T_HOME, T_LAUNCHABLE, T_ACTION, T_WIDGET)) {
+ require(tableExists(db, table)) { "Smart Launcher database without table $table" }
+ }
+ return readHomeScreens(db, grid)
+ }
+ }
+
+ private data class Grid(val columns: Int, val rows: Int, val showLabels: Boolean?)
+
+ /** The home grid from the preferences, or null where a backup does not state it. */
+ private fun readGrid(dir: File): Grid? {
+ val files = dir.listFiles { file -> file.name.startsWith(PREFS_PREFIX) } ?: return null
+ for (file in files) {
+ try {
+ val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file)
+ val strings = document.documentElement.getElementsByTagName("string")
+ for (i in 0 until strings.length) {
+ val node = strings.item(i)
+ val name = node.attributes?.getNamedItem("name")?.nodeValue ?: continue
+ if (!name.startsWith(SL_PROFILE_KEY_PREFIX)) continue
+ val settings = JSONObject(node.textContent).optJSONObject("gridUserSettings") ?: continue
+ val columns = settings.optInt("columns", 0)
+ val rows = settings.optInt("rows", 0)
+ if (columns in 1..MAX_GRID && rows in 1..MAX_GRID) {
+ val labels = if (settings.has("hasLabel")) settings.optBoolean("hasLabel") else null
+ return Grid(columns, rows, labels)
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(TAG, "Unreadable preference file in backup: ${file.name}", e)
+ }
+ }
+ return null
+ }
+
+ private fun readHomeScreens(db: SQLiteDatabase, grid: Grid?): Layout {
+ data class Row(
+ val launchable: Long?,
+ val widget: Long?,
+ val screen: Int,
+ val x: Int,
+ val y: Int,
+ val width: Int,
+ val height: Int,
+ )
+
+ // Smart Launcher can keep more than one arrangement ("configId"); the first is the one
+ // in use on a phone held upright.
+ val rows = ArrayList()
+ db.rawQuery(
+ "SELECT idLaunchable, idWidget, screen, cellX, cellY, spanX, spanY FROM $T_HOME " +
+ "WHERE configId = (SELECT MIN(configId) FROM $T_HOME) ORDER BY zIndex, id",
+ null,
+ ).use { c ->
+ while (c.moveToNext()) {
+ rows.add(
+ Row(
+ launchable = if (c.isNull(0)) null else c.getLong(0),
+ widget = if (c.isNull(1)) null else c.getLong(1),
+ screen = c.getInt(2),
+ x = c.getDouble(3).roundToInt(),
+ y = c.getDouble(4).roundToInt(),
+ width = c.getDouble(5).roundToInt().coerceAtLeast(1),
+ height = c.getDouble(6).roundToInt().coerceAtLeast(1),
+ ),
+ )
+ }
+ }
+
+ val columns = grid?.columns ?: max(MIN_GRID, rows.maxOfOrNull { it.x + it.width } ?: 0)
+ val gridRows = grid?.rows ?: max(MIN_GRID, rows.maxOfOrNull { it.y + it.height } ?: 0)
+ // Launcher3 numbers its screens from 0 without gaps, left to right.
+ val screenIndex = rows.map { it.screen }.distinct().sorted().withIndex().associate { it.value to it.index }
+ val taken = HashSet>()
+
+ val things = ArrayList()
+ var ownWidgets = 0
+ var skipped = 0
+ for (row in rows) {
+ val screen = screenIndex.getValue(row.screen)
+ val place = Place(screen, row.x, row.y, row.width, row.height)
+ val cells = cellsOf(place)
+ // Launcher3 keeps one thing per cell and nothing outside the grid.
+ val fits = row.x >= 0 && row.y >= 0 && row.x + row.width <= columns &&
+ row.y + row.height <= gridRows && cells.none { it in taken }
+
+ val read: HomeThing? = when {
+ row.widget != null -> readWidgetProvider(db, row.widget)?.let { HomeWidget(place, it) }
+ row.launchable != null -> readLaunchable(db, row.launchable, place)
+ else -> null
+ }
+ when {
+ // The only widgets without a provider this can use are Smart Launcher's own.
+ read == null && row.widget != null -> ownWidgets++
+ read == null || !fits -> skipped++
+ else -> {
+ things.add(read)
+ taken.addAll(cells)
+ }
+ }
+ }
+ return Layout(columns, gridRows, grid?.showLabels, things, ownWidgets, skipped)
+ }
+
+ private fun cellsOf(place: Place): List> = buildList {
+ for (x in place.x until place.x + place.width) {
+ for (y in place.y until place.y + place.height) {
+ add(Triple(place.screen, x, y))
+ }
+ }
+ }
+
+ /** The provider of an ordinary app widget, or null for one of Smart Launcher's own. */
+ private fun readWidgetProvider(db: SQLiteDatabase, id: Long): String? =
+ db.rawQuery("SELECT type, provider, userId FROM $T_WIDGET WHERE id = ?", arrayOf(id.toString())).use { c ->
+ if (!c.moveToFirst()) {
+ null
+ } else {
+ val type = c.getInt(0)
+ val provider = if (c.isNull(1)) null else c.getString(1)
+ val user = if (c.isNull(2)) OWNER_USER else c.getInt(2)
+ val component = provider?.let(ComponentName::unflattenFromString)
+ if (type != SL_WIDGET_TYPE_APP || component == null || user != OWNER_USER) {
+ null
+ } else {
+ component.flattenToString()
+ }
+ }
+ }
+
+ /** The icon or folder behind a launchable, or null if it has no target this can use. */
+ private fun readLaunchable(db: SQLiteDatabase, id: Long, place: Place): HomeThing? {
+ val action = readAction(db, id) ?: return null
+ if (action.type != SL_ACTION_TYPE_FOLDER) {
+ return action.toIcon()?.let { HomeIcon(place, it) }
+ }
+ val icons = ArrayList()
+ db.rawQuery(
+ "SELECT id FROM $T_LAUNCHABLE WHERE idParentFolderLaunchable = ? ORDER BY position, id",
+ arrayOf(id.toString()),
+ ).use { c ->
+ while (c.moveToNext()) {
+ readAction(db, c.getLong(0))?.takeIf { it.type != SL_ACTION_TYPE_FOLDER }?.toIcon()?.let(icons::add)
+ }
+ }
+ // Launcher3 has no use for a folder with nothing in it.
+ return if (icons.isEmpty()) null else HomeFolder(place, action.label, icons)
+ }
+
+ private data class Action(
+ val type: Int,
+ val intentUri: String?,
+ val user: Int,
+ val label: String?,
+ val shortcutId: String?,
+ ) {
+ /** Launcher3's form of this action, if it opens an app or one of an app's shortcuts. */
+ fun toIcon(): Icon? {
+ // Icons of a work profile or a second user are left out; -1 means "no user", as on folders.
+ if (user != OWNER_USER && user != NO_USER) return null
+ val intent = try {
+ Intent.parseUri(intentUri ?: return null, 0)
+ } catch (_: URISyntaxException) {
+ return null
+ }
+ val component = intent.component
+ val packageName = component?.packageName ?: intent.`package`
+ return when {
+ !shortcutId.isNullOrEmpty() && packageName != null ->
+ Icon(label, ShortcutKey.makeIntent(shortcutId, packageName).toUri(0), packageName, shortcutId)
+
+ component != null -> Icon(label, launchIntentFor(component).toUri(0), packageName, null)
+
+ else -> null
+ }
+ }
+ }
+
+ /** The first action of a launchable, which is what a tap does. */
+ private fun readAction(db: SQLiteDatabase, launchable: Long): Action? =
+ db.rawQuery(
+ "SELECT type, intentUri, userId, label, deepShortcutId FROM $T_ACTION " +
+ "WHERE idLaunchable = ? ORDER BY actionId LIMIT 1",
+ arrayOf(launchable.toString()),
+ ).use { c ->
+ if (!c.moveToFirst()) {
+ null
+ } else {
+ Action(
+ type = c.getInt(0),
+ intentUri = if (c.isNull(1)) null else c.getString(1),
+ user = if (c.isNull(2)) OWNER_USER else c.getInt(2),
+ label = if (c.isNull(3)) null else c.getString(3),
+ shortcutId = if (c.isNull(4)) null else c.getString(4),
+ )
+ }
+ }
+
+ private fun tableExists(db: SQLiteDatabase, table: String): Boolean =
+ db.rawQuery("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", arrayOf(table)).use {
+ it.moveToFirst()
+ }
+
+ // ---- Writing Launcher3's layout ----------------------------------------------------------
+
+ /**
+ * Writes [layout] as a Launcher3 database at [target]. Returns the app shortcuts in it, by
+ * package, which the launcher has to pin before it may show them.
+ */
+ private fun writeLauncherDb(layout: Layout, target: File): Map> {
+ val profileId = UserCache.INSTANCE.get(context).getSerialNumberForUser(Process.myUserHandle())
+ val shortcuts = HashMap>()
+ val now = System.currentTimeMillis()
+ var nextId = 1
+
+ SQLiteDatabase.openOrCreateDatabase(target, null).use { db ->
+ db.version = DatabaseHelper.SCHEMA_VERSION
+ Favorites.addTableToDb(db, profileId, false)
+
+ fun insert(
+ container: Int,
+ place: Place?,
+ rank: Int,
+ itemType: Int,
+ title: String? = null,
+ intentUri: String? = null,
+ provider: String? = null,
+ ): Int {
+ val id = nextId++
+ db.insertOrThrow(
+ Favorites.TABLE_NAME,
+ null,
+ ContentValues().apply {
+ put(Favorites._ID, id)
+ put(Favorites.TITLE, title)
+ put(Favorites.INTENT, intentUri)
+ put(Favorites.CONTAINER, container)
+ put(Favorites.SCREEN, place?.screen ?: 0)
+ put(Favorites.CELLX, place?.x ?: 0)
+ put(Favorites.CELLY, place?.y ?: 0)
+ put(Favorites.SPANX, place?.width ?: 1)
+ put(Favorites.SPANY, place?.height ?: 1)
+ put(Favorites.ITEM_TYPE, itemType)
+ put(Favorites.APPWIDGET_ID, -1)
+ put(Favorites.APPWIDGET_PROVIDER, provider)
+ put(Favorites.MODIFIED, now)
+ put(Favorites.RESTORED, 0)
+ put(Favorites.PROFILE_ID, profileId)
+ put(Favorites.RANK, rank)
+ put(Favorites.OPTIONS, 0)
+ put(Favorites.APPWIDGET_SOURCE, -1)
+ },
+ )
+ return id
+ }
+
+ fun insertIcon(icon: Icon, container: Int, place: Place?, rank: Int) {
+ val isShortcut = icon.shortcutId != null && icon.packageName != null
+ if (isShortcut) {
+ shortcuts.getOrPut(icon.packageName!!) { HashSet() }.add(icon.shortcutId!!)
+ }
+ insert(
+ container = container,
+ place = place,
+ rank = rank,
+ itemType = if (isShortcut) Favorites.ITEM_TYPE_DEEP_SHORTCUT else Favorites.ITEM_TYPE_APPLICATION,
+ title = icon.title,
+ intentUri = icon.intentUri,
+ )
+ }
+
+ db.beginTransaction()
+ try {
+ for (thing in layout.things) {
+ when (thing) {
+ is HomeIcon -> insertIcon(thing.icon, Favorites.CONTAINER_DESKTOP, thing.place, 0)
+
+ is HomeFolder -> {
+ val folder = insert(
+ container = Favorites.CONTAINER_DESKTOP,
+ place = thing.place,
+ rank = 0,
+ itemType = Favorites.ITEM_TYPE_FOLDER,
+ title = thing.title,
+ )
+ thing.icons.forEachIndexed { rank, icon -> insertIcon(icon, folder, null, rank) }
+ }
+
+ is HomeWidget -> insert(
+ container = Favorites.CONTAINER_DESKTOP,
+ place = thing.place,
+ rank = 0,
+ itemType = Favorites.ITEM_TYPE_APPWIDGET,
+ provider = thing.provider,
+ )
+ }
+ }
+ db.setTransactionSuccessful()
+ } finally {
+ db.endTransaction()
+ }
+ }
+ return shortcuts
+ }
+
+ /** Makes the home grid the size of the backup's, in every place the launcher keeps it. */
+ private fun applyGrid(layout: Layout) {
+ val prefs = PreferenceManager.getInstance(context)
+ val hotseat = prefs.hotseatColumns.get()
+ val gridInfo = DeviceProfileOverrides.DBGridInfo(
+ numHotseatColumns = hotseat,
+ numRows = layout.rows,
+ numColumns = layout.columns,
+ )
+ val gridState = DeviceGridState(
+ layout.columns,
+ layout.rows,
+ hotseat,
+ InvariantDeviceProfile.TYPE_PHONE,
+ gridInfo.dbFile,
+ GridType.GRID_TYPE_ANY,
+ )
+ gridState.writeToPrefs(context, true)
+ gridState.writeToPrefs(context)
+ InvariantDeviceProfile.INSTANCE.get(context).dbFile = gridInfo.dbFile
+ prefs.sp.edit()
+ .putInt(prefs.workspaceColumns.key, layout.columns)
+ .putInt(prefs.workspaceRows.key, layout.rows)
+ .commit()
+ }
+
+ /** Pins the imported app shortcuts, keeping whatever the launcher has pinned already. */
+ private fun pinShortcuts(shortcuts: Map>) {
+ if (shortcuts.isEmpty()) return
+ val launcherApps = context.getSystemService(LauncherApps::class.java) ?: return
+ val user = Process.myUserHandle()
+ for ((packageName, ids) in shortcuts) {
+ val pinned = LinkedHashSet()
+ val current = ShortcutRequest(context, user)
+ .forPackage(packageName)
+ .query(ShortcutRequest.PINNED or LauncherApps.ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY)
+ if (current.wasSuccess()) current.mapTo(pinned) { it.id }
+ pinned.addAll(ids)
+ try {
+ launcherApps.pinShortcuts(packageName, pinned.toList(), user)
+ } catch (e: SecurityException) {
+ Log.w(TAG, "Could not pin the imported shortcuts of $packageName", e)
+ } catch (e: IllegalStateException) {
+ Log.w(TAG, "Could not pin the imported shortcuts of $packageName", e)
+ }
+ }
+ }
+
+ private companion object {
+ const val TAG = "SmartLauncherImport"
+
+ const val SL_DB_ENTRY = "databases/ginlemon.flower.db"
+ const val SL_PREFS_DIR = "shared_prefs/"
+ const val SL_PROFILE_KEY_PREFIX = "launcher_profile_"
+ const val T_HOME = "HomeItem"
+ const val T_LAUNCHABLE = "Launchable"
+ const val T_ACTION = "Action"
+ const val T_WIDGET = "Widget"
+
+ /** `Action.type` of a folder; every other type seen opens an app. */
+ const val SL_ACTION_TYPE_FOLDER = 9
+
+ /** `Widget.type` of an ordinary app widget; the other types are Smart Launcher's own. */
+ const val SL_WIDGET_TYPE_APP = 1
+
+ /** Smart Launcher's user ids: the phone's owner, and "no user" on folders. */
+ const val OWNER_USER = 0
+ const val NO_USER = -1
+
+ const val TEMP_DIR_PREFIX = "smartlauncher_"
+ const val SL_DB = "smartlauncher.db"
+ const val PREFS_PREFIX = "prefs_"
+ const val STAGED_DB = "workspace.db"
+
+ /** Far above any real backup's database; a larger entry is not a backup. */
+ const val MAX_ENTRY_BYTES = 64L * 1024 * 1024
+
+ const val MIN_GRID = 4
+ const val MAX_GRID = 20
+
+ /** The intent Launcher3 itself stores for an app icon. */
+ fun launchIntentFor(component: ComponentName): Intent =
+ Intent(Intent.ACTION_MAIN)
+ .addCategory(Intent.CATEGORY_LAUNCHER)
+ .setComponent(component)
+ .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
+ }
+}
diff --git a/flexera/src/app/flexera/backup/SmartLauncherImportScreen.kt b/flexera/src/app/flexera/backup/SmartLauncherImportScreen.kt
new file mode 100644
index 0000000000..ab780a7ce5
--- /dev/null
+++ b/flexera/src/app/flexera/backup/SmartLauncherImportScreen.kt
@@ -0,0 +1,198 @@
+package app.flexera.backup
+
+import android.app.Activity
+import android.content.Intent
+import android.widget.Toast
+import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.pluralStringResource
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import androidx.core.net.toUri
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.navigation.NavGraphBuilder
+import androidx.navigation.compose.composable
+import androidx.navigation.toRoute
+import app.flexera.backup.SmartLauncherImportViewModel.Event
+import app.flexera.backup.SmartLauncherImportViewModel.State
+import app.lawnchair.ui.preferences.LocalIsExpandedScreen
+import app.lawnchair.ui.preferences.LocalNavController
+import app.lawnchair.ui.preferences.components.layout.PreferenceGroup
+import app.lawnchair.ui.preferences.components.layout.PreferenceLayout
+import app.lawnchair.ui.preferences.components.layout.PreferenceTemplate
+import app.lawnchair.ui.preferences.navigation.ImportSmartLauncherBackup
+import app.lawnchair.util.BackHandler
+import app.lawnchair.util.restartLauncher
+import com.android.launcher3.R
+import java.util.Base64
+
+/**
+ * The screen between choosing a Smart Launcher backup and importing it. It says what the file
+ * holds, what will not come along and what the import replaces, and waits for the owner's word.
+ */
+fun NavGraphBuilder.smartLauncherImportGraph() {
+ composable { entry ->
+ val route: ImportSmartLauncherBackup = entry.toRoute()
+ val backup = remember { String(Base64.getDecoder().decode(route.base64Uri)).toUri() }
+ val viewModel: SmartLauncherImportViewModel = viewModel()
+ DisposableEffect(Unit) {
+ viewModel.open(backup)
+ onDispose { }
+ }
+ SmartLauncherImportScreen(viewModel)
+ }
+}
+
+@Composable
+private fun SmartLauncherImportScreen(viewModel: SmartLauncherImportViewModel) {
+ val context = LocalContext.current
+ val state by viewModel.state.collectAsStateWithLifecycle()
+
+ LaunchedEffect(Unit) {
+ viewModel.events.collect { event ->
+ when (event) {
+ Event.Imported -> {
+ Toast.makeText(context, R.string.flexera_import_done, Toast.LENGTH_SHORT).show()
+ restartLauncher(context)
+ }
+
+ Event.Failed -> Toast.makeText(context, R.string.flexera_import_failed, Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+
+ PreferenceLayout(
+ label = stringResource(id = R.string.flexera_import_smart_launcher),
+ backArrowVisible = !LocalIsExpandedScreen.current,
+ ) {
+ when (val current = state) {
+ State.Reading -> Box(modifier = Modifier.fillMaxSize()) {
+ CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
+ }
+
+ State.Unreadable -> {
+ val back = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
+ LaunchedEffect(Unit) {
+ Toast.makeText(context, R.string.flexera_import_unreadable, Toast.LENGTH_LONG).show()
+ back?.onBackPressed()
+ }
+ }
+
+ is State.Ready -> {
+ // Leaving in the middle of an import would leave the home screens half replaced.
+ if (current.importing) BackHandler {}
+ BackupContents(current.info)
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(top = 8.dp)
+ .padding(horizontal = 16.dp),
+ ) {
+ Button(
+ onClick = viewModel::import,
+ modifier = Modifier.fillMaxWidth(),
+ enabled = !current.importing,
+ ) {
+ Text(text = stringResource(id = R.string.flexera_import_action))
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun BackupContents(info: SmartLauncherBackupConverter.Info) {
+ PreferenceGroup(heading = stringResource(id = R.string.flexera_import_found)) {
+ InfoRow(
+ R.string.flexera_import_screens,
+ stringResource(id = R.string.flexera_import_screens_value, info.screens, info.columns, info.rows),
+ )
+ if (info.apps > 0) InfoRow(R.string.flexera_import_apps, info.apps.toString())
+ if (info.folders > 0) {
+ InfoRow(
+ R.string.flexera_import_folders,
+ pluralStringResource(
+ id = R.plurals.flexera_import_folders_value,
+ count = info.appsInFolders,
+ info.folders,
+ info.appsInFolders,
+ ),
+ )
+ }
+ if (info.widgets > 0) {
+ InfoRow(R.string.flexera_import_widgets, stringResource(id = R.string.flexera_import_widgets_value, info.widgets))
+ }
+ }
+ if (info.ownWidgets > 0 || info.skipped > 0) {
+ PreferenceGroup(heading = stringResource(id = R.string.flexera_import_left_out)) {
+ if (info.ownWidgets > 0) {
+ InfoRow(
+ R.string.flexera_import_own_widgets,
+ pluralStringResource(
+ id = R.plurals.flexera_import_own_widgets_value,
+ count = info.ownWidgets,
+ info.ownWidgets,
+ ),
+ )
+ }
+ if (info.skipped > 0) {
+ InfoRow(
+ R.string.flexera_import_skipped,
+ pluralStringResource(id = R.plurals.flexera_import_skipped_value, count = info.skipped, info.skipped),
+ )
+ }
+ }
+ }
+ PreferenceGroup(heading = stringResource(id = R.string.flexera_import_effect)) {
+ PreferenceTemplate(
+ title = { Text(text = stringResource(id = R.string.flexera_import_effect_title)) },
+ description = { Text(text = stringResource(id = R.string.flexera_import_effect_body)) },
+ )
+ }
+}
+
+@Composable
+private fun InfoRow(labelRes: Int, value: String) {
+ PreferenceTemplate(
+ title = { Text(text = stringResource(id = labelRes)) },
+ description = { Text(text = value) },
+ )
+}
+
+/** Returns an action that lets the owner pick a backup file and then opens the import screen for it. */
+@Composable
+fun smartLauncherImportOpener(): () -> Unit {
+ val navController = LocalNavController.current
+ val request = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
+ if (result.resultCode != Activity.RESULT_OK) return@rememberLauncherForActivityResult
+ val uri = result.data?.data ?: return@rememberLauncherForActivityResult
+ val base64Uri = Base64.getEncoder().encodeToString(uri.toString().toByteArray())
+ navController.navigate(ImportSmartLauncherBackup(base64Uri))
+ }
+ return {
+ // A .slbk file has no file type Android knows, so every file is offered.
+ request.launch(
+ Intent(Intent.ACTION_OPEN_DOCUMENT)
+ .addCategory(Intent.CATEGORY_OPENABLE)
+ .setType("*/*"),
+ )
+ }
+}
diff --git a/flexera/src/app/flexera/backup/SmartLauncherImportViewModel.kt b/flexera/src/app/flexera/backup/SmartLauncherImportViewModel.kt
new file mode 100644
index 0000000000..0d58255cd8
--- /dev/null
+++ b/flexera/src/app/flexera/backup/SmartLauncherImportViewModel.kt
@@ -0,0 +1,74 @@
+package app.flexera.backup
+
+import android.app.Application
+import android.net.Uri
+import android.util.Log
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.viewModelScope
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.receiveAsFlow
+import kotlinx.coroutines.launch
+
+/**
+ * Holds one Smart Launcher import: reads the chosen backup, shows what is in it, and on the
+ * owner's word replaces the home screens with it. Same shape as Lawnchair's view model for a
+ * Nova backup.
+ */
+internal class SmartLauncherImportViewModel(application: Application) : AndroidViewModel(application) {
+
+ sealed interface Event {
+ data object Imported : Event
+ data object Failed : Event
+ }
+
+ sealed interface State {
+ data object Reading : State
+ data object Unreadable : State
+ data class Ready(val info: SmartLauncherBackupConverter.Info, val importing: Boolean = false) : State
+ }
+
+ private var converter: SmartLauncherBackupConverter? = null
+
+ private val mutableState = MutableStateFlow(State.Reading)
+ val state: StateFlow = mutableState.asStateFlow()
+
+ private val eventChannel = Channel(Channel.BUFFERED)
+ val events = eventChannel.receiveAsFlow()
+
+ fun open(backup: Uri) {
+ if (converter != null) return
+ val converter = SmartLauncherBackupConverter(getApplication(), backup).also { converter = it }
+ viewModelScope.launch {
+ mutableState.value = try {
+ State.Ready(converter.parseInfo())
+ } catch (t: Throwable) {
+ Log.e(TAG, "Not a Smart Launcher backup this can read", t)
+ State.Unreadable
+ }
+ }
+ }
+
+ fun import() {
+ val ready = mutableState.value as? State.Ready ?: return
+ val converter = converter ?: return
+ if (ready.importing) return
+ viewModelScope.launch {
+ mutableState.value = ready.copy(importing = true)
+ try {
+ converter.convertAndRestore()
+ eventChannel.send(Event.Imported)
+ } catch (t: Throwable) {
+ Log.e(TAG, "Import failed", t)
+ mutableState.value = ready.copy(importing = false)
+ eventChannel.send(Event.Failed)
+ }
+ }
+ }
+
+ private companion object {
+ const val TAG = "SmartLauncherImport"
+ }
+}
diff --git a/lawnchair/src/app/lawnchair/ui/preferences/destinations/BackupAndRestorePreference.kt b/lawnchair/src/app/lawnchair/ui/preferences/destinations/BackupAndRestorePreference.kt
index 3265695ba8..e14c12cb8d 100644
--- a/lawnchair/src/app/lawnchair/ui/preferences/destinations/BackupAndRestorePreference.kt
+++ b/lawnchair/src/app/lawnchair/ui/preferences/destinations/BackupAndRestorePreference.kt
@@ -40,6 +40,12 @@ fun BackupAndRestorePreference(
subtitle = stringResource(R.string.restore_nova_backup_description),
onClick = restoreNovaBackupOpener(),
)
+ // Flexera Launcher: home screens from a Smart Launcher backup (app.flexera.backup).
+ ClickablePreference(
+ label = stringResource(R.string.flexera_import_smart_launcher),
+ subtitle = stringResource(R.string.flexera_import_smart_launcher_description),
+ onClick = app.flexera.backup.smartLauncherImportOpener(),
+ )
}
}
}
diff --git a/lawnchair/src/app/lawnchair/ui/preferences/navigation/PreferenceNavigation.kt b/lawnchair/src/app/lawnchair/ui/preferences/navigation/PreferenceNavigation.kt
index 5d497bc309..36e91676e8 100644
--- a/lawnchair/src/app/lawnchair/ui/preferences/navigation/PreferenceNavigation.kt
+++ b/lawnchair/src/app/lawnchair/ui/preferences/navigation/PreferenceNavigation.kt
@@ -14,6 +14,7 @@ import androidx.navigation.compose.composable
import androidx.navigation.navDeepLink
import androidx.navigation.toRoute
import app.lawnchair.backup.ui.CreateBackupScreen
+import app.flexera.backup.smartLauncherImportGraph
import app.lawnchair.backup.ui.restoreBackupGraph
import app.lawnchair.backup.ui.restoreNovaBackupGraph
import app.lawnchair.preferences.BasePreferenceManager
@@ -252,5 +253,6 @@ fun PreferenceNavigation(
restoreBackupGraph()
restoreNovaBackupGraph()
+ smartLauncherImportGraph() // Flexera Launcher: Smart Launcher import
}
}
diff --git a/lawnchair/src/app/lawnchair/ui/preferences/navigation/PreferenceRoutes.kt b/lawnchair/src/app/lawnchair/ui/preferences/navigation/PreferenceRoutes.kt
index 35f39d3e39..4ed3d25b64 100644
--- a/lawnchair/src/app/lawnchair/ui/preferences/navigation/PreferenceRoutes.kt
+++ b/lawnchair/src/app/lawnchair/ui/preferences/navigation/PreferenceRoutes.kt
@@ -224,3 +224,8 @@ data class RestoreBackup(val base64Uri: String) : PreferenceRoute
@Serializable
data class RestoreNovaBackup(val base64Uri: String) : PreferenceRoute
+
+// Flexera Launcher: import of a Smart Launcher backup (app.flexera.backup). The route has to
+// be declared here because PreferenceRoute is sealed.
+@Serializable
+data class ImportSmartLauncherBackup(val base64Uri: String) : PreferenceRoute
diff --git a/src/com/android/launcher3/widget/util/WidgetSizeHandler.kt b/src/com/android/launcher3/widget/util/WidgetSizeHandler.kt
index 6a2bb9efa0..2f11df7dc8 100644
--- a/src/com/android/launcher3/widget/util/WidgetSizeHandler.kt
+++ b/src/com/android/launcher3/widget/util/WidgetSizeHandler.kt
@@ -21,6 +21,7 @@ import android.appwidget.AppWidgetManager.OPTION_APPWIDGET_SIZES
import android.appwidget.AppWidgetProviderInfo
import android.content.Context
import android.os.Bundle
+import android.util.Log
import android.util.SizeF
import com.android.launcher3.dagger.ApplicationContext
import com.android.launcher3.util.Executors
@@ -46,13 +47,24 @@ open class WidgetSizeHandler @Inject constructor(@ApplicationContext private val
spanY: Int,
) {
Executors.UI_HELPER_EXECUTOR.execute {
- val widgetManager = AppWidgetManager.getInstance(context)
- val sizeOptions = WidgetSizes.getWidgetSizeOptions(context, info.provider, spanX, spanY)
- if (
- sizeOptions.getWidgetSizeList() !=
- widgetManager.getAppWidgetOptions(widgetId).getWidgetSizeList()
- )
- widgetManager.updateAppWidgetOptions(widgetId, sizeOptions)
+ // Flexera Launcher: a widget that still waits for "tap to set up" has an id that
+ // Android has reserved but not yet tied to a provider. Android answers a size
+ // update for such an id with a NullPointerException of its own (seen on Android 17:
+ // AppWidgetServiceImpl.updateAppWidgetOptions), which arrives here and used to end
+ // the launcher whenever the grid reloaded with such a widget on a home screen. That
+ // is the normal state after a layout import, so the answer is logged and dropped;
+ // the size is sent again when the widget is set up.
+ try {
+ val widgetManager = AppWidgetManager.getInstance(context)
+ val sizeOptions = WidgetSizes.getWidgetSizeOptions(context, info.provider, spanX, spanY)
+ if (
+ sizeOptions.getWidgetSizeList() !=
+ widgetManager.getAppWidgetOptions(widgetId).getWidgetSizeList()
+ )
+ widgetManager.updateAppWidgetOptions(widgetId, sizeOptions)
+ } catch (e: RuntimeException) {
+ Log.w("WidgetSizeHandler", "Android refused the size of widget $widgetId", e)
+ }
}
}