diff --git a/src/com/android/launcher3/graphics/GridCustomizationsProxy.java b/src/com/android/launcher3/graphics/GridCustomizationsProxy.java index 132591c70e..5f668c7b2a 100644 --- a/src/com/android/launcher3/graphics/GridCustomizationsProxy.java +++ b/src/com/android/launcher3/graphics/GridCustomizationsProxy.java @@ -16,7 +16,6 @@ package com.android.launcher3.graphics; import static com.android.launcher3.BuildConfig.IS_DEBUG_DEVICE; -import static com.android.launcher3.Flags.enableLauncherIconShapes; import static com.android.launcher3.preview.PreviewSurfaceRenderer.KEY_BITMAP_GENERATION_DELAY_MS; import static com.android.launcher3.preview.PreviewSurfaceRenderer.KEY_VIEW_HEIGHT; import static com.android.launcher3.preview.PreviewSurfaceRenderer.KEY_VIEW_WIDTH; @@ -38,7 +37,6 @@ import android.net.Uri; import android.os.Binder; import android.os.Bundle; import android.os.Handler; -import android.os.IBinder.DeathRecipient; import android.os.Message; import android.os.Messenger; import android.text.TextUtils; @@ -54,6 +52,7 @@ import com.android.launcher3.LauncherPrefs; import com.android.launcher3.dagger.ApplicationContext; import com.android.launcher3.dagger.LauncherAppSingleton; import com.android.launcher3.model.BgDataModel; +import com.android.launcher3.preview.PreviewLifecycleObserver; import com.android.launcher3.preview.PreviewSurfaceRenderer; import com.android.launcher3.shapes.IconShapeModel; import com.android.launcher3.shapes.ShapesProvider; @@ -114,7 +113,7 @@ public class GridCustomizationsProxy implements ProxyProvider { private static final String KEY_PREVIEW_COUNT = "preview_count"; // is_default means if a certain option is currently set to the system private static final String KEY_IS_DEFAULT = "is_default"; - private static final String KEY_SHAPE_KEY = "shape_key"; + public static final String KEY_SHAPE_KEY = "shape_key"; private static final String KEY_SHAPE_TITLE = "shape_title"; private static final String KEY_PATH = "path"; @@ -122,8 +121,8 @@ public class GridCustomizationsProxy implements ProxyProvider { private static final String KEY_LIST_OPTIONS = "/list_options"; private static final String KEY_SHAPE_OPTIONS = "/shape_options"; // default_grid is for setting grid and shape to system settings - private static final String KEY_DEFAULT_GRID = "/default_grid"; - private static final String SET_SHAPE = "/shape"; + public static final String KEY_DEFAULT_GRID = "/default_grid"; + public static final String SET_SHAPE = "/shape"; private static final String METHOD_GET_PREVIEW = "get_preview"; public static final String METHOD_GET_PREVIEW_BITMAP = "get_preview_bitmap"; @@ -131,8 +130,8 @@ public class GridCustomizationsProxy implements ProxyProvider { /** These methods are used to set monochrome theme */ private static final String GET_ICON_THEMED = "/get_icon_themed"; private static final String SET_ICON_THEMED = "/set_icon_themed"; - private static final String ICON_THEMED = "/icon_themed"; - private static final String BOOLEAN_VALUE = "boolean_value"; + public static final String ICON_THEMED = "/icon_themed"; + public static final String BOOLEAN_VALUE = "boolean_value"; private static final String KEY_SURFACE_PACKAGE = "surface_package"; private static final String KEY_CALLBACK = "callback"; @@ -140,11 +139,7 @@ public class GridCustomizationsProxy implements ProxyProvider { public static final String KEY_GRID_NAME = "grid_name"; public static final String KEY_IMAGE = "image"; - private static final int MESSAGE_ID_UPDATE_PREVIEW = 1337; - private static final int MESSAGE_ID_UPDATE_SHAPE = 2586; - private static final int MESSAGE_ID_UPDATE_GRID = 7414; - private static final int MESSAGE_ID_UPDATE_COLOR = 856; - private static final int MESSAGE_ID_UPDATE_ICON_THEMED = 311; + public static final String KEY_UPDATE_METHOD = "update_method"; // Set of all active previews used to track duplicate memory allocations private final Set mActivePreviews = @@ -271,9 +266,19 @@ public class GridCustomizationsProxy implements ProxyProvider { if (path == null) { return 0; } + + int result = handleUpdate(path, values); + if (result != 0) { + mContext.getContentResolver().notifyChange(uri, null); + } + return result; + } + + public int handleUpdate(@NonNull String path, ContentValues values) { switch (path) { case KEY_DEFAULT_GRID: { String gridName = values.getAsString(KEY_NAME); + gridName = gridName == null ? values.getAsString(KEY_GRID_NAME) : gridName; // Verify that this is a valid grid option GridOption match = null; for (GridOption option : mIdp.parseAllGridOptions(mContext)) { @@ -295,7 +300,6 @@ public class GridCustomizationsProxy implements ProxyProvider { Log.e(TAG, "Fail to load model", e); } } - mContext.getContentResolver().notifyChange(uri, null); return 1; } case SET_SHAPE: @@ -307,7 +311,6 @@ public class GridCustomizationsProxy implements ProxyProvider { case ICON_THEMED: case SET_ICON_THEMED: { mThemeManager.setMonoThemeEnabled(values.getAsBoolean(BOOLEAN_VALUE)); - mContext.getContentResolver().notifyChange(uri, null); return 1; } default: @@ -407,79 +410,6 @@ public class GridCustomizationsProxy implements ProxyProvider { } } - private static class PreviewLifecycleObserver implements Handler.Callback, DeathRecipient { - - public final RunnableList lifeCycleTracker; - public final PreviewSurfaceRenderer renderer; - public boolean destroyed = false; - - PreviewLifecycleObserver( - RunnableList lifeCycleTracker, - PreviewSurfaceRenderer renderer) { - this.lifeCycleTracker = lifeCycleTracker; - this.renderer = renderer; - lifeCycleTracker.add(() -> destroyed = true); - } - - @Override - public boolean handleMessage(Message message) { - if (destroyed) { - return true; - } - - switch (message.what) { - case MESSAGE_ID_UPDATE_PREVIEW: - renderer.hideBottomRow(message.getData().getBoolean(KEY_HIDE_BOTTOM_ROW)); - break; - case MESSAGE_ID_UPDATE_SHAPE: - if (Flags.newCustomizationPickerUi() - && enableLauncherIconShapes()) { - String shapeKey = message.getData().getString(KEY_SHAPE_KEY); - if (!TextUtils.isEmpty(shapeKey)) { - renderer.updateShape(shapeKey); - } - } - break; - case MESSAGE_ID_UPDATE_GRID: - String gridName = message.getData().getString(KEY_GRID_NAME); - renderer.updateGrid(gridName); - break; - case MESSAGE_ID_UPDATE_COLOR: - if (Flags.newCustomizationPickerUi()) { - renderer.previewColor(message.getData()); - } - break; - case MESSAGE_ID_UPDATE_ICON_THEMED: - if (Flags.newCustomizationPickerUi()) { - boolean iconThemed = message.getData().getBoolean(BOOLEAN_VALUE); - renderer.updateTheme(iconThemed); - } - break; - default: - // Unknown command, destroy lifecycle - Log.d(TAG, "Unknown preview command: " + message.what + ", destroying preview"); - MAIN_EXECUTOR.execute(lifeCycleTracker::executeAllAndDestroy); - break; - } - - return true; - } - - @Override - public void binderDied() { - MAIN_EXECUTOR.execute(lifeCycleTracker::executeAllAndDestroy); - } - - /** - * Two renderers are considered same if they have the same host token and display Id - */ - public boolean isSameRenderer(PreviewLifecycleObserver plo) { - return plo != null - && plo.renderer.getHostToken().equals(renderer.getHostToken()) - && plo.renderer.getDisplayId() == renderer.getDisplayId(); - } - } - /** * A WeakReference wrapper around Handler.Callback to avoid passing hard-reference over IPC * when using a Messenger diff --git a/src/com/android/launcher3/model/LoaderTask.java b/src/com/android/launcher3/model/LoaderTask.java index 5f5c7f2a05..c0bd0ef2c9 100644 --- a/src/com/android/launcher3/model/LoaderTask.java +++ b/src/com/android/launcher3/model/LoaderTask.java @@ -259,8 +259,14 @@ public class LoaderTask implements Runnable { LoaderMemoryLogger memoryLogger, LauncherRestoreEventLogger restoreEventLogger) { List allShortcuts = new ArrayList<>(); - loadWorkspace( - allShortcuts, mParams.getWorkspaceSelection(), memoryLogger, restoreEventLogger); + Trace.beginSection("LoadWorkspace"); + try { + loadWorkspaceImpl(allShortcuts, mParams.getWorkspaceSelection(), memoryLogger, + restoreEventLogger); + } finally { + Trace.endSection(); + } + logASplit("loadWorkspace finished"); // 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 @@ -416,25 +422,6 @@ public class LoaderTask implements Runnable { this.notify(); } - public void loadWorkspaceForPreview(String selection) { - loadWorkspace(new ArrayList<>(), selection, null, null); - } - - private void loadWorkspace( - List allDeepShortcuts, - String selection, - @Nullable LoaderMemoryLogger memoryLogger, - @Nullable LauncherRestoreEventLogger restoreEventLogger - ) { - Trace.beginSection("LoadWorkspace"); - try { - loadWorkspaceImpl(allDeepShortcuts, selection, memoryLogger, restoreEventLogger); - } finally { - Trace.endSection(); - } - logASplit("loadWorkspace finished"); - } - private void loadWorkspaceImpl( List allDeepShortcuts, String selection, diff --git a/src/com/android/launcher3/model/ModelInitializer.kt b/src/com/android/launcher3/model/ModelInitializer.kt index 4e4a6febd4..4a4e5f102e 100644 --- a/src/com/android/launcher3/model/ModelInitializer.kt +++ b/src/com/android/launcher3/model/ModelInitializer.kt @@ -64,23 +64,7 @@ constructor( ) { fun initialize(model: LauncherModel) { - fun refreshAndReloadLauncher() { - iconPool.clear() - iconCache.updateIconParams(idp.fillResIconDpi, idp.iconBitmapSize) - model.forceReload() - } - - // IDP changes - val idpChangeListener = OnIDPChangeListener { modelChanged -> - if (modelChanged) refreshAndReloadLauncher() - } - idp.addOnChangeListener(idpChangeListener) - lifeCycle.addCloseable { idp.removeOnChangeListener(idpChangeListener) } - - // Theme changes - val themeChangeListener = ThemeChangeListener { refreshAndReloadLauncher() } - themeManager.addChangeListener(themeChangeListener) - lifeCycle.addCloseable { themeManager.removeChangeListener(themeChangeListener) } + initializeDisplayEvents(model) // System changes val modelCallbacks = model.newModelCallbacks() @@ -140,13 +124,33 @@ constructor( // Custom widgets lifeCycle.addCloseable(customWidgetManager.addWidgetRefreshCallback(model::rebindCallbacks)) + // Install session changes + lifeCycle.addCloseable(installSessionHelper.registerInstallTracker(modelCallbacks)) + } + + fun initializeDisplayEvents(model: LauncherModel) { + fun refreshAndReloadLauncher() { + iconPool.clear() + iconCache.updateIconParams(idp.fillResIconDpi, idp.iconBitmapSize) + model.forceReload() + } + + // IDP changes + val idpChangeListener = OnIDPChangeListener { modelChanged -> + if (modelChanged) refreshAndReloadLauncher() + } + idp.addOnChangeListener(idpChangeListener) + lifeCycle.addCloseable { idp.removeOnChangeListener(idpChangeListener) } + + // Theme changes + val themeChangeListener = ThemeChangeListener { refreshAndReloadLauncher() } + themeManager.addChangeListener(themeChangeListener) + lifeCycle.addCloseable { themeManager.removeChangeListener(themeChangeListener) } + // Icon changes lifeCycle.addCloseable( iconProvider.registerIconChangeListener(model::onAppIconChanged, MODEL_EXECUTOR.handler) ) - - // Install session changes - lifeCycle.addCloseable(installSessionHelper.registerInstallTracker(modelCallbacks)) } companion object { diff --git a/src/com/android/launcher3/preview/LauncherPreviewRenderer.java b/src/com/android/launcher3/preview/LauncherPreviewRenderer.java index 487cb6417f..8257027bf9 100644 --- a/src/com/android/launcher3/preview/LauncherPreviewRenderer.java +++ b/src/com/android/launcher3/preview/LauncherPreviewRenderer.java @@ -15,7 +15,6 @@ */ package com.android.launcher3.preview; -import static android.app.WallpaperManager.FLAG_SYSTEM; import static android.view.View.MeasureSpec.EXACTLY; import static android.view.View.MeasureSpec.makeMeasureSpec; import static android.view.View.VISIBLE; @@ -27,8 +26,6 @@ import static com.android.launcher3.model.ModelUtils.currentScreenContentFilter; import static java.util.Comparator.comparingDouble; import android.app.Fragment; -import android.app.WallpaperColors; -import android.app.WallpaperManager; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; @@ -46,6 +43,8 @@ import android.view.ViewGroup; import android.widget.TextClock; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.UiThread; import androidx.lifecycle.DefaultLifecycleObserver; import androidx.lifecycle.LifecycleOwner; @@ -55,29 +54,34 @@ import com.android.launcher3.DeviceProfile; import com.android.launcher3.Hotseat; import com.android.launcher3.InsettableFrameLayout; import com.android.launcher3.InvariantDeviceProfile; +import com.android.launcher3.LauncherModel; import com.android.launcher3.R; +import com.android.launcher3.Workspace; import com.android.launcher3.WorkspaceLayoutManager; import com.android.launcher3.celllayout.CellLayoutLayoutParams; import com.android.launcher3.celllayout.CellPosMapper; import com.android.launcher3.dagger.LauncherComponentProvider; +import com.android.launcher3.dragndrop.SimpleDragLayer; import com.android.launcher3.graphics.FragmentWithPreview; import com.android.launcher3.model.BgDataModel; import com.android.launcher3.model.data.ItemInfo; +import com.android.launcher3.model.data.WorkspaceData; 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.Themes; +import com.android.launcher3.util.LauncherBindableItemsContainer; import com.android.launcher3.util.window.WindowManagerProxy; import com.android.launcher3.views.BaseDragLayer; import com.android.launcher3.widget.LauncherWidgetHolder; -import com.android.launcher3.widget.LocalColorExtractor; -import com.android.systemui.shared.Flags; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; /** * Utility class for generating the preview of Launcher for a given InvariantDeviceProfile. @@ -88,38 +92,33 @@ import java.util.Map; * 4) Measure and draw the view on a canvas */ public class LauncherPreviewRenderer extends BaseContext - implements WorkspaceLayoutManager, LayoutInflater.Factory2 { + implements WorkspaceLayoutManager, LayoutInflater.Factory2, + LauncherBindableItemsContainer, BgDataModel.Callbacks { + + public final CompletableFuture initialRender = new CompletableFuture<>(); private final Handler mUiHandler; private final InvariantDeviceProfile mIdp; private final DeviceProfile mDp; - private final Rect mInsets; private final LayoutInflater mHomeElementInflater; - private final InsettableFrameLayout mRootView; + private final LauncherPreviewLayout mRootView; private final Hotseat mHotseat; private final Map mWorkspaceScreens = new HashMap<>(); private final ItemInflater mItemInflater; public LauncherPreviewRenderer(Context context, - InvariantDeviceProfile idp, - WallpaperColors wallpaperColorsOverride, - int workspaceScreenId) { - this(context, idp, null, wallpaperColorsOverride, workspaceScreenId); - } + int workspaceScreenId, + @Nullable SparseIntArray wallpaperColorResources, + LauncherModel model, + int themeRes) { - public LauncherPreviewRenderer(Context context, - InvariantDeviceProfile idp, - SparseIntArray previewColorOverride, - WallpaperColors wallpaperColorsOverride, - int workspaceScreenId) { - - super(context, Themes.getActivityThemeRes(context)); + super(context, themeRes); mUiHandler = new Handler(Looper.getMainLooper()); - mIdp = idp; + mIdp = InvariantDeviceProfile.INSTANCE.get(context); mDp = getDeviceProfileForPreview(context).toBuilder(context) .setViewScaleProvider(new PreviewScaleProvider(this)).build(); - mInsets = getInsets(context); - mDp.updateInsets(mInsets); + Rect insets = getInsets(context); + mDp.updateInsets(insets); mHomeElementInflater = LayoutInflater.from( new ContextThemeWrapper(this, R.style.HomeScreenElementTheme)); @@ -128,9 +127,9 @@ public class LauncherPreviewRenderer extends BaseContext int layoutRes = mDp.getDeviceProperties().isTwoPanels() ? R.layout.launcher_preview_two_panel_layout : R.layout.launcher_preview_layout; - mRootView = (InsettableFrameLayout) mHomeElementInflater.inflate( + mRootView = (LauncherPreviewLayout) mHomeElementInflater.inflate( layoutRes, null, false); - mRootView.setInsets(mInsets); + mRootView.setInsets(insets); measureAndLayoutRootView(); mHotseat = mRootView.findViewById(R.id.hotseat); @@ -161,31 +160,6 @@ public class LauncherPreviewRenderer extends BaseContext mWorkspaceScreens.put(workspaceScreenId, firstScreen); } - SparseIntArray wallpaperColorResources; - if (Flags.newCustomizationPickerUi()) { - if (previewColorOverride != null) { - wallpaperColorResources = previewColorOverride; - } else if (wallpaperColorsOverride != null) { - wallpaperColorResources = LocalColorExtractor.newInstance( - context).generateColorsOverride(wallpaperColorsOverride); - } else { - WallpaperColors wallpaperColors = WallpaperManager.getInstance( - context).getWallpaperColors(FLAG_SYSTEM); - wallpaperColorResources = wallpaperColors != null - ? LocalColorExtractor.newInstance(context).generateColorsOverride( - wallpaperColors) - : null; - } - } else { - WallpaperColors wallpaperColors = wallpaperColorsOverride != null - ? wallpaperColorsOverride - : WallpaperManager.getInstance(context).getWallpaperColors(FLAG_SYSTEM); - wallpaperColorResources = wallpaperColors != null - ? LocalColorExtractor.newInstance(context).generateColorsOverride( - wallpaperColors) - : null; - } - LauncherWidgetHolder widgetHolder = LauncherComponentProvider.get(this) .getWidgetHolderFactory().newInstance(this); if (wallpaperColorResources != null) { @@ -201,9 +175,11 @@ public class LauncherPreviewRenderer extends BaseContext mHotseat ); onViewCreated(); + model.addCallbacksAndLoad(this); getLifecycle().addObserver(new DefaultLifecycleObserver() { @Override public void onDestroy(@NonNull LifecycleOwner owner) { + model.removeCallbacks(LauncherPreviewRenderer.this); widgetHolder.destroy(); } }); @@ -214,6 +190,27 @@ public class LauncherPreviewRenderer extends BaseContext return mRootView; } + @NonNull + @Override + public LauncherBindableItemsContainer getContent() { + return this; + } + + @Override + public BaseDragLayer getDragLayer() { + return mRootView; + } + + @Override + public DeviceProfile getDeviceProfile() { + return mDp; + } + + @Override + public Hotseat getHotseat() { + return mHotseat; + } + /** * Returns the device profile based on resource configuration for previewing various display * sizes @@ -229,20 +226,6 @@ public class LauncherPreviewRenderer extends BaseContext ); } - /** - * Returns the insets of the screen closest to the display given by the context - */ - private Rect getInsets(Context context) { - Display display = context.getDisplay(); - return DisplayController.INSTANCE.get(context).getInfo().supportedBounds.stream() - .filter(w -> w.rotationHint == display.getRotation()) - .min(comparingDouble(w -> - Math.pow(display.getWidth() - w.availableSize.x, 2) - + Math.pow(display.getHeight() - w.availableSize.y, 2))) - .map(w -> new Rect(w.insets)) - .orElse(new Rect()); - } - @Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { if ("TextClock".equals(name)) { @@ -275,38 +258,22 @@ public class LauncherPreviewRenderer extends BaseContext return onCreateView(null, name, context, attrs); } - @Override - public BaseDragLayer getDragLayer() { - throw new UnsupportedOperationException(); - } - - @Override - public DeviceProfile getDeviceProfile() { - return mDp; - } - - @Override - public Hotseat getHotseat() { - return mHotseat; - } - /** * Hides the components in the bottom row. * * @param hide True to hide and false to show. */ + @UiThread public void hideBottomRow(boolean hide) { - mUiHandler.post(() -> { - if (mDp.isTaskbarPresent) { - // hotseat icons on bottom - mHotseat.setIconsAlpha(hide ? 0 : 1, ALPHA_CHANNEL_PREVIEW_RENDERER); - if (mDp.isQsbInline) { - mHotseat.setQsbAlpha(hide ? 0 : 1, ALPHA_CHANNEL_PREVIEW_RENDERER); - } - } else { + if (mDp.isTaskbarPresent) { + // hotseat icons on bottom + mHotseat.setIconsAlpha(hide ? 0 : 1, ALPHA_CHANNEL_PREVIEW_RENDERER); + if (mDp.isQsbInline) { mHotseat.setQsbAlpha(hide ? 0 : 1, ALPHA_CHANNEL_PREVIEW_RENDERER); } - }); + } else { + mHotseat.setQsbAlpha(hide ? 0 : 1, ALPHA_CHANNEL_PREVIEW_RENDERER); + } } @Override @@ -319,6 +286,18 @@ public class LauncherPreviewRenderer extends BaseContext return CellPosMapper.DEFAULT; } + private List getAllLayouts() { + List screens = new ArrayList<>(mWorkspaceScreens.values()); + screens.add(getHotseat()); + return screens; + } + + @Nullable + @Override + public View mapOverItems(@NonNull ItemOperator op) { + return Workspace.mapOverCellLayouts(getAllLayouts().toArray(new CellLayout[0]), op); + } + private void dispatchVisibilityAggregated(View view, boolean isVisible) { // Similar to View.dispatchVisibilityAggregated implementation. final boolean thisVisible = view.getVisibility() == VISIBLE; @@ -336,14 +315,15 @@ public class LauncherPreviewRenderer extends BaseContext } } - /** Populate preview and render it. */ - public void populate(BgDataModel dataModel) { + @Override + public void bindCompleteModel(@NonNull WorkspaceData itemIdMap, boolean isBindingSync) { + getAllLayouts().forEach(CellLayout::removeAllViews); + // Separate the items that are on the current screen, and the other remaining items. - dataModel.itemsIdMap.stream() + itemIdMap.stream() .filter(currentScreenContentFilter(IntSet.wrap(mWorkspaceScreens.keySet()))) .forEach(this::inflateAndAdd); - populateHotseatPredictions(dataModel); - + populateHotseatPredictions(itemIdMap); // Add first page QSB if (BuildConfig.QSB_ON_FIRST_SCREEN) { @@ -358,17 +338,21 @@ public class LauncherPreviewRenderer extends BaseContext firstScreen.addViewToCellLayout(qsb, 0, R.id.search_container_workspace, lp, true); } } - measureAndLayoutRootView(); dispatchVisibilityAggregated(mRootView, true); measureAndLayoutRootView(); // Additional measure for views which use auto text size API measureAndLayoutRootView(); + initialRender.complete(mRootView); } - private void populateHotseatPredictions(BgDataModel dataModel) { - List predictions = dataModel.itemsIdMap - .getPredictedContents(CONTAINER_HOTSEAT_PREDICTION); + @Override + public void bindItemsUpdated(@NonNull Set updates) { + updateContainerItems(updates, this); + } + + private void populateHotseatPredictions(WorkspaceData itemIdMap) { + List predictions = itemIdMap.getPredictedContents(CONTAINER_HOTSEAT_PREDICTION); int predictionIndex = 0; for (int rank = 0; rank < mDp.numShownHotseatIcons; rank++) { if (predictions.size() <= predictionIndex) continue; @@ -402,8 +386,22 @@ public class LauncherPreviewRenderer extends BaseContext mRootView.layout(0, 0, width, height); } + /** + * Returns the insets of the screen closest to the display given by the context + */ + private static Rect getInsets(Context context) { + Display display = context.getDisplay(); + return DisplayController.INSTANCE.get(context).getInfo().supportedBounds.stream() + .filter(w -> w.rotationHint == display.getRotation()) + .min(comparingDouble(w -> + Math.pow(display.getWidth() - w.availableSize.x, 2) + + Math.pow(display.getHeight() - w.availableSize.y, 2))) + .map(w -> new Rect(w.insets)) + .orElse(new Rect()); + } + /** Root layout for launcher preview that intercepts all touch events. */ - public static class LauncherPreviewLayout extends InsettableFrameLayout { + public static class LauncherPreviewLayout extends SimpleDragLayer { public LauncherPreviewLayout(Context context, AttributeSet attrs) { super(context, attrs); } diff --git a/src/com/android/launcher3/preview/PreviewContext.kt b/src/com/android/launcher3/preview/PreviewContext.kt index 2d6bdb33c6..3678ad9425 100644 --- a/src/com/android/launcher3/preview/PreviewContext.kt +++ b/src/com/android/launcher3/preview/PreviewContext.kt @@ -20,6 +20,7 @@ import android.content.Context import android.text.TextUtils import com.android.launcher3.InvariantDeviceProfile import com.android.launcher3.Item +import com.android.launcher3.LauncherModel import com.android.launcher3.LauncherPrefs import com.android.launcher3.ProxyPrefs import com.android.launcher3.WorkspaceLayoutManager @@ -35,12 +36,9 @@ 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.ModelInitializer import com.android.launcher3.model.data.LoaderParams import com.android.launcher3.provider.LauncherDbUtils.selectionForWorkspaceScreen import com.android.launcher3.util.SandboxContext @@ -64,8 +62,6 @@ class PreviewContext constructor( base: Context, gridName: String?, - shapeKey: String?, - isMonoThemeEnabled: Boolean, widgetHostId: Int = LauncherWidgetHolder.APPWIDGET_HOST_ID, layoutXml: String? = null, workspacePageId: Int = WorkspaceLayoutManager.FIRST_SCREEN_ID, @@ -79,9 +75,7 @@ constructor( 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 } @@ -174,9 +168,8 @@ constructor( ] ) interface PreviewAppComponent : LauncherAppComponent { - val loaderTaskFactory: LoaderTaskFactory - val baseLauncherBinderFactory: BaseLauncherBinderFactory - val dataModel: BgDataModel + val model: LauncherModel + val modelInitializer: ModelInitializer /** Builder for NexusLauncherAppComponent. */ @Component.Builder diff --git a/src/com/android/launcher3/preview/PreviewLifecycleObserver.kt b/src/com/android/launcher3/preview/PreviewLifecycleObserver.kt new file mode 100644 index 0000000000..9827c47fe5 --- /dev/null +++ b/src/com/android/launcher3/preview/PreviewLifecycleObserver.kt @@ -0,0 +1,117 @@ +/* + * 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.ContentValues +import android.os.Bundle +import android.os.Handler.Callback +import android.os.IBinder.DeathRecipient +import android.os.Message +import android.util.Log +import com.android.launcher3.graphics.GridCustomizationsProxy.ICON_THEMED +import com.android.launcher3.graphics.GridCustomizationsProxy.KEY_DEFAULT_GRID +import com.android.launcher3.graphics.GridCustomizationsProxy.KEY_HIDE_BOTTOM_ROW +import com.android.launcher3.graphics.GridCustomizationsProxy.KEY_UPDATE_METHOD +import com.android.launcher3.graphics.GridCustomizationsProxy.SET_SHAPE +import com.android.launcher3.util.Executors +import com.android.launcher3.util.RunnableList +import com.android.systemui.shared.Flags + +class PreviewLifecycleObserver( + @JvmField val lifeCycleTracker: RunnableList, + @JvmField val renderer: PreviewSurfaceRenderer, +) : Callback, DeathRecipient { + var destroyed: Boolean = false + private set + + init { + lifeCycleTracker.add { destroyed = true } + } + + private fun executeUpdate(command: String, values: Bundle) { + renderer.customizationDelegate.handleUpdate( + command, + ContentValues().apply { + valueSet() + .addAll( + values + .keySet() + .associateBy(keySelector = { it }, valueTransform = { values.get(it) }) + .entries + ) + }, + ) + } + + override fun handleMessage(message: Message): Boolean { + if (destroyed) { + return true + } + + when (message.what) { + MESSAGE_ID_UPDATE_PREVIEW -> + renderer.hideBottomRow(message.data.getBoolean(KEY_HIDE_BOTTOM_ROW)) + + MESSAGE_ID_UPDATE_COLOR -> + if (Flags.newCustomizationPickerUi()) renderer.previewColor(message.data) + + MESSAGE_ID_UPDATE_SHAPE -> executeUpdate(SET_SHAPE, message.data) + + MESSAGE_ID_UPDATE_GRID -> executeUpdate(KEY_DEFAULT_GRID, message.data) + + MESSAGE_ID_UPDATE_ICON_THEMED -> executeUpdate(ICON_THEMED, message.data) + + MESSAGE_ID_UPDATE_COMMAND -> + executeUpdate(message.data.getString(KEY_UPDATE_METHOD) ?: "", message.data) + + else -> { + // Unknown command, destroy lifecycle + Log.d(TAG, "Unknown preview command: " + message.what + ", destroying preview") + Executors.MAIN_EXECUTOR.execute { lifeCycleTracker.executeAllAndDestroy() } + } + } + + return true + } + + override fun binderDied() = + Executors.MAIN_EXECUTOR.execute { lifeCycleTracker.executeAllAndDestroy() } + + /** Two renderers are considered same if they have the same host token and display Id */ + fun isSameRenderer(plo: PreviewLifecycleObserver?): Boolean = + plo != null && + plo.renderer.hostToken == renderer.hostToken && + plo.renderer.displayId == renderer.displayId + + companion object { + const val TAG: String = "PreviewLifecycleObserver" + private const val MESSAGE_ID_UPDATE_PREVIEW = 1337 + private const val MESSAGE_ID_UPDATE_COLOR = 856 + + @Deprecated("Use [MESSAGE_ID_UPDATE_COMMAND] instead") + private const val MESSAGE_ID_UPDATE_SHAPE = 2586 + @Deprecated("Use [MESSAGE_ID_UPDATE_COMMAND] instead") + private const val MESSAGE_ID_UPDATE_GRID = 7414 + @Deprecated("Use [MESSAGE_ID_UPDATE_COMMAND] instead") + private const val MESSAGE_ID_UPDATE_ICON_THEMED = 311 + + /** + * A generic message which delegates the actual update to the customization API The method + * should be keyed using [KEY_UPDATE_METHOD] along with any additional parameters + */ + private const val MESSAGE_ID_UPDATE_COMMAND = 512 + } +} diff --git a/src/com/android/launcher3/preview/PreviewSurfaceRenderer.java b/src/com/android/launcher3/preview/PreviewSurfaceRenderer.java index a4de29d424..b4c9ad4ecb 100644 --- a/src/com/android/launcher3/preview/PreviewSurfaceRenderer.java +++ b/src/com/android/launcher3/preview/PreviewSurfaceRenderer.java @@ -16,6 +16,7 @@ package com.android.launcher3.preview; +import static android.app.WallpaperManager.FLAG_SYSTEM; import static android.content.res.Configuration.UI_MODE_NIGHT_NO; import static android.content.res.Configuration.UI_MODE_NIGHT_YES; import static android.view.Display.DEFAULT_DISPLAY; @@ -23,15 +24,12 @@ import static android.view.Display.DEFAULT_DISPLAY; import static com.android.launcher3.LauncherPrefs.GRID_NAME; import static com.android.launcher3.LauncherPrefs.NON_FIXED_LANDSCAPE_GRID_NAME; import static com.android.launcher3.WorkspaceLayoutManager.FIRST_SCREEN_ID; -import static com.android.launcher3.graphics.ThemeManager.PREF_ICON_SHAPE; -import static com.android.launcher3.graphics.ThemeManager.THEMED_ICONS; -import static com.android.launcher3.provider.LauncherDbUtils.selectionForWorkspaceScreen; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; -import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; import static com.android.launcher3.widget.LauncherWidgetHolder.APPWIDGET_HOST_ID; import static com.android.systemui.shared.Flags.extendibleThemeManager; import android.app.WallpaperColors; +import android.app.WallpaperManager; import android.appwidget.AppWidgetHost; import android.content.Context; import android.content.res.Configuration; @@ -39,7 +37,6 @@ import android.hardware.display.DisplayManager; import android.os.Bundle; import android.os.IBinder; import android.text.TextUtils; -import android.util.Log; import android.util.SparseIntArray; import android.view.ContextThemeWrapper; import android.view.Display; @@ -50,17 +47,10 @@ import android.widget.FrameLayout; import androidx.annotation.Nullable; import androidx.annotation.UiThread; -import androidx.annotation.WorkerThread; -import com.android.launcher3.DeviceProfile; -import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.LauncherPrefs; import com.android.launcher3.dagger.LauncherComponentProvider; 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.UserManagerState; import com.android.launcher3.preview.PreviewContext.PreviewAppComponent; import com.android.launcher3.util.RunnableList; import com.android.launcher3.util.Themes; @@ -69,13 +59,13 @@ import com.android.systemui.shared.Flags; import java.util.Objects; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** Render preview using surface view. */ @SuppressWarnings("NewApi") public class PreviewSurfaceRenderer { - private static final String TAG = "PreviewSurfaceRenderer"; public static final int FADE_IN_ANIMATION_DURATION = 200; public static final String KEY_HOST_TOKEN = "host_token"; public static final String KEY_VIEW_WIDTH = "width"; @@ -94,27 +84,24 @@ 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 final PreviewContext mPreviewContext; + private final PreviewAppComponent mAppComponent; + + private SparseIntArray mPreviewColorOverride; - private String mGridName; - private String mShapeKey; - private boolean mIsMonoThemeEnabled; @Nullable private Boolean mDarkMode; private boolean mDestroyed = false; private boolean mHideQsb; @Nullable private FrameLayout mViewRoot = null; - private boolean mDeletingHostOnExit = false; - private final int mCallingPid; private final IBinder mHostToken; private final int mWidth; private final int mHeight; private final boolean mSkipAnimations; private final int mDisplayId; - private final Display mDisplay; private final WallpaperColors mWallpaperColors; private final RunnableList mLifeCycleTracker; private final SurfaceControlViewHost mSurfaceControlViewHost; @@ -127,17 +114,7 @@ public class PreviewSurfaceRenderer { int callingPid, boolean skipAnimations) throws Exception { mContext = context; mLifeCycleTracker = lifecycleTracker; - mCallingPid = callingPid; - mGridName = bundle.getString("name"); - bundle.remove("name"); - if (mGridName == null) { - mGridName = LauncherPrefs.get(context).get(GRID_NAME); - } - if (Objects.equals(mGridName, FIXED_LANDSCAPE_GRID)) { - mGridName = LauncherPrefs.get(context).get(NON_FIXED_LANDSCAPE_GRID_NAME); - } - mShapeKey = LauncherPrefs.get(context).get(PREF_ICON_SHAPE); - mIsMonoThemeEnabled = LauncherPrefs.get(context).get(THEMED_ICONS); + mWallpaperColors = bundle.getParcelable(KEY_COLORS); if (Flags.newCustomizationPickerUi()) { updateColorOverrides(bundle); @@ -149,11 +126,10 @@ public class PreviewSurfaceRenderer { mHeight = bundle.getInt(KEY_VIEW_HEIGHT); mSkipAnimations = skipAnimations; mDisplayId = bundle.getInt(KEY_DISPLAY_ID); - mDisplay = context.getSystemService(DisplayManager.class) + Display display = context.getSystemService(DisplayManager.class) .getDisplay(mDisplayId); - mLayoutXml = bundle.getString(KEY_LAYOUT_XML); mWorkspacePageId = bundle.getInt(KEY_WORKSPACE_PAGE_ID, FIRST_SCREEN_ID); - if (mDisplay == null) { + if (display == null) { throw new IllegalArgumentException("Display ID does not match any displays."); } @@ -164,6 +140,48 @@ public class PreviewSurfaceRenderer { mLifeCycleTracker)) .get(5, TimeUnit.SECONDS); mLifeCycleTracker.add(this::destroy); + + // Create the preview context + String layoutXml = bundle.getString(KEY_LAYOUT_XML); + boolean isCustomLayout = extendibleThemeManager() && !TextUtils.isEmpty(layoutXml); + int widgetHostId = isCustomLayout ? APPWIDGET_HOST_ID + callingPid : APPWIDGET_HOST_ID; + + + String gridName = bundle.getString("name"); + bundle.remove("name"); + if (gridName == null) { + gridName = LauncherPrefs.get(context).get(GRID_NAME); + } + if (Objects.equals(gridName, FIXED_LANDSCAPE_GRID)) { + gridName = LauncherPrefs.get(context).get(NON_FIXED_LANDSCAPE_GRID_NAME); + } + + mPreviewContext = new PreviewContext( + context.createDisplayContext(display), + gridName, + widgetHostId, + layoutXml); + mAppComponent = (PreviewAppComponent) LauncherComponentProvider.get(mPreviewContext); + mLifeCycleTracker.add(mPreviewContext::onDestroy); + + // Initialize events related to display of existing items + mAppComponent.getModelInitializer().initializeDisplayEvents(mAppComponent.getModel()); + + // When using a custom layout, reset the widget host on destroy + if (extendibleThemeManager() && isCustomLayout) { + 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(); + }); + } + + MAIN_EXECUTOR.submit(() -> { + mAppComponent.getIDP().addOnChangeListener(c -> recreatePreviewRenderer()); + recreatePreviewRenderer(); + }).get(); } public int getDisplayId() { @@ -178,13 +196,6 @@ public class PreviewSurfaceRenderer { return mSurfaceControlViewHost; } - private void setCurrentRenderer(LauncherPreviewRenderer renderer) { - if (mCurrentRenderer != null) { - mCurrentRenderer.onViewDestroyed(); - } - mCurrentRenderer = renderer; - } - private void destroy() { mDestroyed = true; if (mSurfacePackage != null) { @@ -192,63 +203,23 @@ public class PreviewSurfaceRenderer { mSurfacePackage = null; } mSurfaceControlViewHost.release(); - setCurrentRenderer(null); + MAIN_EXECUTOR.execute(this::destroyExistingRenderer); + } + + @UiThread + private void destroyExistingRenderer() { + if (mCurrentRenderer != null) { + mCurrentRenderer.onViewDestroyed(); + } + mCurrentRenderer = null; } /** * Generates the preview in background and returns the generated view */ public CompletableFuture loadAsync() { - CompletableFuture result = new CompletableFuture<>(); - MODEL_EXECUTOR.execute(() -> loadModelData(result)); - return result; - } - - /** - * Update the grid of the launcher preview - * - * @param gridNameOrNull Name of the grid (e.g. normal, practical), or null to reset preview to - * current settings - */ - public void updateGrid(@Nullable String gridNameOrNull) { - String gridName; - if (TextUtils.isEmpty(gridNameOrNull)) { - gridName = LauncherPrefs.get(mContext).get(GRID_NAME); - } else { - gridName = gridNameOrNull; - } - if (gridName.equals(mGridName) || gridName.equals(FIXED_LANDSCAPE_GRID)) { - return; - } - mGridName = gridName; - loadAsync(); - } - - /** - * Update the shapes of the launcher preview - * - * @param shapeKey key for the IconShape model - */ - public void updateShape(String shapeKey) { - if (shapeKey.equals(mShapeKey)) { - Log.w(TAG, "Preview shape already set, skipping. shape=" + mShapeKey); - return; - } - mShapeKey = shapeKey; - loadAsync(); - } - - /** - * Update whether to enable monochrome themed icon - * - * @param isMonoThemeEnabled True if enabling mono themed icons - */ - public void updateTheme(boolean isMonoThemeEnabled) { - if (mIsMonoThemeEnabled == isMonoThemeEnabled) { - return; - } - mIsMonoThemeEnabled = isMonoThemeEnabled; - loadAsync(); + LauncherPreviewRenderer renderer = mCurrentRenderer; + return renderer != null ? renderer.initialRender : CompletableFuture.completedFuture(null); } /** @@ -258,7 +229,9 @@ public class PreviewSurfaceRenderer { */ public void hideBottomRow(boolean hide) { mHideQsb = hide; - loadAsync(); + MAIN_EXECUTOR.execute(() -> { + if (mCurrentRenderer != null) mCurrentRenderer.hideBottomRow(hide); + }); } /** @@ -268,7 +241,14 @@ public class PreviewSurfaceRenderer { */ public void previewColor(Bundle bundle) { updateColorOverrides(bundle); - loadAsync(); + MAIN_EXECUTOR.execute(this::recreatePreviewRenderer); + } + + /** + * Returns the [GridCustomizationsProxy] tried to this preview instance + */ + public GridCustomizationsProxy getCustomizationDelegate() { + return mAppComponent.getGridCustomizationsProxy(); } private void updateColorOverrides(Bundle bundle) { @@ -290,8 +270,12 @@ public class PreviewSurfaceRenderer { * Generates a new context overriding the theme color and the display size without affecting the * main application context */ - private Context getPreviewContext() { - Context context = mContext.createDisplayContext(mDisplay); + @UiThread + private void recreatePreviewRenderer() { + destroyExistingRenderer(); + if (mDestroyed) return; + ContextThemeWrapper context = new ContextThemeWrapper( + mPreviewContext, Themes.getActivityThemeRes(mPreviewContext)); if (mDarkMode != null) { Configuration configuration = new Configuration( context.getResources().getConfiguration()); @@ -302,101 +286,42 @@ public class PreviewSurfaceRenderer { configuration.uiMode &= ~UI_MODE_NIGHT_YES; configuration.uiMode |= UI_MODE_NIGHT_NO; } - context = context.createConfigurationContext(configuration); + context.applyOverrideConfiguration(configuration); } - if (Flags.newCustomizationPickerUi()) { - if (mPreviewColorOverride != null) { - LocalColorExtractor.newInstance(context) - .applyColorsOverride(context, mPreviewColorOverride); - } else if (mWallpaperColors != null) { - LocalColorExtractor.newInstance(context) - .applyColorsOverride(context, mWallpaperColors); - } - if (mWallpaperColors != null) { - return new ContextThemeWrapper(context, - Themes.getActivityThemeRes(context, mWallpaperColors.getColorHints())); - } else { - return new ContextThemeWrapper(context, - Themes.getActivityThemeRes(context)); - } - } else { - if (mWallpaperColors == null) { - return new ContextThemeWrapper(context, - Themes.getActivityThemeRes(context)); - } + final int themeRes = mWallpaperColors == null + ? Themes.getActivityThemeRes(context) + : Themes.getActivityThemeRes(context, mWallpaperColors.getColorHints()); + + final SparseIntArray wallpaperColorResources; + + if (Flags.newCustomizationPickerUi() && mPreviewColorOverride != null) { + LocalColorExtractor.newInstance(context) + .applyColorsOverride(context, mPreviewColorOverride); + wallpaperColorResources = mPreviewColorOverride; + } else if (mWallpaperColors != null) { LocalColorExtractor.newInstance(context) .applyColorsOverride(context, mWallpaperColors); - return new ContextThemeWrapper(context, - Themes.getActivityThemeRes(context, mWallpaperColors.getColorHints())); - } - } - - @WorkerThread - private void loadModelData(CompletableFuture onCompleteCallback) { - final Context inflationContext = getPreviewContext(); - 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, 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); - - MAIN_EXECUTOR.execute(() -> { - renderView(previewContext, appComponent.getDataModel(), idp, onCompleteCallback); - mLifeCycleTracker.add(previewContext::onDestroy); - }); - } - - @UiThread - private void renderView(Context inflationContext, BgDataModel dataModel, - InvariantDeviceProfile idp, CompletableFuture onCompleteCallback) { - if (mDestroyed) { - onCompleteCallback.completeExceptionally(new RuntimeException("Renderer destroyed")); - return; - } - LauncherPreviewRenderer renderer; - if (Flags.newCustomizationPickerUi()) { - renderer = new LauncherPreviewRenderer(inflationContext, idp, mPreviewColorOverride, - mWallpaperColors, mWorkspacePageId); + wallpaperColorResources = LocalColorExtractor.newInstance(context) + .generateColorsOverride(mWallpaperColors); } else { - renderer = new LauncherPreviewRenderer(inflationContext, idp, - mWallpaperColors, mWorkspacePageId); + WallpaperColors wallpaperColors = + WallpaperManager.getInstance(context).getWallpaperColors(FLAG_SYSTEM); + wallpaperColorResources = wallpaperColors == null ? null + : LocalColorExtractor.newInstance(context) + .generateColorsOverride(wallpaperColors); } + + LauncherPreviewRenderer renderer = new LauncherPreviewRenderer( + context, mWorkspacePageId, + wallpaperColorResources, mAppComponent.getModel(), themeRes); renderer.hideBottomRow(mHideQsb); - renderer.populate(dataModel); - - View view = renderer.getRootView(); - setCurrentRenderer(renderer); + Future unused = renderer.initialRender + .thenAcceptAsync(this::setContentRoot, MAIN_EXECUTOR); + mCurrentRenderer = renderer; + } + private void setContentRoot(View view) { view.setPivotX(0); view.setPivotY(0); // This aspect scales the view to fit in the surface and centers it @@ -418,12 +343,11 @@ public class PreviewSurfaceRenderer { view.getMeasuredWidth(), view.getMeasuredHeight() ); - onCompleteCallback.complete(view); return; } if (mViewRoot == null) { - mViewRoot = new FrameLayout(inflationContext); + mViewRoot = new FrameLayout(mPreviewContext); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, // Width FrameLayout.LayoutParams.WRAP_CONTENT // Height @@ -444,7 +368,6 @@ public class PreviewSurfaceRenderer { mViewRoot.removeAllViews(); mViewRoot.addView(view); } - onCompleteCallback.complete(view); } private static class MySurfaceControlViewHost extends SurfaceControlViewHost {