diff --git a/res/layout/launcher_preview_layout.xml b/res/layout/launcher_preview_layout.xml index cf2f2c75ee..31dc977968 100644 --- a/res/layout/launcher_preview_layout.xml +++ b/res/layout/launcher_preview_layout.xml @@ -13,7 +13,7 @@ See the License for the specific language governing permissions and limitations under the License. --> - - mRestoreEventLoggerProvider; @AssistedInject - LoaderTask( + protected LoaderTask( @ApplicationContext Context context, InvariantDeviceProfile idp, LauncherModel model, @@ -180,7 +182,8 @@ public class LoaderTask implements Runnable { @Named("SAFE_MODE") boolean isSafeModeEnabled, @Assisted @NonNull BaseLauncherBinder launcherBinder, @Assisted UserManagerState userManagerState, - Provider restoreEventLoggerFactory) { + Provider restoreEventLoggerFactory, + LoaderParams params) { mContext = context; mIDP = idp; mModel = model; @@ -200,6 +203,7 @@ public class LoaderTask implements Runnable { mInstallingPkgsCached = null; mFolderNameProviderFactory = folderNameProviderFactory; mRestoreEventLoggerProvider = restoreEventLoggerFactory; + mParams = params; } protected synchronized void waitForIdle() { @@ -251,6 +255,121 @@ public class LoaderTask implements Runnable { } } + private void loadAllSurfacesOrdered( + LoaderMemoryLogger memoryLogger, LauncherRestoreEventLogger restoreEventLogger) { + + List allShortcuts = new ArrayList<>(); + loadWorkspace( + allShortcuts, mParams.getWorkspaceSelection(), memoryLogger, restoreEventLogger); + + // Sanitize data re-syncs widgets/shortcuts based on the workspace loaded from db. + // sanitizeData should not be invoked if the workspace is loaded from a db different + // from the main db as defined in the invariant device profile. + // (e.g. both grid preview and minimal device mode uses a different db) + // TODO(b/384731096): Write Unit Test to make sure sanitizeWidgetsShortcutsAndPackages + // actually re-pins shortcuts that are in model but not in ShortcutManager, if possible + // after a simulated restore. + if (Objects.equals(mIDP.dbFile, mDbName) && mParams.getSanitizeData()) { + verifyNotStopped(); + sanitizeWidgetsShortcutsAndPackages(); + logASplit("sanitizeData finished"); + } + + verifyNotStopped(); + mLauncherBinder.bindWorkspace(true /* incrementBindId */, /* isBindSync= */ false); + logASplit("bindWorkspace finished"); + + if (!mParams.getLoadNonWorkspaceItems()) { + logASplit("Skipping remaining items"); + return; + } + + mModelDelegate.workspaceLoadComplete(); + // Notify the installer packages of packages with active installs on the first screen. + sendFirstScreenActiveInstallsBroadcast(); + + // Take a break + waitForIdle(); + logASplit("step 1 loading workspace complete"); + verifyNotStopped(); + + // second step + Trace.beginSection("LoadAllApps"); + List allActivityList; + try { + allActivityList = loadAllApps(); + } finally { + Trace.endSection(); + } + logASplit("loadAllApps finished"); + + verifyNotStopped(); + mLauncherBinder.bindAllApps(); + logASplit("bindAllApps finished"); + + verifyNotStopped(); + IconCacheUpdateHandler updateHandler = mIconCache.getUpdateHandler(); + setIgnorePackages(updateHandler); + updateHandler.updateIcons(allActivityList, + LauncherActivityCachingLogic.INSTANCE, + mModel::onPackageIconsUpdated); + logASplit("update AllApps icon cache finished"); + + verifyNotStopped(); + logASplit("saving all shortcuts in icon cache"); + updateHandler.updateIcons(allShortcuts, CacheableShortcutCachingLogic.INSTANCE, + mModel::onPackageIconsUpdated); + + // Take a break + waitForIdle(); + logASplit("step 2 loading AllApps complete"); + verifyNotStopped(); + + // third step + List allDeepShortcuts = loadDeepShortcuts(); + logASplit("loadDeepShortcuts finished"); + + verifyNotStopped(); + mLauncherBinder.bindDeepShortcuts(); + logASplit("bindDeepShortcuts finished"); + + verifyNotStopped(); + logASplit("saving deep shortcuts in icon cache"); + updateHandler.updateIcons( + convertShortcutsToCacheableShortcuts(allDeepShortcuts, allActivityList), + CacheableShortcutCachingLogic.INSTANCE, + (pkgs, user) -> { }); + + // Take a break + waitForIdle(); + logASplit("step 3 loading all shortcuts complete"); + verifyNotStopped(); + + // fourth step + WidgetsModel widgetsModel = mBgDataModel.widgetsModel; + List allWidgetsList = widgetsModel.update(/*packageUser=*/null); + logASplit("load widgets finished"); + + verifyNotStopped(); + mLauncherBinder.bindWidgets(); + logASplit("bindWidgets finished"); + verifyNotStopped(); + + logASplit("saving all widgets in icon cache"); + updateHandler.updateIcons(allWidgetsList, + CachedObjectCachingLogic.INSTANCE, + mModel::onWidgetLabelsUpdated); + + // fifth step + loadFolderNames(); + + verifyNotStopped(); + updateHandler.finish(); + logASplit("finish icon update"); + + mModelDelegate.modelLoadComplete(); + } + public void run() { synchronized (this) { // Skip fast if we are already stopped. @@ -269,110 +388,8 @@ public class LoaderTask implements Runnable { restoreEventLogger = mRestoreEventLoggerProvider.get(); } try (LauncherModel.LoaderTransaction transaction = mModel.beginLoader(this)) { - List allShortcuts = new ArrayList<>(); - loadWorkspace(allShortcuts, "", memoryLogger, restoreEventLogger); + loadAllSurfacesOrdered(memoryLogger, restoreEventLogger); - // Sanitize data re-syncs widgets/shortcuts based on the workspace loaded from db. - // sanitizeData should not be invoked if the workspace is loaded from a db different - // from the main db as defined in the invariant device profile. - // (e.g. both grid preview and minimal device mode uses a different db) - // TODO(b/384731096): Write Unit Test to make sure sanitizeWidgetsShortcutsAndPackages - // actually re-pins shortcuts that are in model but not in ShortcutManager, if possible - // after a simulated restore. - if (Objects.equals(mIDP.dbFile, mDbName)) { - verifyNotStopped(); - sanitizeWidgetsShortcutsAndPackages(); - logASplit("sanitizeData finished"); - } - - verifyNotStopped(); - mLauncherBinder.bindWorkspace(true /* incrementBindId */, /* isBindSync= */ false); - logASplit("bindWorkspace finished"); - - mModelDelegate.workspaceLoadComplete(); - // Notify the installer packages of packages with active installs on the first screen. - sendFirstScreenActiveInstallsBroadcast(); - - // Take a break - waitForIdle(); - logASplit("step 1 loading workspace complete"); - verifyNotStopped(); - - // second step - Trace.beginSection("LoadAllApps"); - List allActivityList; - try { - allActivityList = loadAllApps(); - } finally { - Trace.endSection(); - } - logASplit("loadAllApps finished"); - - verifyNotStopped(); - mLauncherBinder.bindAllApps(); - logASplit("bindAllApps finished"); - - verifyNotStopped(); - IconCacheUpdateHandler updateHandler = mIconCache.getUpdateHandler(); - setIgnorePackages(updateHandler); - updateHandler.updateIcons(allActivityList, - LauncherActivityCachingLogic.INSTANCE, - mModel::onPackageIconsUpdated); - logASplit("update AllApps icon cache finished"); - - verifyNotStopped(); - logASplit("saving all shortcuts in icon cache"); - updateHandler.updateIcons(allShortcuts, CacheableShortcutCachingLogic.INSTANCE, - mModel::onPackageIconsUpdated); - - // Take a break - waitForIdle(); - logASplit("step 2 loading AllApps complete"); - verifyNotStopped(); - - // third step - List allDeepShortcuts = loadDeepShortcuts(); - logASplit("loadDeepShortcuts finished"); - - verifyNotStopped(); - mLauncherBinder.bindDeepShortcuts(); - logASplit("bindDeepShortcuts finished"); - - verifyNotStopped(); - logASplit("saving deep shortcuts in icon cache"); - updateHandler.updateIcons( - convertShortcutsToCacheableShortcuts(allDeepShortcuts, allActivityList), - CacheableShortcutCachingLogic.INSTANCE, - (pkgs, user) -> { }); - - // Take a break - waitForIdle(); - logASplit("step 3 loading all shortcuts complete"); - verifyNotStopped(); - - // fourth step - WidgetsModel widgetsModel = mBgDataModel.widgetsModel; - List allWidgetsList = widgetsModel.update(/*packageUser=*/null); - logASplit("load widgets finished"); - - verifyNotStopped(); - mLauncherBinder.bindWidgets(); - logASplit("bindWidgets finished"); - verifyNotStopped(); - - logASplit("saving all widgets in icon cache"); - updateHandler.updateIcons(allWidgetsList, - CachedObjectCachingLogic.INSTANCE, - mModel::onWidgetLabelsUpdated); - - // fifth step - loadFolderNames(); - - verifyNotStopped(); - updateHandler.finish(); - logASplit("finish icon update"); - - mModelDelegate.modelLoadComplete(); transaction.commit(); memoryLogger.clearLogs(); if (mIsRestoreFromBackup) { @@ -802,4 +819,5 @@ public class LoaderTask implements Runnable { LoaderTask newLoaderTask(BaseLauncherBinder binder, UserManagerState userState); } + } diff --git a/src/com/android/launcher3/model/data/LoaderParams.kt b/src/com/android/launcher3/model/data/LoaderParams.kt new file mode 100644 index 0000000000..177e576045 --- /dev/null +++ b/src/com/android/launcher3/model/data/LoaderParams.kt @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2025 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.launcher3.model.data + +import javax.inject.Inject + +/** Parameters to customize Loader task */ +data class LoaderParams( + val workspaceSelection: String, + val sanitizeData: Boolean, + val loadNonWorkspaceItems: Boolean, +) { + + @Inject + constructor() : this(workspaceSelection = "", sanitizeData = true, loadNonWorkspaceItems = true) +} diff --git a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java b/src/com/android/launcher3/preview/LauncherPreviewRenderer.java similarity index 66% rename from src/com/android/launcher3/graphics/LauncherPreviewRenderer.java rename to src/com/android/launcher3/preview/LauncherPreviewRenderer.java index 96f4ca69b8..3cf4d57ebc 100644 --- a/src/com/android/launcher3/graphics/LauncherPreviewRenderer.java +++ b/src/com/android/launcher3/preview/LauncherPreviewRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 The Android Open Source Project + * Copyright (C) 2025 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.android.launcher3.graphics; +package com.android.launcher3.preview; import static android.app.WallpaperManager.FLAG_SYSTEM; import static android.view.View.MeasureSpec.EXACTLY; @@ -21,14 +21,8 @@ import static android.view.View.MeasureSpec.makeMeasureSpec; import static android.view.View.VISIBLE; import static com.android.launcher3.Hotseat.ALPHA_CHANNEL_PREVIEW_RENDERER; -import static com.android.launcher3.LauncherPrefs.FIXED_LANDSCAPE_MODE; -import static com.android.launcher3.LauncherPrefs.GRID_NAME; import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION; -import static com.android.launcher3.graphics.ThemeManager.PREF_ICON_SHAPE; -import static com.android.launcher3.graphics.ThemeManager.THEMED_ICONS; import static com.android.launcher3.model.ModelUtils.currentScreenContentFilter; -import static com.android.launcher3.widget.LauncherWidgetHolder.APPWIDGET_HOST_ID; -import static com.android.systemui.shared.Flags.extendibleThemeManager; import static java.util.Comparator.comparingDouble; @@ -41,10 +35,7 @@ import android.content.res.TypedArray; import android.graphics.Rect; import android.os.Handler; import android.os.Looper; -import android.text.TextUtils; import android.util.AttributeSet; -import android.util.Size; -import android.util.SparseArray; import android.util.SparseIntArray; import android.view.ContextThemeWrapper; import android.view.Display; @@ -55,7 +46,6 @@ import android.view.ViewGroup; import android.widget.TextClock; import androidx.annotation.NonNull; -import androidx.annotation.Nullable; import androidx.lifecycle.DefaultLifecycleObserver; import androidx.lifecycle.LifecycleOwner; @@ -65,54 +55,29 @@ import com.android.launcher3.DeviceProfile; import com.android.launcher3.Hotseat; import com.android.launcher3.InsettableFrameLayout; import com.android.launcher3.InvariantDeviceProfile; -import com.android.launcher3.LauncherPrefs; -import com.android.launcher3.ProxyPrefs; import com.android.launcher3.R; import com.android.launcher3.WorkspaceLayoutManager; import com.android.launcher3.celllayout.CellLayoutLayoutParams; import com.android.launcher3.celllayout.CellPosMapper; -import com.android.launcher3.compose.core.widgetpicker.NoOpWidgetPickerModule; -import com.android.launcher3.concurrent.ExecutorsModule; -import com.android.launcher3.dagger.ApiWrapperModule; -import com.android.launcher3.dagger.AppModule; -import com.android.launcher3.dagger.LauncherAppComponent; -import com.android.launcher3.dagger.LauncherAppSingleton; import com.android.launcher3.dagger.LauncherComponentProvider; -import com.android.launcher3.dagger.LauncherConcurrencyModule; -import com.android.launcher3.dagger.PerDisplayModule; -import com.android.launcher3.dagger.PluginManagerWrapperModule; -import com.android.launcher3.dagger.StaticObjectModule; -import com.android.launcher3.dagger.WindowManagerProxyModule; -import com.android.launcher3.model.BaseLauncherBinder.BaseLauncherBinderFactory; +import com.android.launcher3.graphics.FragmentWithPreview; import com.android.launcher3.model.BgDataModel; -import com.android.launcher3.model.LayoutParserFactory; -import com.android.launcher3.model.LayoutParserFactory.XmlLayoutParserFactory; -import com.android.launcher3.model.LoaderTask.LoaderTaskFactory; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.model.data.WorkspaceItemInfo; import com.android.launcher3.util.BaseContext; import com.android.launcher3.util.DisplayController; import com.android.launcher3.util.IntSet; import com.android.launcher3.util.ItemInflater; -import com.android.launcher3.util.SandboxContext; import com.android.launcher3.util.Themes; -import com.android.launcher3.util.dagger.LauncherExecutorsModule; import com.android.launcher3.util.window.WindowManagerProxy; import com.android.launcher3.views.BaseDragLayer; import com.android.launcher3.widget.LauncherWidgetHolder; -import com.android.launcher3.widget.LauncherWidgetHolder.WidgetHolderFactory; import com.android.launcher3.widget.LocalColorExtractor; import com.android.systemui.shared.Flags; -import dagger.BindsInstance; -import dagger.Component; - -import java.io.File; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.UUID; /** * Utility class for generating the preview of Launcher for a given InvariantDeviceProfile. @@ -125,121 +90,33 @@ import java.util.UUID; public class LauncherPreviewRenderer extends BaseContext implements WorkspaceLayoutManager, LayoutInflater.Factory2 { - /** - * Context used just for preview. It also provides a few objects (e.g. UserCache) just for - * preview purposes. - */ - public static class PreviewContext extends SandboxContext { - - private final String mPrefName; - - private final File mDbDir; - - public PreviewContext(Context base, String gridName, String shapeKey, - boolean isMonoThemeEnabled) { - this(base, gridName, shapeKey, APPWIDGET_HOST_ID, null, isMonoThemeEnabled); - } - - public PreviewContext(Context base, String gridName, String shapeKey, - int widgetHostId, @Nullable String layoutXml, boolean isMonoThemeEnabled) { - super(base); - String randomUid = UUID.randomUUID().toString(); - mPrefName = "preview-" + randomUid; - LauncherPrefs prefs = - new ProxyPrefs(this, getSharedPreferences(mPrefName, MODE_PRIVATE)); - prefs.put(GRID_NAME, gridName); - prefs.put(PREF_ICON_SHAPE, shapeKey); - prefs.put(FIXED_LANDSCAPE_MODE, false); - prefs.put(THEMED_ICONS, isMonoThemeEnabled); - - PreviewAppComponent.Builder builder = - DaggerLauncherPreviewRenderer_PreviewAppComponent.builder().bindPrefs(prefs); - if (TextUtils.isEmpty(layoutXml) || !extendibleThemeManager()) { - mDbDir = null; - builder.bindParserFactory(new LayoutParserFactory(this)) - .bindWidgetsFactory( - LauncherComponentProvider.get(base).getWidgetHolderFactory()); - } else { - mDbDir = new File(base.getFilesDir(), randomUid); - emptyDbDir(); - mDbDir.mkdirs(); - builder.bindParserFactory(new XmlLayoutParserFactory(this, layoutXml)) - .bindWidgetsFactory(c -> { - LauncherWidgetHolder holder = new LauncherWidgetHolder(c, widgetHostId); - holder.startListening(); - return holder; - }); - } - initDaggerComponent(builder); - - if (!TextUtils.isEmpty(layoutXml)) { - // Use null the DB file so that we use a new in-memory DB - InvariantDeviceProfile.INSTANCE.get(this).dbFile = null; - } - } - - private void emptyDbDir() { - if (mDbDir != null && mDbDir.exists()) { - Arrays.stream(mDbDir.listFiles()).forEach(File::delete); - } - } - - @Override - protected void cleanUpObjects() { - super.cleanUpObjects(); - deleteSharedPreferences(mPrefName); - if (mDbDir != null) { - emptyDbDir(); - mDbDir.delete(); - } - } - - @Override - public File getDatabasePath(String name) { - return mDbDir != null ? new File(mDbDir, name) : super.getDatabasePath(name); - } - } - private final Handler mUiHandler; private final InvariantDeviceProfile mIdp; private final DeviceProfile mDp; - private final DeviceProfile mDpOrig; private final Rect mInsets; private final LayoutInflater mHomeElementInflater; private final InsettableFrameLayout mRootView; private final Hotseat mHotseat; private final Map mWorkspaceScreens = new HashMap<>(); private final ItemInflater mItemInflater; - private final SparseArray mLauncherWidgetSpanInfo; public LauncherPreviewRenderer(Context context, InvariantDeviceProfile idp, WallpaperColors wallpaperColorsOverride, - int workspaceScreenId, - @Nullable final SparseArray launcherWidgetSpanInfo) { - this(context, idp, null, wallpaperColorsOverride, workspaceScreenId, - launcherWidgetSpanInfo); + int workspaceScreenId) { + this(context, idp, null, wallpaperColorsOverride, workspaceScreenId); } public LauncherPreviewRenderer(Context context, InvariantDeviceProfile idp, SparseIntArray previewColorOverride, WallpaperColors wallpaperColorsOverride, - int workspaceScreenId, - @Nullable final SparseArray launcherWidgetSpanInfo) { + int workspaceScreenId) { super(context, Themes.getActivityThemeRes(context)); mUiHandler = new Handler(Looper.getMainLooper()); mIdp = idp; mDp = getDeviceProfileForPreview(context).toBuilder(context).build(); - if (context instanceof PreviewContext) { - Context tempContext = ((PreviewContext) context).getBaseContext(); - mDpOrig = InvariantDeviceProfile.INSTANCE.get(tempContext) - .getDeviceProfile(tempContext) - .copy(tempContext); - } else { - mDpOrig = mDp; - } mInsets = getInsets(context); mDp.updateInsets(mInsets); @@ -247,19 +124,17 @@ public class LauncherPreviewRenderer extends BaseContext new ContextThemeWrapper(this, R.style.HomeScreenElementTheme)); mHomeElementInflater.setFactory2(this); - int layoutRes = mDp.getDeviceProperties().isTwoPanels() ? R.layout.launcher_preview_two_panel_layout + int layoutRes = mDp.getDeviceProperties().isTwoPanels() + ? R.layout.launcher_preview_two_panel_layout : R.layout.launcher_preview_layout; mRootView = (InsettableFrameLayout) mHomeElementInflater.inflate( layoutRes, null, false); mRootView.setInsets(mInsets); - measureView(mRootView, mDp.getDeviceProperties().getWidthPx(), mDp.getDeviceProperties().getHeightPx()); + measureAndLayoutRootView(); mHotseat = mRootView.findViewById(R.id.hotseat); mHotseat.resetLayout(false); - mLauncherWidgetSpanInfo = launcherWidgetSpanInfo == null ? new SparseArray<>() : - launcherWidgetSpanInfo; - CellLayout firstScreen = mRootView.findViewById(R.id.workspace); firstScreen.setPadding( mDp.workspacePadding.left + mDp.cellLayoutPaddingPx.left, @@ -483,11 +358,11 @@ public class LauncherPreviewRenderer extends BaseContext } } - measureView(mRootView, mDp.getDeviceProperties().getWidthPx(), mDp.getDeviceProperties().getHeightPx()); + measureAndLayoutRootView(); dispatchVisibilityAggregated(mRootView, true); - measureView(mRootView, mDp.getDeviceProperties().getWidthPx(), mDp.getDeviceProperties().getHeightPx()); + measureAndLayoutRootView(); // Additional measure for views which use auto text size API - measureView(mRootView, mDp.getDeviceProperties().getWidthPx(), mDp.getDeviceProperties().getHeightPx()); + measureAndLayoutRootView(); } private void populateHotseatPredictions(BgDataModel dataModel) { @@ -519,9 +394,11 @@ public class LauncherPreviewRenderer extends BaseContext } } - private static void measureView(View view, int width, int height) { - view.measure(makeMeasureSpec(width, EXACTLY), makeMeasureSpec(height, EXACTLY)); - view.layout(0, 0, width, height); + private void measureAndLayoutRootView() { + int width = mDp.getDeviceProperties().getWidthPx(); + int height = mDp.getDeviceProperties().getHeightPx(); + mRootView.measure(makeMeasureSpec(width, EXACTLY), makeMeasureSpec(height, EXACTLY)); + mRootView.layout(0, 0, width, height); } /** Root layout for launcher preview that intercepts all touch events. */ @@ -535,33 +412,4 @@ public class LauncherPreviewRenderer extends BaseContext return true; } } - - @LauncherAppSingleton - // Exclude widget module since we bind widget holder separately - @Component(modules = {WindowManagerProxyModule.class, - ApiWrapperModule.class, - PluginManagerWrapperModule.class, - StaticObjectModule.class, - AppModule.class, - PerDisplayModule.class, - LauncherConcurrencyModule.class, - ExecutorsModule.class, - LauncherExecutorsModule.class, - NoOpWidgetPickerModule.class - }) - public interface PreviewAppComponent extends LauncherAppComponent { - - LoaderTaskFactory getLoaderTaskFactory(); - BaseLauncherBinderFactory getBaseLauncherBinderFactory(); - BgDataModel getDataModel(); - - /** Builder for NexusLauncherAppComponent. */ - @Component.Builder - interface Builder extends LauncherAppComponent.Builder { - @BindsInstance Builder bindPrefs(LauncherPrefs prefs); - @BindsInstance Builder bindParserFactory(LayoutParserFactory parserFactory); - @BindsInstance Builder bindWidgetsFactory(WidgetHolderFactory holderFactory); - PreviewAppComponent build(); - } - } } diff --git a/src/com/android/launcher3/preview/PreviewContext.kt b/src/com/android/launcher3/preview/PreviewContext.kt new file mode 100644 index 0000000000..7ead5c7e54 --- /dev/null +++ b/src/com/android/launcher3/preview/PreviewContext.kt @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2025 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.launcher3.preview + +import android.content.Context +import android.text.TextUtils +import com.android.launcher3.InvariantDeviceProfile +import com.android.launcher3.Item +import com.android.launcher3.LauncherPrefs +import com.android.launcher3.ProxyPrefs +import com.android.launcher3.WorkspaceLayoutManager +import com.android.launcher3.compose.core.widgetpicker.NoOpWidgetPickerModule +import com.android.launcher3.concurrent.ExecutorsModule +import com.android.launcher3.dagger.ApiWrapperModule +import com.android.launcher3.dagger.AppModule +import com.android.launcher3.dagger.LauncherAppComponent +import com.android.launcher3.dagger.LauncherAppSingleton +import com.android.launcher3.dagger.LauncherComponentProvider.appComponent +import com.android.launcher3.dagger.LauncherComponentProvider.get +import com.android.launcher3.dagger.LauncherConcurrencyModule +import com.android.launcher3.dagger.PerDisplayModule +import com.android.launcher3.dagger.PluginManagerWrapperModule +import com.android.launcher3.dagger.StaticObjectModule +import com.android.launcher3.dagger.WindowManagerProxyModule +import com.android.launcher3.graphics.ThemeManager +import com.android.launcher3.model.BaseLauncherBinder.BaseLauncherBinderFactory +import com.android.launcher3.model.BgDataModel +import com.android.launcher3.model.LayoutParserFactory +import com.android.launcher3.model.LayoutParserFactory.XmlLayoutParserFactory +import com.android.launcher3.model.LoaderTask.LoaderTaskFactory +import com.android.launcher3.model.data.LoaderParams +import com.android.launcher3.provider.LauncherDbUtils.selectionForWorkspaceScreen +import com.android.launcher3.util.SandboxContext +import com.android.launcher3.util.dagger.LauncherExecutorsModule +import com.android.launcher3.widget.LauncherWidgetHolder +import com.android.launcher3.widget.LauncherWidgetHolder.WidgetHolderFactory +import com.android.systemui.shared.Flags +import dagger.BindsInstance +import dagger.Component +import java.io.File +import java.util.Arrays +import java.util.UUID + +/** + * Context used just for preview. It also provides a few objects (e.g. UserCache) just for preview + * purposes. + */ +class PreviewContext +@JvmOverloads +constructor( + base: Context, + gridName: String?, + shapeKey: String?, + isMonoThemeEnabled: Boolean, + widgetHostId: Int = LauncherWidgetHolder.APPWIDGET_HOST_ID, + layoutXml: String? = null, + workspacePageId: Int = WorkspaceLayoutManager.FIRST_SCREEN_ID, +) : SandboxContext(base) { + private val mPrefName: String + + private val mDbDir: File? + + init { + val randomUid = UUID.randomUUID().toString() + mPrefName = "preview-$randomUid" + val prefs = ProxyPrefs(this, getSharedPreferences(mPrefName, MODE_PRIVATE)) + prefs.putOrRemove(LauncherPrefs.GRID_NAME, gridName) + prefs.putOrRemove(ThemeManager.PREF_ICON_SHAPE, shapeKey) + prefs.put(LauncherPrefs.FIXED_LANDSCAPE_MODE, false) + prefs.put(ThemeManager.THEMED_ICONS, isMonoThemeEnabled) + + val isTwoPanel = + base.appComponent.idp.supportedProfiles.any { it.deviceProperties.isTwoPanels } + val closestEvenPageId: Int = workspacePageId - (workspacePageId % 2) + val selectionQuery = + if (isTwoPanel) selectionForWorkspaceScreen(closestEvenPageId, closestEvenPageId + 1) + else selectionForWorkspaceScreen(workspacePageId) + + val builder = DaggerPreviewContext_PreviewAppComponent.builder().bindPrefs(prefs) + builder.bindLoaderParams( + LoaderParams( + workspaceSelection = selectionQuery, + sanitizeData = false, + loadNonWorkspaceItems = false, + ) + ) + + if (layoutXml.isNullOrEmpty() || !Flags.extendibleThemeManager()) { + mDbDir = null + builder + .bindParserFactory(LayoutParserFactory(this)) + .bindWidgetsFactory(get(base).widgetHolderFactory) + } else { + mDbDir = File(base.filesDir, randomUid) + emptyDbDir() + mDbDir.mkdirs() + builder.bindParserFactory(XmlLayoutParserFactory(this, layoutXml)).bindWidgetsFactory { + c: Context -> + LauncherWidgetHolder(c, widgetHostId).apply { startListening() } + } + } + initDaggerComponent(builder) + + if (!TextUtils.isEmpty(layoutXml)) { + // Use null the DB file so that we use a new in-memory DB + InvariantDeviceProfile.INSTANCE[this].dbFile = null + } + } + + fun LauncherPrefs.putOrRemove(item: Item, value: T?) { + if (value != null) put(item, value) else remove(item) + } + + private fun emptyDbDir() { + if (mDbDir != null && mDbDir.exists()) { + Arrays.stream(mDbDir.listFiles()).forEach { obj: File -> obj.delete() } + } + } + + override fun cleanUpObjects() { + super.cleanUpObjects() + deleteSharedPreferences(mPrefName) + if (mDbDir != null) { + emptyDbDir() + mDbDir.delete() + } + } + + override fun getDatabasePath(name: String): File { + return if (mDbDir != null) File(mDbDir, name) else super.getDatabasePath(name) + } + + @LauncherAppSingleton // Exclude widget module since we bind widget holder separately + @Component( + modules = + [ + WindowManagerProxyModule::class, + ApiWrapperModule::class, + PluginManagerWrapperModule::class, + StaticObjectModule::class, + AppModule::class, + PerDisplayModule::class, + LauncherConcurrencyModule::class, + ExecutorsModule::class, + LauncherExecutorsModule::class, + NoOpWidgetPickerModule::class, + ] + ) + interface PreviewAppComponent : LauncherAppComponent { + val loaderTaskFactory: LoaderTaskFactory + val baseLauncherBinderFactory: BaseLauncherBinderFactory + val dataModel: BgDataModel + + /** Builder for NexusLauncherAppComponent. */ + @Component.Builder + interface Builder : LauncherAppComponent.Builder { + @BindsInstance fun bindPrefs(prefs: LauncherPrefs): Builder + + @BindsInstance fun bindParserFactory(parserFactory: LayoutParserFactory): Builder + + @BindsInstance fun bindWidgetsFactory(holderFactory: WidgetHolderFactory): Builder + + @BindsInstance fun bindLoaderParams(params: LoaderParams): Builder + + override fun build(): PreviewAppComponent + } + } +} diff --git a/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java b/src/com/android/launcher3/preview/PreviewSurfaceRenderer.java similarity index 72% rename from src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java rename to src/com/android/launcher3/preview/PreviewSurfaceRenderer.java index 4f766a4281..a4de29d424 100644 --- a/src/com/android/launcher3/graphics/PreviewSurfaceRenderer.java +++ b/src/com/android/launcher3/preview/PreviewSurfaceRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2020 The Android Open Source Project + * Copyright (C) 2025 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.launcher3.graphics; +package com.android.launcher3.preview; import static android.content.res.Configuration.UI_MODE_NIGHT_NO; import static android.content.res.Configuration.UI_MODE_NIGHT_YES; @@ -35,14 +35,11 @@ import android.app.WallpaperColors; import android.appwidget.AppWidgetHost; import android.content.Context; import android.content.res.Configuration; -import android.database.Cursor; import android.hardware.display.DisplayManager; import android.os.Bundle; import android.os.IBinder; import android.text.TextUtils; import android.util.Log; -import android.util.Size; -import android.util.SparseArray; import android.util.SparseIntArray; import android.view.ContextThemeWrapper; import android.view.Display; @@ -57,17 +54,14 @@ import androidx.annotation.WorkerThread; import com.android.launcher3.DeviceProfile; import com.android.launcher3.InvariantDeviceProfile; -import com.android.launcher3.LauncherAppState; import com.android.launcher3.LauncherPrefs; -import com.android.launcher3.LauncherSettings; import com.android.launcher3.dagger.LauncherComponentProvider; -import com.android.launcher3.graphics.LauncherPreviewRenderer.PreviewAppComponent; -import com.android.launcher3.graphics.LauncherPreviewRenderer.PreviewContext; +import com.android.launcher3.graphics.GridCustomizationsProxy; import com.android.launcher3.model.BgDataModel; import com.android.launcher3.model.BgDataModel.Callbacks; import com.android.launcher3.model.LoaderTask; -import com.android.launcher3.model.ModelDbController; import com.android.launcher3.model.UserManagerState; +import com.android.launcher3.preview.PreviewContext.PreviewAppComponent; import com.android.launcher3.util.RunnableList; import com.android.launcher3.util.Themes; import com.android.launcher3.widget.LocalColorExtractor; @@ -100,12 +94,12 @@ public class PreviewSurfaceRenderer { public static final String FIXED_LANDSCAPE_GRID = "fixed_landscape_mode"; private final Context mContext; + private final String mLayoutXml; + private final int mWorkspacePageId; + private SparseIntArray mPreviewColorOverride; private String mGridName; - private String mLastSelectedGridName; private String mShapeKey; - private String mLayoutXml; - private int mWorkspacePageId; private boolean mIsMonoThemeEnabled; @Nullable private Boolean mDarkMode; @@ -142,7 +136,6 @@ public class PreviewSurfaceRenderer { if (Objects.equals(mGridName, FIXED_LANDSCAPE_GRID)) { mGridName = LauncherPrefs.get(context).get(NON_FIXED_LANDSCAPE_GRID_NAME); } - mLastSelectedGridName = mGridName; mShapeKey = LauncherPrefs.get(context).get(PREF_ICON_SHAPE); mIsMonoThemeEnabled = LauncherPrefs.get(context).get(THEMED_ICONS); mWallpaperColors = bundle.getParcelable(KEY_COLORS); @@ -202,45 +195,6 @@ public class PreviewSurfaceRenderer { setCurrentRenderer(null); } - /** - * A function that queries for the launcher app widget span info - * - * @return A SparseArray with the app widget id being the key and the span info being the values - */ - @WorkerThread - @Nullable - public SparseArray getLoadedLauncherWidgetInfo() { - final SparseArray widgetInfo = new SparseArray<>(); - final String query = LauncherSettings.Favorites.ITEM_TYPE + " = " - + LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET; - - ModelDbController mainController = - LauncherAppState.getInstance(mContext).getModel().getModelDbController(); - try (Cursor c = mainController.query( - new String[] { - LauncherSettings.Favorites.APPWIDGET_ID, - LauncherSettings.Favorites.SPANX, - LauncherSettings.Favorites.SPANY - }, query, null, null)) { - final int appWidgetIdIndex = c.getColumnIndexOrThrow( - LauncherSettings.Favorites.APPWIDGET_ID); - final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); - final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); - while (c.moveToNext()) { - final int appWidgetId = c.getInt(appWidgetIdIndex); - final int spanX = c.getInt(spanXIndex); - final int spanY = c.getInt(spanYIndex); - - widgetInfo.append(appWidgetId, new Size(spanX, spanY)); - } - } catch (Exception e) { - Log.e(TAG, "Error querying for launcher widget info", e); - return null; - } - - return widgetInfo; - } - /** * Generates the preview in background and returns the generated view */ @@ -378,78 +332,53 @@ public class PreviewSurfaceRenderer { } } - private boolean shouldReloadModelData() { - // When changing the grid, we reload the model data as the widgets would have been bound - // with last selected grid. - return InvariantDeviceProfile.INSTANCE.get(mContext).isFixedLandscape - || !mGridName.equals(mLastSelectedGridName) - || !mShapeKey.equals(LauncherPrefs.INSTANCE.get(mContext).get(PREF_ICON_SHAPE)) - || mIsMonoThemeEnabled != LauncherPrefs.INSTANCE.get(mContext).get(THEMED_ICONS) - || !TextUtils.isEmpty(mLayoutXml); - } - @WorkerThread private void loadModelData(CompletableFuture onCompleteCallback) { final Context inflationContext = getPreviewContext(); - if (shouldReloadModelData()) { - boolean isCustomLayout = extendibleThemeManager() && !TextUtils.isEmpty(mLayoutXml); - int widgetHostId = isCustomLayout ? APPWIDGET_HOST_ID + mCallingPid : APPWIDGET_HOST_ID; + boolean isCustomLayout = extendibleThemeManager() && !TextUtils.isEmpty(mLayoutXml); + int widgetHostId = isCustomLayout ? APPWIDGET_HOST_ID + mCallingPid : APPWIDGET_HOST_ID; - // Start the migration - PreviewContext previewContext = new PreviewContext( - inflationContext, mGridName, mShapeKey, widgetHostId, mLayoutXml, - mIsMonoThemeEnabled); - PreviewAppComponent appComponent = - (PreviewAppComponent) LauncherComponentProvider.get(previewContext); + // Start the migration + PreviewContext previewContext = new PreviewContext( + inflationContext, mGridName, mShapeKey, mIsMonoThemeEnabled, + widgetHostId, mLayoutXml); + PreviewAppComponent appComponent = + (PreviewAppComponent) LauncherComponentProvider.get(previewContext); - if (extendibleThemeManager() && isCustomLayout && !mDeletingHostOnExit) { - mDeletingHostOnExit = true; - mLifeCycleTracker.add(() -> { - AppWidgetHost host = new AppWidgetHost(mContext, widgetHostId); - // Start listening here, so that any previous active host is disabled - host.startListening(); - host.stopListening(); - host.deleteHost(); - }); - } - - LoaderTask task = appComponent.getLoaderTaskFactory().newLoaderTask( - appComponent.getBaseLauncherBinderFactory().createBinder(new Callbacks[0]), - new UserManagerState()); - - InvariantDeviceProfile idp = appComponent.getIDP(); - DeviceProfile deviceProfile = idp.getDeviceProfile(previewContext); - - int closestEvenPageId = mWorkspacePageId - (mWorkspacePageId % 2); - String query = deviceProfile.getDeviceProperties().isTwoPanels() - ? selectionForWorkspaceScreen(closestEvenPageId, closestEvenPageId + 1) - : selectionForWorkspaceScreen(mWorkspacePageId); - task.loadWorkspaceForPreview(query); - final SparseArray spanInfo = getLoadedLauncherWidgetInfo(); - MAIN_EXECUTOR.execute(() -> { - renderView(previewContext, appComponent.getDataModel(), spanInfo, idp, - onCompleteCallback); - mLifeCycleTracker.add(previewContext::onDestroy); - }); - } else { - LauncherAppState.getInstance(inflationContext).getModel().loadAsync(dataModel -> { - if (dataModel != null) { - MAIN_EXECUTOR.execute(() -> renderView(inflationContext, dataModel, - null, LauncherAppState.getIDP(inflationContext), onCompleteCallback)); - } else { - onCompleteCallback.completeExceptionally( - new RuntimeException("Model loading failed")); - Log.e(TAG, "Model loading failed"); - } + if (extendibleThemeManager() && isCustomLayout && !mDeletingHostOnExit) { + mDeletingHostOnExit = true; + mLifeCycleTracker.add(() -> { + AppWidgetHost host = new AppWidgetHost(mContext, widgetHostId); + // Start listening here, so that any previous active host is disabled + host.startListening(); + host.stopListening(); + host.deleteHost(); }); } - mLastSelectedGridName = mGridName; + + LoaderTask task = appComponent.getLoaderTaskFactory().newLoaderTask( + appComponent.getBaseLauncherBinderFactory().createBinder(new Callbacks[0]), + new UserManagerState()); + + InvariantDeviceProfile idp = appComponent.getIDP(); + DeviceProfile deviceProfile = idp.getDeviceProfile(previewContext); + + int closestEvenPageId = mWorkspacePageId - (mWorkspacePageId % 2); + String query = deviceProfile.getDeviceProperties().isTwoPanels() + ? selectionForWorkspaceScreen(closestEvenPageId, closestEvenPageId + 1) + : selectionForWorkspaceScreen(mWorkspacePageId); + + task.loadWorkspaceForPreview(query); + + MAIN_EXECUTOR.execute(() -> { + renderView(previewContext, appComponent.getDataModel(), idp, onCompleteCallback); + mLifeCycleTracker.add(previewContext::onDestroy); + }); } @UiThread private void renderView(Context inflationContext, BgDataModel dataModel, - @Nullable final SparseArray launcherWidgetSpanInfo, InvariantDeviceProfile idp, - CompletableFuture onCompleteCallback) { + InvariantDeviceProfile idp, CompletableFuture onCompleteCallback) { if (mDestroyed) { onCompleteCallback.completeExceptionally(new RuntimeException("Renderer destroyed")); return; @@ -457,10 +386,10 @@ public class PreviewSurfaceRenderer { LauncherPreviewRenderer renderer; if (Flags.newCustomizationPickerUi()) { renderer = new LauncherPreviewRenderer(inflationContext, idp, mPreviewColorOverride, - mWallpaperColors, mWorkspacePageId, launcherWidgetSpanInfo); + mWallpaperColors, mWorkspacePageId); } else { renderer = new LauncherPreviewRenderer(inflationContext, idp, - mWallpaperColors, mWorkspacePageId, launcherWidgetSpanInfo); + mWallpaperColors, mWorkspacePageId); } renderer.hideBottomRow(mHideQsb); renderer.populate(dataModel);