When set to "true" in the result of startActivityForResult, the client that launched the
- * picker knows that activity was closed due to pending drag.
- */
- private static final String EXTRA_IS_PENDING_WIDGET_DRAG = "is_pending_widget_drag";
-
- // Intent extras that specify the desired widget width and height. If these are not specified in
- // the intent, then widgets will not be filtered for size.
- private static final String EXTRA_DESIRED_WIDGET_WIDTH = "desired_widget_width";
- private static final String EXTRA_DESIRED_WIDGET_HEIGHT = "desired_widget_height";
- /**
- * Widgets currently added by the user in the UI surface.
- *
This allows widget picker to exclude existing widgets from suggestions.
- */
- private static final String EXTRA_ADDED_APP_WIDGETS = "added_app_widgets";
- /**
- * A unique identifier of the surface hosting the widgets;
- *
"widgets" is reserved for home screen surface.
- *
"widgets_hub" is reserved for glanceable hub surface.
- */
- private static final String EXTRA_UI_SURFACE = "ui_surface";
- private static final Pattern UI_SURFACE_PATTERN =
- Pattern.compile("^(widgets|widgets_hub)$");
- private SimpleDragLayer mDragLayer;
- private WidgetsModel mModel;
- private LauncherAppState mApp;
- private WidgetPredictionsRequester mWidgetPredictionsRequester;
- private final PopupDataProvider mPopupDataProvider = new PopupDataProvider(i -> {});
-
- private int mDesiredWidgetWidth;
- private int mDesiredWidgetHeight;
- private int mWidgetCategoryFilter;
- @Nullable
- private String mUiSurface;
- // Widgets existing on the host surface.
- @NonNull
- private List mAddedWidgets = new ArrayList<>();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
-
- mApp = LauncherAppState.getInstance(this);
- InvariantDeviceProfile idp = mApp.getInvariantDeviceProfile();
- mDeviceProfile = idp.getDeviceProfile(this);
- mModel = new WidgetsModel();
-
- setContentView(R.layout.widget_picker_activity);
- mDragLayer = findViewById(R.id.drag_layer);
- mDragLayer.recreateControllers();
-
- WindowInsetsController wc = mDragLayer.getWindowInsetsController();
- wc.hide(navigationBars() + statusBars());
-
- BaseWidgetSheet widgetSheet = WidgetsFullSheet.show(this, true);
- widgetSheet.disableNavBarScrim(true);
- widgetSheet.addOnCloseListener(this::finish);
-
- parseIntentExtras();
- refreshAndBindWidgets();
- }
-
- private void parseIntentExtras() {
- // A value of 0 for either size means that no filtering will occur in that dimension. If
- // both values are 0, then no size filtering will occur.
- mDesiredWidgetWidth =
- getIntent().getIntExtra(EXTRA_DESIRED_WIDGET_WIDTH, 0);
- mDesiredWidgetHeight =
- getIntent().getIntExtra(EXTRA_DESIRED_WIDGET_HEIGHT, 0);
-
- // Defaults to '0' to indicate that there isn't a category filter.
- mWidgetCategoryFilter =
- getIntent().getIntExtra(AppWidgetManager.EXTRA_CATEGORY_FILTER, 0);
-
- String uiSurfaceParam = getIntent().getStringExtra(EXTRA_UI_SURFACE);
- if (uiSurfaceParam != null && UI_SURFACE_PATTERN.matcher(uiSurfaceParam).matches()) {
- mUiSurface = uiSurfaceParam;
- }
- if (Utilities.ATLEAST_T) {
- ArrayList addedWidgets = getIntent().getParcelableArrayListExtra(
- EXTRA_ADDED_APP_WIDGETS, AppWidgetProviderInfo.class);
- if (addedWidgets != null) {
- mAddedWidgets = addedWidgets;
- }
- }
- }
-
- @NonNull
- @Override
- public PopupDataProvider getPopupDataProvider() {
- return mPopupDataProvider;
- }
-
- @Override
- public SimpleDragLayer getDragLayer() {
- return mDragLayer;
- }
-
- @Override
- public View.OnClickListener getItemOnClickListener() {
- return v -> {
- final AppWidgetProviderInfo info =
- (v instanceof WidgetCell) ? ((WidgetCell) v).getWidgetItem().widgetInfo : null;
- if (info == null || info.provider == null) {
- return;
- }
-
- setResult(RESULT_OK, new Intent()
- .putExtra(Intent.EXTRA_COMPONENT_NAME, info.provider)
- .putExtra(Intent.EXTRA_USER, info.getProfile()));
-
- finish();
- };
- }
-
- @Override
- public View.OnLongClickListener getAllAppsItemLongClickListener() {
- return view -> {
- if (!(view instanceof WidgetCell widgetCell)) return false;
-
- if (widgetCell.getWidgetView().getDrawable() == null
- && widgetCell.getAppWidgetHostViewPreview() == null) {
- // The widget preview hasn't been loaded; so, we abort the drag.
- return false;
- }
-
- final AppWidgetProviderInfo info = widgetCell.getWidgetItem().widgetInfo;
- if (info == null || info.provider == null) {
- return false;
- }
-
- View dragView = widgetCell.getDragAndDropView();
- if (dragView == null) {
- return false;
- }
-
- ClipData clipData = new ClipData(
- new ClipDescription(
- /* label= */ "", // not displayed anywhere; so, set to empty.
- new String[]{MIMETYPE_TEXT_INTENT}
- ),
- new ClipData.Item(new Intent()
- .putExtra(Intent.EXTRA_USER, info.getProfile())
- .putExtra(Intent.EXTRA_COMPONENT_NAME, info.provider))
- );
-
- // Set result indicating activity was closed due a widget being dragged.
- setResult(RESULT_OK, new Intent()
- .putExtra(EXTRA_IS_PENDING_WIDGET_DRAG, true));
-
- // DRAG_FLAG_GLOBAL permits dragging data beyond app window.
- return dragView.startDragAndDrop(
- clipData,
- new View.DragShadowBuilder(dragView),
- /* myLocalState= */ null,
- View.DRAG_FLAG_GLOBAL
- );
- };
- }
-
- /** Updates the model with widgets and provides them after applying the provided filter. */
- private void refreshAndBindWidgets() {
- MODEL_EXECUTOR.execute(() -> {
- LauncherAppState app = LauncherAppState.getInstance(this);
- mModel.update(app, null);
- final List allWidgets =
- mModel.getFilteredWidgetsListForPicker(
- app.getContext(),
- /*widgetItemFilter=*/ widget -> {
- final WidgetAcceptabilityVerdict verdict =
- isWidgetAcceptable(widget);
- verdict.maybeLogVerdict();
- return verdict.isAcceptable;
- }
- );
- bindWidgets(allWidgets);
- if (mUiSurface != null) {
- Map> allWidgetsMap = allWidgets.stream()
- .filter(WidgetsListHeaderEntry.class::isInstance)
- .collect(Collectors.toMap(
- entry -> PackageUserKey.fromPackageItemInfo(entry.mPkgItem),
- entry -> entry.mWidgets)
- );
- mWidgetPredictionsRequester = new WidgetPredictionsRequester(app.getContext(),
- mUiSurface, allWidgetsMap);
- mWidgetPredictionsRequester.request(mAddedWidgets, this::bindRecommendedWidgets);
- }
- });
- }
-
- private void bindWidgets(List widgets) {
- MAIN_EXECUTOR.execute(() -> mPopupDataProvider.setAllWidgets(widgets));
- }
-
- private void bindRecommendedWidgets(List recommendedWidgets) {
- MAIN_EXECUTOR.execute(() -> mPopupDataProvider.setRecommendedWidgets(recommendedWidgets));
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- if (mWidgetPredictionsRequester != null) {
- mWidgetPredictionsRequester.clear();
- }
- }
-
- private WidgetAcceptabilityVerdict isWidgetAcceptable(WidgetItem widget) {
- final AppWidgetProviderInfo info = widget.widgetInfo;
- if (info == null) {
- return rejectWidget(widget, "shortcut");
- }
-
- if (mWidgetCategoryFilter > 0 && (info.widgetCategory & mWidgetCategoryFilter) == 0) {
- return rejectWidget(
- widget,
- "doesn't match category filter [filter=%d, widget=%d]",
- mWidgetCategoryFilter,
- info.widgetCategory);
- }
-
- if (mDesiredWidgetWidth == 0 && mDesiredWidgetHeight == 0) {
- // Accept the widget if the desired dimensions are unspecified.
- return acceptWidget(widget);
- }
-
- final boolean isHorizontallyResizable =
- (info.resizeMode & AppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0;
- if (mDesiredWidgetWidth > 0 && isHorizontallyResizable) {
- if (info.maxResizeWidth > 0
- && info.maxResizeWidth >= info.minWidth
- && info.maxResizeWidth < mDesiredWidgetWidth) {
- return rejectWidget(
- widget,
- "maxResizeWidth[%d] < mDesiredWidgetWidth[%d]",
- info.maxResizeWidth,
- mDesiredWidgetWidth);
- }
-
- final int minWidth = Math.min(info.minResizeWidth, info.minWidth);
- if (minWidth > mDesiredWidgetWidth) {
- return rejectWidget(
- widget,
- "min(minWidth[%d], minResizeWidth[%d]) > mDesiredWidgetWidth[%d]",
- info.minWidth,
- info.minResizeWidth,
- mDesiredWidgetWidth);
- }
- }
-
- final boolean isVerticallyResizable =
- (info.resizeMode & AppWidgetProviderInfo.RESIZE_VERTICAL) != 0;
- if (mDesiredWidgetHeight > 0 && isVerticallyResizable) {
- if (info.maxResizeHeight > 0
- && info.maxResizeHeight >= info.minHeight
- && info.maxResizeHeight < mDesiredWidgetHeight) {
- return rejectWidget(
- widget,
- "maxResizeHeight[%d] < mDesiredWidgetHeight[%d]",
- info.maxResizeHeight,
- mDesiredWidgetHeight);
- }
-
- final int minHeight = Math.min(info.minResizeHeight, info.minHeight);
- if (minHeight > mDesiredWidgetHeight) {
- return rejectWidget(
- widget,
- "min(minHeight[%d], minResizeHeight[%d]) > mDesiredWidgetHeight[%d]",
- info.minHeight,
- info.minResizeHeight,
- mDesiredWidgetHeight);
- }
- }
-
- if (!isHorizontallyResizable || !isVerticallyResizable) {
- return rejectWidget(widget, "not resizeable");
- }
-
- return acceptWidget(widget);
- }
-
- private static WidgetAcceptabilityVerdict rejectWidget(
- WidgetItem widget, String rejectionReason, Object... args) {
- return new WidgetAcceptabilityVerdict(
- false,
- widget.widgetInfo != null
- ? widget.widgetInfo.provider.flattenToShortString()
- : widget.label,
- String.format(Locale.ENGLISH, rejectionReason, args));
- }
-
- private static WidgetAcceptabilityVerdict acceptWidget(WidgetItem widget) {
- return new WidgetAcceptabilityVerdict(
- true, widget.widgetInfo.provider.flattenToShortString(), "");
- }
-
- private record WidgetAcceptabilityVerdict(
- boolean isAcceptable, String widgetLabel, String reason) {
- void maybeLogVerdict() {
- // Only log a verdict if a reason is specified.
- if (Log.isLoggable(TAG, Log.DEBUG) && !reason.isEmpty()) {
- Log.i(TAG, String.format(
- Locale.ENGLISH,
- "%s: %s because %s",
- widgetLabel,
- isAcceptable ? "accepted" : "rejected",
- reason));
- }
- }
- }
-}
diff --git a/quickstep/src/com/android/launcher3/hybridhotseat/HotseatPredictionModel.java b/quickstep/src/com/android/launcher3/hybridhotseat/HotseatPredictionModel.java
deleted file mode 100644
index 56945ba0a6..0000000000
--- a/quickstep/src/com/android/launcher3/hybridhotseat/HotseatPredictionModel.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2020 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.hybridhotseat;
-
-import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION;
-import static com.android.launcher3.model.PredictionHelper.getAppTargetFromItemInfo;
-import static com.android.launcher3.model.PredictionHelper.isTrackedForHotseatPrediction;
-import static com.android.launcher3.model.PredictionHelper.wrapAppTargetWithItemLocation;
-
-import android.app.prediction.AppTarget;
-import android.app.prediction.AppTargetEvent;
-import android.content.Context;
-import android.os.Bundle;
-
-import com.android.launcher3.model.BgDataModel;
-import com.android.launcher3.model.BgDataModel.FixedContainerItems;
-import com.android.launcher3.model.data.ItemInfo;
-
-import java.util.ArrayList;
-
-/**
- * Model helper for app predictions in workspace
- */
-public class HotseatPredictionModel {
- private static final String BUNDLE_KEY_PIN_EVENTS = "pin_events";
- private static final String BUNDLE_KEY_CURRENT_ITEMS = "current_items";
-
- /**
- * Creates and returns bundle using workspace items
- */
- public static Bundle convertDataModelToAppTargetBundle(Context context, BgDataModel dataModel) {
- Bundle bundle = new Bundle();
- ArrayList events = new ArrayList<>();
- ArrayList workspaceItems = dataModel.getAllWorkspaceItems();
- for (ItemInfo item : workspaceItems) {
- AppTarget target = getAppTargetFromItemInfo(context, item);
- if (target != null && !isTrackedForHotseatPrediction(item)) continue;
- events.add(wrapAppTargetWithItemLocation(target, AppTargetEvent.ACTION_PIN, item));
- }
- ArrayList currentTargets = new ArrayList<>();
- FixedContainerItems hotseatItems = dataModel.extraItems.get(CONTAINER_HOTSEAT_PREDICTION);
- if (hotseatItems != null) {
- for (ItemInfo itemInfo : hotseatItems.items) {
- AppTarget target = getAppTargetFromItemInfo(context, itemInfo);
- if (target != null) currentTargets.add(target);
- }
- }
- bundle.putParcelableArrayList(BUNDLE_KEY_PIN_EVENTS, events);
- bundle.putParcelableArrayList(BUNDLE_KEY_CURRENT_ITEMS, currentTargets);
- return bundle;
- }
-}
diff --git a/quickstep/src/com/android/launcher3/model/PredictionHelper.java b/quickstep/src/com/android/launcher3/model/PredictionHelper.java
deleted file mode 100644
index dbd99e1eab..0000000000
--- a/quickstep/src/com/android/launcher3/model/PredictionHelper.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2021 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;
-
-import static com.android.launcher3.logger.LauncherAtom.ContainerInfo.ContainerCase.WORKSPACE;
-
-import android.app.prediction.AppTarget;
-import android.app.prediction.AppTargetEvent;
-import android.app.prediction.AppTargetId;
-import android.content.ComponentName;
-import android.content.Context;
-
-import androidx.annotation.Nullable;
-
-import com.android.launcher3.LauncherSettings;
-import com.android.launcher3.Workspace;
-import com.android.launcher3.logger.LauncherAtom;
-import com.android.launcher3.model.data.ItemInfo;
-import com.android.launcher3.model.data.LauncherAppWidgetInfo;
-import com.android.launcher3.model.data.WorkspaceItemInfo;
-import com.android.launcher3.shortcuts.ShortcutKey;
-
-import java.util.Locale;
-
-/** Helper class with methods for converting launcher items to form usable by predictors */
-public final class PredictionHelper {
- private static final String APP_LOCATION_HOTSEAT = "hotseat";
- private static final String APP_LOCATION_WORKSPACE = "workspace";
-
- /**
- * Creates and returns an {@link AppTarget} object for an {@link ItemInfo}. Returns null
- * if item type is not supported in predictions
- */
- @Nullable
- public static AppTarget getAppTargetFromItemInfo(Context context, ItemInfo info) {
- if (info == null) return null;
- if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
- && info instanceof LauncherAppWidgetInfo
- && ((LauncherAppWidgetInfo) info).providerName != null) {
- ComponentName cn = ((LauncherAppWidgetInfo) info).providerName;
- return new AppTarget.Builder(new AppTargetId("widget:" + cn.getPackageName()),
- cn.getPackageName(), info.user).setClassName(cn.getClassName()).build();
- } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION
- && info.getTargetComponent() != null) {
- ComponentName cn = info.getTargetComponent();
- return new AppTarget.Builder(new AppTargetId("app:" + cn.getPackageName()),
- cn.getPackageName(), info.user).setClassName(cn.getClassName()).build();
- } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT
- && info instanceof WorkspaceItemInfo) {
- ShortcutKey shortcutKey = ShortcutKey.fromItemInfo(info);
- //TODO: switch to using full shortcut info
- return new AppTarget.Builder(new AppTargetId("shortcut:" + shortcutKey.getId()),
- shortcutKey.componentName.getPackageName(), shortcutKey.user).build();
- } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
- return new AppTarget.Builder(new AppTargetId("folder:" + info.id),
- context.getPackageName(), info.user).build();
- } else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APP_PAIR) {
- return new AppTarget.Builder(new AppTargetId("app_pair:" + info.id),
- context.getPackageName(), info.user).build();
- }
- return null;
- }
-
- /**
- * Creates and returns {@link AppTargetEvent} from an {@link AppTarget}, action, and item
- * location using {@link ItemInfo}
- */
- public static AppTargetEvent wrapAppTargetWithItemLocation(
- AppTarget target, int action, ItemInfo info) {
- String location = String.format(Locale.ENGLISH, "%s/%d/[%d,%d]/[%d,%d]",
- info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT
- ? APP_LOCATION_HOTSEAT : APP_LOCATION_WORKSPACE,
- info.screenId, info.cellX, info.cellY, info.spanX, info.spanY);
- return new AppTargetEvent.Builder(target, action).setLaunchLocation(location).build();
- }
-
- /**
- * Helper method to determine if {@link ItemInfo} should be tracked and reported to hotseat
- * predictors
- */
- public static boolean isTrackedForHotseatPrediction(ItemInfo info) {
- return info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT || (
- info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP
- && info.screenId == Workspace.FIRST_SCREEN_ID);
- }
-
- /**
- * Helper method to determine if {@link LauncherAtom.ItemInfo} should be tracked and reported to
- * hotseat predictors
- */
- public static boolean isTrackedForHotseatPrediction(LauncherAtom.ItemInfo info) {
- LauncherAtom.ContainerInfo ci = info.getContainerInfo();
- switch (ci.getContainerCase()) {
- case HOTSEAT:
- return true;
- case WORKSPACE:
- return ci.getWorkspace().getPageIndex() == 0;
- default:
- return false;
- }
- }
-
- /**
- * Helper method to determine if {@link ItemInfo} should be tracked and reported to widget
- * predictors
- */
- public static boolean isTrackedForWidgetPrediction(ItemInfo info) {
- return info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
- && info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP;
- }
-
- /**
- * Helper method to determine if {@link LauncherAtom.ItemInfo} should be tracked and reported
- * to widget predictors
- */
- public static boolean isTrackedForWidgetPrediction(LauncherAtom.ItemInfo info) {
- return info.getItemCase() == LauncherAtom.ItemInfo.ItemCase.WIDGET
- && info.getContainerInfo().getContainerCase() == WORKSPACE;
- }
-}
diff --git a/quickstep/src/com/android/launcher3/secondarydisplay/SecondaryDisplayPredictionsImpl.java b/quickstep/src/com/android/launcher3/secondarydisplay/SecondaryDisplayPredictionsImpl.java
deleted file mode 100644
index 8b71f01396..0000000000
--- a/quickstep/src/com/android/launcher3/secondarydisplay/SecondaryDisplayPredictionsImpl.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2022 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.secondarydisplay;
-
-import static com.android.launcher3.util.OnboardingPrefs.ALL_APPS_VISITED_COUNT;
-
-import android.content.Context;
-
-import com.android.launcher3.appprediction.AppsDividerView;
-import com.android.launcher3.appprediction.PredictionRowView;
-import com.android.launcher3.model.BgDataModel;
-import com.android.launcher3.views.ActivityContext;
-
-/**
- * Implementation of SecondaryDisplayPredictions.
- */
-@SuppressWarnings("unused")
-public final class SecondaryDisplayPredictionsImpl extends SecondaryDisplayPredictions {
-
- private final ActivityContext mActivityContext;
- private final Context mContext;
-
- public SecondaryDisplayPredictionsImpl(Context context) {
- mContext = context;
- mActivityContext = ActivityContext.lookupContext(context);
- }
-
- @Override
- void updateAppDivider() {
- mActivityContext.getAppsView().getFloatingHeaderView()
- .findFixedRowByType(AppsDividerView.class)
- .setShowAllAppsLabel(!ALL_APPS_VISITED_COUNT.hasReachedMax(mContext));
- ALL_APPS_VISITED_COUNT.increment(mContext);
- }
-
- @Override
- public void setPredictedApps(BgDataModel.FixedContainerItems item) {
- mActivityContext.getAppsView().getFloatingHeaderView()
- .findFixedRowByType(PredictionRowView.class)
- .setPredictedApps(item.items);
- }
-}
diff --git a/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.java b/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.java
deleted file mode 100644
index 4a8672fb6d..0000000000
--- a/quickstep/src/com/android/launcher3/statehandlers/DesktopVisibilityController.java
+++ /dev/null
@@ -1,358 +0,0 @@
-/*
- * Copyright (C) 2022 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.statehandlers;
-
-import static android.view.View.VISIBLE;
-
-import static com.android.launcher3.LauncherState.BACKGROUND_APP;
-import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
-import static com.android.window.flags2.Flags.enableDesktopWindowingWallpaperActivity;
-
-import android.os.Debug;
-import android.util.Log;
-import android.view.View;
-
-import androidx.annotation.Nullable;
-
-import com.android.launcher3.Launcher;
-import com.android.launcher3.LauncherState;
-import com.android.launcher3.statemanager.StatefulActivity;
-import com.android.launcher3.uioverrides.QuickstepLauncher;
-import com.android.launcher3.util.DisplayController;
-import com.android.quickstep.GestureState;
-import com.android.quickstep.SystemUiProxy;
-import com.android.wm.shell.desktopmode.IDesktopTaskListener;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Controls the visibility of the workspace and the resumed / paused state when desktop mode
- * is enabled.
- */
-public class DesktopVisibilityController {
-
- private static final String TAG = "DesktopVisController";
- private static final boolean DEBUG = false;
- private final Launcher mLauncher;
- private final Set mDesktopVisibilityListeners = new HashSet<>();
-
- private int mVisibleDesktopTasksCount;
- private boolean mInOverviewState;
- private boolean mBackgroundStateEnabled;
- private boolean mGestureInProgress;
-
- @Nullable
- private IDesktopTaskListener mDesktopTaskListener;
-
- public DesktopVisibilityController(Launcher launcher) {
- mLauncher = launcher;
- }
-
- /**
- * Register a listener with System UI to receive updates about desktop tasks state
- */
- public void registerSystemUiListener() {
- mDesktopTaskListener = new IDesktopTaskListener.Stub() {
- @Override
- public void onTasksVisibilityChanged(int displayId, int visibleTasksCount) {
- MAIN_EXECUTOR.execute(() -> {
- if (displayId == mLauncher.getDisplayId()) {
- if (DEBUG) {
- Log.d(TAG, "desktop visible tasks count changed=" + visibleTasksCount);
- }
- setVisibleDesktopTasksCount(visibleTasksCount);
- }
- });
- }
-
- @Override
- public void onStashedChanged(int displayId, boolean stashed) {
- Log.w(TAG, "IDesktopTaskListener: onStashedChanged is deprecated");
- }
- };
- SystemUiProxy.INSTANCE.get(mLauncher).setDesktopTaskListener(mDesktopTaskListener);
- }
-
- /**
- * Clear listener from System UI that was set with {@link #registerSystemUiListener()}
- */
- public void unregisterSystemUiListener() {
- SystemUiProxy.INSTANCE.get(mLauncher).setDesktopTaskListener(null);
- mDesktopTaskListener = null;
- }
-
- /**
- * Whether desktop tasks are visible in desktop mode.
- */
- public boolean areDesktopTasksVisible() {
- boolean desktopTasksVisible = mVisibleDesktopTasksCount > 0;
- if (DEBUG) {
- Log.d(TAG, "areDesktopTasksVisible: desktopVisible=" + desktopTasksVisible
- + " overview=" + mInOverviewState);
- }
- return desktopTasksVisible && !mInOverviewState;
- }
-
- /**
- * Number of visible desktop windows in desktop mode.
- */
- public int getVisibleDesktopTasksCount() {
- return mVisibleDesktopTasksCount;
- }
-
- /** Registers a listener for Desktop Mode visibility updates. */
- public void registerDesktopVisibilityListener(DesktopVisibilityListener listener) {
- mDesktopVisibilityListeners.add(listener);
- }
-
- /** Removes a previously registered Desktop Mode visibility listener. */
- public void unregisterDesktopVisibilityListener(DesktopVisibilityListener listener) {
- mDesktopVisibilityListeners.remove(listener);
- }
-
- /**
- * Sets the number of desktop windows that are visible and updates launcher visibility based on
- * it.
- */
- public void setVisibleDesktopTasksCount(int visibleTasksCount) {
- if (DEBUG) {
- Log.d(TAG, "setVisibleDesktopTasksCount: visibleTasksCount=" + visibleTasksCount
- + " currentValue=" + mVisibleDesktopTasksCount);
- }
-
- if (visibleTasksCount != mVisibleDesktopTasksCount) {
- final boolean wasVisible = mVisibleDesktopTasksCount > 0;
- final boolean isVisible = visibleTasksCount > 0;
- final boolean wereDesktopTasksVisibleBefore = areDesktopTasksVisible();
- mVisibleDesktopTasksCount = visibleTasksCount;
- final boolean areDesktopTasksVisibleNow = areDesktopTasksVisible();
- if (wereDesktopTasksVisibleBefore != areDesktopTasksVisibleNow) {
- notifyDesktopVisibilityListeners(areDesktopTasksVisibleNow);
- }
-
- if (!enableDesktopWindowingWallpaperActivity() && wasVisible != isVisible) {
- // TODO: b/333533253 - Remove after flag rollout
- if (mVisibleDesktopTasksCount > 0) {
- setLauncherViewsVisibility(View.INVISIBLE);
- if (!mInOverviewState) {
- // When desktop tasks are visible & we're not in overview, we want launcher
- // to appear paused, this ensures that taskbar displays.
- markLauncherPaused();
- }
- } else {
- setLauncherViewsVisibility(View.VISIBLE);
- // If desktop tasks aren't visible, ensure that launcher appears resumed to
- // behave normally.
- markLauncherResumed();
- }
- }
- }
- }
-
- /**
- * Process launcher state change and update launcher view visibility based on desktop state
- */
- public void onLauncherStateChanged(LauncherState state) {
- if (DEBUG) {
- Log.d(TAG, "onLauncherStateChanged: newState=" + state);
- }
- setBackgroundStateEnabled(state == BACKGROUND_APP);
- // Desktop visibility tracks overview and background state separately
- setOverviewStateEnabled(state != BACKGROUND_APP && state.isRecentsViewVisible);
- }
-
- private void setOverviewStateEnabled(boolean overviewStateEnabled) {
- if (DEBUG) {
- Log.d(TAG, "setOverviewStateEnabled: enabled=" + overviewStateEnabled
- + " currentValue=" + mInOverviewState);
- }
- if (overviewStateEnabled != mInOverviewState) {
- final boolean wereDesktopTasksVisibleBefore = areDesktopTasksVisible();
- mInOverviewState = overviewStateEnabled;
- final boolean areDesktopTasksVisibleNow = areDesktopTasksVisible();
- if (wereDesktopTasksVisibleBefore != areDesktopTasksVisibleNow) {
- notifyDesktopVisibilityListeners(areDesktopTasksVisibleNow);
- }
-
- if (enableDesktopWindowingWallpaperActivity()) {
- return;
- }
- // TODO: b/333533253 - Clean up after flag rollout
-
- if (mInOverviewState) {
- setLauncherViewsVisibility(View.VISIBLE);
- markLauncherResumed();
- } else if (areDesktopTasksVisibleNow && !mGestureInProgress) {
- // Switching out of overview state and gesture finished.
- // If desktop tasks are still visible, hide launcher again.
- setLauncherViewsVisibility(View.INVISIBLE);
- markLauncherPaused();
- }
- }
- }
-
- private void notifyDesktopVisibilityListeners(boolean areDesktopTasksVisible) {
- if (DEBUG) {
- Log.d(TAG, "notifyDesktopVisibilityListeners: visible=" + areDesktopTasksVisible);
- }
- for (DesktopVisibilityListener listener : mDesktopVisibilityListeners) {
- listener.onDesktopVisibilityChanged(areDesktopTasksVisible);
- }
- DisplayController.handleInfoChangeForDesktopMode(mLauncher);
- }
-
- /**
- * TODO: b/333533253 - Remove after flag rollout
- */
- private void setBackgroundStateEnabled(boolean backgroundStateEnabled) {
- if (DEBUG) {
- Log.d(TAG, "setBackgroundStateEnabled: enabled=" + backgroundStateEnabled
- + " currentValue=" + mBackgroundStateEnabled);
- }
- if (backgroundStateEnabled != mBackgroundStateEnabled) {
- mBackgroundStateEnabled = backgroundStateEnabled;
- if (mBackgroundStateEnabled) {
- setLauncherViewsVisibility(View.VISIBLE);
- markLauncherResumed();
- } else if (areDesktopTasksVisible() && !mGestureInProgress) {
- // Switching out of background state. If desktop tasks are visible, pause launcher.
- setLauncherViewsVisibility(View.INVISIBLE);
- markLauncherPaused();
- }
- }
- }
-
- /**
- * Whether recents gesture is currently in progress.
- *
- * TODO: b/333533253 - Remove after flag rollout
- */
- public boolean isRecentsGestureInProgress() {
- return mGestureInProgress;
- }
-
- /**
- * Notify controller that recents gesture has started.
- *
- * TODO: b/333533253 - Remove after flag rollout
- */
- public void setRecentsGestureStart() {
- if (DEBUG) {
- Log.d(TAG, "setRecentsGestureStart");
- }
- setRecentsGestureInProgress(true);
- }
-
- /**
- * Notify controller that recents gesture finished with the given
- * {@link com.android.quickstep.GestureState.GestureEndTarget}
- *
- * TODO: b/333533253 - Remove after flag rollout
- */
- public void setRecentsGestureEnd(@Nullable GestureState.GestureEndTarget endTarget) {
- if (DEBUG) {
- Log.d(TAG, "setRecentsGestureEnd: endTarget=" + endTarget);
- }
- setRecentsGestureInProgress(false);
-
- if (endTarget == null) {
- // Gesture did not result in a new end target. Ensure launchers gets paused again.
- markLauncherPaused();
- }
- }
-
- /**
- * TODO: b/333533253 - Remove after flag rollout
- */
- private void setRecentsGestureInProgress(boolean gestureInProgress) {
- if (gestureInProgress != mGestureInProgress) {
- mGestureInProgress = gestureInProgress;
- }
- }
-
- /**
- * TODO: b/333533253 - Remove after flag rollout
- */
- private void setLauncherViewsVisibility(int visibility) {
- if (enableDesktopWindowingWallpaperActivity()) {
- return;
- }
- if (DEBUG) {
- Log.d(TAG, "setLauncherViewsVisibility: visibility=" + visibility + " "
- + Debug.getCaller());
- }
- View workspaceView = mLauncher.getWorkspace();
- if (workspaceView != null) {
- workspaceView.setVisibility(visibility);
- }
- View dragLayer = mLauncher.getDragLayer();
- if (dragLayer != null) {
- dragLayer.setVisibility(visibility);
- }
- if (mLauncher instanceof QuickstepLauncher ql && ql.getTaskbarUIController() != null
- && mVisibleDesktopTasksCount != 0) {
- ql.getTaskbarUIController().onLauncherVisibilityChanged(visibility == VISIBLE);
- }
- }
-
- /**
- * TODO: b/333533253 - Remove after flag rollout
- */
- private void markLauncherPaused() {
- if (enableDesktopWindowingWallpaperActivity()) {
- return;
- }
- if (DEBUG) {
- Log.d(TAG, "markLauncherPaused " + Debug.getCaller());
- }
- StatefulActivity activity =
- QuickstepLauncher.ACTIVITY_TRACKER.getCreatedActivity();
- if (activity != null) {
- activity.setPaused();
- }
- }
-
- /**
- * TODO: b/333533253 - Remove after flag rollout
- */
- private void markLauncherResumed() {
- if (enableDesktopWindowingWallpaperActivity()) {
- return;
- }
- if (DEBUG) {
- Log.d(TAG, "markLauncherResumed " + Debug.getCaller());
- }
- StatefulActivity activity =
- QuickstepLauncher.ACTIVITY_TRACKER.getCreatedActivity();
- // Check activity state before calling setResumed(). Launcher may have been actually
- // paused (eg fullscreen task moved to front).
- // In this case we should not mark the activity as resumed.
- if (activity != null && activity.isResumed()) {
- activity.setResumed();
- }
- }
-
- /** A listener for when the user enters/exits Desktop Mode. */
- public interface DesktopVisibilityListener {
- /**
- * Callback for when the user enters or exits Desktop Mode
- *
- * @param visible whether Desktop Mode is now visible
- */
- void onDesktopVisibilityChanged(boolean visible);
- }
-}
diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java
deleted file mode 100644
index 8e8ab93832..0000000000
--- a/quickstep/src/com/android/launcher3/taskbar/TaskbarManager.java
+++ /dev/null
@@ -1,686 +0,0 @@
-/*
- * Copyright (C) 2021 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.taskbar;
-
-import static android.content.Context.RECEIVER_NOT_EXPORTED;
-import static android.view.Display.DEFAULT_DISPLAY;
-import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR;
-import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL;
-
-import static com.android.launcher3.BaseActivity.EVENT_DESTROYED;
-import static com.android.launcher3.Flags.enableUnfoldStateAnimation;
-import static com.android.launcher3.config.FeatureFlags.ENABLE_TASKBAR_NAVBAR_UNIFICATION;
-import static com.android.launcher3.config.FeatureFlags.enableTaskbarNoRecreate;
-import static com.android.launcher3.util.DisplayController.CHANGE_DENSITY;
-import static com.android.launcher3.util.DisplayController.CHANGE_DESKTOP_MODE;
-import static com.android.launcher3.util.DisplayController.CHANGE_NAVIGATION_MODE;
-import static com.android.launcher3.util.DisplayController.CHANGE_TASKBAR_PINNING;
-import static com.android.launcher3.util.DisplayController.TASKBAR_NOT_DESTROYED_TAG;
-import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
-import static com.android.launcher3.util.FlagDebugUtils.formatFlagChange;
-import static com.android.quickstep.util.SystemActionConstants.ACTION_SHOW_TASKBAR;
-import static com.android.quickstep.util.SystemActionConstants.SYSTEM_ACTION_ID_TASKBAR;
-
-import android.annotation.SuppressLint;
-import android.app.PendingIntent;
-import android.content.ComponentCallbacks;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.ActivityInfo;
-import android.content.res.Configuration;
-import android.hardware.display.DisplayManager;
-import android.net.Uri;
-import android.os.Handler;
-import android.os.Trace;
-import android.provider.Settings;
-import android.util.Log;
-import android.view.Display;
-import android.view.MotionEvent;
-import android.view.WindowManager;
-import android.widget.FrameLayout;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-import androidx.annotation.VisibleForTesting;
-
-import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.Launcher;
-import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.anim.AnimatorPlaybackController;
-import com.android.launcher3.statemanager.StatefulActivity;
-import com.android.launcher3.taskbar.TaskbarNavButtonController.TaskbarNavButtonCallbacks;
-import com.android.launcher3.taskbar.unfold.NonDestroyableScopedUnfoldTransitionProgressProvider;
-import com.android.launcher3.uioverrides.QuickstepLauncher;
-import com.android.launcher3.util.DisplayController;
-import com.android.launcher3.util.SettingsCache;
-import com.android.launcher3.util.SimpleBroadcastReceiver;
-import com.android.quickstep.AllAppsActionManager;
-import com.android.quickstep.RecentsActivity;
-import com.android.quickstep.SystemUiProxy;
-import com.android.quickstep.util.AssistUtils;
-import com.android.systemui.shared.system.QuickStepContract;
-import com.android.systemui.shared.system.QuickStepContract.SystemUiStateFlags;
-import com.android.systemui.unfold.UnfoldTransitionProgressProvider;
-import com.android.systemui.unfold.util.ScopedUnfoldTransitionProgressProvider;
-
-import java.io.PrintWriter;
-import java.util.StringJoiner;
-
-import app.lawnchair.LawnchairApp;
-
-/**
- * Class to manage taskbar lifecycle
- */
-public class TaskbarManager {
- private static final String TAG = "TaskbarManager";
- private static final boolean DEBUG = false;
-
- /**
- * All the configurations which do not initiate taskbar recreation.
- * This includes all the configurations defined in Launcher's manifest entry and
- * ActivityController#filterConfigChanges
- */
- private static final int SKIP_RECREATE_CONFIG_CHANGES = ActivityInfo.CONFIG_WINDOW_CONFIGURATION
- | ActivityInfo.CONFIG_KEYBOARD
- | ActivityInfo.CONFIG_KEYBOARD_HIDDEN
- | ActivityInfo.CONFIG_MCC
- | ActivityInfo.CONFIG_MNC
- | ActivityInfo.CONFIG_NAVIGATION
- | ActivityInfo.CONFIG_ORIENTATION
- | ActivityInfo.CONFIG_SCREEN_SIZE
- | ActivityInfo.CONFIG_SCREEN_LAYOUT
- | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE;
-
-
- private final Context mContext;
- private final @Nullable Context mNavigationBarPanelContext;
- private WindowManager mWindowManager;
- private FrameLayout mTaskbarRootLayout;
- private boolean mAddedWindow;
- private final TaskbarNavButtonController mNavButtonController;
- private final ComponentCallbacks mComponentCallbacks;
-
- private final SimpleBroadcastReceiver mShutdownReceiver =
- new SimpleBroadcastReceiver(i -> destroyExistingTaskbar());
-
- // The source for this provider is set when Launcher is available
- // We use 'non-destroyable' version here so the original provider won't be destroyed
- // as it is tied to the activity lifecycle, not the taskbar lifecycle.
- // It's destruction/creation will be managed by the activity.
- private final ScopedUnfoldTransitionProgressProvider mUnfoldProgressProvider =
- new NonDestroyableScopedUnfoldTransitionProgressProvider();
-
- private TaskbarActivityContext mTaskbarActivityContext;
- private StatefulActivity mActivity;
- /**
- * Cache a copy here so we can initialize state whenever taskbar is recreated, since
- * this class does not get re-initialized w/ new taskbars.
- */
- private final TaskbarSharedState mSharedState = new TaskbarSharedState();
-
- /**
- * We use WindowManager's ComponentCallbacks() for internal UI changes (similar to an Activity)
- * which comes via a different channel
- */
- private final RecreationListener mRecreationListener = new RecreationListener();
-
- private class RecreationListener implements DisplayController.DisplayInfoChangeListener {
- @Override
- public void onDisplayInfoChanged(Context context, DisplayController.Info info, int flags) {
- if ((flags & (CHANGE_DENSITY | CHANGE_NAVIGATION_MODE | CHANGE_DESKTOP_MODE
- | CHANGE_TASKBAR_PINNING)) != 0) {
- recreateTaskbar();
- }
- }
- }
- private final SettingsCache.OnChangeListener mOnSettingsChangeListener = c -> recreateTaskbar();
-
- private boolean mUserUnlocked = false;
-
- private final SimpleBroadcastReceiver mTaskbarBroadcastReceiver =
- new SimpleBroadcastReceiver(this::showTaskbarFromBroadcast);
-
- private final AllAppsActionManager mAllAppsActionManager;
-
- private final Runnable mActivityOnDestroyCallback = new Runnable() {
- @Override
- public void run() {
- if (mActivity != null) {
- mActivity.removeOnDeviceProfileChangeListener(
- mDebugActivityDeviceProfileChanged);
- Log.d(TASKBAR_NOT_DESTROYED_TAG,
- "unregistering activity lifecycle callbacks from "
- + "onActivityDestroyed.");
- mActivity.removeEventCallback(EVENT_DESTROYED, this);
- }
- mActivity = null;
- debugWhyTaskbarNotDestroyed("clearActivity");
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.setUIController(TaskbarUIController.DEFAULT);
- }
- mUnfoldProgressProvider.setSourceProvider(null);
- }
- };
-
- UnfoldTransitionProgressProvider.TransitionProgressListener mUnfoldTransitionProgressListener =
- new UnfoldTransitionProgressProvider.TransitionProgressListener() {
- @Override
- public void onTransitionStarted() {
- Log.d(TASKBAR_NOT_DESTROYED_TAG,
- "fold/unfold transition started getting called.");
- }
-
- @Override
- public void onTransitionProgress(float progress) {
- Log.d(TASKBAR_NOT_DESTROYED_TAG,
- "fold/unfold transition progress : " + progress);
- }
-
- @Override
- public void onTransitionFinishing() {
- Log.d(TASKBAR_NOT_DESTROYED_TAG,
- "fold/unfold transition finishing getting called.");
-
- }
-
- @Override
- public void onTransitionFinished() {
- Log.d(TASKBAR_NOT_DESTROYED_TAG,
- "fold/unfold transition finished getting called.");
-
- }
- };
-
- @SuppressLint("WrongConstant")
- public TaskbarManager(
- Context context,
- AllAppsActionManager allAppsActionManager,
- TaskbarNavButtonCallbacks navCallbacks) {
-
- Display display =
- context.getSystemService(DisplayManager.class).getDisplay(DEFAULT_DISPLAY);
- mContext = context.createWindowContext(display,
- ENABLE_TASKBAR_NAVBAR_UNIFICATION ? TYPE_NAVIGATION_BAR : TYPE_NAVIGATION_BAR_PANEL,
- null);
- mAllAppsActionManager = allAppsActionManager;
- mNavigationBarPanelContext = ENABLE_TASKBAR_NAVBAR_UNIFICATION
- ? context.createWindowContext(display, TYPE_NAVIGATION_BAR_PANEL, null)
- : null;
- if (enableTaskbarNoRecreate()) {
- mWindowManager = mContext.getSystemService(WindowManager.class);
- mTaskbarRootLayout = new FrameLayout(mContext) {
- @Override
- public boolean dispatchTouchEvent(MotionEvent ev) {
- // The motion events can be outside the view bounds of task bar, and hence
- // manually dispatching them to the drag layer here.
- if (mTaskbarActivityContext != null
- && mTaskbarActivityContext.getDragLayer().isAttachedToWindow()) {
- return mTaskbarActivityContext.getDragLayer().dispatchTouchEvent(ev);
- }
- return super.dispatchTouchEvent(ev);
- }
- };
- }
- mNavButtonController = new TaskbarNavButtonController(
- context,
- navCallbacks,
- SystemUiProxy.INSTANCE.get(mContext),
- new Handler(),
- AssistUtils.newInstance(mContext));
- mComponentCallbacks = new ComponentCallbacks() {
- private Configuration mOldConfig = mContext.getResources().getConfiguration();
-
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
- Trace.instantForTrack(Trace.TRACE_TAG_APP, "TaskbarManager",
- "onConfigurationChanged: " + newConfig);
- debugWhyTaskbarNotDestroyed(
- "TaskbarManager#mComponentCallbacks.onConfigurationChanged: " + newConfig);
- DeviceProfile dp = mUserUnlocked
- ? LauncherAppState.getIDP(mContext).getDeviceProfile(mContext)
- : null;
- int configDiff = mOldConfig.diff(newConfig) & ~SKIP_RECREATE_CONFIG_CHANGES;
-
- if ((configDiff & ActivityInfo.CONFIG_UI_MODE) != 0) {
- // Only recreate for theme changes, not other UI mode changes such as docking.
- int oldUiNightMode = (mOldConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK);
- int newUiNightMode = (newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK);
- if (oldUiNightMode == newUiNightMode) {
- configDiff &= ~ActivityInfo.CONFIG_UI_MODE;
- }
- }
-
- debugWhyTaskbarNotDestroyed("ComponentCallbacks#onConfigurationChanged() "
- + "configDiff=" + Configuration.configurationDiffToString(configDiff));
- if (configDiff != 0 || mTaskbarActivityContext == null) {
- recreateTaskbar();
- } else {
- // Config change might be handled without re-creating the taskbar
- if (dp != null && !isTaskbarEnabled(dp)) {
- destroyExistingTaskbar();
- } else {
- if (dp != null && isTaskbarEnabled(dp)) {
- if (ENABLE_TASKBAR_NAVBAR_UNIFICATION) {
- // Re-initialize for screen size change? Should this be done
- // by looking at screen-size change flag in configDiff in the
- // block above?
- recreateTaskbar();
- } else {
- mTaskbarActivityContext.updateDeviceProfile(dp);
- }
- }
- mTaskbarActivityContext.onConfigurationChanged(configDiff);
- }
- }
- mOldConfig = new Configuration(newConfig);
- // reset taskbar was pinned value, so we don't automatically unstash taskbar upon
- // user unfolding the device.
- mSharedState.setTaskbarWasPinned(false);
- }
-
- @Override
- public void onLowMemory() { }
- };
-
- if (LawnchairApp.isRecentsEnabled ()) {
- final Uri USER_SETUP_COMPLETE_URI = Settings.Secure.getUriFor(
- Settings.Secure.USER_SETUP_COMPLETE);
-
- final Uri NAV_BAR_KIDS_MODE = Settings.Secure.getUriFor(
- Settings.Secure.NAV_BAR_KIDS_MODE);
- SettingsCache.INSTANCE.get(mContext)
- .register(USER_SETUP_COMPLETE_URI, mOnSettingsChangeListener);
- SettingsCache.INSTANCE.get(mContext)
- .register(NAV_BAR_KIDS_MODE, mOnSettingsChangeListener);
- }
-
- Log.d(TASKBAR_NOT_DESTROYED_TAG, "registering component callbacks from constructor.");
- mContext.registerComponentCallbacks(mComponentCallbacks);
- mShutdownReceiver.register(mContext, Intent.ACTION_SHUTDOWN);
- UI_HELPER_EXECUTOR.execute(() -> {
- mSharedState.taskbarSystemActionPendingIntent = PendingIntent.getBroadcast(
- mContext,
- SYSTEM_ACTION_ID_TASKBAR,
- new Intent(ACTION_SHOW_TASKBAR).setPackage(mContext.getPackageName()),
- PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
- mContext.registerReceiver(
- mTaskbarBroadcastReceiver,
- new IntentFilter(ACTION_SHOW_TASKBAR),
- RECEIVER_NOT_EXPORTED);
- });
-
- debugWhyTaskbarNotDestroyed("TaskbarManager created");
- recreateTaskbar();
- }
-
- private void destroyExistingTaskbar() {
- debugWhyTaskbarNotDestroyed("destroyExistingTaskbar: " + mTaskbarActivityContext);
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.onDestroy();
- if (!ENABLE_TASKBAR_NAVBAR_UNIFICATION || enableTaskbarNoRecreate()) {
- mTaskbarActivityContext = null;
- }
- }
- DeviceProfile dp = mUserUnlocked ?
- LauncherAppState.getIDP(mContext).getDeviceProfile(mContext) : null;
- if (dp == null || !isTaskbarEnabled(dp)) {
- removeTaskbarRootViewFromWindow();
- }
- }
-
- /**
- * Show Taskbar upon receiving broadcast
- */
- private void showTaskbarFromBroadcast(Intent intent) {
- if (ACTION_SHOW_TASKBAR.equals(intent.getAction()) && mTaskbarActivityContext != null) {
- mTaskbarActivityContext.showTaskbarFromBroadcast();
- }
- }
-
- /**
- * Toggles All Apps for Taskbar or Launcher depending on the current state.
- */
- public void toggleAllApps() {
- if (mTaskbarActivityContext == null || mTaskbarActivityContext.canToggleHomeAllApps()) {
- // Home All Apps should be toggled from this class, because the controllers are not
- // initialized when Taskbar is disabled (i.e. TaskbarActivityContext is null).
- if (mActivity instanceof Launcher l) l.toggleAllAppsSearch();
- } else {
- mTaskbarActivityContext.toggleAllAppsSearch();
- }
- }
-
- /**
- * Displays a frame of the first Launcher reveal animation.
- *
- * This should be used to run a first Launcher reveal animation whose progress matches a swipe
- * progress.
- */
- public AnimatorPlaybackController createLauncherStartFromSuwAnim(int duration) {
- return mTaskbarActivityContext == null
- ? null : mTaskbarActivityContext.createLauncherStartFromSuwAnim(duration);
- }
-
- /**
- * Called when the user is unlocked
- */
- public void onUserUnlocked() {
- mUserUnlocked = true;
- DisplayController.INSTANCE.get(mContext).addChangeListener(mRecreationListener);
- recreateTaskbar();
- addTaskbarRootViewToWindow();
- }
-
- /**
- * Sets a {@link StatefulActivity} to act as taskbar callback
- */
- public void setActivity(@NonNull StatefulActivity activity) {
- if (mActivity == activity) {
- return;
- }
- removeActivityCallbacksAndListeners();
- mActivity = activity;
- debugWhyTaskbarNotDestroyed("Set mActivity=" + mActivity);
- mActivity.addOnDeviceProfileChangeListener(mDebugActivityDeviceProfileChanged);
- Log.d(TASKBAR_NOT_DESTROYED_TAG,
- "registering activity lifecycle callbacks from setActivity().");
- mActivity.addEventCallback(EVENT_DESTROYED, mActivityOnDestroyCallback);
- UnfoldTransitionProgressProvider unfoldTransitionProgressProvider =
- getUnfoldTransitionProgressProviderForActivity(activity);
- if (unfoldTransitionProgressProvider != null) {
- unfoldTransitionProgressProvider.addCallback(mUnfoldTransitionProgressListener);
- }
- mUnfoldProgressProvider.setSourceProvider(unfoldTransitionProgressProvider);
-
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.setUIController(
- createTaskbarUIControllerForActivity(mActivity));
- }
- }
-
- /**
- * Returns an {@link UnfoldTransitionProgressProvider} to use while the given StatefulActivity
- * is active.
- */
- private UnfoldTransitionProgressProvider getUnfoldTransitionProgressProviderForActivity(
- StatefulActivity activity) {
- if (!enableUnfoldStateAnimation()) {
- if (activity instanceof QuickstepLauncher ql) {
- return ql.getUnfoldTransitionProgressProvider();
- }
- } else {
- return SystemUiProxy.INSTANCE.get(mContext).getUnfoldTransitionProvider();
- }
- return null;
- }
-
- /**
- * Creates a {@link TaskbarUIController} to use while the given StatefulActivity is active.
- */
- private TaskbarUIController createTaskbarUIControllerForActivity(StatefulActivity activity) {
- if (activity instanceof QuickstepLauncher) {
- return new LauncherTaskbarUIController((QuickstepLauncher) activity);
- }
- if (activity instanceof RecentsActivity) {
- return new FallbackTaskbarUIController((RecentsActivity) activity);
- }
- return TaskbarUIController.DEFAULT;
- }
-
- /**
- * This method is called multiple times (ex. initial init, then when user unlocks) in which case
- * we fully want to destroy an existing taskbar and create a new one.
- * In other case (folding/unfolding) we don't need to remove and add window.
- */
- @VisibleForTesting
- public synchronized void recreateTaskbar() {
- Trace.beginSection("recreateTaskbar");
- try {
- DeviceProfile dp = mUserUnlocked ?
- LauncherAppState.getIDP(mContext).getDeviceProfile(mContext) : null;
-
- // All Apps action is unrelated to navbar unification, so we only need to check DP.
- final boolean isLargeScreenTaskbar = dp != null && dp.isTaskbarPresent;
- mAllAppsActionManager.setTaskbarPresent(isLargeScreenTaskbar);
-
- destroyExistingTaskbar();
-
- boolean isTaskbarEnabled = dp != null && isTaskbarEnabled(dp);
- debugWhyTaskbarNotDestroyed("recreateTaskbar: isTaskbarEnabled=" + isTaskbarEnabled
- + " [dp != null (i.e. mUserUnlocked)]=" + (dp != null)
- + " FLAG_HIDE_NAVBAR_WINDOW=" + ENABLE_TASKBAR_NAVBAR_UNIFICATION
- + " dp.isTaskbarPresent=" + (dp == null ? "null" : dp.isTaskbarPresent));
- if (!isTaskbarEnabled) {
- SystemUiProxy.INSTANCE.get(mContext)
- .notifyTaskbarStatus(/* visible */ false, /* stashed */ false);
- return;
- }
-
- if (enableTaskbarNoRecreate() || mTaskbarActivityContext == null) {
- mTaskbarActivityContext = new TaskbarActivityContext(mContext,
- mNavigationBarPanelContext, dp, mNavButtonController,
- mUnfoldProgressProvider);
- } else {
- mTaskbarActivityContext.updateDeviceProfile(dp);
- }
- mSharedState.startTaskbarVariantIsTransient =
- DisplayController.isTransientTaskbar(mTaskbarActivityContext);
- mSharedState.allAppsVisible = mSharedState.allAppsVisible && isLargeScreenTaskbar;
- mTaskbarActivityContext.init(mSharedState);
-
- if (mActivity != null) {
- mTaskbarActivityContext.setUIController(
- createTaskbarUIControllerForActivity(mActivity));
- }
-
- if (enableTaskbarNoRecreate()) {
- addTaskbarRootViewToWindow();
- mTaskbarRootLayout.removeAllViews();
- mTaskbarRootLayout.addView(mTaskbarActivityContext.getDragLayer());
- mTaskbarActivityContext.notifyUpdateLayoutParams();
- }
- } finally {
- Trace.endSection();
- }
- }
-
- public void onSystemUiFlagsChanged(@SystemUiStateFlags long systemUiStateFlags) {
- if (DEBUG) {
- Log.d(TAG, "SysUI flags changed: " + formatFlagChange(systemUiStateFlags,
- mSharedState.sysuiStateFlags, QuickStepContract::getSystemUiStateString));
- }
- mSharedState.sysuiStateFlags = systemUiStateFlags;
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.updateSysuiStateFlags(systemUiStateFlags, false /* fromInit */);
- }
- }
-
- public void onLongPressHomeEnabled(boolean assistantLongPressEnabled) {
- if (mNavButtonController != null) {
- mNavButtonController.setAssistantLongPressEnabled(assistantLongPressEnabled);
- }
- }
-
- /**
- * Sets the flag indicating setup UI is visible
- */
- public void setSetupUIVisible(boolean isVisible) {
- mSharedState.setupUIVisible = isVisible;
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.setSetupUIVisible(isVisible);
- }
- }
-
- private boolean isTaskbarEnabled(DeviceProfile deviceProfile) {
- return ENABLE_TASKBAR_NAVBAR_UNIFICATION || deviceProfile.isTaskbarPresent;
- }
-
- public void onRotationProposal(int rotation, boolean isValid) {
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.onRotationProposal(rotation, isValid);
- }
- }
-
- public void disableNavBarElements(int displayId, int state1, int state2, boolean animate) {
- mSharedState.disableNavBarDisplayId = displayId;
- mSharedState.disableNavBarState1 = state1;
- mSharedState.disableNavBarState2 = state2;
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.disableNavBarElements(displayId, state1, state2, animate);
- }
- }
-
- public void onSystemBarAttributesChanged(int displayId, int behavior) {
- mSharedState.systemBarAttrsDisplayId = displayId;
- mSharedState.systemBarAttrsBehavior = behavior;
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.onSystemBarAttributesChanged(displayId, behavior);
- }
- }
-
- public void onNavButtonsDarkIntensityChanged(float darkIntensity) {
- mSharedState.navButtonsDarkIntensity = darkIntensity;
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.onNavButtonsDarkIntensityChanged(darkIntensity);
- }
- }
-
- public void onNavigationBarLumaSamplingEnabled(int displayId, boolean enable) {
- mSharedState.mLumaSamplingDisplayId = displayId;
- mSharedState.mIsLumaSamplingEnabled = enable;
- if (mTaskbarActivityContext != null) {
- mTaskbarActivityContext.onNavigationBarLumaSamplingEnabled(displayId, enable);
- }
- }
-
- private void removeActivityCallbacksAndListeners() {
- if (mActivity != null) {
- mActivity.removeOnDeviceProfileChangeListener(mDebugActivityDeviceProfileChanged);
- Log.d(TASKBAR_NOT_DESTROYED_TAG,
- "unregistering activity lifecycle callbacks from "
- + "removeActivityCallbackAndListeners().");
- mActivity.removeEventCallback(EVENT_DESTROYED, mActivityOnDestroyCallback);
- UnfoldTransitionProgressProvider unfoldTransitionProgressProvider =
- getUnfoldTransitionProgressProviderForActivity(mActivity);
- if (unfoldTransitionProgressProvider != null) {
- unfoldTransitionProgressProvider.removeCallback(mUnfoldTransitionProgressListener);
- }
- }
- }
-
- /**
- * Called when the manager is no longer needed
- */
- public void destroy() {
- debugWhyTaskbarNotDestroyed("TaskbarManager#destroy()");
- removeActivityCallbacksAndListeners();
- UI_HELPER_EXECUTOR.execute(
- () -> mTaskbarBroadcastReceiver.unregisterReceiverSafely(mContext));
- destroyExistingTaskbar();
- removeTaskbarRootViewFromWindow();
- if (mUserUnlocked) {
- DisplayController.INSTANCE.get(mContext).removeChangeListener(mRecreationListener);
- }
- if (LawnchairApp.isRecentsEnabled()) {
- final Uri USER_SETUP_COMPLETE_URI = Settings.Secure.getUriFor(
- Settings.Secure.USER_SETUP_COMPLETE);
- final Uri NAV_BAR_KIDS_MODE = Settings.Secure.getUriFor(
- Settings.Secure.NAV_BAR_KIDS_MODE);
-
- SettingsCache.INSTANCE.get(mContext)
- .unregister(USER_SETUP_COMPLETE_URI, mOnSettingsChangeListener);
- SettingsCache.INSTANCE.get(mContext)
- .unregister(NAV_BAR_KIDS_MODE, mOnSettingsChangeListener);
- }
-
- Log.d(TASKBAR_NOT_DESTROYED_TAG, "unregistering component callbacks from destroy().");
- mContext.unregisterComponentCallbacks(mComponentCallbacks);
- mContext.unregisterReceiver(mShutdownReceiver);
- }
-
- public @Nullable TaskbarActivityContext getCurrentActivityContext() {
- return mTaskbarActivityContext;
- }
-
- public void dumpLogs(String prefix, PrintWriter pw) {
- pw.println(prefix + "TaskbarManager:");
- if (mTaskbarActivityContext == null) {
- pw.println(prefix + "\tTaskbarActivityContext: null");
- } else {
- mTaskbarActivityContext.dumpLogs(prefix + "\t", pw);
- }
- }
-
- @VisibleForTesting
- void addTaskbarRootViewToWindow() {
- if (enableTaskbarNoRecreate() && !mAddedWindow && mTaskbarActivityContext != null) {
- mWindowManager.addView(mTaskbarRootLayout,
- mTaskbarActivityContext.getWindowLayoutParams());
- mAddedWindow = true;
- }
- }
-
- @VisibleForTesting
- void removeTaskbarRootViewFromWindow() {
- if (enableTaskbarNoRecreate() && mAddedWindow) {
- mWindowManager.removeViewImmediate(mTaskbarRootLayout);
- mAddedWindow = false;
- }
- }
-
- /** Temp logs for b/254119092. */
- public void debugWhyTaskbarNotDestroyed(String debugReason) {
- StringJoiner log = new StringJoiner("\n");
- log.add(debugReason);
-
- boolean activityTaskbarPresent = mActivity != null
- && mActivity.getDeviceProfile().isTaskbarPresent;
- boolean contextTaskbarPresent = mUserUnlocked
- && LauncherAppState.getIDP(mContext).getDeviceProfile(mContext).isTaskbarPresent;
- if (activityTaskbarPresent == contextTaskbarPresent) {
- log.add("mActivity and mContext agree taskbarIsPresent=" + contextTaskbarPresent);
- Log.d(TASKBAR_NOT_DESTROYED_TAG, log.toString());
- return;
- }
-
- log.add("mActivity and mContext device profiles have different values, add more logs.");
-
- log.add("\tmActivity logs:");
- log.add("\t\tmActivity=" + mActivity);
- if (mActivity != null) {
- log.add("\t\tmActivity.getResources().getConfiguration()="
- + mActivity.getResources().getConfiguration());
- log.add("\t\tmActivity.getDeviceProfile().isTaskbarPresent="
- + activityTaskbarPresent);
- }
- log.add("\tmContext logs:");
- log.add("\t\tmContext=" + mContext);
- log.add("\t\tmContext.getResources().getConfiguration()="
- + mContext.getResources().getConfiguration());
- if (mUserUnlocked) {
- log.add("\t\tLauncherAppState.getIDP().getDeviceProfile(mContext).isTaskbarPresent="
- + contextTaskbarPresent);
- } else {
- log.add("\t\tCouldn't get DeviceProfile because !mUserUnlocked");
- }
-
- Log.d(TASKBAR_NOT_DESTROYED_TAG, log.toString());
- }
-
- private final DeviceProfile.OnDeviceProfileChangeListener mDebugActivityDeviceProfileChanged =
- dp -> debugWhyTaskbarNotDestroyed("mActivity onDeviceProfileChanged");
-}
\ No newline at end of file
diff --git a/quickstep/src/com/android/launcher3/taskbar/allapps/TaskbarAllAppsFallbackSearchContainer.java b/quickstep/src/com/android/launcher3/taskbar/allapps/TaskbarAllAppsFallbackSearchContainer.java
deleted file mode 100644
index 53fe06d32c..0000000000
--- a/quickstep/src/com/android/launcher3/taskbar/allapps/TaskbarAllAppsFallbackSearchContainer.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2022 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.taskbar.allapps;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.view.View;
-
-import androidx.annotation.Nullable;
-
-import com.android.launcher3.ExtendedEditText;
-import com.android.launcher3.allapps.ActivityAllAppsContainerView;
-import com.android.launcher3.allapps.SearchUiManager;
-
-/** Empty search container for Taskbar All Apps used as a fallback if search is not supported. */
-public class TaskbarAllAppsFallbackSearchContainer extends View implements SearchUiManager {
- public TaskbarAllAppsFallbackSearchContainer(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
- }
-
- public TaskbarAllAppsFallbackSearchContainer(
- Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- }
-
- @Override
- public void initializeSearch(ActivityAllAppsContainerView> containerView) {
- // Do nothing.
- }
-
- @Override
- public void resetSearch() {
- // Do nothing.
- }
-
- @Nullable
- @Override
- public ExtendedEditText getEditText() {
- return null;
- }
-}
diff --git a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleStashController.java b/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleStashController.java
deleted file mode 100644
index 4f927f07c3..0000000000
--- a/quickstep/src/com/android/launcher3/taskbar/bubbles/BubbleStashController.java
+++ /dev/null
@@ -1,481 +0,0 @@
-/*
- * Copyright (C) 2023 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.taskbar.bubbles;
-
-import static java.lang.Math.abs;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.AnimatorSet;
-import android.annotation.Nullable;
-import android.view.InsetsController;
-import android.view.MotionEvent;
-import android.view.View;
-
-import com.android.launcher3.R;
-import com.android.launcher3.anim.AnimatedFloat;
-import com.android.launcher3.taskbar.StashedHandleViewController;
-import com.android.launcher3.taskbar.TaskbarActivityContext;
-import com.android.launcher3.taskbar.TaskbarControllers;
-import com.android.launcher3.taskbar.TaskbarInsetsController;
-import com.android.launcher3.taskbar.TaskbarStashController;
-import com.android.launcher3.util.MultiPropertyFactory;
-import com.android.wm.shell.common.bubbles.BubbleBarLocation;
-import com.android.wm.shell.shared.animation.PhysicsAnimator;
-
-/**
- * Coordinates between controllers such as BubbleBarView and
- * BubbleHandleViewController to
- * create a cohesive animation between stashed/unstashed states.
- */
-public class BubbleStashController {
-
- private static final String TAG = "BubbleStashController";
-
- /**
- * How long to stash/unstash.
- */
- public static final long BAR_STASH_DURATION = InsetsController.ANIMATION_DURATION_RESIZE;
-
- /**
- * The scale bubble bar animates to when being stashed.
- */
- private static final float STASHED_BAR_SCALE = 0.5f;
-
- protected final TaskbarActivityContext mActivity;
-
- // Initialized in init.
- private TaskbarControllers mControllers;
- private TaskbarInsetsController mTaskbarInsetsController;
- private BubbleBarViewController mBarViewController;
- private BubbleStashedHandleViewController mHandleViewController;
- private TaskbarStashController mTaskbarStashController;
-
- private MultiPropertyFactory.MultiProperty mIconAlphaForStash;
- private AnimatedFloat mIconScaleForStash;
- private AnimatedFloat mIconTranslationYForStash;
- private MultiPropertyFactory.MultiProperty mBubbleStashedHandleAlpha;
-
- private boolean mRequestedStashState;
- private boolean mRequestedExpandedState;
-
- private boolean mIsStashed;
- private int mStashedHeight;
- private int mUnstashedHeight;
- private boolean mBubblesShowingOnHome;
- private boolean mBubblesShowingOnOverview;
- private boolean mIsSysuiLocked;
-
- private final float mHandleCenterFromScreenBottom;
-
- @Nullable
- private AnimatorSet mAnimator;
-
- public BubbleStashController(TaskbarActivityContext activity) {
- mActivity = activity;
- // the handle is centered within the stashed taskbar area
- mHandleCenterFromScreenBottom = mActivity.getResources().getDimensionPixelSize(R.dimen.bubblebar_stashed_size)
- / 2f;
- }
-
- public void init(TaskbarControllers controllers, BubbleControllers bubbleControllers) {
- mControllers = controllers;
- mTaskbarInsetsController = controllers.taskbarInsetsController;
- mBarViewController = bubbleControllers.bubbleBarViewController;
- mHandleViewController = bubbleControllers.bubbleStashedHandleViewController;
- mTaskbarStashController = controllers.taskbarStashController;
-
- mIconAlphaForStash = mBarViewController.getBubbleBarAlpha().get(0);
- mIconScaleForStash = mBarViewController.getBubbleBarScale();
- mIconTranslationYForStash = mBarViewController.getBubbleBarTranslationY();
-
- mBubbleStashedHandleAlpha = mHandleViewController.getStashedHandleAlpha().get(
- StashedHandleViewController.ALPHA_INDEX_STASHED);
-
- mStashedHeight = mHandleViewController.getStashedHeight();
- mUnstashedHeight = mHandleViewController.getUnstashedHeight();
- }
-
- /**
- * Returns the touchable height of the bubble bar based on it's stashed state.
- */
- public int getTouchableHeight() {
- return mIsStashed ? mStashedHeight : mUnstashedHeight;
- }
-
- /**
- * Returns whether the bubble bar is currently stashed.
- */
- public boolean isStashed() {
- return mIsStashed;
- }
-
- /**
- * Animates the handle (or bubble bar depending on state) to be visible after
- * the device is
- * unlocked.
- *
- *
- * Normally either the bubble bar or the handle is visible,
- * and {@link #showBubbleBar(boolean)} and {@link #stashBubbleBar()} are used to
- * transition
- * between these two states. But the transition from the state where both the
- * bar and handle
- * are invisible is slightly different.
- */
- private void animateAfterUnlock() {
- AnimatorSet animatorSet = new AnimatorSet();
- if (mBubblesShowingOnHome || mBubblesShowingOnOverview) {
- mIsStashed = false;
- animatorSet.playTogether(mIconScaleForStash.animateToValue(1),
- mIconTranslationYForStash.animateToValue(getBubbleBarTranslationY()),
- mIconAlphaForStash.animateToValue(1));
- } else {
- mIsStashed = true;
- animatorSet.playTogether(mBubbleStashedHandleAlpha.animateToValue(1));
- }
-
- animatorSet.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- onIsStashedChanged();
- }
- });
- animatorSet.setDuration(BAR_STASH_DURATION).start();
- }
-
- /**
- * Called when launcher enters or exits the home page. Bubbles are unstashed on
- * home.
- */
- public void setBubblesShowingOnHome(boolean onHome) {
- if (mBubblesShowingOnHome != onHome) {
- mBubblesShowingOnHome = onHome;
-
- if (!mBarViewController.hasBubbles()) {
- // if there are no bubbles, there's nothing to show, so just return.
- return;
- }
-
- if (mBubblesShowingOnHome) {
- showBubbleBar(/* expanded= */ false);
- // When transitioning from app to home the stash animator may already have been
- // created, so we need to animate the bubble bar here to align with hotseat.
- if (!mIsStashed) {
- mIconTranslationYForStash.animateToValue(getBubbleBarTranslationYForHotseat())
- .start();
- }
- // If the bubble bar is already unstashed, the taskbar touchable region won't be
- // updated correctly, so force an update here.
- mControllers
- .runAfterInit(() -> mTaskbarInsetsController.onTaskbarOrBubblebarWindowHeightOrInsetsChanged());
- } else if (!mBarViewController.isExpanded()) {
- stashBubbleBar();
- }
- }
- }
-
- /** Whether bubbles are showing on the launcher home page. */
- public boolean isBubblesShowingOnHome() {
- return mBubblesShowingOnHome;
- }
-
- // TODO: when tapping on an app in overview, this is a bit delayed compared to
- // taskbar stashing
- /**
- * Called when launcher enters or exits overview. Bubbles are unstashed on
- * overview.
- */
- public void setBubblesShowingOnOverview(boolean onOverview) {
- if (mBubblesShowingOnOverview != onOverview) {
- mBubblesShowingOnOverview = onOverview;
- if (!mBubblesShowingOnOverview && !mBarViewController.isExpanded()) {
- stashBubbleBar();
- } else {
- // When transitioning to overview the stash animator may already have been
- // created, so we need to animate the bubble bar here to align with taskbar.
- mIconTranslationYForStash.animateToValue(getBubbleBarTranslationYForTaskbar())
- .start();
- }
- }
- }
-
- /** Whether bubbles are showing on Overview. */
- public boolean isBubblesShowingOnOverview() {
- return mBubblesShowingOnOverview;
- }
-
- /**
- * Called when sysui locked state changes, when locked, bubble bar is stashed.
- */
- public void onSysuiLockedStateChange(boolean isSysuiLocked) {
- if (isSysuiLocked != mIsSysuiLocked) {
- mIsSysuiLocked = isSysuiLocked;
- if (!mIsSysuiLocked && mBarViewController.hasBubbles()) {
- animateAfterUnlock();
- }
- }
- }
-
- /**
- * Stashes the bubble bar if allowed based on other state (e.g. on home and
- * overview the
- * bar does not stash).
- */
- public void stashBubbleBar() {
- mRequestedStashState = true;
- mRequestedExpandedState = false;
- updateStashedAndExpandedState();
- }
-
- /**
- * Shows the bubble bar, and expands bubbles depending on
- * {@param expandBubbles}.
- */
- public void showBubbleBar(boolean expandBubbles) {
- mRequestedStashState = false;
- mRequestedExpandedState = expandBubbles;
- updateStashedAndExpandedState();
- }
-
- private void updateStashedAndExpandedState() {
- if (mBarViewController.isHiddenForNoBubbles()) {
- // If there are no bubbles the bar and handle are invisible, nothing to do here.
- return;
- }
- boolean isStashed = mRequestedStashState
- && !mBubblesShowingOnHome
- && !mBubblesShowingOnOverview;
- if (mIsStashed != isStashed) {
- // notify the view controller that the stash state is about to change so that it
- // can
- // cancel an ongoing animation if there is one.
- // note that this has to be called before updating mIsStashed with the new
- // value,
- // otherwise interrupting an ongoing animation may update it again with the
- // wrong state
- mBarViewController.onStashStateChanging();
- mIsStashed = isStashed;
- if (mAnimator != null) {
- mAnimator.cancel();
- }
- mAnimator = createStashAnimator(mIsStashed, BAR_STASH_DURATION);
- mAnimator.start();
- onIsStashedChanged();
- }
- if (mBarViewController.isExpanded() != mRequestedExpandedState) {
- mBarViewController.setExpanded(mRequestedExpandedState);
- }
- }
-
- /**
- * Create a stash animation.
- *
- * @param isStashed whether it's a stash animation or an unstash animation
- * @param duration duration of the animation
- * @return the animation
- */
- private AnimatorSet createStashAnimator(boolean isStashed, long duration) {
- AnimatorSet animatorSet = new AnimatorSet();
-
- AnimatorSet fullLengthAnimatorSet = new AnimatorSet();
- // Not exactly half and may overlap. See [first|second]HalfDurationScale below.
- AnimatorSet firstHalfAnimatorSet = new AnimatorSet();
- AnimatorSet secondHalfAnimatorSet = new AnimatorSet();
-
- final float firstHalfDurationScale;
- final float secondHalfDurationScale;
-
- if (isStashed) {
- firstHalfDurationScale = 0.75f;
- secondHalfDurationScale = 0.5f;
-
- fullLengthAnimatorSet.play(
- mIconTranslationYForStash.animateToValue(getStashTranslation()));
-
- firstHalfAnimatorSet.playTogether(
- mIconAlphaForStash.animateToValue(0),
- mIconScaleForStash.animateToValue(STASHED_BAR_SCALE));
- secondHalfAnimatorSet.playTogether(
- mBubbleStashedHandleAlpha.animateToValue(1));
- } else {
- firstHalfDurationScale = 0.5f;
- secondHalfDurationScale = 0.75f;
-
- final float translationY = getBubbleBarTranslationY();
-
- fullLengthAnimatorSet.playTogether(
- mIconScaleForStash.animateToValue(1),
- mIconTranslationYForStash.animateToValue(translationY));
-
- firstHalfAnimatorSet.playTogether(
- mBubbleStashedHandleAlpha.animateToValue(0));
- secondHalfAnimatorSet.playTogether(
- mIconAlphaForStash.animateToValue(1));
- }
-
- fullLengthAnimatorSet.play(mHandleViewController.createRevealAnimToIsStashed(isStashed));
-
- fullLengthAnimatorSet.setDuration(duration);
- firstHalfAnimatorSet.setDuration((long) (duration * firstHalfDurationScale));
- secondHalfAnimatorSet.setDuration((long) (duration * secondHalfDurationScale));
- secondHalfAnimatorSet.setStartDelay((long) (duration * (1 - secondHalfDurationScale)));
-
- animatorSet.playTogether(fullLengthAnimatorSet, firstHalfAnimatorSet,
- secondHalfAnimatorSet);
- animatorSet.addListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mAnimator = null;
- mControllers.runAfterInit(() -> {
- if (isStashed) {
- mBarViewController.setExpanded(false);
- }
- mTaskbarInsetsController.onTaskbarOrBubblebarWindowHeightOrInsetsChanged();
- });
- }
- });
- return animatorSet;
- }
-
- private float getStashTranslation() {
- return (mUnstashedHeight - mStashedHeight) / 2f;
- }
-
- private void onIsStashedChanged() {
- mControllers.runAfterInit(() -> {
- mHandleViewController.onIsStashedChanged();
- mTaskbarInsetsController.onTaskbarOrBubblebarWindowHeightOrInsetsChanged();
- });
- }
-
- public float getBubbleBarTranslationYForTaskbar() {
- return -mActivity.getDeviceProfile().taskbarBottomMargin;
- }
-
- private float getBubbleBarTranslationYForHotseat() {
- final float hotseatBottomSpace = mActivity.getDeviceProfile().hotseatBarBottomSpacePx;
- final float hotseatCellHeight = mActivity.getDeviceProfile().hotseatCellHeightPx;
- return -hotseatBottomSpace - hotseatCellHeight + mUnstashedHeight - abs(
- hotseatCellHeight - mUnstashedHeight) / 2;
- }
-
- public float getBubbleBarTranslationY() {
- // If we're on home, adjust the translation so the bubble bar aligns with
- // hotseat.
- // Otherwise we're either showing in an app or in overview. In either case
- // adjust it so
- // the bubble bar aligns with the taskbar.
- return mBubblesShowingOnHome ? getBubbleBarTranslationYForHotseat()
- : getBubbleBarTranslationYForTaskbar();
- }
-
- /**
- * The difference on the Y axis between the center of the handle and the center
- * of the bubble
- * bar.
- */
- public float getDiffBetweenHandleAndBarCenters() {
- // the difference between the centers of the handle and the bubble bar is the
- // difference
- // between their distance from the bottom of the screen.
-
- float barCenter = mBarViewController.getBubbleBarCollapsedHeight() / 2f;
- return mHandleCenterFromScreenBottom - barCenter;
- }
-
- /** The distance the handle moves as part of the new bubble animation. */
- public float getStashedHandleTranslationForNewBubbleAnimation() {
- // the should move up to the top of the stashed taskbar area. it is centered
- // within it so
- // it should move the same distance as it is away from the bottom.
- return -mHandleCenterFromScreenBottom;
- }
-
- /** Checks whether the motion event is over the stash handle. */
- public boolean isEventOverStashHandle(MotionEvent ev) {
- return mHandleViewController.isEventOverHandle(ev);
- }
-
- /** Set a bubble bar location */
- public void setBubbleBarLocation(BubbleBarLocation bubbleBarLocation) {
- mHandleViewController.setBubbleBarLocation(bubbleBarLocation);
- }
-
- /** Returns the [PhysicsAnimator] for the stashed handle view. */
- public PhysicsAnimator getStashedHandlePhysicsAnimator() {
- return mHandleViewController.getPhysicsAnimator();
- }
-
- /** Notifies taskbar that it should update its touchable region. */
- public void updateTaskbarTouchRegion() {
- mTaskbarInsetsController.onTaskbarOrBubblebarWindowHeightOrInsetsChanged();
- }
-
- /** Shows the bubble bar immediately without animation. */
- public void showBubbleBarImmediate() {
- mHandleViewController.setTranslationYForSwipe(0);
- mIconTranslationYForStash.updateValue(getBubbleBarTranslationY());
- mIconAlphaForStash.setValue(1);
- mIconScaleForStash.updateValue(1);
- mIsStashed = false;
- onIsStashedChanged();
- }
-
- /** Stashes the bubble bar immediately without animation. */
- public void stashBubbleBarImmediate() {
- mHandleViewController.setTranslationYForSwipe(0);
- mBubbleStashedHandleAlpha.setValue(1);
- mIconAlphaForStash.setValue(0);
- mIconTranslationYForStash.updateValue(getStashTranslation());
- mIconScaleForStash.updateValue(STASHED_BAR_SCALE);
- mIsStashed = true;
- onIsStashedChanged();
- }
-
- /**
- * Updates the values of the internal animators after the new bubble animation
- * was interrupted
- *
- * @param isStashed whether the current state should be stashed
- * @param bubbleBarTranslationY the current bubble bar translation. this is only
- * used if the
- * bubble bar is showing to ensure that the stash
- * animator runs
- * smoothly.
- */
- public void onNewBubbleAnimationInterrupted(boolean isStashed, float bubbleBarTranslationY) {
- if (isStashed) {
- mBubbleStashedHandleAlpha.setValue(1);
- mIconAlphaForStash.setValue(0);
- mIconScaleForStash.updateValue(STASHED_BAR_SCALE);
- mIconTranslationYForStash.updateValue(getStashTranslation());
- } else {
- mBubbleStashedHandleAlpha.setValue(0);
- mHandleViewController.setTranslationYForSwipe(0);
- mIconAlphaForStash.setValue(1);
- mIconScaleForStash.updateValue(1);
- mIconTranslationYForStash.updateValue(bubbleBarTranslationY);
- }
- mIsStashed = isStashed;
- onIsStashedChanged();
- }
-
- /** Set the translation Y for the stashed handle. */
- public void setHandleTranslationY(float ty) {
- mHandleViewController.setTranslationYForSwipe(ty);
- }
-}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/BaseRecentsViewStateController.java b/quickstep/src/com/android/launcher3/uioverrides/BaseRecentsViewStateController.java
deleted file mode 100644
index 14d391ba1c..0000000000
--- a/quickstep/src/com/android/launcher3/uioverrides/BaseRecentsViewStateController.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2019 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.uioverrides;
-
-import static com.android.app.animation.Interpolators.ACCELERATE_DECELERATE;
-import static com.android.app.animation.Interpolators.AGGRESSIVE_EASE_IN_OUT;
-import static com.android.app.animation.Interpolators.FINAL_FRAME;
-import static com.android.app.animation.Interpolators.INSTANT;
-import static com.android.app.animation.Interpolators.LINEAR;
-import static com.android.launcher3.LauncherState.QUICK_SWITCH_FROM_HOME;
-import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_SPLIT_SELECTION_EXIT_HOME;
-import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_FADE;
-import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_MODAL;
-import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SCALE;
-import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_SPLIT_SELECT_INSTRUCTIONS_FADE;
-import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_X;
-import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_TRANSLATE_Y;
-import static com.android.launcher3.states.StateAnimationConfig.SKIP_OVERVIEW;
-import static com.android.quickstep.views.RecentsView.ADJACENT_PAGE_HORIZONTAL_OFFSET;
-import static com.android.quickstep.views.RecentsView.RECENTS_GRID_PROGRESS;
-import static com.android.quickstep.views.RecentsView.RECENTS_SCALE_PROPERTY;
-import static com.android.quickstep.views.RecentsView.TASK_SECONDARY_TRANSLATION;
-import static com.android.quickstep.views.RecentsView.TASK_THUMBNAIL_SPLASH_ALPHA;
-
-import android.util.FloatProperty;
-import android.view.animation.Interpolator;
-
-import androidx.annotation.NonNull;
-
-import com.android.launcher3.LauncherState;
-import com.android.launcher3.anim.PendingAnimation;
-import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.statemanager.StateManager.StateHandler;
-import com.android.launcher3.states.StateAnimationConfig;
-import com.android.quickstep.views.RecentsView;
-
-/**
- * State handler for recents view. Manages UI changes and animations for recents view based off the
- * current {@link LauncherState}.
- *
- * @param the recents view
- */
-public abstract class BaseRecentsViewStateController
- implements StateHandler {
- protected final T mRecentsView;
- protected final QuickstepLauncher mLauncher;
-
- public BaseRecentsViewStateController(@NonNull QuickstepLauncher launcher) {
- mLauncher = launcher;
- mRecentsView = launcher.getOverviewPanel();
- }
-
- @Override
- public void setState(@NonNull LauncherState state) {
- float[] scaleAndOffset = state.getOverviewScaleAndOffset(mLauncher);
- RECENTS_SCALE_PROPERTY.set(mRecentsView, scaleAndOffset[0]);
- ADJACENT_PAGE_HORIZONTAL_OFFSET.set(mRecentsView, scaleAndOffset[1]);
- TASK_SECONDARY_TRANSLATION.set(mRecentsView, 0f);
-
- getContentAlphaProperty().set(mRecentsView, state.isRecentsViewVisible ? 1f : 0);
- getTaskModalnessProperty().set(mRecentsView, state.getOverviewModalness());
- RECENTS_GRID_PROGRESS.set(mRecentsView,
- state.displayOverviewTasksAsGrid(mLauncher.getDeviceProfile()) ? 1f : 0f);
- TASK_THUMBNAIL_SPLASH_ALPHA.set(mRecentsView, state.showTaskThumbnailSplash() ? 1f : 0f);
- }
-
- @Override
- public void setStateWithAnimation(LauncherState toState, StateAnimationConfig config,
- PendingAnimation builder) {
- if (config.hasAnimationFlag(SKIP_OVERVIEW)) {
- return;
- }
- setStateWithAnimationInternal(toState, config, builder);
- builder.addEndListener(success -> {
- if (!success) {
- mRecentsView.reset();
- }
- });
- }
-
- /**
- * Core logic for animating the recents view UI.
- *
- * @param toState state to animate to
- * @param config current animation config
- * @param setter animator set builder
- */
- void setStateWithAnimationInternal(@NonNull final LauncherState toState,
- @NonNull StateAnimationConfig config, @NonNull PendingAnimation setter) {
- float[] scaleAndOffset = toState.getOverviewScaleAndOffset(mLauncher);
- setter.setFloat(mRecentsView, RECENTS_SCALE_PROPERTY, scaleAndOffset[0],
- config.getInterpolator(ANIM_OVERVIEW_SCALE, LINEAR));
- setter.setFloat(mRecentsView, ADJACENT_PAGE_HORIZONTAL_OFFSET, scaleAndOffset[1],
- config.getInterpolator(ANIM_OVERVIEW_TRANSLATE_X, LINEAR));
- setter.setFloat(mRecentsView, TASK_SECONDARY_TRANSLATION, 0f,
- config.getInterpolator(ANIM_OVERVIEW_TRANSLATE_Y, LINEAR));
-
- boolean exitingOverview =
- !FeatureFlags.enableSplitContextually() && !toState.isRecentsViewVisible;
- if (mRecentsView.isSplitSelectionActive() && exitingOverview) {
- setter.add(mRecentsView.getSplitSelectController().getSplitAnimationController()
- .createPlaceholderDismissAnim(mLauncher, LAUNCHER_SPLIT_SELECTION_EXIT_HOME,
- setter.getDuration()));
- setter.setViewAlpha(
- mRecentsView.getSplitInstructionsView(),
- 0,
- config.getInterpolator(
- ANIM_OVERVIEW_SPLIT_SELECT_INSTRUCTIONS_FADE,
- LINEAR
- )
- );
- }
-
- setter.setFloat(mRecentsView, getContentAlphaProperty(),
- toState.isRecentsViewVisible ? 1 : 0,
- config.getInterpolator(ANIM_OVERVIEW_FADE, AGGRESSIVE_EASE_IN_OUT));
-
- setter.setFloat(
- mRecentsView, getTaskModalnessProperty(),
- toState.getOverviewModalness(),
- config.getInterpolator(ANIM_OVERVIEW_MODAL, LINEAR));
-
- LauncherState fromState = mLauncher.getStateManager().getState();
- setter.setFloat(mRecentsView, TASK_THUMBNAIL_SPLASH_ALPHA,
- toState.showTaskThumbnailSplash() ? 1f : 0f,
- getOverviewInterpolator(fromState, toState));
-
- setter.setFloat(mRecentsView, RECENTS_GRID_PROGRESS,
- toState.displayOverviewTasksAsGrid(mLauncher.getDeviceProfile()) ? 1f : 0f,
- getOverviewInterpolator(fromState, toState));
- }
-
- private Interpolator getOverviewInterpolator(LauncherState fromState, LauncherState toState) {
- return fromState == QUICK_SWITCH_FROM_HOME
- ? ACCELERATE_DECELERATE
- : toState.isRecentsViewVisible ? INSTANT : FINAL_FRAME;
- }
-
- abstract FloatProperty getTaskModalnessProperty();
-
- /**
- * Get property for content alpha for the recents view.
- *
- * @return the float property for the view's content alpha
- */
- abstract FloatProperty getContentAlphaProperty();
-}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/QuickstepAppWidgetHost.java b/quickstep/src/com/android/launcher3/uioverrides/QuickstepAppWidgetHost.java
deleted file mode 100644
index 45813ce52e..0000000000
--- a/quickstep/src/com/android/launcher3/uioverrides/QuickstepAppWidgetHost.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Copyright (C) 2022 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.uioverrides;
-
-import static com.android.launcher3.widget.LauncherWidgetHolder.APPWIDGET_HOST_ID;
-
-import android.appwidget.AppWidgetHost;
-import android.appwidget.AppWidgetProviderInfo;
-import android.content.Context;
-import android.os.Looper;
-
-import androidx.annotation.NonNull;
-
-import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.util.Executors;
-import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
-import com.android.launcher3.widget.LauncherWidgetHolder;
-
-import java.util.function.IntConsumer;
-
-/**
- * {@link AppWidgetHost} that is used to receive the changes to the widgets without
- * storing any {@code Activity} info like that of the launcher.
- */
-final class QuickstepAppWidgetHost extends AppWidgetHost {
- private final @NonNull Context mContext;
- private final @NonNull IntConsumer mAppWidgetRemovedCallback;
- private final @NonNull LauncherWidgetHolder.ProviderChangedListener mProvidersChangedListener;
-
- QuickstepAppWidgetHost(@NonNull Context context, @NonNull IntConsumer appWidgetRemovedCallback,
- @NonNull LauncherWidgetHolder.ProviderChangedListener listener,
- @NonNull Looper looper) {
- super(context, APPWIDGET_HOST_ID, null, looper);
- mContext = context;
- mAppWidgetRemovedCallback = appWidgetRemovedCallback;
- mProvidersChangedListener = listener;
- }
-
- @Override
- protected void onProvidersChanged() {
- mProvidersChangedListener.notifyWidgetProvidersChanged();
- }
-
- @Override
- public void onAppWidgetRemoved(int appWidgetId) {
- // Route the call via model thread, in case it comes while a loader-bind is in progress
- Executors.MODEL_EXECUTOR.execute(
- () -> Executors.MAIN_EXECUTOR.execute(
- () -> mAppWidgetRemovedCallback.accept(appWidgetId)));
- }
-
- @Override
- protected void onProviderChanged(int appWidgetId, @NonNull AppWidgetProviderInfo appWidget) {
- LauncherAppWidgetProviderInfo info = LauncherAppWidgetProviderInfo.fromProviderInfo(
- mContext, appWidget);
- super.onProviderChanged(appWidgetId, info);
- // The super method updates the dimensions of the providerInfo. Update the
- // launcher spans accordingly.
- info.initSpans(mContext, LauncherAppState.getIDP(mContext));
- }
-}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.java b/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.java
deleted file mode 100644
index 235ec7b101..0000000000
--- a/quickstep/src/com/android/launcher3/uioverrides/RecentsViewStateController.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (C) 2017 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.uioverrides;
-
-import static com.android.app.animation.Interpolators.LINEAR;
-import static com.android.launcher3.LauncherState.CLEAR_ALL_BUTTON;
-import static com.android.launcher3.LauncherState.OVERVIEW;
-import static com.android.launcher3.LauncherState.OVERVIEW_ACTIONS;
-import static com.android.launcher3.LauncherState.OVERVIEW_SPLIT_SELECT;
-import static com.android.launcher3.states.StateAnimationConfig.ANIM_OVERVIEW_ACTIONS_FADE;
-import static com.android.quickstep.views.RecentsView.CONTENT_ALPHA;
-import static com.android.quickstep.views.RecentsView.FULLSCREEN_PROGRESS;
-import static com.android.quickstep.views.RecentsView.TASK_MODALNESS;
-import static com.android.quickstep.views.RecentsView.TASK_PRIMARY_SPLIT_TRANSLATION;
-import static com.android.quickstep.views.RecentsView.TASK_SECONDARY_SPLIT_TRANSLATION;
-import static com.android.quickstep.views.TaskView.FLAG_UPDATE_ALL;
-import static com.android.wm.shell.Flags.enableSplitContextual;
-
-import android.animation.AnimatorSet;
-import android.annotation.TargetApi;
-import android.os.Build;
-import android.util.FloatProperty;
-import android.util.Log;
-import android.util.Pair;
-
-import androidx.annotation.NonNull;
-
-import com.android.launcher3.LauncherState;
-import com.android.launcher3.Utilities;
-import com.android.launcher3.anim.AnimatedFloat;
-import com.android.launcher3.anim.AnimatorListeners;
-import com.android.launcher3.anim.PendingAnimation;
-import com.android.launcher3.anim.PropertySetter;
-import com.android.launcher3.states.StateAnimationConfig;
-import com.android.quickstep.orientation.RecentsPagedOrientationHandler;
-import com.android.quickstep.util.AnimUtils;
-import com.android.quickstep.util.SplitAnimationTimings;
-import com.android.quickstep.views.ClearAllButton;
-import com.android.quickstep.views.LauncherRecentsView;
-import com.android.quickstep.views.RecentsView;
-
-/**
- * State handler for handling UI changes for {@link LauncherRecentsView}. In addition to managing
- * the basic view properties, this class also manages changes in the task visuals.
- */
-@TargetApi(Build.VERSION_CODES.O)
-public final class RecentsViewStateController extends
- BaseRecentsViewStateController {
-
- public RecentsViewStateController(QuickstepLauncher launcher) {
- super(launcher);
- }
-
- @Override
- public void setState(@NonNull LauncherState state) {
- super.setState(state);
- if (state.isRecentsViewVisible) {
- mRecentsView.updateEmptyMessage();
- } else {
- mRecentsView.resetTaskVisuals();
- }
- setAlphas(PropertySetter.NO_ANIM_PROPERTY_SETTER, new StateAnimationConfig(), state);
- mRecentsView.setFullscreenProgress(state.getOverviewFullscreenProgress());
- // In Overview, we may be layering app surfaces behind Launcher, so we need to notify
- // DepthController to prevent optimizations which might occlude the layers behind
- mLauncher.getDepthController().setHasContentBehindLauncher(state.isRecentsViewVisible);
-
- PendingAnimation builder =
- new PendingAnimation(state.getTransitionDuration(mLauncher, true));
-
- handleSplitSelectionState(state, builder, /* animate */false);
- }
-
- @Override
- void setStateWithAnimationInternal(@NonNull LauncherState toState,
- @NonNull StateAnimationConfig config, @NonNull PendingAnimation builder) {
- super.setStateWithAnimationInternal(toState, config, builder);
-
- if (toState.isRecentsViewVisible) {
- // While animating into recents, update the visible task data as needed
- builder.addOnFrameCallback(() -> mRecentsView.loadVisibleTaskData(FLAG_UPDATE_ALL));
- mRecentsView.updateEmptyMessage();
- // TODO(b/246283207): Remove logging once root cause of flake detected.
- if (Utilities.isRunningInTestHarness()) {
- Log.d("b/246283207", "RecentsView#setStateWithAnimationInternal getCurrentPage(): "
- + mRecentsView.getCurrentPage()
- + ", getScrollForPage(getCurrentPage())): "
- + mRecentsView.getScrollForPage(mRecentsView.getCurrentPage()));
- }
- } else {
- builder.addListener(
- AnimatorListeners.forSuccessCallback(mRecentsView::resetTaskVisuals));
- }
- // In Overview, we may be layering app surfaces behind Launcher, so we need to notify
- // DepthController to prevent optimizations which might occlude the layers behind
- builder.addListener(AnimatorListeners.forSuccessCallback(() ->
- mLauncher.getDepthController().setHasContentBehindLauncher(
- toState.isRecentsViewVisible)));
-
- handleSplitSelectionState(toState, builder, /* animate */true);
-
- setAlphas(builder, config, toState);
- builder.setFloat(mRecentsView, FULLSCREEN_PROGRESS,
- toState.getOverviewFullscreenProgress(), LINEAR);
- }
-
- /**
- * Create or dismiss split screen select animations.
- * @param builder if null then this will run the split select animations right away, otherwise
- * will add animations to builder.
- */
- private void handleSplitSelectionState(@NonNull LauncherState toState,
- @NonNull PendingAnimation builder, boolean animate) {
- boolean goingToOverviewFromWorkspaceContextual = enableSplitContextual() &&
- toState == OVERVIEW && mLauncher.isSplitSelectionActive();
- if (toState != OVERVIEW_SPLIT_SELECT && !goingToOverviewFromWorkspaceContextual) {
- // Not going to split
- return;
- }
-
- // Create transition animations to split select
- RecentsPagedOrientationHandler orientationHandler =
- ((RecentsView) mLauncher.getOverviewPanel()).getPagedOrientationHandler();
- Pair, FloatProperty> taskViewsFloat =
- orientationHandler.getSplitSelectTaskOffset(
- TASK_PRIMARY_SPLIT_TRANSLATION, TASK_SECONDARY_SPLIT_TRANSLATION,
- mLauncher.getDeviceProfile());
-
- SplitAnimationTimings timings =
- AnimUtils.getDeviceOverviewToSplitTimings(mLauncher.getDeviceProfile().isTablet);
- if (!goingToOverviewFromWorkspaceContextual) {
- // This animation is already done for the contextual case, don't redo it
- mRecentsView.createSplitSelectInitAnimation(builder,
- toState.getTransitionDuration(mLauncher, true /* isToState */));
- }
- // Shift tasks vertically downward to get out of placeholder view
- builder.setFloat(mRecentsView, taskViewsFloat.first,
- toState.getSplitSelectTranslation(mLauncher),
- timings.getGridSlidePrimaryInterpolator());
- // Zero out horizontal translation
- builder.setFloat(mRecentsView, taskViewsFloat.second,
- 0,
- timings.getGridSlideSecondaryInterpolator());
-
- if (!animate) {
- AnimatorSet as = builder.buildAnim();
- as.start();
- as.end();
- }
- }
-
- private void setAlphas(PropertySetter propertySetter, StateAnimationConfig config,
- LauncherState state) {
- float clearAllButtonAlpha = state.areElementsVisible(mLauncher, CLEAR_ALL_BUTTON) ? 1 : 0;
- propertySetter.setFloat(mRecentsView.getClearAllButton(), ClearAllButton.VISIBILITY_ALPHA,
- clearAllButtonAlpha, LINEAR);
- float overviewButtonAlpha = state.areElementsVisible(mLauncher, OVERVIEW_ACTIONS) ? 1 : 0;
- propertySetter.setFloat(mLauncher.getActionsView().getVisibilityAlpha(),
- AnimatedFloat.VALUE, overviewButtonAlpha, config.getInterpolator(
- ANIM_OVERVIEW_ACTIONS_FADE, LINEAR));
- }
-
- @Override
- FloatProperty getTaskModalnessProperty() {
- return TASK_MODALNESS;
- }
-
- @Override
- FloatProperty getContentAlphaProperty() {
- return CONTENT_ALPHA;
- }
-}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java b/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java
deleted file mode 100644
index 205da70513..0000000000
--- a/quickstep/src/com/android/launcher3/uioverrides/touchcontrollers/TaskViewTouchController.java
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
- * Copyright (C) 2018 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.uioverrides.touchcontrollers;
-
-import static com.android.launcher3.AbstractFloatingView.TYPE_TOUCH_CONTROLLER_NO_INTERCEPT;
-import static com.android.launcher3.LauncherAnimUtils.SUCCESS_TRANSITION_PROGRESS;
-import static com.android.launcher3.touch.SingleAxisSwipeDetector.DIRECTION_BOTH;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.content.Context;
-import android.os.VibrationEffect;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.animation.Interpolator;
-
-import com.android.app.animation.Interpolators;
-import com.android.launcher3.AbstractFloatingView;
-import com.android.launcher3.LauncherAnimUtils;
-import com.android.launcher3.R;
-import com.android.launcher3.Utilities;
-import com.android.launcher3.anim.AnimatorPlaybackController;
-import com.android.launcher3.anim.PendingAnimation;
-import com.android.launcher3.touch.BaseSwipeDetector;
-import com.android.launcher3.touch.SingleAxisSwipeDetector;
-import com.android.launcher3.util.DisplayController;
-import com.android.launcher3.util.FlingBlockCheck;
-import com.android.launcher3.util.TouchController;
-import com.android.launcher3.util.VibratorWrapper;
-import com.android.launcher3.views.BaseDragLayer;
-import com.android.quickstep.orientation.RecentsPagedOrientationHandler;
-import com.android.quickstep.util.VibrationConstants;
-import com.android.quickstep.views.RecentsView;
-import com.android.quickstep.views.RecentsViewContainer;
-import com.android.quickstep.views.TaskView;
-
-/**
- * Touch controller for handling task view card swipes
- */
-public abstract class TaskViewTouchController
- extends AnimatorListenerAdapter implements TouchController,
- SingleAxisSwipeDetector.Listener {
-
- private static final float ANIMATION_PROGRESS_FRACTION_MIDPOINT = 0.5f;
- private static final long MIN_TASK_DISMISS_ANIMATION_DURATION = 300;
- private static final long MAX_TASK_DISMISS_ANIMATION_DURATION = 600;
-
- public static final int TASK_DISMISS_VIBRATION_PRIMITIVE =
- VibrationEffect.Composition.PRIMITIVE_TICK;
- public static final float TASK_DISMISS_VIBRATION_PRIMITIVE_SCALE = 1f;
- public static final VibrationEffect TASK_DISMISS_VIBRATION_FALLBACK =
- VibrationConstants.EFFECT_TEXTURE_TICK;
-
- protected final CONTAINER mContainer;
- private final SingleAxisSwipeDetector mDetector;
- private final RecentsView mRecentsView;
- private final int[] mTempCords = new int[2];
- private final boolean mIsRtl;
-
- private AnimatorPlaybackController mCurrentAnimation;
- private boolean mCurrentAnimationIsGoingUp;
- private boolean mAllowGoingUp;
- private boolean mAllowGoingDown;
-
- private boolean mNoIntercept;
-
- private float mDisplacementShift;
- private float mProgressMultiplier;
- private float mEndDisplacement;
- private boolean mDraggingEnabled = true;
- private FlingBlockCheck mFlingBlockCheck = new FlingBlockCheck();
- private Float mOverrideVelocity = null;
-
- private TaskView mTaskBeingDragged;
-
- private boolean mIsDismissHapticRunning = false;
-
- public TaskViewTouchController(CONTAINER container) {
- mContainer = container;
- mRecentsView = container.getOverviewPanel();
- mIsRtl = Utilities.isRtl(container.getResources());
- SingleAxisSwipeDetector.Direction dir =
- mRecentsView.getPagedOrientationHandler().getUpDownSwipeDirection();
- mDetector = new SingleAxisSwipeDetector(container, this, dir);
- }
-
- private boolean canInterceptTouch(MotionEvent ev) {
- if ((ev.getEdgeFlags() & Utilities.EDGE_NAV_BAR) != 0) {
- // Don't intercept swipes on the nav bar, as user might be trying to go home
- // during a task dismiss animation.
- if (mCurrentAnimation != null) {
- mCurrentAnimation.getAnimationPlayer().end();
- }
- return false;
- }
- if (mCurrentAnimation != null) {
- mCurrentAnimation.forceFinishIfCloseToEnd();
- }
- if (mCurrentAnimation != null) {
- // If we are already animating from a previous state, we can intercept.
- return true;
- }
- if (AbstractFloatingView.getTopOpenViewWithType(
- mContainer, TYPE_TOUCH_CONTROLLER_NO_INTERCEPT) != null) {
- return false;
- }
- return isRecentsInteractive();
- }
-
- protected abstract boolean isRecentsInteractive();
-
- /** Is recents view showing a single task in a modal way. */
- protected abstract boolean isRecentsModal();
-
- protected void onUserControlledAnimationCreated(AnimatorPlaybackController animController) {
- }
-
- @Override
- public void onAnimationCancel(Animator animation) {
- if (mCurrentAnimation != null && animation == mCurrentAnimation.getTarget()) {
- clearState();
- }
- }
-
- @Override
- public boolean onControllerInterceptTouchEvent(MotionEvent ev) {
- if ((ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL)
- && mCurrentAnimation == null) {
- clearState();
- }
- if (ev.getAction() == MotionEvent.ACTION_DOWN) {
- mNoIntercept = !canInterceptTouch(ev);
- if (mNoIntercept) {
- return false;
- }
-
- // Now figure out which direction scroll events the controller will start
- // calling the callbacks.
- int directionsToDetectScroll = 0;
- boolean ignoreSlopWhenSettling = false;
- if (mCurrentAnimation != null) {
- directionsToDetectScroll = DIRECTION_BOTH;
- ignoreSlopWhenSettling = true;
- } else {
- mTaskBeingDragged = null;
-
- for (int i = 0; i < mRecentsView.getTaskViewCount(); i++) {
- TaskView view = mRecentsView.getTaskViewAt(i);
-
- if (mRecentsView.isTaskViewVisible(view) && mContainer.getDragLayer()
- .isEventOverView(view, ev)) {
- // Disable swiping up and down if the task overlay is modal.
- if (isRecentsModal()) {
- mTaskBeingDragged = null;
- break;
- }
- mTaskBeingDragged = view;
- int upDirection = mRecentsView.getPagedOrientationHandler()
- .getUpDirection(mIsRtl);
-
- // The task can be dragged up to dismiss it
- mAllowGoingUp = true;
-
- // The task can be dragged down to open it if:
- // - It's the current page
- // - We support gestures to enter overview
- // - It's the focused task if in grid view
- // - The task is snapped
- mAllowGoingDown = i == mRecentsView.getCurrentPage()
- && DisplayController.getNavigationMode(mContainer).hasGestures
- && (!mRecentsView.showAsGrid() || mTaskBeingDragged.isFocusedTask())
- && mRecentsView.isTaskInExpectedScrollPosition(i);
-
- directionsToDetectScroll = mAllowGoingDown ? DIRECTION_BOTH : upDirection;
- break;
- }
- }
- if (mTaskBeingDragged == null) {
- mNoIntercept = true;
- return false;
- }
- }
-
- mDetector.setDetectableScrollConditions(
- directionsToDetectScroll, ignoreSlopWhenSettling);
- }
-
- if (mNoIntercept) {
- return false;
- }
-
- onControllerTouchEvent(ev);
- return mDetector.isDraggingOrSettling();
- }
-
- @Override
- public boolean onControllerTouchEvent(MotionEvent ev) {
- return mDetector.onTouchEvent(ev);
- }
-
- private void reInitAnimationController(boolean goingUp) {
- if (mCurrentAnimation != null && mCurrentAnimationIsGoingUp == goingUp) {
- // No need to init
- return;
- }
- if ((goingUp && !mAllowGoingUp) || (!goingUp && !mAllowGoingDown)) {
- // Trying to re-init in an unsupported direction.
- return;
- }
- if (mCurrentAnimation != null) {
- mCurrentAnimation.setPlayFraction(0);
- mCurrentAnimation.getTarget().removeListener(this);
- mCurrentAnimation.dispatchOnCancel();
- }
-
- RecentsPagedOrientationHandler orientationHandler =
- mRecentsView.getPagedOrientationHandler();
- mCurrentAnimationIsGoingUp = goingUp;
- BaseDragLayer dl = mContainer.getDragLayer();
- final int secondaryLayerDimension = orientationHandler.getSecondaryDimension(dl);
- long maxDuration = 2 * secondaryLayerDimension;
- int verticalFactor = orientationHandler.getTaskDragDisplacementFactor(mIsRtl);
- int secondaryTaskDimension = orientationHandler.getSecondaryDimension(mTaskBeingDragged);
- // The interpolator controlling the most prominent visual movement. We use this to determine
- // whether we passed SUCCESS_TRANSITION_PROGRESS.
- final Interpolator currentInterpolator;
- PendingAnimation pa;
- if (goingUp) {
- currentInterpolator = Interpolators.LINEAR;
- pa = new PendingAnimation(maxDuration);
- mRecentsView.createTaskDismissAnimation(pa, mTaskBeingDragged,
- true /* animateTaskView */, true /* removeTask */, maxDuration,
- false /* dismissingForSplitSelection*/);
-
- mEndDisplacement = -secondaryTaskDimension;
- } else {
- currentInterpolator = Interpolators.ZOOM_IN;
- pa = mRecentsView.createTaskLaunchAnimation(
- mTaskBeingDragged, maxDuration, currentInterpolator);
-
- // Since the thumbnail is what is filling the screen, based the end displacement on it.
- View thumbnailView = mTaskBeingDragged.getFirstThumbnailViewDeprecated();
- mTempCords[1] = orientationHandler.getSecondaryDimension(thumbnailView);
- dl.getDescendantCoordRelativeToSelf(thumbnailView, mTempCords);
- mEndDisplacement = secondaryLayerDimension - mTempCords[1];
- }
- mEndDisplacement *= verticalFactor;
- mCurrentAnimation = pa.createPlaybackController();
-
- // Setting this interpolator doesn't affect the visual motion, but is used to determine
- // whether we successfully reached the target state in onDragEnd().
- mCurrentAnimation.getTarget().setInterpolator(currentInterpolator);
- onUserControlledAnimationCreated(mCurrentAnimation);
- mCurrentAnimation.getTarget().addListener(this);
- mCurrentAnimation.dispatchOnStart();
- mProgressMultiplier = 1 / mEndDisplacement;
- }
-
- @Override
- public void onDragStart(boolean start, float startDisplacement) {
- if (!mDraggingEnabled) return;
-
- RecentsPagedOrientationHandler orientationHandler =
- mRecentsView.getPagedOrientationHandler();
- if (mCurrentAnimation == null) {
- reInitAnimationController(orientationHandler.isGoingUp(startDisplacement, mIsRtl));
- mDisplacementShift = 0;
- } else {
- mDisplacementShift = mCurrentAnimation.getProgressFraction() / mProgressMultiplier;
- mCurrentAnimation.pause();
- }
- mFlingBlockCheck.unblockFling();
- mOverrideVelocity = null;
- }
-
- @Override
- public boolean onDrag(float displacement) {
- if (!mDraggingEnabled) return true;
-
- RecentsPagedOrientationHandler orientationHandler =
- mRecentsView.getPagedOrientationHandler();
- float totalDisplacement = displacement + mDisplacementShift;
- boolean isGoingUp = totalDisplacement == 0 ? mCurrentAnimationIsGoingUp :
- orientationHandler.isGoingUp(totalDisplacement, mIsRtl);
- if (isGoingUp != mCurrentAnimationIsGoingUp) {
- reInitAnimationController(isGoingUp);
- mFlingBlockCheck.blockFling();
- } else {
- mFlingBlockCheck.onEvent();
- }
-
- if (isGoingUp) {
- if (mCurrentAnimation.getProgressFraction() < ANIMATION_PROGRESS_FRACTION_MIDPOINT) {
- // Halve the value when dismissing, as we are animating the drag across the full
- // length for only the first half of the progress
- mCurrentAnimation.setPlayFraction(
- Utilities.boundToRange(totalDisplacement * mProgressMultiplier / 2, 0, 1));
- } else {
- // Set mOverrideVelocity to control task dismiss velocity in onDragEnd
- int velocityDimenId = R.dimen.default_task_dismiss_drag_velocity;
- if (mRecentsView.showAsGrid()) {
- if (mTaskBeingDragged.isFocusedTask()) {
- velocityDimenId =
- R.dimen.default_task_dismiss_drag_velocity_grid_focus_task;
- } else {
- velocityDimenId = R.dimen.default_task_dismiss_drag_velocity_grid;
- }
- }
- mOverrideVelocity = -mTaskBeingDragged.getResources().getDimension(velocityDimenId);
-
- // Once halfway through task dismissal interpolation, switch from reversible
- // dragging-task animation to playing the remaining task translation animations,
- // while this is in progress disable dragging.
- mDraggingEnabled = false;
- }
- } else {
- mCurrentAnimation.setPlayFraction(
- Utilities.boundToRange(totalDisplacement * mProgressMultiplier, 0, 1));
- }
-
- return true;
- }
-
- @Override
- public void onDragEnd(float velocity) {
- if (mOverrideVelocity != null) {
- velocity = mOverrideVelocity;
- mOverrideVelocity = null;
- }
- // Limit velocity, as very large scalar values make animations play too quickly
- float maxTaskDismissDragVelocity = mTaskBeingDragged.getResources().getDimension(
- R.dimen.max_task_dismiss_drag_velocity);
- velocity = Utilities.boundToRange(velocity, -maxTaskDismissDragVelocity,
- maxTaskDismissDragVelocity);
- boolean fling = mDraggingEnabled && mDetector.isFling(velocity);
- final boolean goingToEnd;
- boolean blockedFling = fling && mFlingBlockCheck.isBlocked();
- if (blockedFling) {
- fling = false;
- }
- RecentsPagedOrientationHandler orientationHandler =
- mRecentsView.getPagedOrientationHandler();
- boolean goingUp = orientationHandler.isGoingUp(velocity, mIsRtl);
- float progress = mCurrentAnimation.getProgressFraction();
- float interpolatedProgress = mCurrentAnimation.getInterpolatedProgress();
- if (fling) {
- goingToEnd = goingUp == mCurrentAnimationIsGoingUp;
- } else {
- goingToEnd = interpolatedProgress > SUCCESS_TRANSITION_PROGRESS;
- }
- long animationDuration = BaseSwipeDetector.calculateDuration(
- velocity, goingToEnd ? (1 - progress) : progress);
- if (blockedFling && !goingToEnd) {
- animationDuration *= LauncherAnimUtils.blockedFlingDurationFactor(velocity);
- }
- // Due to very high or low velocity dismissals, animation durations can be inconsistently
- // long or short. Bound the duration for animation of task translations for a more
- // standardized feel.
- animationDuration = Utilities.boundToRange(animationDuration,
- MIN_TASK_DISMISS_ANIMATION_DURATION, MAX_TASK_DISMISS_ANIMATION_DURATION);
-
- mCurrentAnimation.setEndAction(this::clearState);
- mCurrentAnimation.startWithVelocity(mContainer, goingToEnd, Math.abs(velocity),
- mEndDisplacement, animationDuration);
- if (goingUp && goingToEnd && !mIsDismissHapticRunning) {
- VibratorWrapper.INSTANCE.get(mContainer).vibrate(TASK_DISMISS_VIBRATION_PRIMITIVE,
- TASK_DISMISS_VIBRATION_PRIMITIVE_SCALE, TASK_DISMISS_VIBRATION_FALLBACK);
- mIsDismissHapticRunning = true;
- }
-
- mDraggingEnabled = true;
- }
-
- private void clearState() {
- mDetector.finishedScrolling();
- mDetector.setDetectableScrollConditions(0, false);
- mDraggingEnabled = true;
- mTaskBeingDragged = null;
- mCurrentAnimation = null;
- mIsDismissHapticRunning = false;
- }
-}
\ No newline at end of file
diff --git a/quickstep/src/com/android/quickstep/LauncherSearchIndexablesProvider.java b/quickstep/src/com/android/quickstep/LauncherSearchIndexablesProvider.java
deleted file mode 100644
index 5d6fbe2ca6..0000000000
--- a/quickstep/src/com/android/quickstep/LauncherSearchIndexablesProvider.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2018 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.quickstep;
-
-import android.annotation.TargetApi;
-import android.content.Intent;
-import android.content.pm.LauncherApps;
-import android.content.pm.ResolveInfo;
-import android.content.res.TypedArray;
-import android.content.res.XmlResourceParser;
-import android.database.Cursor;
-import android.database.MatrixCursor;
-import android.os.Build;
-import android.provider.SearchIndexablesContract.XmlResource;
-import android.provider.SearchIndexablesProvider;
-import android.util.Xml;
-
-import com.android.launcher3.R;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import java.io.IOException;
-
-import static android.provider.SearchIndexablesContract.INDEXABLES_RAW_COLUMNS;
-import static android.provider.SearchIndexablesContract.INDEXABLES_XML_RES_COLUMNS;
-import static android.provider.SearchIndexablesContract.NON_INDEXABLES_KEYS_COLUMNS;
-
-@TargetApi(Build.VERSION_CODES.O)
-public class LauncherSearchIndexablesProvider extends SearchIndexablesProvider {
- @Override
- public boolean onCreate() {
- return true;
- }
-
- @Override
- public Cursor queryXmlResources(String[] strings) {
- MatrixCursor cursor = new MatrixCursor(INDEXABLES_XML_RES_COLUMNS);
- ResolveInfo settingsActivity = getContext().getPackageManager().resolveActivity(
- new Intent(Intent.ACTION_APPLICATION_PREFERENCES)
- .setPackage(getContext().getPackageName()), 0);
- cursor.newRow()
- .add(XmlResource.COLUMN_XML_RESID, R.xml.indexable_launcher_prefs)
- .add(XmlResource.COLUMN_INTENT_ACTION, Intent.ACTION_APPLICATION_PREFERENCES)
- .add(XmlResource.COLUMN_INTENT_TARGET_PACKAGE, getContext().getPackageName())
- .add(XmlResource.COLUMN_INTENT_TARGET_CLASS, settingsActivity.activityInfo.name);
- return cursor;
- }
-
- @Override
- public Cursor queryRawData(String[] projection) {
- return new MatrixCursor(INDEXABLES_RAW_COLUMNS);
- }
-
- @Override
- public Cursor queryNonIndexableKeys(String[] projection) {
- MatrixCursor cursor = new MatrixCursor(NON_INDEXABLES_KEYS_COLUMNS);
- if (!getContext().getSystemService(LauncherApps.class).hasShortcutHostPermission()) {
- // We are not the current launcher. Hide all preferences
- try (XmlResourceParser parser = getContext().getResources()
- .getXml(R.xml.indexable_launcher_prefs)) {
- final int depth = parser.getDepth();
- final int[] attrs = new int[] { android.R.attr.key };
- int type;
- while (((type = parser.next()) != XmlPullParser.END_TAG ||
- parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
- if (type == XmlPullParser.START_TAG) {
- TypedArray a = getContext().obtainStyledAttributes(
- Xml.asAttributeSet(parser), attrs);
- cursor.addRow(new String[] {a.getString(0)});
- a.recycle();
- }
- }
- } catch (IOException |XmlPullParserException e) {
- throw new RuntimeException(e);
- }
- }
- return cursor;
- }
-}
diff --git a/quickstep/src/com/android/quickstep/OverviewCommandHelper.java b/quickstep/src/com/android/quickstep/OverviewCommandHelper.java
deleted file mode 100644
index 7da92bce90..0000000000
--- a/quickstep/src/com/android/quickstep/OverviewCommandHelper.java
+++ /dev/null
@@ -1,525 +0,0 @@
-/*
- * Copyright (C) 2018 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.quickstep;
-
-import static com.android.launcher3.PagedView.INVALID_PAGE;
-import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_OVERVIEW_SHOW_OVERVIEW_FROM_3_BUTTON;
-import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_OVERVIEW_SHOW_OVERVIEW_FROM_KEYBOARD_QUICK_SWITCH;
-import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_OVERVIEW_SHOW_OVERVIEW_FROM_KEYBOARD_SHORTCUT;
-import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
-import static com.android.quickstep.util.ActiveGestureLog.INTENT_EXTRA_LOG_TRACE_ID;
-
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.content.Intent;
-import android.graphics.PointF;
-import android.os.SystemClock;
-import android.os.Trace;
-import android.util.Log;
-import android.view.View;
-
-import androidx.annotation.BinderThread;
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-import androidx.annotation.UiThread;
-
-import com.android.internal.jank.Cuj;
-import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.logger.LauncherAtom;
-import com.android.launcher3.logging.StatsLogManager;
-import com.android.launcher3.statemanager.StatefulActivity;
-import com.android.launcher3.taskbar.TaskbarUIController;
-import com.android.launcher3.util.RunnableList;
-import com.android.quickstep.RecentsAnimationCallbacks.RecentsAnimationListener;
-import com.android.quickstep.util.ActiveGestureLog;
-import com.android.quickstep.views.RecentsView;
-import com.android.quickstep.views.RecentsViewContainer;
-import com.android.quickstep.views.TaskView;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-import com.android.systemui.shared.system.InteractionJankMonitorWrapper;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-/**
- * Helper class to handle various atomic commands for switching between Overview.
- */
-public class OverviewCommandHelper {
- private static final String TAG = "OverviewCommandHelper";
-
- public static final int TYPE_SHOW = 1;
- public static final int TYPE_KEYBOARD_INPUT = 2;
- public static final int TYPE_HIDE = 3;
- public static final int TYPE_TOGGLE = 4;
- public static final int TYPE_HOME = 5;
-
- /**
- * Use case for needing a queue is double tapping recents button in 3 button nav.
- * Size of 2 should be enough. We'll toss in one more because we're kind hearted.
- */
- private final static int MAX_QUEUE_SIZE = 3;
-
- private static final String TRANSITION_NAME = "Transition:toOverview";
-
- private final TouchInteractionService mService;
- private final OverviewComponentObserver mOverviewComponentObserver;
- private final TaskAnimationManager mTaskAnimationManager;
- private final ArrayList mPendingCommands = new ArrayList<>();
-
- /**
- * Index of the TaskView that should be focused when launching Overview. Persisted so that we
- * do not lose the focus across multiple calls of
- * {@link OverviewCommandHelper#executeCommand(CommandInfo)} for the same command
- */
- private int mKeyboardTaskFocusIndex = -1;
-
- /**
- * Whether we should incoming toggle commands while a previous toggle command is still ongoing.
- * This serves as a rate-limiter to prevent overlapping animations that can clobber each other
- * and prevent clean-up callbacks from running. This thus prevents a recurring set of bugs with
- * janky recents animations and unresponsive home and overview buttons.
- */
- private boolean mWaitForToggleCommandComplete = false;
-
- public OverviewCommandHelper(TouchInteractionService service,
- OverviewComponentObserver observer,
- TaskAnimationManager taskAnimationManager) {
- mService = service;
- mOverviewComponentObserver = observer;
- mTaskAnimationManager = taskAnimationManager;
- }
-
- /**
- * Called when the command finishes execution.
- */
- private void scheduleNextTask(CommandInfo command) {
- if (mPendingCommands.isEmpty()) {
- Log.d(TAG, "no pending commands to schedule");
- return;
- }
- if (mPendingCommands.get(0) != command) {
- Log.d(TAG, "next task not scheduled."
- + " mPendingCommands[0] type is " + mPendingCommands.get(0)
- + " - command type is: " + command);
- return;
- }
- Log.d(TAG, "scheduleNextTask called: " + command);
- mPendingCommands.remove(0);
- executeNext();
- }
-
- /**
- * Executes the next command from the queue. If the command finishes immediately (returns true),
- * it continues to execute the next command, until the queue is empty of a command defer's its
- * completion (returns false).
- */
- @UiThread
- private void executeNext() {
- if (mPendingCommands.isEmpty()) {
- Log.d(TAG, "executeNext - mPendingCommands is empty");
- return;
- }
- CommandInfo cmd = mPendingCommands.get(0);
-
- boolean result = executeCommand(cmd);
- Log.d(TAG, "executeNext cmd type: " + cmd + ", result: " + result);
- if (result) {
- scheduleNextTask(cmd);
- }
- }
-
- @UiThread
- private void addCommand(CommandInfo cmd) {
- boolean wasEmpty = mPendingCommands.isEmpty();
- mPendingCommands.add(cmd);
- if (wasEmpty) {
- executeNext();
- }
- }
-
- /**
- * Adds a command to be executed next, after all pending tasks are completed.
- * Max commands that can be queued is {@link #MAX_QUEUE_SIZE}.
- * Requests after reaching that limit will be silently dropped.
- */
- @BinderThread
- public void addCommand(int type) {
- if (mPendingCommands.size() >= MAX_QUEUE_SIZE) {
- Log.d(TAG, "the pending command queue is full (" + mPendingCommands.size() + "). "
- + "command not added: " + type);
- return;
- }
- Log.d(TAG, "adding command type: " + type);
- CommandInfo cmd = new CommandInfo(type);
- MAIN_EXECUTOR.execute(() -> addCommand(cmd));
- }
-
- @UiThread
- public void clearPendingCommands() {
- Log.d(TAG, "clearing pending commands - size: " + mPendingCommands.size());
- mPendingCommands.clear();
- }
-
- @UiThread
- public boolean canStartHomeSafely() {
- return mPendingCommands.isEmpty() || mPendingCommands.get(0).type == TYPE_HOME;
- }
-
- @Nullable
- private TaskView getNextTask(RecentsView view) {
- final TaskView runningTaskView = view.getRunningTaskView();
-
- if (runningTaskView == null) {
- return view.getTaskViewAt(0);
- } else {
- final TaskView nextTask = view.getNextTaskView();
- return nextTask != null ? nextTask : runningTaskView;
- }
- }
-
- private boolean launchTask(RecentsView recents, @Nullable TaskView taskView, CommandInfo cmd) {
- RunnableList callbackList = null;
- if (taskView != null) {
- mWaitForToggleCommandComplete = true;
- taskView.setEndQuickSwitchCuj(true);
- callbackList = taskView.launchTasks();
- }
-
- if (callbackList != null) {
- callbackList.add(() -> {
- Log.d(TAG, "launching task callback: " + cmd);
- scheduleNextTask(cmd);
- mWaitForToggleCommandComplete = false;
- });
- Log.d(TAG, "launching task - waiting for callback: " + cmd);
- return false;
- } else {
- recents.startHome();
- mWaitForToggleCommandComplete = false;
- return true;
- }
- }
-
- /**
- * Executes the task and returns true if next task can be executed. If false, then the next
- * task is deferred until {@link #scheduleNextTask} is called
- */
- private & RecentsViewContainer> boolean executeCommand(
- CommandInfo cmd) {
- if (mWaitForToggleCommandComplete && cmd.type == TYPE_TOGGLE) {
- Log.d(TAG, "executeCommand: " + cmd
- + " - waiting for toggle command complete");
- return true;
- }
- BaseActivityInterface, T> activityInterface =
- mOverviewComponentObserver.getActivityInterface();
-
- RecentsView, ?> visibleRecentsView = activityInterface.getVisibleRecentsView();
- RecentsView, ?> createdRecentsView;
-
- Log.d(TAG, "executeCommand: " + cmd
- + " - visibleRecentsView: " + visibleRecentsView);
- if (visibleRecentsView == null) {
- T activity = activityInterface.getCreatedContainer();
- createdRecentsView = activity == null ? null : activity.getOverviewPanel();
- DeviceProfile dp = activity == null ? null : activity.getDeviceProfile();
- TaskbarUIController uiController = activityInterface.getTaskbarController();
- boolean allowQuickSwitch = FeatureFlags.ENABLE_KEYBOARD_QUICK_SWITCH.get()
- && uiController != null
- && dp != null
- && (dp.isTablet || dp.isTwoPanels);
-
- switch (cmd.type) {
- case TYPE_HIDE:
- if (!allowQuickSwitch) {
- return true;
- }
- mKeyboardTaskFocusIndex = uiController.launchFocusedTask();
- if (mKeyboardTaskFocusIndex == -1) {
- return true;
- }
- break;
- case TYPE_KEYBOARD_INPUT:
- if (allowQuickSwitch) {
- uiController.openQuickSwitchView();
- return true;
- } else {
- mKeyboardTaskFocusIndex = 0;
- break;
- }
- case TYPE_HOME:
- ActiveGestureLog.INSTANCE.addLog(
- "OverviewCommandHelper.executeCommand(TYPE_HOME)");
- mService.startActivity(mOverviewComponentObserver.getHomeIntent());
- return true;
- case TYPE_SHOW:
- // When Recents is not currently visible, the command's type is TYPE_SHOW
- // when overview is triggered via the keyboard overview button or Action+Tab
- // keys (Not Alt+Tab which is KQS). The overview button on-screen in 3-button
- // nav is TYPE_TOGGLE.
- mKeyboardTaskFocusIndex = 0;
- break;
- default:
- // continue below to handle displaying Recents.
- }
- } else {
- createdRecentsView = visibleRecentsView;
- switch (cmd.type) {
- case TYPE_SHOW:
- // already visible
- return true;
- case TYPE_KEYBOARD_INPUT: {
- if (visibleRecentsView.isHandlingTouch()) {
- return true;
- }
- }
- case TYPE_HIDE: {
- if (visibleRecentsView.isHandlingTouch()) {
- return true;
- }
- mKeyboardTaskFocusIndex = INVALID_PAGE;
- int currentPage = visibleRecentsView.getNextPage();
- TaskView tv = (currentPage >= 0
- && currentPage < visibleRecentsView.getTaskViewCount())
- ? (TaskView) visibleRecentsView.getPageAt(currentPage)
- : null;
- return launchTask(visibleRecentsView, tv, cmd);
- }
- case TYPE_TOGGLE:
- return launchTask(visibleRecentsView, getNextTask(visibleRecentsView), cmd);
- case TYPE_HOME:
- visibleRecentsView.startHome();
- return true;
- }
- }
-
- if (createdRecentsView != null) {
- createdRecentsView.setKeyboardTaskFocusIndex(mKeyboardTaskFocusIndex);
- }
- // Handle recents view focus when launching from home
- Animator.AnimatorListener animatorListener = new AnimatorListenerAdapter() {
-
- @Override
- public void onAnimationStart(Animator animation) {
- super.onAnimationStart(animation);
- updateRecentsViewFocus(cmd);
- logShowOverviewFrom(cmd.type);
- }
-
- @Override
- public void onAnimationEnd(Animator animation) {
- Log.d(TAG, "switching to Overview state - onAnimationEnd: " + cmd);
- super.onAnimationEnd(animation);
- onRecentsViewFocusUpdated(cmd);
- scheduleNextTask(cmd);
- }
- };
- if (activityInterface.switchToRecentsIfVisible(animatorListener)) {
- Log.d(TAG, "switching to Overview state - waiting: " + cmd);
- // If successfully switched, wait until animation finishes
- return false;
- }
-
- final T activity = activityInterface.getCreatedContainer();
- if (activity != null) {
- InteractionJankMonitorWrapper.begin(
- activity.getRootView(),
- Cuj.CUJ_LAUNCHER_QUICK_SWITCH);
- }
-
- GestureState gestureState = mService.createGestureState(GestureState.DEFAULT_STATE,
- GestureState.TrackpadGestureType.NONE);
- gestureState.setHandlingAtomicEvent(true);
- AbsSwipeUpHandler interactionHandler = mService.getSwipeUpHandlerFactory()
- .newHandler(gestureState, cmd.createTime);
- interactionHandler.setGestureEndCallback(
- () -> onTransitionComplete(cmd, interactionHandler));
- interactionHandler.initWhenReady("OverviewCommandHelper: cmd.type=" + cmd.type);
-
- RecentsAnimationListener recentAnimListener = new RecentsAnimationListener() {
- @Override
- public void onRecentsAnimationStart(RecentsAnimationController controller,
- RecentsAnimationTargets targets) {
- updateRecentsViewFocus(cmd);
- logShowOverviewFrom(cmd.type);
- activityInterface.runOnInitBackgroundStateUI(() ->
- interactionHandler.onGestureEnded(0, new PointF()));
- cmd.removeListener(this);
- }
-
- @Override
- public void onRecentsAnimationCanceled(HashMap thumbnailDatas) {
- interactionHandler.onGestureCancelled();
- cmd.removeListener(this);
-
- T createdActivity = activityInterface.getCreatedContainer();
- if (createdActivity == null) {
- return;
- }
- if (createdRecentsView != null) {
- createdRecentsView.onRecentsAnimationComplete();
- }
- }
- };
-
- if (visibleRecentsView != null) {
- visibleRecentsView.moveRunningTaskToFront();
- }
- if (mTaskAnimationManager.isRecentsAnimationRunning()) {
- cmd.mActiveCallbacks = mTaskAnimationManager.continueRecentsAnimation(gestureState);
- cmd.mActiveCallbacks.addListener(interactionHandler);
- mTaskAnimationManager.notifyRecentsAnimationState(interactionHandler);
- interactionHandler.onGestureStarted(true /*isLikelyToStartNewTask*/);
-
- cmd.mActiveCallbacks.addListener(recentAnimListener);
- mTaskAnimationManager.notifyRecentsAnimationState(recentAnimListener);
- } else {
- Intent intent = new Intent(interactionHandler.getLaunchIntent());
- intent.putExtra(INTENT_EXTRA_LOG_TRACE_ID, gestureState.getGestureId());
- cmd.mActiveCallbacks = mTaskAnimationManager.startRecentsAnimation(
- gestureState, intent, interactionHandler);
- interactionHandler.onGestureStarted(false /*isLikelyToStartNewTask*/);
- cmd.mActiveCallbacks.addListener(recentAnimListener);
- }
- Trace.beginAsyncSection(TRANSITION_NAME, 0);
- Log.d(TAG, "switching via recents animation - onGestureStarted: " + cmd);
- return false;
- }
-
- private void onTransitionComplete(CommandInfo cmd, AbsSwipeUpHandler handler) {
- Log.d(TAG, "switching via recents animation - onTransitionComplete: " + cmd);
- cmd.removeListener(handler);
- Trace.endAsyncSection(TRANSITION_NAME, 0);
- onRecentsViewFocusUpdated(cmd);
- scheduleNextTask(cmd);
- }
-
- private void updateRecentsViewFocus(CommandInfo cmd) {
- RecentsView recentsView =
- mOverviewComponentObserver.getActivityInterface().getVisibleRecentsView();
- if (recentsView == null || (cmd.type != TYPE_KEYBOARD_INPUT && cmd.type != TYPE_HIDE
- && cmd.type != TYPE_SHOW)) {
- return;
- }
- // When the overview is launched via alt tab (cmd type is TYPE_KEYBOARD_INPUT),
- // the touch mode somehow is not change to false by the Android framework.
- // The subsequent tab to go through tasks in overview can only be dispatched to
- // focuses views, while focus can only be requested in
- // {@link View#requestFocusNoSearch(int, Rect)} when touch mode is false. To note,
- // here we launch overview with live tile.
- recentsView.getViewRootImpl().touchModeChanged(false);
- // Ensure that recents view has focus so that it receives the followup key inputs
- if (requestFocus(recentsView.getTaskViewAt(mKeyboardTaskFocusIndex))) {
- return;
- }
- if (requestFocus(recentsView.getNextTaskView())) {
- return;
- }
- if (requestFocus(recentsView.getTaskViewAt(0))) {
- return;
- }
- requestFocus(recentsView);
- }
-
- private void onRecentsViewFocusUpdated(CommandInfo cmd) {
- RecentsView recentsView =
- mOverviewComponentObserver.getActivityInterface().getVisibleRecentsView();
- if (recentsView == null
- || cmd.type != TYPE_HIDE
- || mKeyboardTaskFocusIndex == INVALID_PAGE) {
- return;
- }
- recentsView.setKeyboardTaskFocusIndex(INVALID_PAGE);
- recentsView.setCurrentPage(mKeyboardTaskFocusIndex);
- mKeyboardTaskFocusIndex = INVALID_PAGE;
- }
-
- private boolean requestFocus(@Nullable View taskView) {
- if (taskView == null) {
- return false;
- }
- taskView.post(() -> {
- taskView.requestFocus();
- taskView.requestAccessibilityFocus();
- });
- return true;
- }
-
- private & RecentsViewContainer>
- void logShowOverviewFrom(int cmdType) {
- BaseActivityInterface, T> activityInterface =
- mOverviewComponentObserver.getActivityInterface();
- var container = activityInterface.getCreatedContainer();
- if (container != null) {
- StatsLogManager.LauncherEvent event;
- switch (cmdType) {
- case TYPE_SHOW -> event = LAUNCHER_OVERVIEW_SHOW_OVERVIEW_FROM_KEYBOARD_SHORTCUT;
- case TYPE_HIDE ->
- event = LAUNCHER_OVERVIEW_SHOW_OVERVIEW_FROM_KEYBOARD_QUICK_SWITCH;
- case TYPE_TOGGLE -> event = LAUNCHER_OVERVIEW_SHOW_OVERVIEW_FROM_3_BUTTON;
- default -> {
- return;
- }
- }
-
- StatsLogManager.newInstance(container.asContext())
- .logger()
- .withContainerInfo(LauncherAtom.ContainerInfo.newBuilder()
- .setTaskSwitcherContainer(
- LauncherAtom.TaskSwitcherContainer.getDefaultInstance())
- .build())
- .log(event);
- }
- }
-
- public void dump(PrintWriter pw) {
- pw.println("OverviewCommandHelper:");
- pw.println(" mPendingCommands=" + mPendingCommands.size());
- if (!mPendingCommands.isEmpty()) {
- pw.println(" pendingCommandType=" + mPendingCommands.get(0).type);
- }
- pw.println(" mKeyboardTaskFocusIndex=" + mKeyboardTaskFocusIndex);
- pw.println(" mWaitForToggleCommandComplete=" + mWaitForToggleCommandComplete);
- }
-
- private static class CommandInfo {
- public final long createTime = SystemClock.elapsedRealtime();
- public final int type;
- RecentsAnimationCallbacks mActiveCallbacks;
-
- CommandInfo(int type) {
- this.type = type;
- }
-
- void removeListener(RecentsAnimationListener listener) {
- if (mActiveCallbacks != null) {
- mActiveCallbacks.removeListener(listener);
- }
- }
-
- @NonNull
- @Override
- public String toString() {
- return "CommandInfo("
- + "type=" + type + ", "
- + "createTime=" + createTime + ", "
- + "mActiveCallbacks=" + mActiveCallbacks
- + ")";
- }
- }
-}
diff --git a/quickstep/src/com/android/quickstep/TaskIconCache.java b/quickstep/src/com/android/quickstep/TaskIconCache.java
deleted file mode 100644
index f45bacb33b..0000000000
--- a/quickstep/src/com/android/quickstep/TaskIconCache.java
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright (C) 2018 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.quickstep;
-
-import static com.android.launcher3.Flags.enableOverviewIconMenu;
-import static com.android.launcher3.util.DisplayController.CHANGE_DENSITY;
-import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
-
-import android.annotation.Nullable;
-import android.app.ActivityManager;
-import android.app.ActivityManager.TaskDescription;
-import android.content.Context;
-import android.content.pm.ActivityInfo;
-import android.content.pm.PackageManager;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-import android.os.UserHandle;
-import android.text.TextUtils;
-import android.util.SparseArray;
-
-import androidx.annotation.WorkerThread;
-
-import com.android.launcher3.R;
-import com.android.launcher3.Utilities;
-import com.android.launcher3.icons.BaseIconFactory;
-import com.android.launcher3.icons.BaseIconFactory.IconOptions;
-import com.android.launcher3.icons.BitmapInfo;
-import com.android.launcher3.icons.IconProvider;
-import com.android.launcher3.pm.UserCache;
-import com.android.launcher3.util.CancellableTask;
-import com.android.launcher3.util.DisplayController;
-import com.android.launcher3.util.DisplayController.DisplayInfoChangeListener;
-import com.android.launcher3.util.DisplayController.Info;
-import com.android.launcher3.util.FlagOp;
-import com.android.launcher3.util.Preconditions;
-import com.android.quickstep.util.TaskKeyLruCache;
-import com.android.quickstep.util.TaskVisualsChangeListener;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.Task.TaskKey;
-import com.android.systemui.shared.system.PackageManagerWrapper;
-
-import java.util.concurrent.Executor;
-import java.util.function.Consumer;
-
-/**
- * Manages the caching of task icons and related data.
- */
-public class TaskIconCache implements DisplayInfoChangeListener {
-
- private final Executor mBgExecutor;
-
- private final Context mContext;
- private final TaskKeyLruCache mIconCache;
- private final SparseArray mDefaultIcons = new SparseArray<>();
- private BitmapInfo mDefaultIconBase = null;
-
- private final IconProvider mIconProvider;
-
- private BaseIconFactory mIconFactory;
-
- @Nullable
- public TaskVisualsChangeListener mTaskVisualsChangeListener = null;
-
- public TaskIconCache(Context context, Executor bgExecutor, IconProvider iconProvider) {
- mContext = context;
- mBgExecutor = bgExecutor;
- mIconProvider = iconProvider;
-
- Resources res = context.getResources();
- int cacheSize = res.getInteger(R.integer.recentsIconCacheSize);
-
- mIconCache = new TaskKeyLruCache<>(cacheSize);
-
- DisplayController.INSTANCE.get(mContext).addChangeListener(this);
- }
-
- @Override
- public void onDisplayInfoChanged(Context context, Info info, int flags) {
- if ((flags & CHANGE_DENSITY) != 0) {
- clearCache();
- }
- }
-
- /**
- * Asynchronously fetches the icon and other task data.
- *
- * @param task The task to fetch the data for
- * @param callback The callback to receive the task after its data has been populated.
- * @return A cancelable handle to the request
- */
- public CancellableTask updateIconInBackground(Task task, Consumer callback) {
- Preconditions.assertUIThread();
- if (task.icon != null) {
- // Nothing to load, the icon is already loaded
- callback.accept(task);
- return null;
- }
- CancellableTask request = new CancellableTask<>(
- () -> getCacheEntry(task),
- MAIN_EXECUTOR,
- result -> {
- task.icon = result.icon;
- task.titleDescription = result.contentDescription;
- task.title = result.title;
- callback.accept(task);
- dispatchIconUpdate(task.key.id);
- }
- );
- mBgExecutor.execute(request);
- return request;
- }
-
- /**
- * Clears the icon cache
- */
- public void clearCache() {
- mBgExecutor.execute(this::resetFactory);
- }
-
- void onTaskRemoved(TaskKey taskKey) {
- mIconCache.remove(taskKey);
- }
-
- void invalidateCacheEntries(String pkg, UserHandle handle) {
- mBgExecutor.execute(() -> mIconCache.removeAll(key ->
- pkg.equals(key.getPackageName()) && handle.getIdentifier() == key.userId));
- }
-
- @WorkerThread
- private TaskCacheEntry getCacheEntry(Task task) {
- TaskCacheEntry entry = mIconCache.getAndInvalidateIfModified(task.key);
- if (entry != null) {
- return entry;
- }
-
- TaskDescription desc = task.taskDescription;
- TaskKey key = task.key;
- ActivityInfo activityInfo = null;
-
- // Create new cache entry
- entry = new TaskCacheEntry();
-
- // Load icon
- // TODO: Load icon resource (b/143363444)
- Bitmap icon = getIcon(desc, key.userId);
- if (icon != null) {
- entry.icon = getBitmapInfo(
- new BitmapDrawable(mContext.getResources(), icon),
- key.userId,
- desc.getPrimaryColor(),
- false /* isInstantApp */).newIcon(mContext);
- } else {
- activityInfo = PackageManagerWrapper.getInstance().getActivityInfo(
- key.getComponent(), key.userId);
- if (activityInfo != null) {
- BitmapInfo bitmapInfo = getBitmapInfo(
- mIconProvider.getIcon(activityInfo),
- key.userId,
- desc.getPrimaryColor(),
- activityInfo.applicationInfo.isInstantApp());
- entry.icon = bitmapInfo.newIcon(mContext);
- } else {
- entry.icon = getDefaultIcon(key.userId);
- }
- }
-
- // Skip loading the content description if the activity no longer exists
- if (activityInfo == null) {
- activityInfo = PackageManagerWrapper.getInstance().getActivityInfo(
- key.getComponent(), key.userId);
- }
- if (activityInfo != null) {
- entry.contentDescription = getBadgedContentDescription(
- activityInfo, task.key.userId, task.taskDescription);
- if (enableOverviewIconMenu()) {
- entry.title = Utilities.trim(activityInfo.loadLabel(mContext.getPackageManager()));
- }
- }
-
- mIconCache.put(task.key, entry);
- return entry;
- }
-
- private Bitmap getIcon(ActivityManager.TaskDescription desc, int userId) {
- if (desc.getInMemoryIcon() != null) {
- return desc.getInMemoryIcon();
- }
- return ActivityManager.TaskDescription.loadTaskDescriptionIcon(
- desc.getIconFilename(), userId);
- }
-
- private String getBadgedContentDescription(ActivityInfo info, int userId, TaskDescription td) {
- PackageManager pm = mContext.getPackageManager();
- String taskLabel = td == null ? null : Utilities.trim(td.getLabel());
- if (TextUtils.isEmpty(taskLabel)) {
- taskLabel = Utilities.trim(info.loadLabel(pm));
- }
-
- String applicationLabel = Utilities.trim(info.applicationInfo.loadLabel(pm));
- String badgedApplicationLabel = userId != UserHandle.myUserId()
- ? pm.getUserBadgedLabel(applicationLabel, UserHandle.of(userId)).toString()
- : applicationLabel;
- return applicationLabel.equals(taskLabel)
- ? badgedApplicationLabel : badgedApplicationLabel + " " + taskLabel;
- }
-
- @WorkerThread
- private Drawable getDefaultIcon(int userId) {
- synchronized (mDefaultIcons) {
- if (mDefaultIconBase == null) {
- try (BaseIconFactory bif = getIconFactory()) {
- mDefaultIconBase = bif.makeDefaultIcon();
- }
- }
-
- int index;
- if ((index = mDefaultIcons.indexOfKey(userId)) >= 0) {
- return mDefaultIcons.valueAt(index).newIcon(mContext);
- } else {
- BitmapInfo info = mDefaultIconBase.withFlags(
- UserCache.INSTANCE.get(mContext).getUserInfo(UserHandle.of(userId))
- .applyBitmapInfoFlags(FlagOp.NO_OP));
- mDefaultIcons.put(userId, info);
- return info.newIcon(mContext);
- }
- }
- }
-
- @WorkerThread
- private BitmapInfo getBitmapInfo(Drawable drawable, int userId,
- int primaryColor, boolean isInstantApp) {
- try (BaseIconFactory bif = getIconFactory()) {
- bif.setWrapperBackgroundColor(primaryColor);
-
- // User version code O, so that the icon is always wrapped in an adaptive icon container
- return bif.createBadgedIconBitmap(drawable,
- new IconOptions()
- .setUser(UserCache.INSTANCE.get(mContext)
- .getUserInfo(UserHandle.of(userId)))
- .setInstantApp(isInstantApp)
- .setExtractedColor(0));
- }
- }
-
- @WorkerThread
- private BaseIconFactory getIconFactory() {
- if (mIconFactory == null) {
- mIconFactory = new BaseIconFactory(mContext,
- DisplayController.INSTANCE.get(mContext).getInfo().getDensityDpi(),
- mContext.getResources().getDimensionPixelSize(
- R.dimen.task_icon_cache_default_icon_size));
- }
- return mIconFactory;
- }
-
- @WorkerThread
- private void resetFactory() {
- mIconFactory = null;
- mIconCache.evictAll();
- }
-
- private static class TaskCacheEntry {
- public Drawable icon;
- public String contentDescription = "";
- public String title = "";
- }
-
- void registerTaskVisualsChangeListener(TaskVisualsChangeListener newListener) {
- mTaskVisualsChangeListener = newListener;
- }
-
- void removeTaskVisualsChangeListener() {
- mTaskVisualsChangeListener = null;
- }
-
- void dispatchIconUpdate(int taskId) {
- if (mTaskVisualsChangeListener != null) {
- mTaskVisualsChangeListener.onTaskIconChanged(taskId);
- }
- }
-}
\ No newline at end of file
diff --git a/quickstep/src/com/android/quickstep/TaskThumbnailCache.java b/quickstep/src/com/android/quickstep/TaskThumbnailCache.java
deleted file mode 100644
index 38e927f95f..0000000000
--- a/quickstep/src/com/android/quickstep/TaskThumbnailCache.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * Copyright (C) 2018 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.quickstep;
-
-import static com.android.launcher3.Flags.enableGridOnlyOverview;
-import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
-
-import android.content.Context;
-import android.content.res.Resources;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.VisibleForTesting;
-
-import com.android.launcher3.R;
-import com.android.launcher3.util.CancellableTask;
-import com.android.launcher3.util.Preconditions;
-import com.android.quickstep.task.thumbnail.data.TaskThumbnailDataSource;
-import com.android.quickstep.util.TaskKeyByLastActiveTimeCache;
-import com.android.quickstep.util.TaskKeyCache;
-import com.android.quickstep.util.TaskKeyLruCache;
-import com.android.systemui.shared.recents.model.Task;
-import com.android.systemui.shared.recents.model.Task.TaskKey;
-import com.android.systemui.shared.recents.model.ThumbnailData;
-import com.android.systemui.shared.system.ActivityManagerWrapper;
-
-import java.util.ArrayList;
-import java.util.concurrent.Executor;
-import java.util.function.Consumer;
-
-public class TaskThumbnailCache implements TaskThumbnailDataSource {
-
- private final Executor mBgExecutor;
- private final TaskKeyCache mCache;
- private final HighResLoadingState mHighResLoadingState;
- private final boolean mEnableTaskSnapshotPreloading;
- private final Context mContext;
-
- public static class HighResLoadingState {
- private boolean mForceHighResThumbnails;
- private boolean mVisible;
- private boolean mFlingingFast;
- private boolean mHighResLoadingEnabled;
- private ArrayList mCallbacks = new ArrayList<>();
-
- public interface HighResLoadingStateChangedCallback {
- void onHighResLoadingStateChanged(boolean enabled);
- }
-
- private HighResLoadingState(Context context) {
- // If the device does not support low-res thumbnails, only attempt to load high-res
- // thumbnails
- mForceHighResThumbnails = !supportsLowResThumbnails();
- }
-
- public void addCallback(HighResLoadingStateChangedCallback callback) {
- mCallbacks.add(callback);
- }
-
- public void removeCallback(HighResLoadingStateChangedCallback callback) {
- mCallbacks.remove(callback);
- }
-
- public void setVisible(boolean visible) {
- mVisible = visible;
- updateState();
- }
-
- public void setFlingingFast(boolean flingingFast) {
- mFlingingFast = flingingFast;
- updateState();
- }
-
- public boolean isEnabled() {
- return mHighResLoadingEnabled;
- }
-
- private void updateState() {
- boolean prevState = mHighResLoadingEnabled;
- mHighResLoadingEnabled = mForceHighResThumbnails || (mVisible && !mFlingingFast);
- if (prevState != mHighResLoadingEnabled) {
- for (int i = mCallbacks.size() - 1; i >= 0; i--) {
- mCallbacks.get(i).onHighResLoadingStateChanged(mHighResLoadingEnabled);
- }
- }
- }
- }
-
- public TaskThumbnailCache(Context context, Executor bgExecutor) {
- this(context, bgExecutor,
- context.getResources().getInteger(R.integer.recentsThumbnailCacheSize));
- }
-
- private TaskThumbnailCache(Context context, Executor bgExecutor, int cacheSize) {
- this(context, bgExecutor,
- enableGridOnlyOverview() ? new TaskKeyByLastActiveTimeCache<>(cacheSize)
- : new TaskKeyLruCache<>(cacheSize));
- }
-
- @VisibleForTesting
- TaskThumbnailCache(Context context, Executor bgExecutor, TaskKeyCache cache) {
- mBgExecutor = bgExecutor;
- mHighResLoadingState = new HighResLoadingState(context);
- mContext = context;
-
- Resources res = context.getResources();
- mEnableTaskSnapshotPreloading = res.getBoolean(R.bool.config_enableTaskSnapshotPreloading);
- mCache = cache;
- }
-
- /**
- * Synchronously fetches the thumbnail for the given task at the specified resolution level, and
- * puts it in the cache.
- */
- public void updateThumbnailInCache(Task task, boolean lowResolution) {
- if (task == null) {
- return;
- }
- Preconditions.assertUIThread();
- // Fetch the thumbnail for this task and put it in the cache
- if (task.thumbnail == null) {
- updateThumbnailInBackground(task.key, lowResolution,
- t -> task.thumbnail = t);
- }
- }
-
- /**
- * Synchronously updates the thumbnail in the cache if it is already there.
- */
- public void updateTaskSnapShot(int taskId, ThumbnailData thumbnail) {
- Preconditions.assertUIThread();
- mCache.updateIfAlreadyInCache(taskId, thumbnail);
- }
-
- /**
- * Asynchronously fetches the icon and other task data for the given {@param task}.
- *
- * @param callback The callback to receive the task after its data has been populated.
- * @return A cancelable handle to the request
- */
- @Override
- public CancellableTask updateThumbnailInBackground(
- Task task, @NonNull Consumer callback) {
- Preconditions.assertUIThread();
-
- boolean lowResolution = !mHighResLoadingState.isEnabled();
- if (task.thumbnail != null && task.thumbnail.getThumbnail() != null
- && (!task.thumbnail.reducedResolution || lowResolution)) {
- // Nothing to load, the thumbnail is already high-resolution or matches what the
- // request, so just callback
- callback.accept(task.thumbnail);
- return null;
- }
-
- return updateThumbnailInBackground(task.key, !mHighResLoadingState.isEnabled(), t -> {
- task.thumbnail = t;
- callback.accept(t);
- });
- }
-
- /**
- * Updates cache size and remove excess entries if current size is more than new cache size.
- *
- * @return whether cache size has increased
- */
- public boolean updateCacheSizeAndRemoveExcess() {
- int newSize = mContext.getResources().getInteger(R.integer.recentsThumbnailCacheSize);
- int oldSize = mCache.getMaxSize();
- if (newSize == oldSize) {
- // Return if no change in size
- return false;
- }
-
- mCache.updateCacheSizeAndRemoveExcess(newSize);
- return newSize > oldSize;
- }
-
- private CancellableTask updateThumbnailInBackground(TaskKey key,
- boolean lowResolution, Consumer callback) {
- Preconditions.assertUIThread();
-
- ThumbnailData cachedThumbnail = mCache.getAndInvalidateIfModified(key);
- if (cachedThumbnail != null && cachedThumbnail.getThumbnail() != null
- && (!cachedThumbnail.reducedResolution || lowResolution)) {
- // Already cached, lets use that thumbnail
- callback.accept(cachedThumbnail);
- return null;
- }
-
- CancellableTask request = new CancellableTask<>(
- () -> {
- ThumbnailData thumbnailData = ActivityManagerWrapper.getInstance()
- .getTaskThumbnail(key.id, lowResolution);
- return thumbnailData.getThumbnail() != null ? thumbnailData
- : ActivityManagerWrapper.getInstance().takeTaskThumbnail(key.id);
- },
- MAIN_EXECUTOR,
- result -> {
- // Avoid an async timing issue that a low res entry replaces an existing high
- // res entry in high res enabled state, so we check before putting it to cache
- if (enableGridOnlyOverview() && result.reducedResolution
- && getHighResLoadingState().isEnabled()) {
- ThumbnailData newCachedThumbnail = mCache.getAndInvalidateIfModified(key);
- if (newCachedThumbnail != null && newCachedThumbnail.getThumbnail() != null
- && !newCachedThumbnail.reducedResolution) {
- return;
- }
- }
- mCache.put(key, result);
- callback.accept(result);
- }
- );
- mBgExecutor.execute(request);
- return request;
- }
-
- /**
- * Clears the cache.
- */
- public void clear() {
- mCache.evictAll();
- }
-
- /**
- * Removes the cached thumbnail for the given task.
- */
- public void remove(Task.TaskKey key) {
- mCache.remove(key);
- }
-
- /**
- * @return The cache size.
- */
- public int getCacheSize() {
- return mCache.getMaxSize();
- }
-
- /**
- * @return The mutable high-res loading state.
- */
- public HighResLoadingState getHighResLoadingState() {
- return mHighResLoadingState;
- }
-
- /**
- * @return Whether to enable background preloading of task thumbnails.
- */
- public boolean isPreloadingEnabled() {
- return mEnableTaskSnapshotPreloading && mHighResLoadingState.mVisible;
- }
-
- /**
- * @return Whether device supports low-res thumbnails. Low-res files are an optimization
- * for faster load times of snapshots. Devices can optionally disable low-res files so that
- * they only store snapshots at high-res scale. The actual scale can be configured in
- * frameworks/base config overlay.
- */
- private static boolean supportsLowResThumbnails() {
- Resources res = Resources.getSystem();
- int resId = res.getIdentifier("config_lowResTaskSnapshotScale", "dimen", "android");
- if (resId != 0) {
- return 0 < res.getFloat(resId);
- }
- return true;
- }
-
-}
diff --git a/quickstep/src/com/android/quickstep/fallback/RecentsTaskController.java b/quickstep/src/com/android/quickstep/fallback/RecentsTaskController.java
deleted file mode 100644
index 2cb398cfff..0000000000
--- a/quickstep/src/com/android/quickstep/fallback/RecentsTaskController.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2018 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.quickstep.fallback;
-
-import com.android.launcher3.uioverrides.touchcontrollers.TaskViewTouchController;
-import com.android.quickstep.RecentsActivity;
-
-public class RecentsTaskController extends TaskViewTouchController {
-
- public RecentsTaskController(RecentsActivity activity) {
- super(activity);
- }
-
- @Override
- protected boolean isRecentsInteractive() {
- return mContainer.hasWindowFocus() || mContainer.getStateManager().getState().hasLiveTile();
- }
-
- @Override
- protected boolean isRecentsModal() {
- return false;
- }
-}
diff --git a/quickstep/src/com/android/quickstep/fallback/window/RecentsDisplayModel.kt b/quickstep/src/com/android/quickstep/fallback/window/RecentsDisplayModel.kt
deleted file mode 100644
index 5b88686cb8..0000000000
--- a/quickstep/src/com/android/quickstep/fallback/window/RecentsDisplayModel.kt
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2024 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.quickstep.fallback.window
-
-import android.content.Context
-import android.util.Log
-import android.view.Display
-import android.view.Display.DEFAULT_DISPLAY
-import androidx.core.util.valueIterator
-import com.android.launcher3.dagger.ApplicationContext
-import com.android.launcher3.dagger.LauncherAppSingleton
-import com.android.launcher3.util.DaggerSingletonObject
-import com.android.launcher3.util.DaggerSingletonTracker
-import com.android.launcher3.util.WallpaperColorHints
-import com.android.quickstep.DisplayModel
-import com.android.quickstep.FallbackWindowInterface
-import com.android.quickstep.RecentsAnimationDeviceState
-import com.android.quickstep.TaskAnimationManager
-import com.android.quickstep.dagger.QuickstepBaseAppComponent
-import com.android.quickstep.fallback.window.RecentsDisplayModel.RecentsDisplayResource
-import com.android.quickstep.fallback.window.RecentsWindowFlags.Companion.enableOverviewInWindow
-import java.io.PrintWriter
-import javax.inject.Inject
-
-@LauncherAppSingleton
-class RecentsDisplayModel
-@Inject
-constructor(
- @ApplicationContext context: Context,
- private val wallpaperColorHints: WallpaperColorHints,
- tracker: DaggerSingletonTracker,
-) : DisplayModel(context) {
-
- companion object {
- private const val TAG = "RecentsDisplayModel"
- private const val DEBUG = false
-
- @JvmStatic
- val INSTANCE: DaggerSingletonObject =
- DaggerSingletonObject(
- QuickstepBaseAppComponent::getRecentsDisplayModel
- )
- }
-
- init {
- if (enableOverviewInWindow) {
- initializeDisplays()
- } else {
- // Always create resource for default display
- storeDisplayResource(DEFAULT_DISPLAY)
- }
- tracker.addCloseable { destroy() }
- }
-
- override fun createDisplayResource(display: Display): RecentsDisplayResource {
- return RecentsDisplayResource(
- display.displayId,
- context.createDisplayContext(display),
- wallpaperColorHints.hints,
- )
- }
-
- fun getRecentsWindowManager(displayId: Int): RecentsWindowManager? {
- if (DEBUG) Log.d(TAG, "getRecentsWindowManager for display $displayId")
- return getDisplayResource(displayId)?.recentsWindowManager
- }
-
- fun getFallbackWindowInterface(displayId: Int): FallbackWindowInterface? {
- if (DEBUG) Log.d(TAG, "getFallbackWindowInterface for display $displayId")
- return getDisplayResource(displayId)?.fallbackWindowInterface
- }
-
- fun getTaskAnimationManager(displayId: Int): TaskAnimationManager? {
- return getDisplayResource(displayId)?.taskAnimationManager
- }
-
- val activeDisplayResources: Iterable
- get() =
- object : Iterable {
- override fun iterator() = displayResourceArray.valueIterator()
- }
-
- data class RecentsDisplayResource(
- val displayId: Int,
- val displayContext: Context,
- val wallpaperColorHints: Int,
- ) : DisplayResource() {
- val recentsWindowManager =
- if (enableOverviewInWindow) RecentsWindowManager(displayContext, wallpaperColorHints)
- else null
- val fallbackWindowInterface =
- if (enableOverviewInWindow) FallbackWindowInterface(recentsWindowManager) else null
- val taskAnimationManager =
- TaskAnimationManager(
- displayContext,
- RecentsAnimationDeviceState.INSTANCE.get(displayContext),
- displayId,
- )
-
- override fun cleanup() {
- recentsWindowManager?.destroy()
- }
-
- override fun dump(prefix: String, writer: PrintWriter) {
- writer.println("${prefix}RecentsDisplayResource:")
-
- writer.println("${prefix}\tdisplayId=${displayId}")
- writer.println("${prefix}\tdisplayContext=${displayContext}")
- writer.println("${prefix}\twallpaperColorHints=${wallpaperColorHints}")
- writer.println("${prefix}\trecentsWindowManager=${recentsWindowManager}")
- writer.println("${prefix}\tfallbackWindowInterface=${fallbackWindowInterface}")
- }
- }
-}
diff --git a/quickstep/src/com/android/quickstep/inputconsumers/ResetGestureInputConsumer.java b/quickstep/src/com/android/quickstep/inputconsumers/ResetGestureInputConsumer.java
deleted file mode 100644
index 349f4d2f2f..0000000000
--- a/quickstep/src/com/android/quickstep/inputconsumers/ResetGestureInputConsumer.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2019 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.quickstep.inputconsumers;
-
-import android.view.MotionEvent;
-
-import com.android.launcher3.taskbar.TaskbarActivityContext;
-import com.android.quickstep.InputConsumer;
-import com.android.quickstep.TaskAnimationManager;
-
-import java.util.function.Supplier;
-
-/**
- * A NO_OP input consumer which also resets any pending gesture
- */
-public class ResetGestureInputConsumer implements InputConsumer {
-
- private final TaskAnimationManager mTaskAnimationManager;
- private final Supplier mActivityContextSupplier;
-
- public ResetGestureInputConsumer(
- TaskAnimationManager taskAnimationManager,
- Supplier activityContextSupplier) {
- mTaskAnimationManager = taskAnimationManager;
- mActivityContextSupplier = activityContextSupplier;
- }
-
- @Override
- public int getType() {
- return TYPE_RESET_GESTURE;
- }
-
- @Override
- public void onMotionEvent(MotionEvent ev) {
- if (ev.getAction() == MotionEvent.ACTION_DOWN
- && mTaskAnimationManager.isRecentsAnimationRunning()) {
- TaskbarActivityContext tac = mActivityContextSupplier.get();
- mTaskAnimationManager.finishRunningRecentsAnimation(
- /* toHome= */ tac != null && !tac.isInApp());
- }
- }
-}
diff --git a/quickstep/src/com/android/quickstep/interaction/TutorialStepIndicator.java b/quickstep/src/com/android/quickstep/interaction/TutorialStepIndicator.java
deleted file mode 100644
index ae0e725aad..0000000000
--- a/quickstep/src/com/android/quickstep/interaction/TutorialStepIndicator.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2021 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.quickstep.interaction;
-
-import android.content.Context;
-import android.graphics.drawable.Drawable;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.widget.ImageView;
-import android.widget.LinearLayout;
-
-import androidx.appcompat.content.res.AppCompatResources;
-
-import com.android.launcher3.R;
-import com.android.launcher3.Utilities;
-import com.android.launcher3.icons.GraphicsUtils;
-
-/** Indicator displaying the current progress through the gesture navigation tutorial. */
-public class TutorialStepIndicator extends LinearLayout {
-
- private static final String LOG_TAG = "TutorialStepIndicator";
-
- private int mCurrentStep = -1;
- private int mTotalSteps = -1;
-
- public TutorialStepIndicator(Context context) {
- super(context);
- }
-
- public TutorialStepIndicator(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public TutorialStepIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- }
-
- public TutorialStepIndicator(Context context, AttributeSet attrs, int defStyleAttr,
- int defStyleRes) {
- super(context, attrs, defStyleAttr, defStyleRes);
- }
-
- /**
- * Updates this indicator to display totalSteps indicator pills, with the first currentStep
- * pills highlighted.
- */
- public void setTutorialProgress(int currentStep, int totalSteps) {
- if (currentStep <= 0) {
- Log.w(LOG_TAG, "Current step number invalid: " + currentStep + ". Assuming step 1.");
- currentStep = 1;
- }
- if (totalSteps <= 0) {
- Log.w(LOG_TAG, "Total number of steps invalid: " + totalSteps + ". Assuming 1 step.");
- totalSteps = 1;
- }
- if (currentStep > totalSteps) {
- Log.w(LOG_TAG, "Current step number greater than the total number of steps. Assuming"
- + " final step.");
- currentStep = totalSteps;
- }
- if (totalSteps < 2) {
- setVisibility(GONE);
- return;
- }
- setVisibility(VISIBLE);
- mCurrentStep = currentStep;
- mTotalSteps = totalSteps;
-
- initializeStepIndicators();
- }
-
- private void initializeStepIndicators() {
- for (int i = mTotalSteps; i < getChildCount(); i++) {
- removeViewAt(i);
- }
- int activeStepIndicatorColor = GraphicsUtils.getAttrColor(
- getContext(), android.R.attr.textColorPrimary);
- int inactiveStepIndicatorColor = GraphicsUtils.getAttrColor(
- getContext(), android.R.attr.textColorSecondaryInverse);
- for (int i = 0; i < mTotalSteps; i++) {
- Drawable pageIndicatorPillDrawable = AppCompatResources.getDrawable(
- getContext(), R.drawable.tutorial_step_indicator_pill);
-
- if (i >= getChildCount()) {
- ImageView pageIndicatorPill = new ImageView(getContext());
- pageIndicatorPill.setImageDrawable(pageIndicatorPillDrawable);
-
- LinearLayout.LayoutParams lp = new LayoutParams(
- LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
-
- lp.setMarginStart(Utilities.dpToPx(3));
- lp.setMarginEnd(Utilities.dpToPx(3));
-
- addView(pageIndicatorPill, lp);
- }
- if (pageIndicatorPillDrawable != null) {
- if (i < mCurrentStep) {
- pageIndicatorPillDrawable.setTint(activeStepIndicatorColor);
- } else {
- pageIndicatorPillDrawable.setTint(inactiveStepIndicatorColor);
- }
- }
- }
- }
-}
diff --git a/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java b/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java
deleted file mode 100644
index eeacee1cf6..0000000000
--- a/quickstep/src/com/android/quickstep/orientation/PortraitPagedViewHandler.java
+++ /dev/null
@@ -1,820 +0,0 @@
-/*
- * Copyright (C) 2024 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.quickstep.orientation;
-
-import static android.view.Gravity.BOTTOM;
-import static android.view.Gravity.CENTER_HORIZONTAL;
-import static android.view.Gravity.END;
-import static android.view.Gravity.START;
-import static android.view.Gravity.TOP;
-import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
-import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
-
-import static com.android.launcher3.Flags.enableOverviewIconMenu;
-import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
-import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
-import static com.android.launcher3.touch.SingleAxisSwipeDetector.VERTICAL;
-import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT;
-import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT;
-import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_TYPE_MAIN;
-
-import android.graphics.Matrix;
-import android.graphics.Point;
-import android.graphics.PointF;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.graphics.drawable.ShapeDrawable;
-import android.util.FloatProperty;
-import android.util.Pair;
-import android.view.Gravity;
-import android.view.Surface;
-import android.view.View;
-import android.widget.FrameLayout;
-import android.widget.LinearLayout;
-
-import androidx.annotation.NonNull;
-
-import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.R;
-import com.android.launcher3.Utilities;
-import com.android.launcher3.logger.LauncherAtom;
-import com.android.launcher3.touch.DefaultPagedViewHandler;
-import com.android.launcher3.touch.SingleAxisSwipeDetector;
-import com.android.launcher3.util.SplitConfigurationOptions;
-import com.android.launcher3.util.SplitConfigurationOptions.SplitBounds;
-import com.android.launcher3.util.SplitConfigurationOptions.SplitPositionOption;
-import com.android.launcher3.util.SplitConfigurationOptions.StagePosition;
-import com.android.quickstep.views.IconAppChipView;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class PortraitPagedViewHandler extends DefaultPagedViewHandler implements
- RecentsPagedOrientationHandler {
-
- private final Matrix mTmpMatrix = new Matrix();
- private final RectF mTmpRectF = new RectF();
-
- @Override
- public T getPrimaryValue(T x, T y) {
- return x;
- }
-
- @Override
- public T getSecondaryValue(T x, T y) {
- return y;
- }
-
- @Override
- public boolean isLayoutNaturalToLauncher() {
- return true;
- }
-
- @Override
- public void adjustFloatingIconStartVelocity(PointF velocity) {
- //no-op
- }
-
- @Override
- public void fixBoundsForHomeAnimStartRect(RectF outStartRect, DeviceProfile deviceProfile) {
- if (outStartRect.left > deviceProfile.widthPx) {
- outStartRect.offsetTo(0, outStartRect.top);
- } else if (outStartRect.left < -deviceProfile.widthPx) {
- outStartRect.offsetTo(0, outStartRect.top);
- }
- }
-
- @Override
- public void setSecondary(T target, Float2DAction action, float param) {
- action.call(target, 0, param);
- }
-
- @Override
- public void set(T target, Int2DAction action, int primaryParam,
- int secondaryParam) {
- action.call(target, primaryParam, secondaryParam);
- }
-
- @Override
- public int getPrimarySize(View view) {
- return view.getWidth();
- }
-
- @Override
- public float getPrimarySize(RectF rect) {
- return rect.width();
- }
-
- @Override
- public float getStart(RectF rect) {
- return rect.left;
- }
-
- @Override
- public float getEnd(RectF rect) {
- return rect.right;
- }
-
- @Override
- public void rotateInsets(@NonNull Rect insets, @NonNull Rect outInsets) {
- outInsets.set(insets);
- }
-
- @Override
- public int getClearAllSidePadding(View view, boolean isRtl) {
- return (isRtl ? view.getPaddingRight() : - view.getPaddingLeft()) / 2;
- }
-
- @Override
- public int getSecondaryDimension(View view) {
- return view.getHeight();
- }
-
- @Override
- public FloatProperty getPrimaryViewTranslate() {
- return VIEW_TRANSLATE_X;
- }
-
- @Override
- public FloatProperty getSecondaryViewTranslate() {
- return VIEW_TRANSLATE_Y;
- }
-
- @Override
- public float getDegreesRotated() {
- return 0;
- }
-
- @Override
- public int getRotation() {
- return Surface.ROTATION_0;
- }
-
- @Override
- public void setPrimaryScale(View view, float scale) {
- view.setScaleX(scale);
- }
-
- @Override
- public void setSecondaryScale(View view, float scale) {
- view.setScaleY(scale);
- }
-
- public int getSecondaryTranslationDirectionFactor() {
- return -1;
- }
-
- @Override
- public int getSplitTranslationDirectionFactor(int stagePosition, DeviceProfile deviceProfile) {
- if (deviceProfile.isLeftRightSplit && stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT) {
- return -1;
- } else {
- return 1;
- }
- }
-
- @Override
- public float getTaskMenuX(float x, View thumbnailView,
- DeviceProfile deviceProfile, float taskInsetMargin, View taskViewIcon) {
- if (deviceProfile.isLandscape) {
- return x + taskInsetMargin
- + (thumbnailView.getMeasuredWidth() - thumbnailView.getMeasuredHeight()) / 2f;
- } else {
- return x + taskInsetMargin;
- }
- }
-
- @Override
- public float getTaskMenuY(float y, View thumbnailView, int stagePosition,
- View taskMenuView, float taskInsetMargin, View taskViewIcon) {
- return y + taskInsetMargin;
- }
-
- @Override
- public int getTaskMenuWidth(View thumbnailView, DeviceProfile deviceProfile,
- @StagePosition int stagePosition) {
- if (enableOverviewIconMenu()) {
- return thumbnailView.getResources().getDimensionPixelSize(
- R.dimen.task_thumbnail_icon_menu_expanded_width);
- }
- int padding = thumbnailView.getResources()
- .getDimensionPixelSize(R.dimen.task_menu_edge_padding);
- return (deviceProfile.isLandscape && !deviceProfile.isTablet
- ? thumbnailView.getMeasuredHeight()
- : thumbnailView.getMeasuredWidth()) - (2 * padding);
- }
-
- @Override
- public int getTaskMenuHeight(float taskInsetMargin, DeviceProfile deviceProfile,
- float taskMenuX, float taskMenuY) {
- return (int) (deviceProfile.heightPx - deviceProfile.getInsets().top - taskMenuY
- - deviceProfile.getOverviewActionsClaimedSpaceBelow());
- }
-
- @Override
- public void setTaskOptionsMenuLayoutOrientation(DeviceProfile deviceProfile,
- LinearLayout taskMenuLayout, int dividerSpacing,
- ShapeDrawable dividerDrawable) {
- taskMenuLayout.setOrientation(LinearLayout.VERTICAL);
- dividerDrawable.setIntrinsicHeight(dividerSpacing);
- taskMenuLayout.setDividerDrawable(dividerDrawable);
- }
-
- @Override
- public void setLayoutParamsForTaskMenuOptionItem(LinearLayout.LayoutParams lp,
- LinearLayout viewGroup, DeviceProfile deviceProfile) {
- viewGroup.setOrientation(LinearLayout.HORIZONTAL);
- lp.width = LinearLayout.LayoutParams.MATCH_PARENT;
- lp.height = WRAP_CONTENT;
- }
-
- @Override
- public Pair getDwbLayoutTranslations(int taskViewWidth,
- int taskViewHeight, SplitBounds splitBounds, DeviceProfile deviceProfile,
- View[] thumbnailViews, int desiredTaskId, View banner) {
- float translationX = 0;
- float translationY = 0;
- FrameLayout.LayoutParams bannerParams = (FrameLayout.LayoutParams) banner.getLayoutParams();
- banner.setPivotX(0);
- banner.setPivotY(0);
- banner.setRotation(getDegreesRotated());
- if (splitBounds == null) {
- // Single, fullscreen case
- bannerParams.width = MATCH_PARENT;
- bannerParams.gravity = BOTTOM | CENTER_HORIZONTAL;
- return new Pair<>(translationX, translationY);
- }
-
- bannerParams.gravity =
- BOTTOM | (deviceProfile.isLeftRightSplit ? START : CENTER_HORIZONTAL);
-
- // Set correct width
- if (desiredTaskId == splitBounds.leftTopTaskId) {
- bannerParams.width = thumbnailViews[0].getMeasuredWidth();
- } else {
- bannerParams.width = thumbnailViews[1].getMeasuredWidth();
- }
-
- // Set translations
- if (deviceProfile.isLeftRightSplit) {
- if (desiredTaskId == splitBounds.rightBottomTaskId) {
- float leftTopTaskPercent = splitBounds.appsStackedVertically
- ? splitBounds.topTaskPercent
- : splitBounds.leftTaskPercent;
- float dividerThicknessPercent = splitBounds.appsStackedVertically
- ? splitBounds.dividerHeightPercent
- : splitBounds.dividerWidthPercent;
- translationX = ((taskViewWidth * leftTopTaskPercent)
- + (taskViewWidth * dividerThicknessPercent));
- }
- } else {
- if (desiredTaskId == splitBounds.leftTopTaskId) {
- FrameLayout.LayoutParams snapshotParams =
- (FrameLayout.LayoutParams) thumbnailViews[0]
- .getLayoutParams();
- float bottomRightTaskPlusDividerPercent = splitBounds.appsStackedVertically
- ? (1f - splitBounds.topTaskPercent)
- : (1f - splitBounds.leftTaskPercent);
- translationY = -((taskViewHeight - snapshotParams.topMargin)
- * bottomRightTaskPlusDividerPercent);
- }
- }
- return new Pair<>(translationX, translationY);
- }
-
- /* ---------- The following are only used by TaskViewTouchHandler. ---------- */
-
- @Override
- public SingleAxisSwipeDetector.Direction getUpDownSwipeDirection() {
- return VERTICAL;
- }
-
- @Override
- public int getUpDirection(boolean isRtl) {
- // Ignore rtl since it only affects X value displacement, Y displacement doesn't change
- return SingleAxisSwipeDetector.DIRECTION_POSITIVE;
- }
-
- @Override
- public boolean isGoingUp(float displacement, boolean isRtl) {
- // Ignore rtl since it only affects X value displacement, Y displacement doesn't change
- return displacement < 0;
- }
-
- @Override
- public int getTaskDragDisplacementFactor(boolean isRtl) {
- // Ignore rtl since it only affects X value displacement, Y displacement doesn't change
- return 1;
- }
-
- /* -------------------- */
- @Override
- public int getDistanceToBottomOfRect(DeviceProfile dp, Rect rect) {
- return dp.heightPx - rect.bottom;
- }
-
- @Override
- public List getSplitPositionOptions(DeviceProfile dp) {
- if (dp.isTablet) {
- return Utilities.getSplitPositionOptions(dp);
- }
-
- List options = new ArrayList<>();
- if (dp.isSeascape()) {
- options.add(new SplitPositionOption(
- R.drawable.ic_split_horizontal, R.string.recent_task_option_split_screen,
- STAGE_POSITION_BOTTOM_OR_RIGHT, STAGE_TYPE_MAIN));
- } else if (dp.isLeftRightSplit) {
- options.add(new SplitPositionOption(
- R.drawable.ic_split_horizontal, R.string.recent_task_option_split_screen,
- STAGE_POSITION_TOP_OR_LEFT, STAGE_TYPE_MAIN));
- } else {
- // Only add top option
- options.add(new SplitPositionOption(
- R.drawable.ic_split_vertical, R.string.recent_task_option_split_screen,
- STAGE_POSITION_TOP_OR_LEFT, STAGE_TYPE_MAIN));
- }
- return options;
- }
-
- @Override
- public void getInitialSplitPlaceholderBounds(int placeholderHeight, int placeholderInset,
- DeviceProfile dp, @StagePosition int stagePosition, Rect out) {
- int screenWidth = dp.widthPx;
- int screenHeight = dp.heightPx;
- boolean pinToRight = stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT;
- int insetSizeAdjustment = getPlaceholderSizeAdjustment(dp, pinToRight);
-
- out.set(0, 0, screenWidth, placeholderHeight + insetSizeAdjustment);
- if (!dp.isLeftRightSplit) {
- // portrait, phone or tablet - spans width of screen, nothing else to do
- out.inset(placeholderInset, 0);
-
- // Adjust the top to account for content off screen. This will help to animate the view
- // in with rounded corners.
- int totalHeight = (int) (1.0f * screenHeight / 2 * (screenWidth - 2 * placeholderInset)
- / screenWidth);
- out.top -= (totalHeight - placeholderHeight);
- return;
- }
-
- // Now we rotate the portrait rect depending on what side we want pinned
-
- float postRotateScale = (float) screenHeight / screenWidth;
- mTmpMatrix.reset();
- mTmpMatrix.postRotate(pinToRight ? 90 : 270);
- mTmpMatrix.postTranslate(pinToRight ? screenWidth : 0, pinToRight ? 0 : screenWidth);
- // The placeholder height stays constant after rotation, so we don't change width scale
- mTmpMatrix.postScale(1, postRotateScale);
-
- mTmpRectF.set(out);
- mTmpMatrix.mapRect(mTmpRectF);
- mTmpRectF.inset(0, placeholderInset);
- mTmpRectF.roundOut(out);
-
- // Adjust the top to account for content off screen. This will help to animate the view in
- // with rounded corners.
- int totalWidth = (int) (1.0f * screenWidth / 2 * (screenHeight - 2 * placeholderInset)
- / screenHeight);
- int width = out.width();
- if (pinToRight) {
- out.right += totalWidth - width;
- } else {
- out.left -= totalWidth - width;
- }
- }
-
- @Override
- public void updateSplitIconParams(View out, float onScreenRectCenterX,
- float onScreenRectCenterY, float fullscreenScaleX, float fullscreenScaleY,
- int drawableWidth, int drawableHeight, DeviceProfile dp,
- @StagePosition int stagePosition) {
- boolean pinToRight = stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT;
- float insetAdjustment = getPlaceholderSizeAdjustment(dp, pinToRight) / 2f;
- if (!dp.isLeftRightSplit) {
- out.setX(onScreenRectCenterX / fullscreenScaleX
- - 1.0f * drawableWidth / 2);
- out.setY((onScreenRectCenterY + insetAdjustment) / fullscreenScaleY
- - 1.0f * drawableHeight / 2);
- } else {
- if (pinToRight) {
- out.setX((onScreenRectCenterX - insetAdjustment) / fullscreenScaleX
- - 1.0f * drawableWidth / 2);
- } else {
- out.setX((onScreenRectCenterX + insetAdjustment) / fullscreenScaleX
- - 1.0f * drawableWidth / 2);
- }
- out.setY(onScreenRectCenterY / fullscreenScaleY
- - 1.0f * drawableHeight / 2);
- }
- }
-
- /**
- * The split placeholder comes with a default inset to buffer the icon from the top of the
- * screen. But if the device already has a large inset (from cutouts etc), use that instead.
- */
- private int getPlaceholderSizeAdjustment(DeviceProfile dp, boolean pinToRight) {
- int insetThickness;
- if (!dp.isLandscape) {
- insetThickness = dp.getInsets().top;
- } else {
- insetThickness = pinToRight ? dp.getInsets().right : dp.getInsets().left;
- }
- return Math.max(insetThickness - dp.splitPlaceholderInset, 0);
- }
-
- @Override
- public void setSplitInstructionsParams(View out, DeviceProfile dp, int splitInstructionsHeight,
- int splitInstructionsWidth) {
- out.setPivotX(0);
- out.setPivotY(splitInstructionsHeight);
- out.setRotation(getDegreesRotated());
- int distanceToEdge;
- if (dp.isPhone) {
- if (dp.isLandscape) {
- distanceToEdge = out.getResources().getDimensionPixelSize(
- R.dimen.split_instructions_bottom_margin_phone_landscape);
- } else {
- distanceToEdge = out.getResources().getDimensionPixelSize(
- R.dimen.split_instructions_bottom_margin_phone_portrait);
- }
- } else {
- distanceToEdge = dp.getOverviewActionsClaimedSpaceBelow();
- }
-
- // Center the view in case of unbalanced insets on left or right of screen
- int insetCorrectionX = (dp.getInsets().right - dp.getInsets().left) / 2;
- // Adjust for any insets on the bottom edge
- int insetCorrectionY = dp.getInsets().bottom;
- out.setTranslationX(insetCorrectionX);
- out.setTranslationY(-distanceToEdge + insetCorrectionY);
- FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) out.getLayoutParams();
- lp.gravity = CENTER_HORIZONTAL | BOTTOM;
- out.setLayoutParams(lp);
- }
-
- @Override
- public void getFinalSplitPlaceholderBounds(int splitDividerSize, DeviceProfile dp,
- @StagePosition int stagePosition, Rect out1, Rect out2) {
- int screenHeight = dp.heightPx;
- int screenWidth = dp.widthPx;
- out1.set(0, 0, screenWidth, screenHeight / 2 - splitDividerSize);
- out2.set(0, screenHeight / 2 + splitDividerSize, screenWidth, screenHeight);
- if (!dp.isLeftRightSplit) {
- // Portrait - the window bounds are always top and bottom half
- return;
- }
-
- // Now we rotate the portrait rect depending on what side we want pinned
- boolean pinToRight = stagePosition == STAGE_POSITION_BOTTOM_OR_RIGHT;
- float postRotateScale = (float) screenHeight / screenWidth;
-
- mTmpMatrix.reset();
- mTmpMatrix.postRotate(pinToRight ? 90 : 270);
- mTmpMatrix.postTranslate(pinToRight ? screenHeight : 0, pinToRight ? 0 : screenWidth);
- mTmpMatrix.postScale(1 / postRotateScale, postRotateScale);
-
- mTmpRectF.set(out1);
- mTmpMatrix.mapRect(mTmpRectF);
- mTmpRectF.roundOut(out1);
-
- mTmpRectF.set(out2);
- mTmpMatrix.mapRect(mTmpRectF);
- mTmpRectF.roundOut(out2);
- }
-
- @Override
- public void setSplitTaskSwipeRect(DeviceProfile dp, Rect outRect,
- SplitBounds splitInfo, int desiredStagePosition) {
- float topLeftTaskPercent = splitInfo.appsStackedVertically
- ? splitInfo.topTaskPercent
- : splitInfo.leftTaskPercent;
- float dividerBarPercent = splitInfo.appsStackedVertically
- ? splitInfo.dividerHeightPercent
- : splitInfo.dividerWidthPercent;
-
- int taskbarHeight = dp.isTransientTaskbar ? 0 : dp.taskbarHeight;
- float scale = (float) outRect.height() / (dp.availableHeightPx - taskbarHeight);
- float topTaskHeight = dp.availableHeightPx * topLeftTaskPercent;
- float scaledTopTaskHeight = topTaskHeight * scale;
- float dividerHeight = dp.availableHeightPx * dividerBarPercent;
- float scaledDividerHeight = dividerHeight * scale;
-
- if (desiredStagePosition == SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT) {
- if (dp.isLeftRightSplit) {
- outRect.right = outRect.left + Math.round(outRect.width() * topLeftTaskPercent);
- } else {
- outRect.bottom = Math.round(outRect.top + scaledTopTaskHeight);
- }
- } else {
- if (dp.isLeftRightSplit) {
- outRect.left += Math.round(outRect.width()
- * (topLeftTaskPercent + dividerBarPercent));
- } else {
- outRect.top += Math.round(scaledTopTaskHeight + scaledDividerHeight);
- }
- }
- }
-
- @Override
- public void measureGroupedTaskViewThumbnailBounds(View primarySnapshot, View secondarySnapshot,
- int parentWidth, int parentHeight, SplitBounds splitBoundsConfig,
- DeviceProfile dp, boolean isRtl) {
- int spaceAboveSnapshot = dp.overviewTaskThumbnailTopMarginPx;
- int totalThumbnailHeight = parentHeight - spaceAboveSnapshot;
- float dividerScale = splitBoundsConfig.appsStackedVertically
- ? splitBoundsConfig.dividerHeightPercent
- : splitBoundsConfig.dividerWidthPercent;
- Pair taskViewSizes =
- getGroupedTaskViewSizes(dp, splitBoundsConfig, parentWidth, parentHeight);
- if (dp.isLeftRightSplit) {
- int scaledDividerBar = Math.round(parentWidth * dividerScale);
- if (isRtl) {
- int translationX = taskViewSizes.second.x + scaledDividerBar;
- primarySnapshot.setTranslationX(-translationX);
- secondarySnapshot.setTranslationX(0);
- } else {
- int translationX = taskViewSizes.first.x + scaledDividerBar;
- secondarySnapshot.setTranslationX(translationX);
- primarySnapshot.setTranslationX(0);
- }
- secondarySnapshot.setTranslationY(spaceAboveSnapshot);
-
- // Reset unused translations
- primarySnapshot.setTranslationY(0);
- } else {
- float finalDividerHeight = Math.round(totalThumbnailHeight * dividerScale);
- float translationY = taskViewSizes.first.y + spaceAboveSnapshot + finalDividerHeight;
- secondarySnapshot.setTranslationY(translationY);
-
- FrameLayout.LayoutParams primaryParams =
- (FrameLayout.LayoutParams) primarySnapshot.getLayoutParams();
- FrameLayout.LayoutParams secondaryParams =
- (FrameLayout.LayoutParams) secondarySnapshot.getLayoutParams();
- secondaryParams.topMargin = 0;
- primaryParams.topMargin = spaceAboveSnapshot;
-
- // Reset unused translations
- primarySnapshot.setTranslationY(0);
- secondarySnapshot.setTranslationX(0);
- primarySnapshot.setTranslationX(0);
- }
- primarySnapshot.measure(
- View.MeasureSpec.makeMeasureSpec(taskViewSizes.first.x, View.MeasureSpec.EXACTLY),
- View.MeasureSpec.makeMeasureSpec(taskViewSizes.first.y, View.MeasureSpec.EXACTLY));
- secondarySnapshot.measure(
- View.MeasureSpec.makeMeasureSpec(taskViewSizes.second.x, View.MeasureSpec.EXACTLY),
- View.MeasureSpec.makeMeasureSpec(taskViewSizes.second.y,
- View.MeasureSpec.EXACTLY));
- primarySnapshot.setScaleX(1);
- secondarySnapshot.setScaleX(1);
- primarySnapshot.setScaleY(1);
- secondarySnapshot.setScaleY(1);
- }
-
- @Override
- public Pair getGroupedTaskViewSizes(
- DeviceProfile dp,
- SplitBounds splitBoundsConfig,
- int parentWidth,
- int parentHeight) {
- int spaceAboveSnapshot = dp.overviewTaskThumbnailTopMarginPx;
- int totalThumbnailHeight = parentHeight - spaceAboveSnapshot;
- float dividerScale = splitBoundsConfig.appsStackedVertically
- ? splitBoundsConfig.dividerHeightPercent
- : splitBoundsConfig.dividerWidthPercent;
- float taskPercent = splitBoundsConfig.appsStackedVertically
- ? splitBoundsConfig.topTaskPercent
- : splitBoundsConfig.leftTaskPercent;
-
- Point firstTaskViewSize = new Point();
- Point secondTaskViewSize = new Point();
-
- if (dp.isLeftRightSplit) {
- int scaledDividerBar = Math.round(parentWidth * dividerScale);
- firstTaskViewSize.x = Math.round(parentWidth * taskPercent);
- firstTaskViewSize.y = totalThumbnailHeight;
-
- secondTaskViewSize.x = parentWidth - firstTaskViewSize.x - scaledDividerBar;
- secondTaskViewSize.y = totalThumbnailHeight;
- } else {
- int taskbarHeight = dp.isTransientTaskbar ? 0 : dp.taskbarHeight;
- float scale = (float) totalThumbnailHeight / (dp.availableHeightPx - taskbarHeight);
- float topTaskHeight = dp.availableHeightPx * taskPercent;
- float finalDividerHeight = Math.round(totalThumbnailHeight * dividerScale);
- float scaledTopTaskHeight = topTaskHeight * scale;
- firstTaskViewSize.x = parentWidth;
- firstTaskViewSize.y = Math.round(scaledTopTaskHeight);
-
- secondTaskViewSize.x = parentWidth;
- secondTaskViewSize.y = Math.round(totalThumbnailHeight - firstTaskViewSize.y
- - finalDividerHeight);
- }
-
- return new Pair<>(firstTaskViewSize, secondTaskViewSize);
- }
-
- @Override
- public void setTaskIconParams(FrameLayout.LayoutParams iconParams, int taskIconMargin,
- int taskIconHeight, int thumbnailTopMargin, boolean isRtl) {
- iconParams.gravity = TOP | CENTER_HORIZONTAL;
- // Reset margins, since they may have been set on rotation
- iconParams.leftMargin = iconParams.rightMargin = 0;
- iconParams.topMargin = iconParams.bottomMargin = 0;
- }
-
- @Override
- public void setIconAppChipChildrenParams(FrameLayout.LayoutParams iconParams,
- int chipChildMarginStart) {
- iconParams.setMarginStart(chipChildMarginStart);
- iconParams.gravity = Gravity.START | Gravity.CENTER_VERTICAL;
- iconParams.topMargin = 0;
- }
-
- @Override
- public void setIconAppChipMenuParams(IconAppChipView iconAppChipView,
- FrameLayout.LayoutParams iconMenuParams, int iconMenuMargin, int thumbnailTopMargin) {
- iconMenuParams.gravity = TOP | START;
- iconMenuParams.setMarginStart(iconMenuMargin);
- iconMenuParams.topMargin = thumbnailTopMargin;
- iconMenuParams.bottomMargin = 0;
- iconMenuParams.setMarginEnd(0);
-
- iconAppChipView.setPivotX(0);
- iconAppChipView.setPivotY(0);
- iconAppChipView.setSplitTranslationY(0);
- iconAppChipView.setRotation(getDegreesRotated());
- }
-
- @Override
- public void setSplitIconParams(View primaryIconView, View secondaryIconView,
- int taskIconHeight, int primarySnapshotWidth, int primarySnapshotHeight,
- int groupedTaskViewHeight, int groupedTaskViewWidth, boolean isRtl,
- DeviceProfile deviceProfile, SplitBounds splitConfig) {
- FrameLayout.LayoutParams primaryIconParams =
- (FrameLayout.LayoutParams) primaryIconView.getLayoutParams();
- FrameLayout.LayoutParams secondaryIconParams = enableOverviewIconMenu()
- ? (FrameLayout.LayoutParams) secondaryIconView.getLayoutParams()
- : new FrameLayout.LayoutParams(primaryIconParams);
-
- if (enableOverviewIconMenu()) {
- IconAppChipView primaryAppChipView = (IconAppChipView) primaryIconView;
- IconAppChipView secondaryAppChipView = (IconAppChipView) secondaryIconView;
- primaryIconParams.gravity = TOP | START;
- secondaryIconParams.gravity = TOP | START;
- secondaryIconParams.topMargin = primaryIconParams.topMargin;
- secondaryIconParams.setMarginStart(primaryIconParams.getMarginStart());
- if (deviceProfile.isLeftRightSplit) {
- if (isRtl) {
- int secondarySnapshotWidth = groupedTaskViewWidth - primarySnapshotWidth;
- primaryAppChipView.setSplitTranslationX(-secondarySnapshotWidth);
- } else {
- secondaryAppChipView.setSplitTranslationX(primarySnapshotWidth);
- }
- } else {
- primaryAppChipView.setSplitTranslationX(0);
- secondaryAppChipView.setSplitTranslationX(0);
- int dividerThickness = Math.min(splitConfig.visualDividerBounds.width(),
- splitConfig.visualDividerBounds.height());
- secondaryAppChipView.setSplitTranslationY(
- primarySnapshotHeight + (deviceProfile.isTablet ? 0 : dividerThickness));
- }
- } else if (deviceProfile.isLeftRightSplit) {
- // We calculate the "midpoint" of the thumbnail area, and place the icons there.
- // This is the place where the thumbnail area splits by default, in a near-50/50 split.
- // It is usually not exactly 50/50, due to insets/screen cutouts.
- int fullscreenInsetThickness = deviceProfile.isSeascape()
- ? deviceProfile.getInsets().right
- : deviceProfile.getInsets().left;
- int fullscreenMidpointFromBottom = ((deviceProfile.widthPx
- - fullscreenInsetThickness) / 2);
- float midpointFromEndPct = (float) fullscreenMidpointFromBottom
- / deviceProfile.widthPx;
- float insetPct = (float) fullscreenInsetThickness / deviceProfile.widthPx;
- int spaceAboveSnapshots = 0;
- int overviewThumbnailAreaThickness = groupedTaskViewWidth - spaceAboveSnapshots;
- int bottomToMidpointOffset = (int) (overviewThumbnailAreaThickness
- * midpointFromEndPct);
- int insetOffset = (int) (overviewThumbnailAreaThickness * insetPct);
-
- if (deviceProfile.isSeascape()) {
- primaryIconParams.gravity = TOP | (isRtl ? END : START);
- secondaryIconParams.gravity = TOP | (isRtl ? END : START);
- if (splitConfig.initiatedFromSeascape) {
- // if the split was initiated from seascape,
- // the task on the right (secondary) is slightly larger
- primaryIconView.setTranslationX(bottomToMidpointOffset - taskIconHeight);
- secondaryIconView.setTranslationX(bottomToMidpointOffset);
- } else {
- // if not,
- // the task on the left (primary) is slightly larger
- primaryIconView.setTranslationX(bottomToMidpointOffset + insetOffset
- - taskIconHeight);
- secondaryIconView.setTranslationX(bottomToMidpointOffset + insetOffset);
- }
- } else {
- primaryIconParams.gravity = TOP | (isRtl ? START : END);
- secondaryIconParams.gravity = TOP | (isRtl ? START : END);
- if (!splitConfig.initiatedFromSeascape) {
- // if the split was initiated from landscape,
- // the task on the left (primary) is slightly larger
- primaryIconView.setTranslationX(-bottomToMidpointOffset);
- secondaryIconView.setTranslationX(-bottomToMidpointOffset + taskIconHeight);
- } else {
- // if not,
- // the task on the right (secondary) is slightly larger
- primaryIconView.setTranslationX(-bottomToMidpointOffset - insetOffset);
- secondaryIconView.setTranslationX(-bottomToMidpointOffset - insetOffset
- + taskIconHeight);
- }
- }
- } else {
- primaryIconParams.gravity = TOP | CENTER_HORIZONTAL;
- // shifts icon half a width left (height is used here since icons are square)
- primaryIconView.setTranslationX(-(taskIconHeight / 2f));
- secondaryIconParams.gravity = TOP | CENTER_HORIZONTAL;
- secondaryIconView.setTranslationX(taskIconHeight / 2f);
- }
- if (!enableOverviewIconMenu()) {
- primaryIconView.setTranslationY(0);
- secondaryIconView.setTranslationY(0);
- }
-
- primaryIconView.setLayoutParams(primaryIconParams);
- secondaryIconView.setLayoutParams(secondaryIconParams);
- }
-
- @Override
- public int getDefaultSplitPosition(DeviceProfile deviceProfile) {
- if (!deviceProfile.isTablet) {
- throw new IllegalStateException("Default position available only for large screens");
- }
- if (deviceProfile.isLeftRightSplit) {
- return STAGE_POSITION_BOTTOM_OR_RIGHT;
- } else {
- return STAGE_POSITION_TOP_OR_LEFT;
- }
- }
-
- @Override
- public Pair getSplitSelectTaskOffset(FloatProperty primary,
- FloatProperty secondary, DeviceProfile deviceProfile) {
- if (deviceProfile.isLeftRightSplit) { // or seascape
- return new Pair<>(primary, secondary);
- } else {
- return new Pair<>(secondary, primary);
- }
- }
-
- @Override
- public float getFloatingTaskOffscreenTranslationTarget(View floatingTask, RectF onScreenRect,
- @StagePosition int stagePosition, DeviceProfile dp) {
- if (dp.isLeftRightSplit) {
- float currentTranslationX = floatingTask.getTranslationX();
- return stagePosition == STAGE_POSITION_TOP_OR_LEFT
- ? currentTranslationX - onScreenRect.width()
- : currentTranslationX + onScreenRect.width();
- } else {
- float currentTranslationY = floatingTask.getTranslationY();
- return currentTranslationY - onScreenRect.height();
- }
- }
-
- @Override
- public void setFloatingTaskPrimaryTranslation(View floatingTask, float translation,
- DeviceProfile dp) {
- if (dp.isLeftRightSplit) {
- floatingTask.setTranslationX(translation);
- } else {
- floatingTask.setTranslationY(translation);
- }
-
- }
-
- @Override
- public float getFloatingTaskPrimaryTranslation(View floatingTask, DeviceProfile dp) {
- return dp.isLeftRightSplit
- ? floatingTask.getTranslationX()
- : floatingTask.getTranslationY();
- }
-
- @NonNull
- @Override
- public LauncherAtom.TaskSwitcherContainer.OrientationHandler getHandlerTypeForLogging() {
- return LauncherAtom.TaskSwitcherContainer.OrientationHandler.PORTRAIT;
- }
-}
diff --git a/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewModel.kt b/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewModel.kt
deleted file mode 100644
index 4511ea714c..0000000000
--- a/quickstep/src/com/android/quickstep/task/thumbnail/TaskThumbnailViewModel.kt
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2024 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.quickstep.task.thumbnail
-
-import android.annotation.ColorInt
-import android.graphics.Rect
-import androidx.core.graphics.ColorUtils
-import com.android.quickstep.recents.data.RecentTasksRepository
-import com.android.quickstep.recents.viewmodel.RecentsViewData
-import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.BackgroundOnly
-import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.LiveTile
-import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.Snapshot
-import com.android.quickstep.task.thumbnail.TaskThumbnailUiState.Uninitialized
-import com.android.quickstep.task.viewmodel.TaskViewData
-import com.android.systemui.shared.recents.model.Task
-import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.combine
-import kotlinx.coroutines.flow.distinctUntilChanged
-import kotlinx.coroutines.flow.flatMapLatest
-import kotlinx.coroutines.flow.flowOf
-import kotlinx.coroutines.flow.map
-
-@OptIn(ExperimentalCoroutinesApi::class)
-class TaskThumbnailViewModel(
- recentsViewData: RecentsViewData,
- taskViewData: TaskViewData,
- private val tasksRepository: RecentTasksRepository,
-) {
- private val task = MutableStateFlow>(flowOf(null))
- private var boundTaskIsRunning = false
-
- val recentsFullscreenProgress = recentsViewData.fullscreenProgress
- val inheritedScale =
- combine(recentsViewData.scale, taskViewData.scale) { recentsScale, taskScale ->
- recentsScale * taskScale
- }
- val uiState: Flow =
- task
- .flatMapLatest { taskFlow ->
- taskFlow.map { taskVal ->
- when {
- taskVal == null -> Uninitialized
- boundTaskIsRunning -> LiveTile
- isBackgroundOnly(taskVal) ->
- BackgroundOnly(taskVal.colorBackground.removeAlpha())
- isSnapshotState(taskVal) -> {
- val bitmap = taskVal.thumbnail?.thumbnail!!
- Snapshot(
- bitmap,
- Rect(0, 0, bitmap.width, bitmap.height),
- taskVal.colorBackground.removeAlpha()
- )
- }
- else -> Uninitialized
- }
- }
- }
- .distinctUntilChanged()
-
- fun bind(taskThumbnail: TaskThumbnail) {
- boundTaskIsRunning = taskThumbnail.isRunning
- task.value = tasksRepository.getTaskDataById(taskThumbnail.taskId)
- }
-
- private fun isBackgroundOnly(task: Task): Boolean = task.isLocked || task.thumbnail == null
-
- private fun isSnapshotState(task: Task): Boolean {
- val thumbnailPresent = task.thumbnail?.thumbnail != null
- val taskLocked = task.isLocked
-
- return thumbnailPresent && !taskLocked
- }
-
- @ColorInt private fun Int.removeAlpha(): Int = ColorUtils.setAlphaComponent(this, 0xff)
-}
diff --git a/quickstep/src/com/android/quickstep/task/viewmodel/TaskViewData.kt b/quickstep/src/com/android/quickstep/task/viewmodel/TaskViewData.kt
deleted file mode 100644
index a8b5112860..0000000000
--- a/quickstep/src/com/android/quickstep/task/viewmodel/TaskViewData.kt
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2024 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.quickstep.task.viewmodel
-
-import kotlinx.coroutines.flow.MutableStateFlow
-
-class TaskViewData {
- // This is typically a View concern but it is used to invalidate rendering in other Views
- val scale = MutableStateFlow(1f)
-}
diff --git a/quickstep/src/com/android/quickstep/util/ActiveGestureErrorDetector.java b/quickstep/src/com/android/quickstep/util/ActiveGestureErrorDetector.java
deleted file mode 100644
index cfa6b9891f..0000000000
--- a/quickstep/src/com/android/quickstep/util/ActiveGestureErrorDetector.java
+++ /dev/null
@@ -1,454 +0,0 @@
-/*
- * Copyright (C) 2022 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.quickstep.util;
-
-import android.util.ArraySet;
-
-import androidx.annotation.NonNull;
-
-import java.io.PrintWriter;
-import java.util.Set;
-
-/**
- * Utility class for tracking gesture navigation events as they happen, then detecting and reporting
- * known issues at log dump time.
- */
-public class ActiveGestureErrorDetector {
-
- /**
- * Enums associated to gesture navigation events.
- */
- public enum GestureEvent {
- MOTION_DOWN, MOTION_UP, MOTION_MOVE, SET_END_TARGET, SET_END_TARGET_HOME,
- SET_END_TARGET_NEW_TASK, SET_END_TARGET_ALL_APPS, ON_SETTLED_ON_END_TARGET,
- ON_START_RECENTS_ANIMATION, ON_FINISH_RECENTS_ANIMATION, ON_CANCEL_RECENTS_ANIMATION,
- START_RECENTS_ANIMATION, FINISH_RECENTS_ANIMATION, CANCEL_RECENTS_ANIMATION,
- SET_ON_PAGE_TRANSITION_END_CALLBACK, CANCEL_CURRENT_ANIMATION, CLEANUP_SCREENSHOT,
- SCROLLER_ANIMATION_ABORTED, TASK_APPEARED, EXPECTING_TASK_APPEARED,
- FLAG_USING_OTHER_ACTIVITY_INPUT_CONSUMER, LAUNCHER_DESTROYED, RECENT_TASKS_MISSING,
- INVALID_VELOCITY_ON_SWIPE_UP, RECENTS_ANIMATION_START_PENDING,
-
- /**
- * These GestureEvents are specifically associated to state flags that get set in
- * {@link com.android.quickstep.MultiStateCallback}. If a state flag needs to be tracked
- * for error detection, an enum should be added here and that state flag-enum pair should
- * be added to the state flag's container class' {@code getTrackedEventForState} method.
- */
- STATE_GESTURE_STARTED, STATE_GESTURE_COMPLETED, STATE_GESTURE_CANCELLED,
- STATE_END_TARGET_ANIMATION_FINISHED, STATE_RECENTS_SCROLLING_FINISHED,
- STATE_CAPTURE_SCREENSHOT, STATE_SCREENSHOT_CAPTURED, STATE_HANDLER_INVALIDATED,
- STATE_RECENTS_ANIMATION_CANCELED, STATE_LAUNCHER_DRAWN(true, false);
-
- public final boolean mLogEvent;
- public final boolean mTrackEvent;
-
- GestureEvent() {
- this(false, true);
- }
-
- GestureEvent(boolean logEvent, boolean trackEvent) {
- mLogEvent = logEvent;
- mTrackEvent = trackEvent;
- }
- }
-
- private ActiveGestureErrorDetector() {}
-
- private static final long ON_START_RECENT_ANIMATION_TIME_LIMIT = 500;
-
- protected static void analyseAndDump(
- @NonNull String prefix,
- @NonNull PrintWriter writer,
- @NonNull ActiveGestureLog.EventLog eventLog) {
- writer.println(prefix + "Error messages for gesture ID: " + eventLog.logId);
- if (!eventLog.mIsFullyGesturalNavMode) {
- writer.println(prefix
- + "\tSkipping gesture error detection because gesture navigation not enabled");
- return;
- }
-
- boolean errorDetected = false;
- // Use a Set since the order is inherently checked in the loop.
- final Set encounteredEvents = new ArraySet<>();
- // Set flags and check order of operations.
- long lastStartRecentAnimationEventEntryTime = 0;
- for (ActiveGestureLog.EventEntry eventEntry : eventLog.eventEntries) {
- GestureEvent gestureEvent = eventEntry.getGestureEvent();
- if (gestureEvent == null) {
- continue;
- }
- encounteredEvents.add(gestureEvent);
-
- switch (gestureEvent) {
- case MOTION_UP:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.MOTION_DOWN),
- prefix,
- /* errorMessage= */ "Motion up detected before/without"
- + " motion down.",
- writer);
- break;
- case ON_SETTLED_ON_END_TARGET:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.SET_END_TARGET),
- prefix,
- /* errorMessage= */ "onSettledOnEndTarget called "
- + "before/without setEndTarget.",
- writer);
- break;
- case FINISH_RECENTS_ANIMATION:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.START_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */ "finishRecentsAnimation called "
- + "before/without startRecentsAnimation.",
- writer);
- break;
- case CANCEL_RECENTS_ANIMATION:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.START_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */ "cancelRecentsAnimation called "
- + "before/without startRecentsAnimation.",
- writer);
- break;
- case CLEANUP_SCREENSHOT:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.STATE_SCREENSHOT_CAPTURED),
- prefix,
- /* errorMessage= */ "recents activity screenshot was "
- + "cleaned up before/without STATE_SCREENSHOT_CAPTURED "
- + "being set.",
- writer);
- break;
- case SCROLLER_ANIMATION_ABORTED:
- errorDetected |= printErrorIfTrue(
- encounteredEvents.contains(GestureEvent.SET_END_TARGET_HOME)
- && !encounteredEvents.contains(
- GestureEvent.ON_SETTLED_ON_END_TARGET),
- prefix,
- /* errorMessage= */ "recents view scroller animation "
- + "aborted after setting end target HOME, but before"
- + " settling on end target.",
- writer);
- break;
- case TASK_APPEARED:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.EXPECTING_TASK_APPEARED),
- prefix,
- /* errorMessage= */ "onTasksAppeared was not expected to be called",
- writer);
- if (encounteredEvents.contains(GestureEvent.EXPECTING_TASK_APPEARED)) {
- // Remove both events so that we can properly detect following errors.
- encounteredEvents.remove(GestureEvent.EXPECTING_TASK_APPEARED);
- encounteredEvents.remove(GestureEvent.TASK_APPEARED);
- }
- break;
- case LAUNCHER_DESTROYED:
- errorDetected |= printErrorIfTrue(
- true,
- prefix,
- /* errorMessage= */ "Launcher destroyed mid-gesture",
- writer);
- break;
- case STATE_GESTURE_COMPLETED:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.MOTION_UP),
- prefix,
- /* errorMessage= */ "STATE_GESTURE_COMPLETED set "
- + "before/without motion up.",
- writer);
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.STATE_GESTURE_STARTED),
- prefix,
- /* errorMessage= */ "STATE_GESTURE_COMPLETED set "
- + "before/without STATE_GESTURE_STARTED.",
- writer);
- break;
- case STATE_GESTURE_CANCELLED:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.MOTION_UP),
- prefix,
- /* errorMessage= */ "STATE_GESTURE_CANCELLED set "
- + "before/without motion up.",
- writer);
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.STATE_GESTURE_STARTED),
- prefix,
- /* errorMessage= */ "STATE_GESTURE_CANCELLED set "
- + "before/without STATE_GESTURE_STARTED.",
- writer);
- break;
- case STATE_SCREENSHOT_CAPTURED:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.STATE_CAPTURE_SCREENSHOT),
- prefix,
- /* errorMessage= */ "STATE_SCREENSHOT_CAPTURED set "
- + "before/without STATE_CAPTURE_SCREENSHOT.",
- writer);
- break;
- case STATE_RECENTS_SCROLLING_FINISHED:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(
- GestureEvent.SET_ON_PAGE_TRANSITION_END_CALLBACK),
- prefix,
- /* errorMessage= */ "STATE_RECENTS_SCROLLING_FINISHED "
- + "set before/without calling "
- + "setOnPageTransitionEndCallback.",
- writer);
- break;
- case STATE_RECENTS_ANIMATION_CANCELED:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(
- GestureEvent.START_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */ "STATE_RECENTS_ANIMATION_CANCELED "
- + "set before/without startRecentsAnimation.",
- writer);
- break;
- case RECENT_TASKS_MISSING:
- errorDetected |= printErrorIfTrue(
- true,
- prefix,
- /* errorMessage= */ "SystemUiProxy.mRecentTasks missing,"
- + " couldn't start the recents activity",
- writer);
- break;
- case ON_START_RECENTS_ANIMATION:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.START_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */ "ON_START_RECENTS_ANIMATION "
- + "onAnimationStart callback ran before startRecentsAnimation",
- writer);
- errorDetected |= printErrorIfTrue(
- eventEntry.getTime() - lastStartRecentAnimationEventEntryTime
- > ON_START_RECENT_ANIMATION_TIME_LIMIT,
- prefix,
- /* errorMessage= */"ON_START_RECENTS_ANIMATION "
- + "startRecentsAnimation was never called or onAnimationStart "
- + "callback was called more than 500 ms after "
- + "startRecentsAnimation.",
- writer);
- lastStartRecentAnimationEventEntryTime = 0;
- break;
- case ON_CANCEL_RECENTS_ANIMATION:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.ON_START_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */ "ON_CANCEL_RECENTS_ANIMATION "
- + "onAnimationCanceled callback ran before onAnimationStart "
- + "callback",
- writer);
- break;
- case ON_FINISH_RECENTS_ANIMATION:
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.ON_START_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */ "ON_FINISH_RECENTS_ANIMATION "
- + "onAnimationFinished callback ran before onAnimationStart "
- + "callback",
- writer);
- break;
- case INVALID_VELOCITY_ON_SWIPE_UP:
- errorDetected |= printErrorIfTrue(
- true,
- prefix,
- /* errorMessage= */ "invalid velocity on swipe up gesture.",
- writer);
- break;
- case START_RECENTS_ANIMATION:
- lastStartRecentAnimationEventEntryTime = eventEntry.getTime();
- break;
- case RECENTS_ANIMATION_START_PENDING:
- errorDetected |= printErrorIfTrue(
- true,
- prefix,
- /* errorMessage= */ (eventEntry.getDuplicateCount() + 1)
- + " gesture(s) attempted while a requested recents"
- + " animation is still pending.",
- writer);
- break;
- case EXPECTING_TASK_APPEARED:
- case MOTION_DOWN:
- case SET_END_TARGET:
- case SET_END_TARGET_HOME:
- case SET_END_TARGET_ALL_APPS:
- case SET_END_TARGET_NEW_TASK:
- case SET_ON_PAGE_TRANSITION_END_CALLBACK:
- case CANCEL_CURRENT_ANIMATION:
- case FLAG_USING_OTHER_ACTIVITY_INPUT_CONSUMER:
- case STATE_GESTURE_STARTED:
- case STATE_END_TARGET_ANIMATION_FINISHED:
- case STATE_CAPTURE_SCREENSHOT:
- case STATE_HANDLER_INVALIDATED:
- case STATE_LAUNCHER_DRAWN:
- default:
- // No-Op
- }
- }
-
- // Check that all required events were found.
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.MOTION_DOWN),
- prefix,
- /* errorMessage= */ "Motion down never detected.",
- writer);
- errorDetected |= printErrorIfTrue(
- !encounteredEvents.contains(GestureEvent.MOTION_UP),
- prefix,
- /* errorMessage= */ "Motion up never detected.",
- writer);
-
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(GestureEvent.SET_END_TARGET)
- && !encounteredEvents.contains(GestureEvent.ON_SETTLED_ON_END_TARGET),
- prefix,
- /* errorMessage= */ "setEndTarget was called, but "
- + "onSettledOnEndTarget wasn't.",
- writer);
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(GestureEvent.SET_END_TARGET)
- && !encounteredEvents.contains(
- GestureEvent.STATE_END_TARGET_ANIMATION_FINISHED),
- prefix,
- /* errorMessage= */ "setEndTarget was called, but "
- + "STATE_END_TARGET_ANIMATION_FINISHED was never set.",
- writer);
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(GestureEvent.SET_END_TARGET)
- && !encounteredEvents.contains(
- GestureEvent.STATE_RECENTS_SCROLLING_FINISHED),
- prefix,
- /* errorMessage= */ "setEndTarget was called, but "
- + "STATE_RECENTS_SCROLLING_FINISHED was never set.",
- writer);
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(
- GestureEvent.STATE_END_TARGET_ANIMATION_FINISHED)
- && encounteredEvents.contains(
- GestureEvent.STATE_RECENTS_SCROLLING_FINISHED)
- && !encounteredEvents.contains(GestureEvent.ON_SETTLED_ON_END_TARGET),
- prefix,
- /* errorMessage= */ "STATE_END_TARGET_ANIMATION_FINISHED and "
- + "STATE_RECENTS_SCROLLING_FINISHED were set, but onSettledOnEndTarget "
- + "wasn't called.",
- writer);
-
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(
- GestureEvent.START_RECENTS_ANIMATION)
- && !encounteredEvents.contains(GestureEvent.FINISH_RECENTS_ANIMATION)
- && !encounteredEvents.contains(GestureEvent.CANCEL_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */ "startRecentsAnimation was called, but "
- + "finishRecentsAnimation and cancelRecentsAnimation weren't.",
- writer);
-
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(GestureEvent.STATE_GESTURE_STARTED)
- && !encounteredEvents.contains(GestureEvent.STATE_GESTURE_COMPLETED)
- && !encounteredEvents.contains(GestureEvent.STATE_GESTURE_CANCELLED),
- prefix,
- /* errorMessage= */ "STATE_GESTURE_STARTED was set, but "
- + "STATE_GESTURE_COMPLETED and STATE_GESTURE_CANCELLED weren't.",
- writer);
-
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(
- GestureEvent.STATE_CAPTURE_SCREENSHOT)
- && !encounteredEvents.contains(GestureEvent.STATE_SCREENSHOT_CAPTURED),
- prefix,
- /* errorMessage= */ "STATE_CAPTURE_SCREENSHOT was set, but "
- + "STATE_SCREENSHOT_CAPTURED wasn't.",
- writer);
-
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(
- GestureEvent.SET_ON_PAGE_TRANSITION_END_CALLBACK)
- && !encounteredEvents.contains(
- GestureEvent.STATE_RECENTS_SCROLLING_FINISHED),
- prefix,
- /* errorMessage= */ "setOnPageTransitionEndCallback called, but "
- + "STATE_RECENTS_SCROLLING_FINISHED wasn't set.",
- writer);
-
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(
- GestureEvent.FLAG_USING_OTHER_ACTIVITY_INPUT_CONSUMER)
- && !encounteredEvents.contains(GestureEvent.CANCEL_CURRENT_ANIMATION)
- && !encounteredEvents.contains(GestureEvent.STATE_HANDLER_INVALIDATED),
- prefix,
- /* errorMessage= */ "AbsSwipeUpHandler.cancelCurrentAnimation "
- + "wasn't called and STATE_HANDLER_INVALIDATED wasn't set.",
- writer);
-
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(
- GestureEvent.STATE_RECENTS_ANIMATION_CANCELED)
- && !encounteredEvents.contains(GestureEvent.CLEANUP_SCREENSHOT),
- prefix,
- /* errorMessage= */ "STATE_RECENTS_ANIMATION_CANCELED was set but "
- + "the task screenshot wasn't cleaned up.",
- writer);
-
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(
- GestureEvent.EXPECTING_TASK_APPEARED)
- && !encounteredEvents.contains(GestureEvent.TASK_APPEARED),
- prefix,
- /* errorMessage= */ "onTaskAppeared was expected to be called but wasn't.",
- writer);
-
- errorDetected |= printErrorIfTrue(
- /* condition= */ encounteredEvents.contains(GestureEvent.START_RECENTS_ANIMATION)
- && !encounteredEvents.contains(GestureEvent.ON_START_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */
- "startRecentAnimation was called but onAnimationStart callback was not",
- writer);
- errorDetected |= printErrorIfTrue(
- /* condition= */
- encounteredEvents.contains(GestureEvent.FINISH_RECENTS_ANIMATION)
- && !encounteredEvents.contains(GestureEvent.ON_FINISH_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */
- "finishController was called but onAnimationFinished callback was not",
- writer);
- errorDetected |= printErrorIfTrue(
- /* condition= */
- encounteredEvents.contains(GestureEvent.CANCEL_RECENTS_ANIMATION)
- && !encounteredEvents.contains(GestureEvent.ON_CANCEL_RECENTS_ANIMATION),
- prefix,
- /* errorMessage= */
- "onRecentsAnimationCanceled was called but onAnimationCanceled was not",
- writer);
-
- if (!errorDetected) {
- writer.println(prefix + "\tNo errors detected.");
- }
- }
-
- private static boolean printErrorIfTrue(
- boolean condition, String prefix, String errorMessage, PrintWriter writer) {
- if (!condition) {
- return false;
- }
- writer.println(prefix + "\t- " + errorMessage);
-
- return true;
- }
-}
diff --git a/quickstep/src/com/android/quickstep/util/ActiveGestureLog.java b/quickstep/src/com/android/quickstep/util/ActiveGestureLog.java
deleted file mode 100644
index c54862aba3..0000000000
--- a/quickstep/src/com/android/quickstep/util/ActiveGestureLog.java
+++ /dev/null
@@ -1,376 +0,0 @@
-/*
- * Copyright (C) 2019 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.quickstep.util;
-
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
-
-import com.android.launcher3.util.Preconditions;
-
-import java.io.PrintWriter;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Locale;
-import java.util.Objects;
-
-/**
- * A log to keep track of the active gesture.
- */
-public class ActiveGestureLog {
-
- private static final int MAX_GESTURES_TRACKED = 15;
-
- public static final ActiveGestureLog INSTANCE = new ActiveGestureLog();
-
- private boolean mIsFullyGesturalNavMode;
-
- /**
- * NOTE: This value should be kept same as
- * ActivityTaskManagerService#INTENT_EXTRA_LOG_TRACE_ID in platform
- */
- public static final String INTENT_EXTRA_LOG_TRACE_ID = "INTENT_EXTRA_LOG_TRACE_ID";
-
- private final EventLog[] logs;
- private int nextIndex;
- private int mCurrentLogId = 100;
-
- private ActiveGestureLog() {
- this.logs = new EventLog[MAX_GESTURES_TRACKED];
- this.nextIndex = 0;
- }
-
- /**
- * Track the given event for error detection.
- *
- * @param gestureEvent GestureEvent representing an event during the current gesture's
- * execution.
- */
- public void trackEvent(@Nullable ActiveGestureErrorDetector.GestureEvent gestureEvent) {
- addLog(CompoundString.NO_OP, gestureEvent);
- }
-
- /**
- * Adds a log to be printed at log-dump-time.
- */
- public void addLog(@NonNull String event) {
- addLog(event, null);
- }
-
- public void addLog(@NonNull String event, int extras) {
- addLog(event, extras, null);
- }
-
- public void addLog(@NonNull String event, boolean extras) {
- addLog(event, extras, null);
- }
-
- /**
- * Adds a log to be printed at log-dump-time and track the associated event for error detection.
- *
- * @param gestureEvent GestureEvent representing the event being logged.
- */
- public void addLog(
- @NonNull String event, @Nullable ActiveGestureErrorDetector.GestureEvent gestureEvent) {
- addLog(new CompoundString(event), gestureEvent);
- }
-
- public void addLog(
- @NonNull String event,
- int extras,
- @Nullable ActiveGestureErrorDetector.GestureEvent gestureEvent) {
- addLog(new CompoundString(event).append(": ").append(extras), gestureEvent);
- }
-
- public void addLog(
- @NonNull String event,
- boolean extras,
- @Nullable ActiveGestureErrorDetector.GestureEvent gestureEvent) {
- addLog(new CompoundString(event).append(": ").append(extras), gestureEvent);
- }
-
- public void addLog(@NonNull CompoundString compoundString) {
- addLog(compoundString, null);
- }
-
- public void addLog(
- @NonNull CompoundString compoundString,
- @Nullable ActiveGestureErrorDetector.GestureEvent gestureEvent) {
- EventLog lastEventLog = logs[(nextIndex + logs.length - 1) % logs.length];
- if (lastEventLog == null || mCurrentLogId != lastEventLog.logId) {
- EventLog eventLog = new EventLog(mCurrentLogId, mIsFullyGesturalNavMode);
- EventEntry eventEntry = new EventEntry();
-
- eventEntry.update(compoundString, gestureEvent);
- eventLog.eventEntries.add(eventEntry);
- logs[nextIndex] = eventLog;
- nextIndex = (nextIndex + 1) % logs.length;
- return;
- }
-
- // Update the last EventLog
- List lastEventEntries = lastEventLog.eventEntries;
- EventEntry lastEntry = !lastEventEntries.isEmpty()
- ? lastEventEntries.get(lastEventEntries.size() - 1) : null;
-
- // Update the last EventEntry if it's a duplicate
- if (isEntrySame(lastEntry, compoundString, gestureEvent)) {
- lastEntry.duplicateCount++;
- return;
- }
- EventEntry eventEntry = new EventEntry();
-
- eventEntry.update(compoundString, gestureEvent);
- lastEventEntries.add(eventEntry);
- }
-
- public void dump(String prefix, PrintWriter writer) {
- writer.println(prefix + "ActiveGestureErrorDetector:");
- for (int i = 0; i < logs.length; i++) {
- EventLog eventLog = logs[(nextIndex + i) % logs.length];
- if (eventLog == null) {
- continue;
- }
- ActiveGestureErrorDetector.analyseAndDump(prefix + '\t', writer, eventLog);
- }
-
- writer.println(prefix + "ActiveGestureLog history:");
- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSSZ ", Locale.US);
- Date date = new Date();
- for (int i = 0; i < logs.length; i++) {
- EventLog eventLog = logs[(nextIndex + i) % logs.length];
- if (eventLog == null) {
- continue;
- }
-
- writer.println(prefix + "\tLogs for logId: " + eventLog.logId);
- for (EventEntry eventEntry : eventLog.eventEntries) {
- if (eventEntry.mCompoundString.mIsNoOp) {
- continue;
- }
- date.setTime(eventEntry.time);
-
- StringBuilder msg = new StringBuilder(prefix + "\t\t")
- .append(sdf.format(date))
- .append(eventEntry.mCompoundString);
- if (eventEntry.duplicateCount > 0) {
- msg.append(" & ").append(eventEntry.duplicateCount).append(" similar events");
- }
- writer.println(msg);
- }
- }
- }
-
- /**
- * Increments and returns the current log ID. This should be used every time a new log trace
- * is started.
- */
- public int incrementLogId() {
- return mCurrentLogId++;
- }
-
- public void setIsFullyGesturalNavMode(boolean isFullyGesturalNavMode) {
- mIsFullyGesturalNavMode = isFullyGesturalNavMode;
- }
-
- /** Returns the current log ID. This should be used when a log trace is being reused. */
- public int getLogId() {
- return mCurrentLogId;
- }
-
- private boolean isEntrySame(
- EventEntry entry,
- CompoundString compoundString,
- ActiveGestureErrorDetector.GestureEvent gestureEvent) {
- return entry != null
- && entry.mCompoundString.equals(compoundString)
- && entry.gestureEvent == gestureEvent;
- }
-
- /** A single event entry. */
- protected static class EventEntry {
-
- @NonNull private CompoundString mCompoundString;
- private ActiveGestureErrorDetector.GestureEvent gestureEvent;
- private long time;
- private int duplicateCount;
-
- private EventEntry() {}
-
- @Nullable
- protected ActiveGestureErrorDetector.GestureEvent getGestureEvent() {
- return gestureEvent;
- }
-
- public int getDuplicateCount() {
- return duplicateCount;
- }
-
- private void update(
- @NonNull CompoundString compoundString,
- ActiveGestureErrorDetector.GestureEvent gestureEvent) {
- this.mCompoundString = compoundString;
- this.gestureEvent = gestureEvent;
- time = System.currentTimeMillis();
- duplicateCount = 0;
- }
-
- public long getTime() {
- return time;
- }
- }
-
- /** An entire log of entries associated with a single log ID */
- protected static class EventLog {
-
- protected final List eventEntries = new ArrayList<>();
- protected final int logId;
- protected final boolean mIsFullyGesturalNavMode;
-
- private EventLog(int logId, boolean isFullyGesturalNavMode) {
- this.logId = logId;
- mIsFullyGesturalNavMode = isFullyGesturalNavMode;
- }
- }
-
- /** A buildable string stored as an array for memory efficiency. */
- public static class CompoundString {
-
- public static final CompoundString NO_OP = new CompoundString();
-
- private final List mSubstrings;
- private final List