From 6b5e912e10c6407bbe29668af8b7f043a88985e7 Mon Sep 17 00:00:00 2001 From: MrSluffy Date: Sun, 15 Dec 2024 17:20:02 +0800 Subject: [PATCH] enhancement folder related issues - Closing from app to home where weird artifacts shown - Duplicated icon after adding new icon in the folder - Stuck icon when moving from app to home closes the following - #5084 - #5081 - #5074 --- .../launcher3/QuickstepTransitionManager.java | 14 +- .../QuickstepInteractionHandler.java | 29 +- .../uioverrides/QuickstepLauncher.java | 56 -- .../quickstep/LauncherSwipeHandlerV2.java | 75 ++- .../quickstep/SwipeUpAnimationLogic.java | 39 +- src/com/android/launcher3/BubbleTextView.java | 15 +- src/com/android/launcher3/Launcher.java | 40 +- src/com/android/launcher3/Utilities.java | 2 +- .../launcher3/dragndrop/DragLayer.java | 4 +- .../android/launcher3/dragndrop/DragView.java | 4 +- src/com/android/launcher3/folder/Folder.java | 555 ++++++++++++------ .../folder/FolderAnimationManager.java | 59 +- .../launcher3/folder/FolderGridOrganizer.java | 16 +- .../android/launcher3/folder/FolderIcon.java | 77 +-- .../launcher3/folder/FolderPagedView.java | 2 +- .../android/launcher3/model/LoaderTask.java | 15 +- .../launcher3/model/data/ItemInfo.java | 75 ++- .../android/launcher3/util/StableViewInfo.kt | 56 ++ .../launcher3/views/BubbleTextHolder.java | 2 +- .../launcher3/views/FloatingIconView.java | 38 +- ...ew.java => FloatingIconViewCompanion.java} | 21 +- .../launcher3/views/FloatingSurfaceView.java | 29 +- 22 files changed, 716 insertions(+), 507 deletions(-) create mode 100644 src/com/android/launcher3/util/StableViewInfo.kt rename src/com/android/launcher3/views/{IconLabelDotView.java => FloatingIconViewCompanion.java} (52%) diff --git a/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java b/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java index 9ab9ea2c3d..d31c8b7ac4 100644 --- a/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java +++ b/quickstep/src/com/android/launcher3/QuickstepTransitionManager.java @@ -55,7 +55,6 @@ import static com.android.launcher3.config.FeatureFlags.ENABLE_BACK_SWIPE_HOME_A import static com.android.launcher3.config.FeatureFlags.ENABLE_SCRIM_FOR_APP_LAUNCH; import static com.android.launcher3.config.FeatureFlags.KEYGUARD_ANIMATION; import static com.android.launcher3.config.FeatureFlags.SEPARATE_RECENTS_ACTIVITY; -import static com.android.launcher3.model.data.ItemInfo.NO_MATCHING_ID; import static com.android.launcher3.testing.shared.TestProtocol.WALLPAPER_OPEN_ANIMATION_FINISHED_MESSAGE; import static com.android.launcher3.util.DisplayController.isTransientTaskbar; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; @@ -139,6 +138,7 @@ import com.android.launcher3.util.ActivityOptionsWrapper; import com.android.launcher3.util.DynamicResource; import com.android.launcher3.util.ObjectWrapper; import com.android.launcher3.util.RunnableList; +import com.android.launcher3.util.StableViewInfo; import com.android.launcher3.util.Themes; import com.android.launcher3.views.FloatingIconView; import com.android.launcher3.views.ScrimView; @@ -1360,16 +1360,8 @@ public class QuickstepTransitionManager implements OnDeviceProfileChangeListener ? new ArrayList<>() : runningTaskTarget.taskInfo.launchCookies; - int launchCookieItemId = NO_MATCHING_ID; - for (IBinder cookie : launchCookies) { - Integer itemId = ObjectWrapper.unwrap(cookie); - if (itemId != null) { - launchCookieItemId = itemId; - break; - } - } - - return mLauncher.getFirstMatchForAppClose(launchCookieItemId, packageName, + return mLauncher.getFirstMatchForAppClose( + StableViewInfo.fromLaunchCookies(launchCookies), packageName, UserHandle.of(runningTaskTarget.taskInfo.userId), true /* supportsAllAppsState */); } diff --git a/quickstep/src/com/android/launcher3/uioverrides/QuickstepInteractionHandler.java b/quickstep/src/com/android/launcher3/uioverrides/QuickstepInteractionHandler.java index 63d2ff24d3..b46bfc7418 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/QuickstepInteractionHandler.java +++ b/quickstep/src/com/android/launcher3/uioverrides/QuickstepInteractionHandler.java @@ -57,7 +57,7 @@ public class QuickstepInteractionHandler implements RemoteViews.InteractionHandl @SuppressWarnings("NewApi") @Override public boolean onInteraction(View view, PendingIntent pendingIntent, - RemoteViews.RemoteResponse remoteResponse) { + RemoteViews.RemoteResponse remoteResponse) { LauncherAppWidgetHostView hostView = findHostViewAncestor(view); if (hostView == null) { Log.e(TAG, "View did not have a LauncherAppWidgetHostView ancestor."); @@ -74,15 +74,8 @@ public class QuickstepInteractionHandler implements RemoteViews.InteractionHandl Pair options = remoteResponse.getLaunchOptions(view); ActivityOptionsWrapper activityOptions = mLauncher.getAppTransitionManager() .getActivityLaunchOptions(hostView); - Object itemInfo = hostView.getTag(); - IBinder launchCookie = null; - if (itemInfo instanceof ItemInfo) { - launchCookie = mLauncher.getLaunchCookie((ItemInfo) itemInfo); - activityOptions.options.setLaunchCookie(launchCookie); - } - if (Utilities.ATLEAST_S && !pendingIntent.isActivity() && LawnchairApp.isRecentsEnabled()) { - // In the event this pending intent eventually launches an activity, i.e. a - // trampoline, + if (!pendingIntent.isActivity()) { + // In the event this pending intent eventually launches an activity, i.e. a trampoline, // use the Quickstep transition animation. try { IActivityTaskManagerHidden atm = Refine.unsafeCast(ActivityTaskManager.getService()); @@ -90,7 +83,7 @@ public class QuickstepInteractionHandler implements RemoteViews.InteractionHandl atm.registerRemoteAnimationForNextActivityStart( pendingIntent.getCreatorPackage(), activityOptions.options.getRemoteAnimationAdapter(), - launchCookie); + activityOptions.options.getLaunchCookie()); } catch (NoSuchMethodError e) { atm.registerRemoteAnimationForNextActivityStart( pendingIntent.getCreatorPackage(), @@ -99,16 +92,18 @@ public class QuickstepInteractionHandler implements RemoteViews.InteractionHandl } catch (RemoteException e) { // Do nothing. } + } + try { activityOptions.options.setPendingIntentLaunchFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - if (Utilities.ATLEAST_T) { - activityOptions.options.setSplashScreenStyle(SplashScreen.SPLASH_SCREEN_STYLE_SOLID_COLOR); - } - Utilities.allowBGLaunch(activityOptions.options); - + activityOptions.options.setSplashScreenStyle(SplashScreen.SPLASH_SCREEN_STYLE_SOLID_COLOR); + activityOptions.options.setPendingIntentBackgroundActivityStartMode( + ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED); + } catch (Throwable t) { + // ignore } options = Pair.create(options.first, activityOptions.options); if (pendingIntent.isActivity()) { - logAppLaunch(itemInfo); + logAppLaunch(hostView.getTag()); } return RemoteViews.startPendingIntent(hostView, pendingIntent, options); } diff --git a/quickstep/src/com/android/launcher3/uioverrides/QuickstepLauncher.java b/quickstep/src/com/android/launcher3/uioverrides/QuickstepLauncher.java index 3334b32b45..03aa100608 100644 --- a/quickstep/src/com/android/launcher3/uioverrides/QuickstepLauncher.java +++ b/quickstep/src/com/android/launcher3/uioverrides/QuickstepLauncher.java @@ -40,7 +40,6 @@ import static com.android.launcher3.config.FeatureFlags.enableSplitContextually; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_APP_LAUNCH_TAP; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_SPLIT_SELECTION_EXIT_HOME; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_SPLIT_SELECTION_EXIT_INTERRUPTED; -import static com.android.launcher3.model.data.ItemInfo.NO_MATCHING_ID; import static com.android.launcher3.popup.QuickstepSystemShortcut.getSplitSelectShortcutByPosition; import static com.android.launcher3.popup.SystemShortcut.APP_INFO; import static com.android.launcher3.popup.SystemShortcut.DONT_SUGGEST_APP; @@ -1192,7 +1191,6 @@ public class QuickstepLauncher extends Launcher implements RecentsViewContainer (v != null && v.getDisplay() != null) ? v.getDisplay().getDisplayId() : Display.DEFAULT_DISPLAY); Utilities.allowBGLaunch(activityOptions.options); - addLaunchCookie(item, activityOptions.options); return activityOptions; } @@ -1214,60 +1212,6 @@ public class QuickstepLauncher extends Launcher implements RecentsViewContainer mSplitWithKeyboardShortcutController.enterStageSplit(leftOrTop); } - /** - * Adds a new launch cookie for the activity launch if supported. - * - * @param info the item info for the launch - * @param opts the options to set the launchCookie on. - */ - public void addLaunchCookie(ItemInfo info, ActivityOptions opts) { - IBinder launchCookie = getLaunchCookie(info); - if (launchCookie != null) { - opts.setLaunchCookie(launchCookie); - } - } - - /** - * Return a new launch cookie for the activity launch if supported. - * - * @param info the item info for the launch - */ - public IBinder getLaunchCookie(ItemInfo info) { - if (info == null) { - return null; - } - switch (info.container) { - case Favorites.CONTAINER_DESKTOP: - case Favorites.CONTAINER_HOTSEAT: - case Favorites.CONTAINER_PRIVATESPACE: - // Fall through and continue it's on the workspace (we don't support swiping back - // to other containers like all apps or the hotseat predictions (which can change) - break; - default: - if (info.container >= 0) { - // Also allow swiping to folders - break; - } - // Reset any existing launch cookies associated with the cookie - return ObjectWrapper.wrap(NO_MATCHING_ID); - } - switch (info.itemType) { - case Favorites.ITEM_TYPE_APPLICATION: - case Favorites.ITEM_TYPE_DEEP_SHORTCUT: - case Favorites.ITEM_TYPE_APPWIDGET: - // Fall through and continue if it's an app, shortcut, or widget - break; - default: - // Reset any existing launch cookies associated with the cookie - return ObjectWrapper.wrap(NO_MATCHING_ID); - } - return ObjectWrapper.wrap(new Integer(info.id)); - } - - public void setHintUserWillBeActive() { - addActivityFlags(ACTIVITY_STATE_USER_WILL_BE_ACTIVE); - } - @Override public void onDisplayInfoChanged(Context context, DisplayController.Info info, int flags) { super.onDisplayInfoChanged(context, info, flags); diff --git a/quickstep/src/com/android/quickstep/LauncherSwipeHandlerV2.java b/quickstep/src/com/android/quickstep/LauncherSwipeHandlerV2.java index 3c665906b5..413ddbc9f8 100644 --- a/quickstep/src/com/android/quickstep/LauncherSwipeHandlerV2.java +++ b/quickstep/src/com/android/quickstep/LauncherSwipeHandlerV2.java @@ -20,7 +20,6 @@ import static com.android.app.animation.Interpolators.LINEAR; import static com.android.launcher3.Flags.enableScalingRevealHomeAnimation; import static com.android.launcher3.LauncherState.NORMAL; import static com.android.launcher3.Utilities.mapBoundToRange; -import static com.android.launcher3.model.data.ItemInfo.NO_MATCHING_ID; import static com.android.launcher3.views.FloatingIconView.SHAPE_PROGRESS_DURATION; import static com.android.launcher3.views.FloatingIconView.getFloatingIconView; @@ -42,7 +41,7 @@ import com.android.launcher3.anim.AnimatorPlaybackController; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.states.StateAnimationConfig; import com.android.launcher3.uioverrides.QuickstepLauncher; -import com.android.launcher3.util.ObjectWrapper; +import com.android.launcher3.util.StableViewInfo; import com.android.launcher3.views.ClipIconView; import com.android.launcher3.views.FloatingIconView; import com.android.launcher3.views.FloatingView; @@ -62,12 +61,12 @@ import java.util.List; /** * Temporary class to allow easier refactoring */ -public class LauncherSwipeHandlerV2 extends - AbsSwipeUpHandler { +public class LauncherSwipeHandlerV2 extends AbsSwipeUpHandler< + QuickstepLauncher, RecentsView, LauncherState> { public LauncherSwipeHandlerV2(Context context, RecentsAnimationDeviceState deviceState, - TaskAnimationManager taskAnimationManager, GestureState gestureState, long touchTimeMs, - boolean continuingLastGesture, InputConsumerController inputConsumer) { + TaskAnimationManager taskAnimationManager, GestureState gestureState, long touchTimeMs, + boolean continuingLastGesture, InputConsumerController inputConsumer) { super(context, deviceState, taskAnimationManager, gestureState, touchTimeMs, continuingLastGesture, inputConsumer); } @@ -95,8 +94,8 @@ public class LauncherSwipeHandlerV2 extends TaskView sourceTaskView = mRecentsView == null && targetTaskView == null ? null : targetTaskView == null - ? mRecentsView.getRunningTaskView() - : targetTaskView; + ? mRecentsView.getRunningTaskView() + : targetTaskView; final View workspaceView = findWorkspaceView( targetTaskView == null ? launchCookies : Collections.emptyList(), sourceTaskView); @@ -107,9 +106,6 @@ public class LauncherSwipeHandlerV2 extends || !mContainer.getDesktopVisibilityController().areDesktopTasksVisible()); mContainer.getRootView().setForceHideBackArrow(true); - if (!TaskAnimationManager.ENABLE_SHELL_TRANSITIONS) { - mContainer.setHintUserWillBeActive(); - } if (!canUseWorkspaceView || appCanEnterPip || mIsSwipeForSplit) { return new LauncherHomeAnimationFactory() { @@ -144,8 +140,6 @@ public class LauncherSwipeHandlerV2 extends return new FloatingViewHomeAnimationFactory(floatingIconView) { @Nullable private RectF mTargetRect; - @Nullable - private RectFSpringAnim mSiblingAnimation; @Nullable @Override @@ -172,14 +166,6 @@ public class LauncherSwipeHandlerV2 extends } } - @Override - protected void playScalingRevealAnimation() { - if (mContainer != null) { - new ScalingWorkspaceRevealAnim(mContainer, mSiblingAnimation, - getWindowTargetRect()).start(); - } - } - @Override public void setAnimation(RectFSpringAnim anim) { super.setAnimation(anim); @@ -245,6 +231,8 @@ public class LauncherSwipeHandlerV2 extends isTargetTranslucent, fallbackBackgroundColor); return new FloatingViewHomeAnimationFactory(floatingWidgetView) { + @Nullable + private RectF mTargetRect; @Override @Nullable @@ -254,8 +242,14 @@ public class LauncherSwipeHandlerV2 extends @Override public RectF getWindowTargetRect() { - super.getWindowTargetRect(); - return backgroundLocation; + if (enableScalingRevealHomeAnimation()) { + if (mTargetRect == null) { + mTargetRect = new RectF(backgroundLocation); + } + return mTargetRect; + } else { + return backgroundLocation; + } } @Override @@ -266,10 +260,11 @@ public class LauncherSwipeHandlerV2 extends @Override public void setAnimation(RectFSpringAnim anim) { super.setAnimation(anim); - - anim.addAnimatorListener(floatingWidgetView); - floatingWidgetView.setOnTargetChangeListener(anim::onTargetPositionChanged); - floatingWidgetView.setFastFinishRunnable(anim::end); + mSiblingAnimation = anim; + mSiblingAnimation.addAnimatorListener(floatingWidgetView); + floatingWidgetView.setOnTargetChangeListener( + mSiblingAnimation::onTargetPositionChanged); + floatingWidgetView.setFastFinishRunnable(mSiblingAnimation::end); } @Override @@ -305,18 +300,7 @@ public class LauncherSwipeHandlerV2 extends return null; } - // Find the associated item info for the launch cookie (if available), note that predicted - // apps actually have an id of -1, so use another default id here - int launchCookieItemId = NO_MATCHING_ID; - for (IBinder cookie : launchCookies) { - Integer itemId = ObjectWrapper.unwrap(cookie); - if (itemId != null) { - launchCookieItemId = itemId; - break; - } - } - - return mContainer.getFirstMatchForAppClose(launchCookieItemId, + return mContainer.getFirstMatchForAppClose(StableViewInfo.fromLaunchCookies(launchCookies), sourceTaskView.getFirstTask().key.getComponent().getPackageName(), UserHandle.of(sourceTaskView.getFirstTask().key.userId), false /* supportsAllAppsState */); @@ -330,13 +314,22 @@ public class LauncherSwipeHandlerV2 extends } private class FloatingViewHomeAnimationFactory extends LauncherHomeAnimationFactory { - private final FloatingView mFloatingView; + @Nullable + protected RectFSpringAnim mSiblingAnimation; FloatingViewHomeAnimationFactory(FloatingView floatingView) { mFloatingView = floatingView; } + @Override + protected void playScalingRevealAnimation() { + if (mContainer != null) { + new ScalingWorkspaceRevealAnim(mContainer, mSiblingAnimation, + getWindowTargetRect()).start(); + } + } + @Override public void onCancel() { mFloatingView.fastFinish(); @@ -387,4 +380,4 @@ public class LauncherSwipeHandlerV2 extends } } } -} +} \ No newline at end of file diff --git a/quickstep/src/com/android/quickstep/SwipeUpAnimationLogic.java b/quickstep/src/com/android/quickstep/SwipeUpAnimationLogic.java index ba33c62d9d..79df19f259 100644 --- a/quickstep/src/com/android/quickstep/SwipeUpAnimationLogic.java +++ b/quickstep/src/com/android/quickstep/SwipeUpAnimationLogic.java @@ -26,6 +26,7 @@ import android.graphics.Matrix; import android.graphics.Matrix.ScaleToFit; import android.graphics.Rect; import android.graphics.RectF; +import android.util.Log; import android.view.RemoteAnimationTarget; import androidx.annotation.NonNull; @@ -85,7 +86,7 @@ public abstract class SwipeUpAnimationLogic implements protected boolean mIsSwipeForSplit; public SwipeUpAnimationLogic(Context context, RecentsAnimationDeviceState deviceState, - GestureState gestureState) { + GestureState gestureState) { mContext = context; mDeviceState = deviceState; mGestureState = gestureState; @@ -267,7 +268,7 @@ public abstract class SwipeUpAnimationLogic implements mCurrentShift.updateValue(startProgress); RectF[] startRects = new RectF[mRemoteTargetHandles.length]; for (int i = 0, mRemoteTargetHandlesLength = mRemoteTargetHandles.length; - i < mRemoteTargetHandlesLength; i++) { + i < mRemoteTargetHandlesLength; i++) { RemoteTargetHandle remoteHandle = mRemoteTargetHandles[i]; TaskViewSimulator tvs = remoteHandle.getTaskViewSimulator(); tvs.apply(remoteHandle.getTransformParams().setProgress(startProgress)); @@ -300,14 +301,14 @@ public abstract class SwipeUpAnimationLogic implements * @param homeAnimationFactory The home animation factory. */ protected RectFSpringAnim[] createWindowAnimationToHome(float startProgress, - HomeAnimationFactory homeAnimationFactory) { + HomeAnimationFactory homeAnimationFactory) { // TODO(b/195473584) compute separate end targets for different staged split final RectF targetRect = homeAnimationFactory.getWindowTargetRect(); RectFSpringAnim[] out = new RectFSpringAnim[mRemoteTargetHandles.length]; Matrix[] homeToWindowPositionMap = new Matrix[mRemoteTargetHandles.length]; RectF[] startRects = updateProgressForStartRect(homeToWindowPositionMap, startProgress); for (int i = 0, mRemoteTargetHandlesLength = mRemoteTargetHandles.length; - i < mRemoteTargetHandlesLength; i++) { + i < mRemoteTargetHandlesLength; i++) { RemoteTargetHandle remoteHandle = mRemoteTargetHandles[i]; out[i] = getWindowAnimationToHomeInternal( homeAnimationFactory, @@ -381,6 +382,8 @@ public abstract class SwipeUpAnimationLogic implements protected class SpringAnimationRunner extends AnimationSuccessListener implements RectFSpringAnim.OnUpdateListener, BuilderProxy { + private static final String TAG = "SpringAnimationRunner"; + final Rect mCropRect = new Rect(); final Matrix mMatrix = new Matrix(); @@ -481,10 +484,26 @@ public abstract class SwipeUpAnimationLogic implements return; } mTargetTaskView.setAlpha(mAnimationFactory.isAnimatingIntoIcon() ? 1f : alpha); - float width = mThumbnailStartBounds.width(); - float height = mThumbnailStartBounds.height(); - float scale = Math.min(currentRect.width(), currentRect.height()) - / Math.min(width, height); + float startWidth = mThumbnailStartBounds.width(); + float startHeight = mThumbnailStartBounds.height(); + float currentWidth = currentRect.width(); + float currentHeight = currentRect.height(); + float scale; + + boolean isStartWidthValid = Float.compare(startWidth, 0f) > 0; + boolean isStartHeightValid = Float.compare(startHeight, 0f) > 0; + if (isStartWidthValid && isStartHeightValid) { + scale = Math.min(currentWidth, currentHeight) / Math.min(startWidth, startHeight); + } else { + Log.e(TAG, "TaskView starting bounds are invalid: " + mThumbnailStartBounds); + if (isStartWidthValid) { + scale = currentWidth / startWidth; + } else if (isStartHeightValid) { + scale = currentHeight / startHeight; + } else { + scale = 1f; + } + } mTargetTaskView.setScaleX(scale); mTargetTaskView.setScaleY(scale); @@ -496,7 +515,7 @@ public abstract class SwipeUpAnimationLogic implements @Override public void onBuildTargetParams(SurfaceProperties builder, RemoteAnimationTarget app, - TransformParams params) { + TransformParams params) { builder.setMatrix(mMatrix) .setWindowCrop(mCropRect) .setCornerRadius(params.getCornerRadius()); @@ -606,4 +625,4 @@ public abstract class SwipeUpAnimationLogic implements }; } } -} +} \ No newline at end of file diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java index 97ce00c41d..541e27b58b 100644 --- a/src/com/android/launcher3/BubbleTextView.java +++ b/src/com/android/launcher3/BubbleTextView.java @@ -48,6 +48,7 @@ import android.text.TextPaint; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.util.AttributeSet; +import android.util.Log; import android.util.Property; import android.util.Size; import android.util.TypedValue; @@ -85,12 +86,13 @@ import com.android.launcher3.util.MultiTranslateDelegate; import com.android.launcher3.util.SafeCloseable; import com.android.launcher3.util.ShortcutUtil; import com.android.launcher3.views.ActivityContext; -import com.android.launcher3.views.IconLabelDotView; +import com.android.launcher3.views.FloatingIconViewCompanion; import java.text.NumberFormat; import java.util.HashMap; import java.util.Locale; +import app.lawnchair.LawnchairApp; import app.lawnchair.font.FontManager; import app.lawnchair.preferences.PreferenceManager; import app.lawnchair.util.LawnchairUtilsKt; @@ -103,7 +105,7 @@ import app.lawnchair.util.LawnchairUtilsKt; * too aggressive. */ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, - IconLabelDotView, DraggableView, Reorderable { + FloatingIconViewCompanion, DraggableView, Reorderable { public static final int DISPLAY_WORKSPACE = 0; public static final int DISPLAY_ALL_APPS = 1; @@ -231,7 +233,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, public BubbleTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mActivity = ActivityContext.lookupContext(context); - FastBitmapDrawable.setFlagHoverEnabled(enableCursorHoverStates()); + FastBitmapDrawable.setFlagHoverEnabled(LawnchairApp.isRecentsEnabled() && enableCursorHoverStates()); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BubbleTextView, defStyle, 0); @@ -1275,6 +1277,13 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, }; } + @Override + public void resetIconScale(boolean shouldReset) { + if (shouldReset) { + mIcon.resetScale(); + } + } + private void resetIconScale() { if (mIcon != null) { mIcon.resetScale(); diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java index 0dd0fa6cad..03c30ccfe6 100644 --- a/src/com/android/launcher3/Launcher.java +++ b/src/com/android/launcher3/Launcher.java @@ -72,6 +72,7 @@ import static com.android.launcher3.LauncherState.SPRING_LOADED; import static com.android.launcher3.Utilities.postAsyncCallback; import static com.android.launcher3.config.FeatureFlags.FOLDABLE_SINGLE_PAGE; import static com.android.launcher3.config.FeatureFlags.MULTI_SELECT_EDIT_MODE; +import static com.android.launcher3.folder.FolderGridOrganizer.createFolderGridOrganizer; import static com.android.launcher3.logging.KeyboardStateManager.KeyboardState.HIDE; import static com.android.launcher3.logging.KeyboardStateManager.KeyboardState.SHOW; import static com.android.launcher3.logging.StatsLogManager.EventEnum; @@ -242,6 +243,7 @@ import com.android.launcher3.util.RunnableList; import com.android.launcher3.util.ScreenOnTracker; import com.android.launcher3.util.ScreenOnTracker.ScreenOnListener; import com.android.launcher3.util.SettingsCache; +import com.android.launcher3.util.StableViewInfo; import com.android.launcher3.util.SystemUiController; import com.android.launcher3.util.Themes; import com.android.launcher3.util.Thunk; @@ -827,7 +829,7 @@ public class Launcher extends StatefulActivity View collectionIcon = getWorkspace().getHomescreenIconByItemId(info.container); if (collectionIcon instanceof FolderIcon folderIcon && collectionIcon.getTag() instanceof FolderInfo) { - if (new FolderGridOrganizer(getDeviceProfile()) + if (createFolderGridOrganizer(getDeviceProfile()) .setFolderInfo((FolderInfo) folderIcon.getTag()) .isItemInPreview(info.rank)) { folderIcon.invalidate(); @@ -2494,28 +2496,25 @@ public class Launcher extends StatefulActivity } /** - * Similar to {@link #getFirstMatch} but optimized to finding a suitable view - * for the app close + * Similar to {@link #getFirstMatch} but optimized to finding a suitable view for the app close * animation. * - * @param preferredItemId The id of the preferred item to match to if it - * exists, - * or ItemInfo#NO_MATCHING_ID if you want to not - * match by item id - * @param packageName The package name of the app to match. - * @param user The user of the app to match. - * @param supportsAllAppsState If true and we are in All Apps state, looks for - * view in All Apps. + * @param svi The StableViewInfo of the preferred item to match to if it exists or null + * @param packageName The package name of the app to match. + * @param user The user of the app to match. + * @param supportsAllAppsState If true and we are in All Apps state, looks for view in All Apps. * Else we only looks on the workspace. */ - public @Nullable View getFirstMatchForAppClose(int preferredItemId, String packageName, + public @Nullable View getFirstMatchForAppClose( + @Nullable StableViewInfo svi, String packageName, UserHandle user, boolean supportsAllAppsState) { - final Predicate preferredItem = info -> info != null && info.id == preferredItemId; - final Predicate packageAndUserAndApp = info -> info != null - && info.itemType == ITEM_TYPE_APPLICATION - && info.user.equals(user) - && info.getTargetComponent() != null - && TextUtils.equals(info.getTargetComponent().getPackageName(), + final Predicate preferredItem = svi == null ? i -> false : svi::matches; + final Predicate packageAndUserAndApp = info -> + info != null + && info.itemType == ITEM_TYPE_APPLICATION + && info.user.equals(user) + && info.getTargetComponent() != null + && TextUtils.equals(info.getTargetComponent().getPackageName(), packageName); if (supportsAllAppsState && isInState(LauncherState.ALL_APPS)) { @@ -2540,7 +2539,7 @@ public class Launcher extends StatefulActivity Folder folder = Folder.getOpen(this); if (folder != null) { View v = getFirstMatch(Collections.singletonList( - folder.getContent().getCurrentCellLayout().getShortcutsAndWidgets()), + folder.getContent().getCurrentCellLayout().getShortcutsAndWidgets()), preferredItem, packageAndUserAndApp); if (v == null) { @@ -2552,7 +2551,8 @@ public class Launcher extends StatefulActivity List containers = new ArrayList<>(mWorkspace.getPanelCount() + 1); containers.add(mWorkspace.getHotseat().getShortcutsAndWidgets()); - mWorkspace.forEachVisiblePage(page -> containers.add(((CellLayout) page).getShortcutsAndWidgets())); + mWorkspace.forEachVisiblePage(page + -> containers.add(((CellLayout) page).getShortcutsAndWidgets())); // Order: Preferred item by itself or in folder, then by matching package/user return getFirstMatch(containers, preferredItem, forFolderMatch(preferredItem), diff --git a/src/com/android/launcher3/Utilities.java b/src/com/android/launcher3/Utilities.java index 25e886aab4..dbb199dc2e 100644 --- a/src/com/android/launcher3/Utilities.java +++ b/src/com/android/launcher3/Utilities.java @@ -769,7 +769,7 @@ public final class Utilities { } AdaptiveIconDrawable result; - if(ExtendedBitmapDrawable.isFromIconPack(mainIcon)) return null; + if(ExtendedBitmapDrawable.isFromIconPack(mainIcon) || !PreferenceManager.INSTANCE.get(context).getWrapAdaptiveIcons().get()) return null; if (mainIcon instanceof AdaptiveIconDrawable aid) { result = aid; } else { diff --git a/src/com/android/launcher3/dragndrop/DragLayer.java b/src/com/android/launcher3/dragndrop/DragLayer.java index db693f0fa9..3910da1c2b 100644 --- a/src/com/android/launcher3/dragndrop/DragLayer.java +++ b/src/com/android/launcher3/dragndrop/DragLayer.java @@ -157,7 +157,7 @@ public class DragLayer extends BaseDragLayer implements LauncherOverla isOverFolderOrSearchBar = isEventOverView(topView, ev) || isEventOverAccessibleDropTargetBar(ev); if (!isOverFolderOrSearchBar) { - sendTapOutsideFolderAccessibilityEvent(currentFolder.isEditingName()); + sendTapOutsideFolderAccessibilityEvent(currentFolder.getIsEditingName()); mHoverPointClosesFolder = true; return true; } @@ -167,7 +167,7 @@ public class DragLayer extends BaseDragLayer implements LauncherOverla isOverFolderOrSearchBar = isEventOverView(topView, ev) || isEventOverAccessibleDropTargetBar(ev); if (!isOverFolderOrSearchBar && !mHoverPointClosesFolder) { - sendTapOutsideFolderAccessibilityEvent(currentFolder.isEditingName()); + sendTapOutsideFolderAccessibilityEvent(currentFolder.getIsEditingName()); mHoverPointClosesFolder = true; return true; } else if (!isOverFolderOrSearchBar) { diff --git a/src/com/android/launcher3/dragndrop/DragView.java b/src/com/android/launcher3/dragndrop/DragView.java index de457fc063..fd02972363 100644 --- a/src/com/android/launcher3/dragndrop/DragView.java +++ b/src/com/android/launcher3/dragndrop/DragView.java @@ -67,6 +67,8 @@ import com.android.launcher3.util.RunnableList; import com.android.launcher3.views.ActivityContext; import com.android.launcher3.views.BaseDragLayer; +import app.lawnchair.icons.CustomAdaptiveIconDrawable; + /** A custom view for rendering an icon, folder, shortcut or widget during drag-n-drop. */ public abstract class DragView extends FrameLayout { @@ -265,7 +267,7 @@ public abstract class DragView extends Fram try (LauncherIcons li = LauncherIcons.obtain(mActivity)) { // Since we just want the scale, avoid heavy drawing operations Utilities.scaleRectAboutCenter(bounds, li.getNormalizer().getScale( - new AdaptiveIconDrawable(new ColorDrawable(Color.BLACK), null), + new CustomAdaptiveIconDrawable (new ColorDrawable(Color.BLACK), null), null, null, null)); } diff --git a/src/com/android/launcher3/folder/Folder.java b/src/com/android/launcher3/folder/Folder.java index a1fab8052d..88211fede7 100644 --- a/src/com/android/launcher3/folder/Folder.java +++ b/src/com/android/launcher3/folder/Folder.java @@ -19,6 +19,7 @@ package com.android.launcher3.folder; import static android.text.TextUtils.isEmpty; + import static com.android.launcher3.LauncherAnimUtils.SPRING_LOADED_EXIT_DELAY; import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APP_PAIR; @@ -27,6 +28,7 @@ import static com.android.launcher3.LauncherState.EDIT_MODE; import static com.android.launcher3.LauncherState.NORMAL; import static com.android.launcher3.compat.AccessibilityManagerCompat.sendCustomAccessibilityEvent; import static com.android.launcher3.config.FeatureFlags.ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS; +import static com.android.launcher3.folder.FolderGridOrganizer.createFolderGridOrganizer; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_LABEL_UPDATED; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_DROP_COMPLETED; import static com.android.launcher3.testing.shared.TestProtocol.FOLDER_OPENED_MESSAGE; @@ -35,6 +37,7 @@ import static com.android.launcher3.util.window.RefreshRateTracker.getSingleFram import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; +import android.annotation.ColorInt; import android.annotation.SuppressLint; import android.appwidget.AppWidgetHostView; import android.content.Context; @@ -64,10 +67,9 @@ import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.widget.TextView; -import androidx.annotation.ColorInt; -import androidx.core.graphics.ColorUtils; import androidx.annotation.IntDef; import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; import androidx.core.content.res.ResourcesCompat; import androidx.core.view.WindowInsetsCompat; @@ -102,13 +104,15 @@ import com.android.launcher3.model.data.WorkspaceItemFactory; import com.android.launcher3.model.data.WorkspaceItemInfo; import com.android.launcher3.pageindicators.PageIndicatorDots; import com.android.launcher3.util.Executors; -import com.android.launcher3.util.Themes; import com.android.launcher3.util.LauncherBindableItemsContainer.ItemOperator; +import com.android.launcher3.util.Themes; import com.android.launcher3.util.Thunk; import com.android.launcher3.views.ActivityContext; import com.android.launcher3.views.BaseDragLayer; import com.android.launcher3.views.ClipPathView; import com.android.launcher3.widget.PendingAddShortcutInfo; +import com.androidinternal.graphics.ColorUtils; +import com.patrykmichalik.opto.core.PreferenceExtensionsKt; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -121,6 +125,9 @@ import java.util.StringJoiner; import java.util.stream.Collectors; import java.util.stream.Stream; +import app.lawnchair.preferences2.PreferenceManager2; +import app.lawnchair.theme.color.ColorOption; +import app.lawnchair.theme.color.tokens.ColorTokens; import app.lawnchair.theme.drawable.DrawableTokens; import app.lawnchair.util.EditTextExtensions; import app.lawnchair.util.LawnchairUtilsKt; @@ -141,17 +148,17 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo /** * We avoid measuring {@link #mContent} with a 0 width or height, as this - * results in CellLayout being measured as UNSPECIFIED, which it does not - * support. + * results in CellLayout being measured as UNSPECIFIED, which it does not support. */ - private static final int MIN_CONTENT_DIMEN = 5; + @VisibleForTesting + static final int MIN_CONTENT_DIMEN = 5; public static final int STATE_CLOSED = 0; public static final int STATE_ANIMATING = 1; public static final int STATE_OPEN = 2; @Retention(RetentionPolicy.SOURCE) - @IntDef({ STATE_CLOSED, STATE_ANIMATING, STATE_OPEN }) + @IntDef({STATE_CLOSED, STATE_ANIMATING, STATE_OPEN}) public @interface FolderState { } @@ -174,7 +181,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo private static final int FOLDER_COLOR_ANIMATION_DURATION = 200; private static final int REORDER_DELAY = 250; - private static final int ON_EXIT_CLOSE_DELAY = 400; + static final int ON_EXIT_CLOSE_DELAY = 400; private static final Rect sTempRect = new Rect(); private static final int MIN_FOLDERS_FOR_HARDWARE_OPTIMIZATION = 10; @@ -194,21 +201,20 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo || itemType == ITEM_TYPE_APP_PAIR; } - private final Alarm mReorderAlarm = new Alarm(Looper.getMainLooper()); - private final Alarm mOnExitAlarm = new Alarm(Looper.getMainLooper()); - private final Alarm mOnScrollHintAlarm = new Alarm(Looper.getMainLooper()); - final Alarm mScrollPauseAlarm = new Alarm(Looper.getMainLooper()); + private Alarm mReorderAlarm = new Alarm(Looper.getMainLooper()); + private Alarm mOnExitAlarm = new Alarm(Looper.getMainLooper()); + private Alarm mOnScrollHintAlarm = new Alarm(Looper.getMainLooper()); + private Alarm mScrollPauseAlarm = new Alarm(Looper.getMainLooper()); final ArrayList mItemsInReadingOrder = new ArrayList(); private AnimatorSet mCurrentAnimator; private boolean mIsAnimatingClosed = false; - // Folder can be displayed in Launcher's activity or a separate window (e.g. - // Taskbar). + // Folder can be displayed in Launcher's activity or a separate window (e.g. Taskbar). // Anything specific to Launcher should use mLauncherDelegate, otherwise should // use mActivityContext. - protected final LauncherDelegate mLauncherDelegate; + protected LauncherDelegate mLauncherDelegate; protected final ActivityContext mActivityContext; protected DragController mDragController; @@ -221,7 +227,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo @Thunk FolderPagedView mContent; - public FolderNameEditText mFolderName; + FolderNameEditText mFolderName; private PageIndicatorDots mPageIndicator; protected View mFooter; @@ -233,21 +239,22 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo private Path mClipPath; - @ViewDebug.ExportedProperty(category = "launcher", mapping = { - @ViewDebug.IntToString(from = STATE_CLOSED, to = "STATE_CLOSED"), - @ViewDebug.IntToString(from = STATE_ANIMATING, to = "STATE_ANIMATING"), - @ViewDebug.IntToString(from = STATE_OPEN, to = "STATE_OPEN"), - }) + @ViewDebug.ExportedProperty(category = "launcher", + mapping = { + @ViewDebug.IntToString(from = STATE_CLOSED, to = "STATE_CLOSED"), + @ViewDebug.IntToString(from = STATE_ANIMATING, to = "STATE_ANIMATING"), + @ViewDebug.IntToString(from = STATE_OPEN, to = "STATE_OPEN"), + }) private int mState = STATE_CLOSED; private final List mOnFolderStateChangedListeners = new ArrayList<>(); private OnFolderStateChangedListener mPriorityOnFolderStateChangedListener; @ViewDebug.ExportedProperty(category = "launcher") private boolean mRearrangeOnClose = false; - boolean mItemsInvalidated = false; + private boolean mItemsInvalidated = false; private View mCurrentDragView; private boolean mIsExternalDrag; - private boolean mDragInProgress = false; + private boolean mIsDragInProgress = false; private boolean mDeleteFolderOnDropCompleted = false; private boolean mSuppressFolderDeletion = false; private boolean mItemAddedBackToSelfViaIcon = false; @@ -260,7 +267,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo private int mScrollAreaOffset; @Thunk - int mScrollHintDir = SCROLL_NONE; + private int mScrollHintDir = SCROLL_NONE; @Thunk int mCurrentScrollDir = SCROLL_NONE; @@ -270,13 +277,13 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo private KeyboardInsetAnimationCallback mKeyboardInsetAnimationCallback; private GradientDrawable mBackground; + PreferenceManager2 preferenceManager2; /** * Used to inflate the Workspace from XML. * * @param context The application's context. - * @param attrs The attributes set containing the Workspace's customization - * values. + * @param attrs The attributes set containing the Workspace's customization values. */ public Folder(Context context, AttributeSet attrs) { super(context, attrs); @@ -286,15 +293,12 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mLauncherDelegate = LauncherDelegate.from(mActivityContext); mStatsLogManager = StatsLogManager.newInstance(context); - // We need this view to be focusable in touch mode so that when text editing of - // the folder - // name is complete, we have something to focus on, thus hiding the cursor and - // giving - // reliable behavior when clicking the text field (since it will always gain - // focus on + // We need this view to be focusable in touch mode so that when text editing of the folder + // name is complete, we have something to focus on, thus hiding the cursor and giving + // reliable behavior when clicking the text field (since it will always gain focus on // click). setFocusableInTouchMode(true); - + preferenceManager2 = PreferenceManager2.INSTANCE.get(context); } @Override @@ -330,9 +334,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo | InputType.TYPE_TEXT_FLAG_CAP_WORDS); mFolderName.forceDisableSuggestions(true); mFolderName.setPadding(mFolderName.getPaddingLeft(), - (mFooterHeight - mFolderName.getLineHeight()) / 2, + (getFooterHeight() - mFolderName.getLineHeight()) / 2, mFolderName.getPaddingRight(), - (mFooterHeight - mFolderName.getLineHeight()) / 2); + (getFooterHeight() - mFolderName.getLineHeight()) / 2); @ColorInt int accentColor = Themes.getColorAccent(mFolderName.getContext()); @@ -343,9 +347,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mFolderName.setHighlightColor(ColorUtils.setAlphaComponent(accentColor, 82)); } - mFooter = findViewById(R.id.folder_footer); - mFooterHeight = dp.folderFooterHeightPx; - if (Utilities.ATLEAST_R) { mKeyboardInsetAnimationCallback = new KeyboardInsetAnimationCallback(this); setWindowInsetsAnimationCallback(mKeyboardInsetAnimationCallback); @@ -354,43 +355,54 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo public boolean onLongClick(View v) { // Return if global dragging is not enabled - if (!mLauncherDelegate.isDraggingEnabled()) - return true; + if (!getIsLauncherDraggingEnabled()) return true; return startDrag(v, new DragOptions()); } + @VisibleForTesting + boolean getIsLauncherDraggingEnabled() { + return mLauncherDelegate.isDraggingEnabled(); + } + public boolean startDrag(View v, DragOptions options) { Object tag = v.getTag(); if (tag instanceof ItemInfo item) { mEmptyCellRank = item.rank; mCurrentDragView = v; - mDragController.addDragListener(this); - if (options.isAccessibleDrag) { - mDragController.addDragListener(new AccessibleDragListenerAdapter( - mContent, FolderAccessibilityHelper::new) { - @Override - protected void enableAccessibleDrag(boolean enable, - @Nullable DragObject dragObject) { - super.enableAccessibleDrag(enable, dragObject); - mFooter.setImportantForAccessibility(enable - ? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS - : IMPORTANT_FOR_ACCESSIBILITY_AUTO); - } - }); - } - - mLauncherDelegate.beginDragShared(v, this, options); + addDragListener(options); + callBeginDragShared(v, options); } return true; } + void callBeginDragShared(View v, DragOptions options) { + mLauncherDelegate.beginDragShared(v, this, options); + } + + void addDragListener(DragOptions options) { + getDragController().addDragListener(this); + if (!options.isAccessibleDrag) { + return; + } + getDragController().addDragListener(new AccessibleDragListenerAdapter( + mContent, FolderAccessibilityHelper::new) { + @Override + protected void enableAccessibleDrag(boolean enable, + @Nullable DragObject dragObject) { + super.enableAccessibleDrag(enable, dragObject); + mFooter.setImportantForAccessibility(enable + ? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS + : IMPORTANT_FOR_ACCESSIBILITY_AUTO); + } + }); + } + @Override public void onDragStart(DropTarget.DragObject dragObject, DragOptions options) { if (dragObject.dragSource != this) { return; } - mContent.removeItem(mCurrentDragView); mItemsInvalidated = true; @@ -399,35 +411,28 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo try (SuppressInfoChanges s = new SuppressInfoChanges()) { mInfo.remove(dragObject.dragInfo, true); } - mDragInProgress = true; + mIsDragInProgress = true; mItemAddedBackToSelfViaIcon = false; } @Override public void onDragEnd() { - if (mIsExternalDrag && mDragInProgress) { + if (mIsExternalDrag && mIsDragInProgress) { completeDragExit(); } - mDragInProgress = false; - mDragController.removeDragListener(this); - } - - public boolean isEditingName() { - return mIsEditingName; + mIsDragInProgress = false; + getDragController().removeDragListener(this); } public void startEditingFolderName() { - post(() -> { - showLabelSuggestions(); - mFolderName.setHint(""); - mIsEditingName = true; - }); + showLabelSuggestions(); + mFolderName.setHint(""); + mIsEditingName = true; } @Override public boolean onBackKey() { - // Convert to a string here to ensure that no other state associated with the - // text field + // Convert to a string here to ensure that no other state associated with the text field // gets saved. String newTitle = mFolderName.getText().toString(); if (DEBUG) { @@ -447,8 +452,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo this, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED, getContext().getString(R.string.folder_renamed, newTitle)); - // This ensures that focus is gained every time the field is clicked, which - // selects all + // This ensures that focus is gained every time the field is clicked, which selects all // the text and brings up the soft keyboard if necessary. mFolderName.clearFocus(); @@ -473,7 +477,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo public WindowInsets onApplyWindowInsets(WindowInsets windowInsets) { this.setTranslationY(0); - if (Utilities.ATLEAST_R) { + try { if (windowInsets.isVisible(WindowInsets.Type.ime())) { Insets keyboardInsets = windowInsets.getInsets(WindowInsets.Type.ime()); int folderHeightFromBottom = getHeightFromBottom(); @@ -484,7 +488,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo - mFolderName.getPaddingBottom()); } } - } else { + } catch (Throwable t) { WindowInsetsCompat insetsCompat = WindowInsetsCompat.toWindowInsetsCompat(windowInsets); if (insetsCompat.isVisible(WindowInsetsCompat.Type.ime())) { androidx.core.graphics.Insets keyboardInsets = insetsCompat.getInsets(WindowInsetsCompat.Type.ime()); @@ -505,7 +509,11 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo return mFolderIcon; } - public void setDragController(DragController dragController) { + DragController getDragController() { + return mDragController; + } + + void setDragController(DragController dragController) { mDragController = dragController; } @@ -516,10 +524,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo @Override protected void onAttachedToWindow() { - // requestFocus() causes the focus onto the folder itself, which doesn't cause - // visual - // effect but the next arrow key can start the keyboard focus inside of the - // folder, not + // requestFocus() causes the focus onto the folder itself, which doesn't cause visual + // effect but the next arrow key can start the keyboard focus inside of the folder, not // the folder itself. requestFocus(); super.onAttachedToWindow(); @@ -540,8 +546,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo @Override public View focusSearch(int direction) { - // When the folder is focused, further focus search should be within the folder - // contents. + // When the folder is focused, further focus search should be within the folder contents. return FocusFinder.getInstance().findNextFocus(this, null, direction); } @@ -576,8 +581,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mFolderName.setText(""); mFolderName.setHint(R.string.folder_hint_text); } - // In case any children didn't come across during loading, clean up the folder - // accordingly + // In case any children didn't come across during loading, clean up the folder accordingly mFolderIcon.post(() -> { if (getItemCount() <= 1) { replaceFolderWithFinalItem(); @@ -585,12 +589,12 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo }); } + /** - * Show suggested folder title in FolderEditText if the first suggestion is - * non-empty, push + * Show suggested folder title in FolderEditText if the first suggestion is non-empty, push * rest of the suggestions to InputMethodManager. */ - private void showLabelSuggestions() { + void showLabelSuggestions() { if (mInfo.suggestedFolderNames == null) { return; } @@ -617,10 +621,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo /** * Creates a new UserFolder, inflated from R.layout.user_folder. * - * @param activityContext The main ActivityContext in which to inflate this - * Folder. It must also - * be an instance or ContextWrapper around the Launcher - * activity context. + * @param activityContext The main ActivityContext in which to inflate this Folder. It must also + * be an instance or ContextWrapper around the Launcher activity context. * @return A new UserFolder. */ @SuppressLint("InflateParams") @@ -669,17 +671,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } private boolean shouldUseHardwareLayerForAnimation(CellLayout currentCellLayout) { - if (ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS.get()) - return true; + if (ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS.get()) return true; int folderCount = 0; final ShortcutAndWidgetContainer container = currentCellLayout.getShortcutsAndWidgets(); for (int i = container.getChildCount() - 1; i >= 0; --i) { final View child = container.getChildAt(i); - if (child instanceof AppWidgetHostView) - return false; - if (child instanceof FolderIcon) - ++folderCount; + if (child instanceof AppWidgetHostView) return false; + if (child instanceof FolderIcon) ++folderCount; } return folderCount >= MIN_FOLDERS_FOR_HARDWARE_OPTIMIZATION; } @@ -689,22 +688,21 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo */ public void beginExternalDrag() { mIsExternalDrag = true; - mDragInProgress = true; + mIsDragInProgress = true; // Since this folder opened by another controller, it might not get onDrop or // onDropComplete. Perform cleanup once drag-n-drop ends. - mDragController.addDragListener(this); + getDragController().addDragListener(this); ArrayList items = new ArrayList<>(mInfo.getContents()); mEmptyCellRank = items.size(); - items.add(null); // Add an empty spot at the end + items.add(null); // Add an empty spot at the end animateOpen(items, mEmptyCellRank / mContent.itemsPerPage()); } /** - * Opens the user folder described by the specified tag. The opening of the - * folder + * Opens the user folder described by the specified tag. The opening of the folder * is animated relative to the specified View. If the View is null, no animation * is played. */ @@ -713,22 +711,17 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } /** - * Opens the user folder described by the specified tag. The opening of the - * folder + * Opens the user folder described by the specified tag. The opening of the folder * is animated relative to the specified View. If the View is null, no animation * is played. */ private void animateOpen(List items, int pageNo) { - if (items == null || items.size() <= 1) { - Log.d(TAG, "Couldn't animate folder open because items is: " + items); + if (!shouldAnimateOpen(items)) { return; } Folder openFolder = getOpen(mActivityContext); - if (openFolder != null && openFolder != this) { - // Close any open folder before opening a folder. - openFolder.close(true); - } + closeOpenFolder(openFolder); mContent.bindItems(items); centerAboutIcon(); @@ -742,7 +735,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo // There was a one-off crash where the folder had a parent already. if (getParent() == null) { dragLayer.addView(this); - mDragController.addDropTarget(this); + getDragController().addDropTarget(this); } else { if (FeatureFlags.IS_STUDIO_BUILD) { Log.e(TAG, "Opening folder (" + this + ") which already has a parent:" @@ -753,12 +746,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mContent.completePendingPageChanges(); mContent.setCurrentPage(pageNo); - // This is set to true in close(), but isn't reset to false until - // onDropCompleted(). This - // leads to an inconsistent state if you drag out of the folder and drag back in - // without - // dropping. One resulting issue is that replaceFolderWithFinalItem() can be - // called twice. + // This is set to true in close(), but isn't reset to false until onDropCompleted(). This + // leads to an inconsistent state if you drag out of the folder and drag back in without + // dropping. One resulting issue is that replaceFolderWithFinalItem() can be called twice. mDeleteFolderOnDropCompleted = false; cancelRunningAnimations(); @@ -792,10 +782,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mFolderName.setTranslationX(mContent.mIsRtl ? -translation : translation); mPageIndicator.prepareEntryAnimation(); - // Do not update the flag if we are in drag mode. The flag will be updated, when - // we + // Do not update the flag if we are in drag mode. The flag will be updated, when we // actually drop the icon. - final boolean updateAnimationFlag = !mDragInProgress; + final boolean updateAnimationFlag = !mIsDragInProgress; anim.addListener(new AnimatorListenerAdapter() { @SuppressLint("InlinedApi") @@ -825,17 +814,41 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo addAnimationStartListeners(anim); // Because t=0 has the folder match the folder icon, we can skip the // first frame and have the same movement one frame earlier. + Log.d("b/311077782", "Folder.animateOpen"); anim.setCurrentPlayTime(Math.min(getSingleFrameMs(getContext()), anim.getTotalDuration())); anim.start(); - // Make sure the folder picks up the last drag move even if the finger doesn't - // move. - if (mDragController.isDragging()) { - mDragController.forceTouchMove(); + // Make sure the folder picks up the last drag move even if the finger doesn't move. + if (getDragController().isDragging()) { + getDragController().forceTouchMove(); } mContent.verifyVisibleHighResIcons(mContent.getNextPage()); } + /** + * Determines whether we should animate the folder opening. + */ + boolean shouldAnimateOpen(List items) { + if (items == null || items.size() <= 1) { + Log.d(TAG, "Couldn't animate folder open because items is: " + items); + return false; + } + return true; + } + + /** + * If there's a folder already open, we want to close it before opening another one. + */ + @VisibleForTesting + boolean closeOpenFolder(Folder openFolder) { + if (openFolder != null && openFolder != this) { + // Close any open folder before opening a folder. + openFolder.close(true); + return true; + } + return false; + } + @Override protected boolean isOfType(int type) { return (type & TYPE_FOLDER) != 0; @@ -849,7 +862,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mCurrentAnimator.cancel(); } - if (isEditingName()) { + if (mIsEditingName) { mFolderName.dispatchBackKey(); } @@ -864,8 +877,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo post(this::announceAccessibilityChanges); } - // Notify the accessibility manager that this folder "window" has disappeared - // and no + // Notify the accessibility manager that this folder "window" has disappeared and no // longer occludes the workspace items mActivityContext.getDragLayer().sendAccessibilityEvent( AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); @@ -898,15 +910,13 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo a.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { - if (Utilities.ATLEAST_R) { - setWindowInsetsAnimationCallback(null); - } + setWindowInsetsAnimationCallback(null); mIsAnimatingClosed = true; } @Override public void onAnimationEnd(Animator animation) { - if (mKeyboardInsetAnimationCallback != null && Utilities.ATLEAST_R) { + if (mKeyboardInsetAnimationCallback != null) { setWindowInsetsAnimationCallback(mKeyboardInsetAnimationCallback); } closeComplete(true); @@ -936,7 +946,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo if (parent != null) { parent.removeView(this); } - mDragController.removeDropTarget(this); + getDragController().removeDropTarget(this); clearFocus(); if (mFolderIcon != null) { mFolderIcon.setVisibility(View.VISIBLE); @@ -957,12 +967,12 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mRearrangeOnClose = false; } if (getItemCount() <= 1) { - if (!mDragInProgress && !mSuppressFolderDeletion) { + if (!mIsDragInProgress && !mSuppressFolderDeletion) { replaceFolderWithFinalItem(); - } else if (mDragInProgress) { + } else if (mIsDragInProgress) { mDeleteFolderOnDropCompleted = true; } - } else if (!mDragInProgress) { + } else if (!mIsDragInProgress) { mContent.unbindItems(); } mSuppressFolderDeletion = false; @@ -981,8 +991,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo public void onDragEnter(DragObject d) { mPrevTargetRank = -1; mOnExitAlarm.cancelAlarm(); - // Get the area offset such that the folder only closes if half the drag icon - // width + // Get the area offset such that the folder only closes if half the drag icon width // is outside the folder area mScrollAreaOffset = d.dragView.getDragRegionWidth() / 2 - d.xOffset; } @@ -1083,7 +1092,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } } - private void clearDragInfo() { + @VisibleForTesting + void clearDragInfo() { mCurrentDragView = null; mIsExternalDrag = false; } @@ -1106,8 +1116,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } /** - * When performing an accessibility drop, onDrop is sent immediately after - * onDragEnter. So we + * When performing an accessibility drop, onDrop is sent immediately after onDragEnter. So we * need to complete all transient states based on timers. */ @Override @@ -1120,20 +1129,20 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo @Override public void onDropCompleted(final View target, final DragObject d, - final boolean success) { + final boolean success) { if (success) { if (getItemCount() <= 1) { mDeleteFolderOnDropCompleted = true; } - if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon && target != this) { + if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon + && target != this) { replaceFolderWithFinalItem(); } } else { // The drag failed, we need to return the item to the folder ItemInfo info = d.dragInfo; View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info) - ? mCurrentDragView - : mContent.createNewView(info); + ? mCurrentDragView : mContent.createNewView(info); ArrayList views = getIconsInReadingOrder(); info.rank = Utilities.boundToRange(info.rank, 0, views.size()); views.add(info.rank, icon); @@ -1157,12 +1166,11 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } mDeleteFolderOnDropCompleted = false; - mDragInProgress = false; + mIsDragInProgress = false; mItemAddedBackToSelfViaIcon = false; mCurrentDragView = null; - // Reordering may have occured, and we need to save the new item locations. We - // do this once + // Reordering may have occured, and we need to save the new item locations. We do this once // at the end to prevent unnecessary database operations. updateItemLocationsInDatabaseBatch(false); // Use the item count to check for multi-page as the folder UI may not have @@ -1175,7 +1183,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } private void updateItemLocationsInDatabaseBatch(boolean isBind) { - FolderGridOrganizer verifier = new FolderGridOrganizer( + FolderGridOrganizer verifier = createFolderGridOrganizer( mActivityContext.getDeviceProfile()).setFolderInfo(mInfo); ArrayList items = new ArrayList<>(); @@ -1201,7 +1209,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } public void notifyDrop() { - if (mDragInProgress) { + if (mIsDragInProgress) { mItemAddedBackToSelfViaIcon = true; } } @@ -1225,7 +1233,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo sTempRect.set(mActivityContext.getFolderBoundingBox()); int left = Utilities.boundToRange(centeredLeft, sTempRect.left, sTempRect.right - width); int top = Utilities.boundToRange(centeredTop, sTempRect.top, sTempRect.bottom - height); - int[] inOutPosition = new int[] { left, top }; + int[] inOutPosition = new int[]{left, top}; mActivityContext.updateOpenFolderPosition(inOutPosition, sTempRect, width, height); left = inOutPosition[0]; top = inOutPosition[1]; @@ -1244,28 +1252,41 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } protected int getContentAreaHeight() { - DeviceProfile grid = mActivityContext.getDeviceProfile(); - int maxContentAreaHeight = grid.availableHeightPx - grid.getTotalWorkspacePadding().y - - mFooterHeight; - int height = Math.min(maxContentAreaHeight, + int height = Math.min(getMaxContentAreaHeight(), mContent.getDesiredHeight()); return Math.max(height, MIN_CONTENT_DIMEN); } - private int getContentAreaWidth() { + @VisibleForTesting + int getMaxContentAreaHeight() { + DeviceProfile grid = mActivityContext.getDeviceProfile(); + return grid.availableHeightPx - grid.getTotalWorkspacePadding().y + - getFooterHeight(); + } + + @VisibleForTesting + int getContentAreaWidth() { return Math.max(mContent.getDesiredWidth(), MIN_CONTENT_DIMEN); } - private int getFolderWidth() { + @VisibleForTesting + int getFolderWidth() { return getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth(); } - private int getFolderHeight() { + @VisibleForTesting + int getFolderHeight() { return getFolderHeight(getContentAreaHeight()); } - private int getFolderHeight(int contentAreaHeight) { - return getPaddingTop() + getPaddingBottom() + contentAreaHeight + mFooterHeight; + @VisibleForTesting + int getFolderHeight(int contentAreaHeight) { + return getPaddingTop() + getPaddingBottom() + contentAreaHeight + getFooterHeight(); + } + + @VisibleForTesting + int getFooterHeight() { + return mFooterHeight; } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { @@ -1309,8 +1330,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo return mDestroyed; } - // This method keeps track of the first and last item in the folder for the - // purposes + // This method keeps track of the first and last item in the folder for the purposes // of keyboard focus public void updateTextViewFocus() { final View firstChild = mContent.getFirstItem(); @@ -1320,13 +1340,10 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mFolderName.setNextFocusRightId(lastChild.getId()); mFolderName.setNextFocusLeftId(lastChild.getId()); mFolderName.setNextFocusUpId(lastChild.getId()); - // Hitting TAB from the folder name wraps around to the first item on the - // current - // folder page, and hitting SHIFT+TAB from that item wraps back to the folder - // name. + // Hitting TAB from the folder name wraps around to the first item on the current + // folder page, and hitting SHIFT+TAB from that item wraps back to the folder name. mFolderName.setNextFocusForwardId(firstChild.getId()); - // When clicking off the folder when editing the name, this Folder gains focus. - // When + // When clicking off the folder when editing the name, this Folder gains focus. When // pressing an arrow key from that state, give the focus to the first item. this.setNextFocusDownId(firstChild.getId()); this.setNextFocusRightId(firstChild.getId()); @@ -1370,12 +1387,11 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } PendingAddShortcutInfo pasi = d.dragInfo instanceof PendingAddShortcutInfo - ? (PendingAddShortcutInfo) d.dragInfo - : null; - WorkspaceItemInfo pasiSi = pasi != null ? pasi.getActivityInfo(launcher).createWorkspaceItemInfo() : null; + ? (PendingAddShortcutInfo) d.dragInfo : null; + WorkspaceItemInfo pasiSi = + pasi != null ? pasi.getActivityInfo(launcher).createWorkspaceItemInfo() : null; if (pasi != null && pasiSi == null) { - // There is no WorkspaceItemInfo, so we have to go through a configuration - // activity. + // There is no WorkspaceItemInfo, so we have to go through a configuration activity. pasi.container = mInfo.id; pasi.rank = mEmptyCellRank; @@ -1440,7 +1456,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } // Clear the drag info, as it is no longer being dragged. - mDragInProgress = false; + mIsDragInProgress = false; if (mContent.getPageCount() > 1) { // The animation has already been shown while opening the folder. @@ -1459,10 +1475,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo .log(LAUNCHER_ITEM_DROP_COMPLETED); } - // This is used so the item doesn't immediately appear in the folder when added. - // In one case - // we need to create the illusion that the item isn't added back to the folder - // yet, to + // This is used so the item doesn't immediately appear in the folder when added. In one case + // we need to create the illusion that the item isn't added back to the folder yet, to // to correspond to the animation of the icon back into the folder. This is public void hideItem(ItemInfo info) { View v = getViewForInfo(info); @@ -1480,7 +1494,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo @Override public void onAdd(ItemInfo item, int rank) { - FolderGridOrganizer verifier = new FolderGridOrganizer( + FolderGridOrganizer verifier = createFolderGridOrganizer( mActivityContext.getDeviceProfile()).setFolderInfo(mInfo); verifier.updateRankAndPos(item, rank); mLauncherDelegate.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0, item.cellX, @@ -1511,7 +1525,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } } - private View getViewForInfo(final ItemInfo item) { + @VisibleForTesting + View getViewForInfo(final ItemInfo item) { return mContent.iterateOverItems((info, view) -> info == item); } @@ -1569,7 +1584,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo if (hasFocus) { mFromLabelState = mInfo.getFromLabelState(); mFromTitle = mInfo.title; - startEditingFolderName(); + post(this::startEditingFolderName); } else { StatsLogger statsLogger = mStatsLogManager.logger() .withItemInfo(mInfo) @@ -1661,8 +1676,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } } - // Compares item position based on rank and position giving priority to the - // rank. + // Compares item position based on rank and position giving priority to the rank. public static final Comparator ITEM_POS_COMPARATOR = new Comparator() { @Override @@ -1703,7 +1717,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo /** Navigation bar back key or hardware input back key has been issued. */ @Override public void onBackInvoked() { - if (isEditingName()) { + if (mIsEditingName) { mFolderName.dispatchBackKey(); } else { super.onBackInvoked(); @@ -1715,7 +1729,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo if (ev.getAction() == MotionEvent.ACTION_DOWN) { BaseDragLayer dl = (BaseDragLayer) getParent(); - if (isEditingName()) { + if (mIsEditingName) { if (!dl.isEventOverView(mFolderName, ev)) { mFolderName.dispatchBackKey(); return true; @@ -1735,8 +1749,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } /** - * Alternative to using {@link #getClipToOutline()} as it only works with - * derivatives of + * Alternative to using {@link #getClipToOutline()} as it only works with derivatives of * rounded rect. */ @Override @@ -1763,10 +1776,96 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo return mContent; } - /** - * Returns the height of the current folder's bottom edge from the bottom of the - * screen. - */ + @VisibleForTesting + void setItemAddedBackToSelfViaIcon(boolean value) { + mItemAddedBackToSelfViaIcon = value; + } + + @VisibleForTesting + boolean getItemAddedBackToSelfViaIcon() { + return mItemAddedBackToSelfViaIcon; + } + + @VisibleForTesting + void setIsDragInProgress(boolean value) { + mIsDragInProgress = value; + } + + @VisibleForTesting + boolean getIsDragInProgress() { + return mIsDragInProgress; + } + + @VisibleForTesting + View getCurrentDragView() { + return mCurrentDragView; + } + + @VisibleForTesting + void setCurrentDragView(View view) { + mCurrentDragView = view; + } + + @VisibleForTesting + boolean getItemsInvalidated() { + return mItemsInvalidated; + } + + @VisibleForTesting + void setItemsInvalidated(boolean value) { + mItemsInvalidated = value; + } + + @VisibleForTesting + boolean getIsExternalDrag() { + return mIsExternalDrag; + } + + @VisibleForTesting + void setIsExternalDrag(boolean value) { + mIsExternalDrag = value; + } + + public boolean getIsEditingName() { + return mIsEditingName; + } + + @VisibleForTesting + void setIsEditingName(boolean value) { + mIsEditingName = value; + } + + @VisibleForTesting + void setFolderName(FolderNameEditText value) { + mFolderName = value; + } + + @VisibleForTesting + FolderNameEditText getFolderName() { + return mFolderName; + } + + @VisibleForTesting + boolean getIsOpen() { + return mIsOpen; + } + + @VisibleForTesting + void setIsOpen(boolean value) { + mIsOpen = value; + } + + @VisibleForTesting + boolean getRearrangeOnClose() { + return mRearrangeOnClose; + } + + @VisibleForTesting + void setRearrangeOnClose(boolean value) { + mRearrangeOnClose = value; + } + + /** Returns the height of the current folder's bottom edge from the bottom of the screen. */ private int getHeightFromBottom() { BaseDragLayer.LayoutParams layoutParams = (BaseDragLayer.LayoutParams) getLayoutParams(); int folderBottomPx = layoutParams.y + layoutParams.height; @@ -1775,6 +1874,16 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo return windowBottomPx - folderBottomPx; } + @VisibleForTesting + boolean getDeleteFolderOnDropCompleted() { + return mDeleteFolderOnDropCompleted; + } + + @VisibleForTesting + void setDeleteFolderOnDropCompleted(boolean value) { + mDeleteFolderOnDropCompleted = value; + } + /** * Save this listener for the special case of when we update the state and concurrently * add another listener to {@link #mOnFolderStateChangedListeners} to avoid a @@ -1784,7 +1893,13 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mPriorityOnFolderStateChangedListener = listener; } - private void setState(@FolderState int newState) { + @VisibleForTesting + int getState() { + return mState; + } + + @VisibleForTesting + void setState(@FolderState int newState) { mState = newState; if (mPriorityOnFolderStateChangedListener != null) { mPriorityOnFolderStateChangedListener.onFolderStateChanged(mState); @@ -1796,6 +1911,60 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } } + @VisibleForTesting + Alarm getOnExitAlarm() { + return mOnExitAlarm; + } + + @VisibleForTesting + void setOnExitAlarm(Alarm value) { + mOnExitAlarm = value; + } + + @VisibleForTesting + Alarm getReorderAlarm() { + return mReorderAlarm; + } + + @VisibleForTesting + void setReorderAlarm(Alarm value) { + mReorderAlarm = value; + } + + @VisibleForTesting + Alarm getOnScrollHintAlarm() { + return mOnScrollHintAlarm; + } + + @VisibleForTesting + void setOnScrollHintAlarm(Alarm value) { + mOnScrollHintAlarm = value; + } + + @VisibleForTesting + Alarm getScrollPauseAlarm() { + return mScrollPauseAlarm; + } + + @VisibleForTesting + void setScrollPauseAlarm(Alarm value) { + mScrollPauseAlarm = value; + } + + @VisibleForTesting + int getScrollHintDir() { + return mScrollHintDir; + } + + @VisibleForTesting + void setScrollHintDir(int value) { + mScrollHintDir = value; + } + + @VisibleForTesting + int getScrollAreaOffset() { + return mScrollAreaOffset; + } /** * Adds the provided listener to the running list of Folder listeners * {@link #mOnFolderStateChangedListeners} @@ -1816,4 +1985,4 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo /** See {@link Folder.FolderState} */ void onFolderStateChanged(@FolderState int newState); } -} +} \ No newline at end of file diff --git a/src/com/android/launcher3/folder/FolderAnimationManager.java b/src/com/android/launcher3/folder/FolderAnimationManager.java index 8a2bcdabcf..5241fe4062 100644 --- a/src/com/android/launcher3/folder/FolderAnimationManager.java +++ b/src/com/android/launcher3/folder/FolderAnimationManager.java @@ -21,6 +21,7 @@ import static android.view.View.ALPHA; import static com.android.launcher3.BubbleTextView.TEXT_ALPHA_PROPERTY; import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY; import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW; +import static com.android.launcher3.folder.FolderGridOrganizer.createFolderGridOrganizer; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -49,9 +50,11 @@ import com.android.launcher3.graphics.IconShape.ShapeDelegate; import com.android.launcher3.util.Themes; import com.android.launcher3.views.BaseDragLayer; import com.androidinternal.graphics.ColorUtils; +import com.patrykmichalik.opto.core.PreferenceExtensionsKt; import java.util.List; +import app.lawnchair.theme.color.ColorOption; import app.lawnchair.theme.color.tokens.ColorTokens; import app.lawnchair.util.LawnchairUtilsKt; @@ -64,6 +67,7 @@ import app.lawnchair.util.LawnchairUtilsKt; */ public class FolderAnimationManager { + private static final float EXTRA_FOLDER_REVEAL_RADIUS_PERCENTAGE = 0.125F; private static final int FOLDER_NAME_ALPHA_DURATION = 32; private static final int LARGE_FOLDER_FOOTER_DURATION = 128; @@ -102,7 +106,7 @@ public class FolderAnimationManager { mContext = folder.getContext(); mDeviceProfile = folder.mActivityContext.getDeviceProfile(); - mPreviewVerifier = new FolderGridOrganizer(mDeviceProfile); + mPreviewVerifier = createFolderGridOrganizer(mDeviceProfile); mIsOpening = isOpening; @@ -162,12 +166,9 @@ public class FolderAnimationManager { mFolder.mFooter.setPivotX(0); mFolder.mFooter.setPivotY(0); - // We want to create a small X offset for the preview items, so that they follow their - // expected path to their final locations. ie. an icon should not move right, if it's final - // location is to its left. This value is arbitrarily defined. - int previewItemOffsetX = (int) (previewSize / 2); + int previewItemOffsetX = 0; if (Utilities.isRtl(mContext.getResources())) { - previewItemOffsetX = (int) (lp.width * initialScale - initialSize - previewItemOffsetX); + previewItemOffsetX = (int) (lp.width * initialScale - initialSize); } final int paddingOffsetX = (int) (mContent.getPaddingLeft() * initialScale); @@ -183,9 +184,17 @@ public class FolderAnimationManager { final float yDistance = initialY - lp.y; // Set up the Folder background. - final int previewColor = ColorTokens.FolderPreviewColor.resolveColor(mContext); - final int initialColor = ColorUtils.setAlphaComponent(previewColor, LawnchairUtilsKt.getFolderPreviewAlpha(mContext)); - final int finalColor = ColorTokens.FolderBackgroundColor.resolveColor(mContext); + int previewColor = ColorTokens.FolderPreviewColor.resolveColor(mContext); + int initialColor = ColorUtils.setAlphaComponent(previewColor, LawnchairUtilsKt.getFolderPreviewAlpha(mContext)); + int finalColor = ColorTokens.FolderBackgroundColor.resolveColor(mContext); + + ColorOption colorOption = PreferenceExtensionsKt.firstBlocking(mFolder.preferenceManager2.getFolderColor()); + int folderColor = colorOption.getColorPreferenceEntry().getLightColor().invoke(mContext); + + if (folderColor != 0) { + initialColor = folderColor; + finalColor = folderColor; + } mFolderBackground.mutate(); mFolderBackground.setColor(mIsOpening ? initialColor : finalColor); @@ -244,36 +253,26 @@ public class FolderAnimationManager { play(a, shapeDelegate.createRevealAnimator( mFolder, startRect, endRect, finalRadius, !mIsOpening)); - // Create reveal animator for the folder content (capture the top 4 icons 2x2) - int width = mDeviceProfile.folderCellLayoutBorderSpacePx.x - + mDeviceProfile.folderCellWidthPx * 2; - int rtlExtraWidth = 0; - int height = mDeviceProfile.folderCellLayoutBorderSpacePx.y - + mDeviceProfile.folderCellHeightPx * 2; int page = mIsOpening ? mContent.getCurrentPage() : mContent.getDestinationPage(); - // In RTL we want to move to the last 2 columns of icons in the folder. if (Utilities.isRtl(mContext.getResources())) { page = (mContent.getPageCount() - 1) - page; - CellLayout clAtPage = mContent.getPageAt(page); - if (clAtPage != null) { - int numExtraRows = clAtPage.getCountX() - 2; - rtlExtraWidth = (int) Math.max(numExtraRows * (mDeviceProfile.folderCellWidthPx - + mDeviceProfile.folderCellLayoutBorderSpacePx.x), rtlExtraWidth); - } } - int left = mContent.getPaddingLeft() + page * lp.width; + int left = page * lp.width; + + int extraRadius = (int) ((mDeviceProfile.folderIconSizePx / initialScale) + * EXTRA_FOLDER_REVEAL_RADIUS_PERCENTAGE); Rect contentStart = new Rect( - left + rtlExtraWidth, - 0, - left + width + mContent.getPaddingRight() + rtlExtraWidth, - height); + (int) (left + (startRect.left / initialScale)) - extraRadius, + (int) (startRect.top / initialScale) - extraRadius, + (int) (left + (startRect.right / initialScale)) + extraRadius, + (int) (startRect.bottom / initialScale) + extraRadius); Rect contentEnd = new Rect(left, 0, left + lp.width, lp.height); play(a, shapeDelegate.createRevealAnimator( mFolder.getContent(), contentStart, contentEnd, finalRadius, !mIsOpening)); // Fade in the folder name, as the text can overlap the icons when grid size is small. - mFolder.mFolderName.setAlpha(mIsOpening ? 0f : 1f); - play(a, getAnimator(mFolder.mFolderName, View.ALPHA, 0, 1), + mFolder.getFolderName().setAlpha(mIsOpening ? 0f : 1f); + play(a, getAnimator(mFolder.getFolderName(), View.ALPHA, 0, 1), mIsOpening ? FOLDER_NAME_ALPHA_DURATION : 0, mIsOpening ? mDuration - FOLDER_NAME_ALPHA_DURATION : FOLDER_NAME_ALPHA_DURATION); @@ -334,7 +333,7 @@ public class FolderAnimationManager { mFolder.mFooter.setScaleX(1f); mFolder.mFooter.setScaleY(1f); mFolder.mFooter.setTranslationX(0f); - mFolder.mFolderName.setAlpha(1f); + mFolder.getFolderName().setAlpha(1f); mFolder.setClipChildren(mFolderClipChildren); mFolder.setClipToPadding(mFolderClipToPadding); diff --git a/src/com/android/launcher3/folder/FolderGridOrganizer.java b/src/com/android/launcher3/folder/FolderGridOrganizer.java index 593673d4bd..6219651e8b 100644 --- a/src/com/android/launcher3/folder/FolderGridOrganizer.java +++ b/src/com/android/launcher3/folder/FolderGridOrganizer.java @@ -47,12 +47,19 @@ public class FolderGridOrganizer { /** * Note: must call {@link #setFolderInfo(FolderInfo)} manually for verifier to work. */ - public FolderGridOrganizer(DeviceProfile profile) { - mMaxCountX = profile.numFolderColumns; - mMaxCountY = profile.numFolderRows; + public FolderGridOrganizer(int maxCountX, int maxCountY) { + mMaxCountX = maxCountX; + mMaxCountY = maxCountY; mMaxItemsPerPage = mMaxCountX * mMaxCountY; } + /** + * Creates a FolderGridOrganizer for the given DeviceProfile + */ + public static FolderGridOrganizer createFolderGridOrganizer(DeviceProfile profile) { + return new FolderGridOrganizer(profile.numFolderColumns, profile.numFolderRows); + } + /** * Updates the organizer with the provided folder info */ @@ -194,6 +201,7 @@ public class FolderGridOrganizer { int row = rank / mCountX; return col < PREVIEW_MAX_COLUMNS && row < PREVIEW_MAX_ROWS; } + // If we have less than 4 items do this return rank < MAX_NUM_ITEMS_IN_PREVIEW; } -} +} \ No newline at end of file diff --git a/src/com/android/launcher3/folder/FolderIcon.java b/src/com/android/launcher3/folder/FolderIcon.java index a455bd2633..4c2180cecd 100644 --- a/src/com/android/launcher3/folder/FolderIcon.java +++ b/src/com/android/launcher3/folder/FolderIcon.java @@ -21,6 +21,7 @@ package com.android.launcher3.folder; import static com.android.launcher3.Flags.enableCursorHoverStates; import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.ICON_OVERLAP_FACTOR; import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW; +import static com.android.launcher3.folder.FolderGridOrganizer.createFolderGridOrganizer; import static com.android.launcher3.folder.PreviewItemManager.INITIAL_ITEM_ANIMATION_DURATION; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_AUTO_LABELED; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_AUTO_LABELING_SKIPPED_EMPTY_PRIMARY; @@ -84,7 +85,7 @@ import com.android.launcher3.util.Executors; import com.android.launcher3.util.MultiTranslateDelegate; import com.android.launcher3.util.Thunk; import com.android.launcher3.views.ActivityContext; -import com.android.launcher3.views.IconLabelDotView; +import com.android.launcher3.views.FloatingIconViewCompanion; import com.android.launcher3.widget.PendingAddShortcutInfo; import java.util.ArrayList; @@ -94,29 +95,25 @@ import java.util.function.Predicate; /** * An icon that can appear on in the workspace representing an {@link Folder}. */ -public class FolderIcon extends FrameLayout implements FolderListener, IconLabelDotView, +public class FolderIcon extends FrameLayout implements FolderListener, FloatingIconViewCompanion, DraggableView, Reorderable { private final MultiTranslateDelegate mTranslateDelegate = new MultiTranslateDelegate(this); - @Thunk - ActivityContext mActivity; - @Thunk - Folder mFolder; + @Thunk ActivityContext mActivity; + @Thunk Folder mFolder; public FolderInfo mInfo; private CheckLongPressHelper mLongPressHelper; static final int DROP_IN_ANIMATION_DURATION = 400; - // Flag whether the folder should open itself when an item is dragged over is - // enabled. + // Flag whether the folder should open itself when an item is dragged over is enabled. public static final boolean SPRING_LOADING_ENABLED = true; // Delay when drag enters until the folder opens, in miliseconds. private static final int ON_OPEN_DELAY = 800; - @Thunk - BubbleTextView mFolderName; + @Thunk BubbleTextView mFolderName; PreviewBackground mBackground = new PreviewBackground(getContext()); private boolean mBackgroundIsVisible = true; @@ -144,8 +141,8 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel private float mScaleForReorderBounce = 1f; - private static final Property DOT_SCALE_PROPERTY = new Property(Float.TYPE, - "dotScale") { + private static final Property DOT_SCALE_PROPERTY + = new Property(Float.TYPE, "dotScale") { @Override public Float get(FolderIcon folderIcon) { return folderIcon.mDotScale; @@ -176,7 +173,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel } public static FolderIcon inflateFolderAndIcon(int resId, - T activityContext, ViewGroup group, FolderInfo folderInfo) { + T activityContext, ViewGroup group, FolderInfo folderInfo) { Folder folder = Folder.fromXml(activityContext); FolderIcon icon = inflateIcon(resId, activityContext, group, folderInfo); @@ -190,7 +187,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel * Builds a FolderIcon to be added to the Launcher */ public static FolderIcon inflateIcon(int resId, ActivityContext activity, - @Nullable ViewGroup group, FolderInfo folderInfo) { + @Nullable ViewGroup group, FolderInfo folderInfo) { @SuppressWarnings("all") // suppress dead code warning final boolean error = INITIAL_ITEM_ANIMATION_DURATION >= DROP_IN_ANIMATION_DURATION; if (error) { @@ -229,7 +226,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel icon.setAccessibilityDelegate(activity.getAccessibilityDelegate()); - icon.mPreviewVerifier = new FolderGridOrganizer(activity.getDeviceProfile()); + icon.mPreviewVerifier = createFolderGridOrganizer(activity.getDeviceProfile()); icon.mPreviewVerifier.setFolderInfo(folderInfo); icon.updatePreviewItems(false); @@ -284,8 +281,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel } public void onDragEnter(ItemInfo dragInfo) { - if (mFolder.isDestroyed() || !willAcceptItem(dragInfo)) - return; + if (mFolder.isDestroyed() || !willAcceptItem(dragInfo)) return; CellLayoutLayoutParams lp = (CellLayoutLayoutParams) getLayoutParams(); CellLayout cl = (CellLayout) getParent().getParent(); @@ -310,8 +306,8 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel } public void performCreateAnimation(final ItemInfo destInfo, final View destView, - final ItemInfo srcInfo, final DragObject d, Rect dstRect, - float scaleRelativeToDragLayer) { + final ItemInfo srcInfo, final DragObject d, Rect dstRect, + float scaleRelativeToDragLayer) { final DragView srcView = d.dragView; prepareCreateAnimation(destView); addItem(destInfo); @@ -337,14 +333,12 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel } private void onDrop(final ItemInfo item, DragObject d, Rect finalRect, - float scaleRelativeToDragLayer, int index, boolean itemReturnedOnFailedDrop) { + float scaleRelativeToDragLayer, int index, boolean itemReturnedOnFailedDrop) { item.cellX = -1; item.cellY = -1; DragView animateView = d.dragView; - // Typically, the animateView corresponds to the DragView; however, if this is - // being done - // after a configuration activity (ie. for a Shortcut being dragged from - // AllApps) we + // Typically, the animateView corresponds to the DragView; however, if this is being done + // after a configuration activity (ie. for a Shortcut being dragged from AllApps) we // will not have a view to animate if (animateView != null && mActivity instanceof Launcher) { final Launcher launcher = (Launcher) mActivity; @@ -353,8 +347,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel if (to == null) { to = new Rect(); Workspace workspace = launcher.getWorkspace(); - // Set cellLayout and this to it's final state to compute final animation - // locations + // Set cellLayout and this to it's final state to compute final animation locations workspace.setFinalTransitionTransform(); float scaleX = getScaleX(); float scaleY = getScaleY(); @@ -426,8 +419,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel mFolder.hideItem(item); - if (!itemAdded) - mPreviewItemManager.hidePreviewItem(index, true); + if (!itemAdded) mPreviewItemManager.hidePreviewItem(index, true); FolderNameInfos nameInfos = new FolderNameInfos(); Executors.MODEL_EXECUTOR.post(() -> { @@ -469,7 +461,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel mInfo.setTitle(newTitle, mFolder.mLauncherDelegate.getModelWriter()); onTitleChanged(mInfo.title); - mFolder.mFolderName.setText(mInfo.title); + mFolder.getFolderName().setText(mInfo.title); // Logging for folder creation flow StatsLogManager.newInstance(getContext()).logger() @@ -483,12 +475,13 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel .log(LAUNCHER_FOLDER_AUTO_LABELED); } + public void onDrop(DragObject d, boolean itemReturnedOnFailedDrop) { ItemInfo item; if (d.dragInfo instanceof WorkspaceItemFactory) { // Came from all apps -- make a copy item = ((WorkspaceItemFactory) d.dragInfo).makeWorkspaceItem(getContext()); - } else if (d.dragSource instanceof BaseItemDragListener) { + } else if (d.dragSource instanceof BaseItemDragListener){ // Came from a different window -- make a copy if (d.dragInfo instanceof AppPairInfo) { // dragged item is app pair @@ -611,8 +604,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); - if (!mBackgroundIsVisible) - return; + if (!mBackgroundIsVisible) return; mPreviewItemManager.recomputePreviewDrawingParams(); @@ -620,8 +612,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel mBackground.drawBackground(canvas); } - if (mCurrentPreviewItems.isEmpty() && !mAnimating) - return; + if (mCurrentPreviewItems.isEmpty() && !mAnimating) return; mPreviewItemManager.draw(canvas); @@ -635,8 +626,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel public void drawDot(Canvas canvas) { if (!mForceHideDot && ((mDotInfo != null && mDotInfo.hasDot()) || mDotScale > 0)) { Rect iconBounds = mDotParams.iconBounds; - // FolderIcon draws the icon to be top-aligned (with padding) & - // horizontally-centered + // FolderIcon draws the icon to be top-aligned (with padding) & horizontally-centered int iconSize = mActivity.getDeviceProfile().iconSizePx; iconBounds.left = (getWidth() - iconSize) / 2; iconBounds.right = iconBounds.left + iconSize; @@ -749,8 +739,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel return false; } - // Call the superclass onTouchEvent first, because sometimes it changes the - // state to + // Call the superclass onTouchEvent first, because sometimes it changes the state to // isPressed() on an ACTION_UP super.onTouchEvent(event); mLongPressHelper.onTouchEvent(event); @@ -847,21 +836,17 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel } /** - * Interface that provides callbacks to a parent ViewGroup that hosts this - * FolderIcon. + * Interface that provides callbacks to a parent ViewGroup that hosts this FolderIcon. */ public interface FolderIconParent { /** - * Tells the FolderIconParent to draw a "leave-behind" when the Folder is open - * and leaving a + * Tells the FolderIconParent to draw a "leave-behind" when the Folder is open and leaving a * gap where the FolderIcon would be when the Folder is closed. */ void drawFolderLeaveBehindForIcon(FolderIcon child); - /** - * Tells the FolderIconParent to stop drawing the "leave-behind" as the Folder - * is closed. + * Tells the FolderIconParent to stop drawing the "leave-behind" as the Folder is closed. */ void clearFolderLeaveBehind(FolderIcon child); } -} +} \ No newline at end of file diff --git a/src/com/android/launcher3/folder/FolderPagedView.java b/src/com/android/launcher3/folder/FolderPagedView.java index 8eaa0dceab..6baba99f56 100644 --- a/src/com/android/launcher3/folder/FolderPagedView.java +++ b/src/com/android/launcher3/folder/FolderPagedView.java @@ -103,7 +103,7 @@ public class FolderPagedView extends PagedView implements Cli super(context, attrs); ActivityContext activityContext = ActivityContext.lookupContext(context); DeviceProfile profile = activityContext.getDeviceProfile(); - mOrganizer = new FolderGridOrganizer(profile); + mOrganizer = FolderGridOrganizer.createFolderGridOrganizer(profile); mIsRtl = Utilities.isRtl(getResources()); setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); diff --git a/src/com/android/launcher3/model/LoaderTask.java b/src/com/android/launcher3/model/LoaderTask.java index eaf342df2e..d71a8486ff 100644 --- a/src/com/android/launcher3/model/LoaderTask.java +++ b/src/com/android/launcher3/model/LoaderTask.java @@ -23,6 +23,7 @@ import static com.android.launcher3.Flags.enableSmartspaceRemovalToggle; import static com.android.launcher3.LauncherPrefs.IS_FIRST_LOAD_AFTER_RESTORE; import static com.android.launcher3.LauncherPrefs.SHOULD_SHOW_SMARTSPACE; import static com.android.launcher3.LauncherSettings.Favorites.TABLE_NAME; +import static com.android.launcher3.folder.FolderGridOrganizer.createFolderGridOrganizer; import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_HAS_SHORTCUT_PERMISSION; import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_PRIVATE_PROFILE_QUIET_MODE_ENABLED; import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_QUIET_MODE_CHANGE_PERMISSION; @@ -576,17 +577,9 @@ public class LoaderTask implements Runnable { */ @WorkerThread private void processFolderItems() { - // Sort the folder items, update ranks, and make sure all preview items are high - // res. - List verifiers; - - if (Utilities.ATLEAST_U) { - verifiers = mApp.getInvariantDeviceProfile().supportedProfiles - .stream().map(FolderGridOrganizer::new).toList(); - } else { - verifiers = mApp.getInvariantDeviceProfile().supportedProfiles - .stream().map(FolderGridOrganizer::new).collect(Collectors.toList()); - } + // Sort the folder items, update ranks, and make sure all preview items are high res. + List verifiers = mApp.getInvariantDeviceProfile().supportedProfiles + .stream().map(FolderGridOrganizer::createFolderGridOrganizer).collect(Collectors.toList()); for (CollectionInfo collection : mBgDataModel.collections) { if (!(collection instanceof FolderInfo folder)) { continue; diff --git a/src/com/android/launcher3/model/data/ItemInfo.java b/src/com/android/launcher3/model/data/ItemInfo.java index 93f8c7554d..0ae7b546f6 100644 --- a/src/com/android/launcher3/model/data/ItemInfo.java +++ b/src/com/android/launcher3/model/data/ItemInfo.java @@ -51,6 +51,7 @@ import com.android.launcher3.LauncherSettings.Favorites; import com.android.launcher3.Workspace; import com.android.launcher3.logger.LauncherAtom; import com.android.launcher3.logger.LauncherAtom.AllAppsContainer; +import com.android.launcher3.logger.LauncherAtom.Attribute; import com.android.launcher3.logger.LauncherAtom.ContainerInfo; import com.android.launcher3.logger.LauncherAtom.PredictionContainer; import com.android.launcher3.logger.LauncherAtom.SettingsContainer; @@ -67,6 +68,9 @@ import com.android.launcher3.util.SettingsCache; import com.android.launcher3.util.UserIconInfo; import com.android.systemui.shared.system.SysUiStatsLog; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import java.util.Optional; import app.lawnchair.LawnchairApp; @@ -79,9 +83,6 @@ public class ItemInfo { public static final boolean DEBUG = false; public static final int NO_ID = -1; - // An id that doesn't match any item, including predicted apps with have an - // id=NO_ID - public static final int NO_MATCHING_ID = Integer.MIN_VALUE; /** Hidden field Settings.Secure.NAV_BAR_KIDS_MODE */ private static final Uri NAV_BAR_KIDS_MODE = Settings.Secure.getUriFor("nav_bar_kids_mode"); @@ -114,8 +115,7 @@ public class ItemInfo { /** * The id of the container that holds this item. For the desktop, this will be * {@link Favorites#CONTAINER_DESKTOP}. For the all applications folder it - * will be {@link #NO_ID} (since it is not stored in the settings DB). For user - * folders + * will be {@link #NO_ID} (since it is not stored in the settings DB). For user folders * it will be the id of the folder. */ public int container = NO_ID; @@ -169,8 +169,7 @@ public class ItemInfo { public CharSequence title; /** - * Optionally set: The appTitle might e.g. be different if {@code title} is used - * to + * Optionally set: The appTitle might e.g. be different if {@code title} is used to * display progress (e.g. Downloading..). */ @Nullable @@ -183,8 +182,7 @@ public class ItemInfo { public CharSequence contentDescription; /** - * When the instance is created using {@link #copyFrom}, this field is used to - * keep track of + * When the instance is created using {@link #copyFrom}, this field is used to keep track of * original {@link ComponentName}. */ @Nullable @@ -193,6 +191,12 @@ public class ItemInfo { @NonNull public UserHandle user; + @NonNull + private ExtendedContainers mExtendedContainers = ExtendedContainers.getDefaultInstance(); + + @NonNull + private List mAttributeList = Collections.EMPTY_LIST; + public ItemInfo() { user = Process.myUserHandle(); } @@ -239,8 +243,7 @@ public class ItemInfo { /** * Returns this item's package name. * - * Prioritizes the component package name, then uses the intent package name as - * a fallback. + * Prioritizes the component package name, then uses the intent package name as a fallback. * This ensures deep shortcuts are supported. */ @Nullable @@ -251,8 +254,8 @@ public class ItemInfo { return component != null ? component.getPackageName() : intent != null - ? intent.getPackage() - : null; + ? intent.getPackage() + : null; } public void writeToValues(@NonNull final ContentWriter writer) { @@ -348,8 +351,7 @@ public class ItemInfo { } /** - * Creates {@link LauncherAtom.ItemInfo} with important fields and parent - * container info. + * Creates {@link LauncherAtom.ItemInfo} with important fields and parent container info. */ @NonNull public LauncherAtom.ItemInfo buildProto() { @@ -357,8 +359,7 @@ public class ItemInfo { } /** - * Creates {@link LauncherAtom.ItemInfo} with important fields and parent - * container info. + * Creates {@link LauncherAtom.ItemInfo} with important fields and parent container info. */ @NonNull public LauncherAtom.ItemInfo buildProto(@Nullable final CollectionInfo cInfo) { @@ -408,7 +409,8 @@ public class ItemInfo { break; } if (cInfo != null) { - LauncherAtom.FolderContainer.Builder folderBuilder = LauncherAtom.FolderContainer.newBuilder(); + LauncherAtom.FolderContainer.Builder folderBuilder = + LauncherAtom.FolderContainer.newBuilder(); folderBuilder.setGridX(cellX).setGridY(cellY).setPageIndex(screenId); switch (cInfo.container) { @@ -442,6 +444,7 @@ public class ItemInfo { } UserCache.INSTANCE.executeIfCreated(cache -> itemBuilder.setUserType(getUserType(cache.getUserInfo(user)))); itemBuilder.setRank(rank); + itemBuilder.addAllItemAttributes(mAttributeList); return itemBuilder; } @@ -457,7 +460,7 @@ public class ItemInfo { .build(); case CONTAINER_HOTSEAT_PREDICTION: return ContainerInfo.newBuilder().setPredictedHotseatContainer( - LauncherAtom.PredictedHotseatContainer.newBuilder().setIndex(screenId)) + LauncherAtom.PredictedHotseatContainer.newBuilder().setIndex(screenId)) .build(); case CONTAINER_DESKTOP: return ContainerInfo.newBuilder() @@ -500,7 +503,7 @@ public class ItemInfo { default: if (container <= EXTENDED_CONTAINERS) { return ContainerInfo.newBuilder() - .setExtendedContainers(getExtendedContainer()) + .setExtendedContainers(mExtendedContainers) .build(); } } @@ -508,13 +511,21 @@ public class ItemInfo { } /** - * Returns non-AOSP container wrapped by {@link ExtendedContainers} object. - * Should be overridden - * by build variants. + * Sets extra container info wrapped by {@link ExtendedContainers} object. */ - @NonNull - protected ExtendedContainers getExtendedContainer() { - return ExtendedContainers.getDefaultInstance(); + public void setExtendedContainers(@NonNull ExtendedContainers extendedContainers) { + mExtendedContainers = extendedContainers; + } + + /** + * Adds extra attributes to be added during logs + */ + public void addLogAttributes(List attributeList) { + if (mAttributeList.isEmpty()) { + mAttributeList = new ArrayList<>(attributeList); + } else { + mAttributeList.addAll(attributeList); + } } /** @@ -531,10 +542,18 @@ public class ItemInfo { * Sets the title of the item and writes to DB model if needed. */ public void setTitle(@Nullable final CharSequence title, - @Nullable final ModelWriter modelWriter) { + @Nullable final ModelWriter modelWriter) { this.title = title; } + /** + * Returns a string ID that is stable for a user session, but may not be persisted + */ + @Nullable + public Object getStableId() { + return getComponentKey(); + } + private int getUserType(UserIconInfo info) { if (info == null) { return SysUiStatsLog.LAUNCHER_UICHANGED__USER_TYPE__TYPE_UNKNOWN; @@ -550,4 +569,4 @@ public class ItemInfo { return SysUiStatsLog.LAUNCHER_UICHANGED__USER_TYPE__TYPE_UNKNOWN; } } -} +} \ No newline at end of file diff --git a/src/com/android/launcher3/util/StableViewInfo.kt b/src/com/android/launcher3/util/StableViewInfo.kt new file mode 100644 index 0000000000..34e3fc663f --- /dev/null +++ b/src/com/android/launcher3/util/StableViewInfo.kt @@ -0,0 +1,56 @@ +/* + * 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.launcher3.util + +import android.os.IBinder +import com.android.launcher3.model.data.ItemInfo +import com.android.launcher3.model.data.ItemInfo.NO_ID + +/** Info parameters that can be used to identify a Launcher object */ +data class StableViewInfo(val itemId: Int, val containerId: Int, val stableId: Any) { + + fun matches(info: ItemInfo?) = + info != null && + itemId == info.id && + containerId == info.container && + stableId == info.stableId + + companion object { + + private fun ItemInfo.toStableViewInfo() = + stableId?.let { sId -> + if (id != NO_ID || container != NO_ID) StableViewInfo(id, container, sId) else null + } + + /** + * Return a new launch cookie for the activity launch if supported. + * + * @param info the item info for the launch + */ + @JvmStatic + fun toLaunchCookie(info: ItemInfo?) = + info?.toStableViewInfo()?.let { ObjectWrapper.wrap(it) } + + /** + * Unwraps the binder and returns the first non-null StableViewInfo in the list or null if + * none can be found + */ + @JvmStatic + fun fromLaunchCookies(launchCookies: List) = + launchCookies.firstNotNullOfOrNull { ObjectWrapper.unwrap(it) } + } +} \ No newline at end of file diff --git a/src/com/android/launcher3/views/BubbleTextHolder.java b/src/com/android/launcher3/views/BubbleTextHolder.java index 84f8049ded..d2ae93b5be 100644 --- a/src/com/android/launcher3/views/BubbleTextHolder.java +++ b/src/com/android/launcher3/views/BubbleTextHolder.java @@ -20,7 +20,7 @@ import com.android.launcher3.BubbleTextView; /** * Views that contain {@link BubbleTextView} should implement this interface. */ -public interface BubbleTextHolder extends IconLabelDotView { +public interface BubbleTextHolder extends FloatingIconViewCompanion { BubbleTextView getBubbleText(); @Override diff --git a/src/com/android/launcher3/views/FloatingIconView.java b/src/com/android/launcher3/views/FloatingIconView.java index cca2719ea4..c6642f36e9 100644 --- a/src/com/android/launcher3/views/FloatingIconView.java +++ b/src/com/android/launcher3/views/FloatingIconView.java @@ -22,7 +22,7 @@ import static com.android.launcher3.Flags.enableAdditionalHomeAnimations; import static com.android.launcher3.Utilities.getFullDrawable; import static com.android.launcher3.Utilities.mapToRange; import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; -import static com.android.launcher3.views.IconLabelDotView.setIconAndDotVisible; +import static com.android.launcher3.views.FloatingIconViewCompanion.setPropertiesVisible; import android.animation.Animator; import android.content.Context; @@ -175,8 +175,9 @@ public class FloatingIconView extends FrameLayout implements mLauncher.getDeviceProfile(), taskViewDrawAlpha); if (mFadeOutView != null) { - // The alpha goes from 1 to 0 when progress is 0 and 0.33 respectively. - mFadeOutView.setAlpha(1 - Math.min(1f, mapToRange(progress, 0, 0.33f, 0, 1, LINEAR))); + // The alpha goes from 1 to 0 when progress is 0 and 0.15 respectively. + // This value minimizes view display time while still allowing the view to fade out. + mFadeOutView.setAlpha(1 - Math.min(1f, mapToRange(progress, 0, 0.15f, 0, 1, LINEAR))); } } @@ -252,11 +253,14 @@ public class FloatingIconView extends FrameLayout implements public static void getLocationBoundsForView(Launcher launcher, View v, boolean isOpening, RectF outRect, Rect outViewBounds) { boolean ignoreTransform = !isOpening; - if (v instanceof BubbleTextHolder) { - v = ((BubbleTextHolder) v).getBubbleText(); + if (v instanceof DeepShortcutView dsv) { + v = dsv.getIconView(); ignoreTransform = false; - } else if (v.getParent() instanceof DeepShortcutView) { - v = ((DeepShortcutView) v.getParent()).getIconView(); + } else if (v.getParent() instanceof DeepShortcutView dsv) { + v = dsv.getIconView(); + ignoreTransform = false; + } else if (v instanceof BubbleTextHolder bth) { + v = bth.getBubbleText(); ignoreTransform = false; } if (v == null) { @@ -297,10 +301,10 @@ public class FloatingIconView extends FrameLayout implements Drawable badge = null; if (info instanceof SystemShortcut) { - if (originalView instanceof ImageView) { - drawable = ((ImageView) originalView).getDrawable(); - } else if (originalView instanceof DeepShortcutView) { - drawable = ((DeepShortcutView) originalView).getIconView().getBackground(); + if (originalView instanceof ImageView iv) { + drawable = iv.getDrawable(); + } else if (originalView instanceof DeepShortcutView dsv) { + drawable = dsv.getIconView().getBackground(); } else { drawable = originalView.getBackground(); } @@ -515,6 +519,10 @@ public class FloatingIconView extends FrameLayout implements // When closing an app, we want the item on the workspace to be invisible immediately updateViewsVisibility(false /* isVisible */); } + if (mFadeOutView instanceof FloatingIconViewCompanion fivc) { + fivc.setForceHideDot(true); + fivc.setForceHideRing(true); + } } @Override @@ -652,6 +660,10 @@ public class FloatingIconView extends FrameLayout implements if (view.mFadeOutView != null) { view.mFadeOutView.setAlpha(1f); } + if (view.mFadeOutView instanceof FloatingIconViewCompanion fivc) { + fivc.setForceHideDot(false); + fivc.setForceHideRing(false); + } if (hideOriginal) { view.updateViewsVisibility(true /* isVisible */); @@ -673,10 +685,10 @@ public class FloatingIconView extends FrameLayout implements private void updateViewsVisibility(boolean isVisible) { if (mOriginalIcon != null) { - setIconAndDotVisible(mOriginalIcon, isVisible); + setPropertiesVisible(mOriginalIcon, isVisible); } if (mMatchVisibilityView != null) { - setIconAndDotVisible(mMatchVisibilityView, isVisible); + setPropertiesVisible(mMatchVisibilityView, isVisible); } } diff --git a/src/com/android/launcher3/views/IconLabelDotView.java b/src/com/android/launcher3/views/FloatingIconViewCompanion.java similarity index 52% rename from src/com/android/launcher3/views/IconLabelDotView.java rename to src/com/android/launcher3/views/FloatingIconViewCompanion.java index e9113cf874..bcf39e0e82 100644 --- a/src/com/android/launcher3/views/IconLabelDotView.java +++ b/src/com/android/launcher3/views/FloatingIconViewCompanion.java @@ -18,21 +18,28 @@ package com.android.launcher3.views; import android.view.View; /** - * A view that has an icon, label, and notification dot. + * A view that can be drawn (in some capacity) via) {@link FloatingIconView}. + * This interface allows us to hide certain properties of the view that the FloatingIconView + * cannot draw, which allows us to make a seamless handoff between the FloatingIconView and + * the companion view. */ -public interface IconLabelDotView { +public interface FloatingIconViewCompanion { void setIconVisible(boolean visible); void setForceHideDot(boolean hide); + default void setForceHideRing(boolean hide) {} + default void resetIconScale(boolean shouldReset) {} /** * Sets the visibility of icon and dot of the view */ - static void setIconAndDotVisible(View view, boolean visible) { - if (view instanceof IconLabelDotView) { - ((IconLabelDotView) view).setIconVisible(visible); - ((IconLabelDotView) view).setForceHideDot(!visible); + static void setPropertiesVisible(View view, boolean visible) { + if (view instanceof FloatingIconViewCompanion) { + ((FloatingIconViewCompanion) view).setIconVisible(visible); + ((FloatingIconViewCompanion) view).setForceHideDot(!visible); + ((FloatingIconViewCompanion) view).setForceHideRing(!visible); + ((FloatingIconViewCompanion) view).resetIconScale(true); } else { view.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); } } -} +} \ No newline at end of file diff --git a/src/com/android/launcher3/views/FloatingSurfaceView.java b/src/com/android/launcher3/views/FloatingSurfaceView.java index cab798215c..07cc84c133 100644 --- a/src/com/android/launcher3/views/FloatingSurfaceView.java +++ b/src/com/android/launcher3/views/FloatingSurfaceView.java @@ -15,9 +15,8 @@ */ package com.android.launcher3.views; -import static com.android.launcher3.model.data.ItemInfo.NO_MATCHING_ID; import static com.android.launcher3.views.FloatingIconView.getLocationBoundsForView; -import static com.android.launcher3.views.IconLabelDotView.setIconAndDotVisible; +import static com.android.launcher3.views.FloatingIconViewCompanion.setPropertiesVisible; import android.content.Context; import android.graphics.Canvas; @@ -106,7 +105,9 @@ public class FloatingSurfaceView extends AbstractFloatingView implements private void removeViewImmediate() { // Cancel any pending remove Executors.MAIN_EXECUTOR.getHandler().removeCallbacks(mRemoveViewRunnable); - removeViewFromParent(); + if (isAttachedToWindow()) { + removeViewFromParent(); + } } /** @@ -160,7 +161,7 @@ public class FloatingSurfaceView extends AbstractFloatingView implements if (mContract == null) { return; } - View icon = mLauncher.getFirstMatchForAppClose(NO_MATCHING_ID, + View icon = mLauncher.getFirstMatchForAppClose(null /* StableViewInfo */, mContract.componentName.getPackageName(), mContract.user, false /* supportsAllAppsState */); @@ -213,7 +214,7 @@ public class FloatingSurfaceView extends AbstractFloatingView implements @Override public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, - int format, int width, int height) { + int format, int width, int height) { drawOnSurface(); } @@ -227,17 +228,23 @@ public class FloatingSurfaceView extends AbstractFloatingView implements private void drawOnSurface() { SurfaceHolder surfaceHolder = mSurfaceView.getHolder(); + if (!surfaceHolder.getSurface().isValid()) return; - Canvas c = surfaceHolder.lockHardwareCanvas(); - if (c != null) { - mPicture.draw(c); - surfaceHolder.unlockCanvasAndPost(c); + synchronized (this) { + Canvas c = surfaceHolder.lockHardwareCanvas(); + if (c != null) { + try { + mPicture.draw(c); + } finally { + surfaceHolder.unlockCanvasAndPost(c); + } + } } } private void setCurrentIconVisible(boolean isVisible) { if (mIcon != null) { - setIconAndDotVisible(mIcon, isVisible); + setPropertiesVisible(mIcon, isVisible); } } -} +} \ No newline at end of file