From 1906cc33f9c6a8b58f3f260d184cfb5ac1b225fc Mon Sep 17 00:00:00 2001 From: Tony Wickham Date: Thu, 11 Feb 2021 11:55:24 -0800 Subject: [PATCH 1/6] Refactor Folder to use ActivityContext and BaseDragLayer These are the more generic versions of Launcher and DragLayer, so that Folders can be used in other surfaces. Test: Open and close Folders on home screen, ensure works properly Bug: 171917176 Change-Id: I39b9aedbd8319ca61ea0e776bc95eab585e023d5 --- src/com/android/launcher3/BaseActivity.java | 3 +- src/com/android/launcher3/Launcher.java | 38 ++++++++ src/com/android/launcher3/folder/Folder.java | 89 ++++++++----------- .../folder/FolderAnimationManager.java | 12 ++- .../android/launcher3/folder/FolderIcon.java | 14 +-- .../launcher3/folder/FolderPagedView.java | 5 +- .../launcher3/views/ActivityContext.java | 25 +++++- 7 files changed, 109 insertions(+), 77 deletions(-) diff --git a/src/com/android/launcher3/BaseActivity.java b/src/com/android/launcher3/BaseActivity.java index 8a03facbf2..062ab7112f 100644 --- a/src/com/android/launcher3/BaseActivity.java +++ b/src/com/android/launcher3/BaseActivity.java @@ -31,7 +31,6 @@ import android.graphics.Rect; import android.os.Bundle; import android.os.UserHandle; import android.util.Log; -import android.view.ContextThemeWrapper; import androidx.annotation.IntDef; @@ -333,7 +332,7 @@ public abstract class BaseActivity extends Activity implements ActivityContext { public static T fromContext(Context context) { if (context instanceof BaseActivity) { return (T) context; - } else if (context instanceof ContextThemeWrapper) { + } else if (context instanceof ContextWrapper) { return fromContext(((ContextWrapper) context).getBaseContext()); } else { throw new IllegalArgumentException("Cannot find BaseActivity in parent tree"); diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java index 51e7c7d175..1d6301ba25 100644 --- a/src/com/android/launcher3/Launcher.java +++ b/src/com/android/launcher3/Launcher.java @@ -74,6 +74,7 @@ import android.content.pm.PackageManager; import android.content.res.Configuration; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; +import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.os.CancellationSignal; @@ -1797,6 +1798,43 @@ public class Launcher extends StatefulActivity implements Launche return newFolder; } + @Override + public Rect getFolderBoundingBox() { + // We need to bound the folder to the currently visible workspace area + Rect folderBoundingBox = new Rect(); + getWorkspace().getPageAreaRelativeToDragLayer(folderBoundingBox); + return folderBoundingBox; + } + + @Override + public void updateOpenFolderPosition(int[] inOutPosition, Rect bounds, int width, int height) { + int left = inOutPosition[0]; + int top = inOutPosition[1]; + DeviceProfile grid = getDeviceProfile(); + int distFromEdgeOfScreen = getWorkspace().getPaddingLeft(); + if (grid.isPhone && (grid.availableWidthPx - width) < 4 * distFromEdgeOfScreen) { + // Center the folder if it is very close to being centered anyway, by virtue of + // filling the majority of the viewport. ie. remove it from the uncanny valley + // of centeredness. + left = (grid.availableWidthPx - width) / 2; + } else if (width >= bounds.width()) { + // If the folder doesn't fit within the bounds, center it about the desired bounds + left = bounds.left + (bounds.width() - width) / 2; + } + if (height >= bounds.height()) { + // Folder height is greater than page height, center on page + top = bounds.top + (bounds.height() - height) / 2; + } else { + // Folder height is less than page height, so bound it to the absolute open folder + // bounds if necessary + Rect folderBounds = grid.getAbsoluteOpenFolderBounds(); + left = Math.max(folderBounds.left, Math.min(left, folderBounds.right - width)); + top = Math.max(folderBounds.top, Math.min(top, folderBounds.bottom - height)); + } + inOutPosition[0] = left; + inOutPosition[1] = top; + } + /** * Unbinds the view for the specified item, and removes the item and all its children. * diff --git a/src/com/android/launcher3/folder/Folder.java b/src/com/android/launcher3/folder/Folder.java index 74d8dca98d..9efbc7dcab 100644 --- a/src/com/android/launcher3/folder/Folder.java +++ b/src/com/android/launcher3/folder/Folder.java @@ -46,6 +46,7 @@ import android.util.Log; import android.util.Pair; import android.view.FocusFinder; import android.view.KeyEvent; +import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewDebug; @@ -82,7 +83,6 @@ import com.android.launcher3.accessibility.FolderAccessibilityHelper; import com.android.launcher3.config.FeatureFlags; import com.android.launcher3.dragndrop.DragController; import com.android.launcher3.dragndrop.DragController.DragListener; -import com.android.launcher3.dragndrop.DragLayer; import com.android.launcher3.dragndrop.DragOptions; import com.android.launcher3.logger.LauncherAtom.FromState; import com.android.launcher3.logger.LauncherAtom.ToState; @@ -96,6 +96,8 @@ import com.android.launcher3.model.data.WorkspaceItemInfo; import com.android.launcher3.pageindicators.PageIndicatorDots; import com.android.launcher3.util.Executors; 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; @@ -165,7 +167,11 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo private AnimatorSet mCurrentAnimator; private boolean mIsAnimatingClosed = false; + // Folder can be displayed in Launcher's activity or a separate window (e.g. Taskbar). + // Anything specific to Launcher should use mLauncher, otherwise should use mActivityContext. protected final Launcher mLauncher; + protected final ActivityContext mActivityContext; + protected DragController mDragController; public FolderInfo mInfo; private CharSequence mFromTitle; @@ -228,6 +234,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo setAlwaysDrawnWithCacheEnabled(false); mLauncher = Launcher.getLauncher(context); + mActivityContext = ActivityContext.lookupContext(context); 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 @@ -457,9 +464,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo Collections.sort(children, ITEM_POS_COMPARATOR); updateItemLocationsInDatabaseBatch(true); - DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams(); + BaseDragLayer.LayoutParams lp = (BaseDragLayer.LayoutParams) getLayoutParams(); if (lp == null) { - lp = new DragLayer.LayoutParams(0, 0); + lp = new BaseDragLayer.LayoutParams(0, 0); lp.customPosition = true; setLayoutParams(lp); } @@ -513,13 +520,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo /** * Creates a new UserFolder, inflated from R.layout.user_folder. * - * @param launcher The main activity. + * @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") - static Folder fromXml(Launcher launcher) { - return (Folder) launcher.getLayoutInflater() + static Folder fromXml(T activityContext) { + return (Folder) LayoutInflater.from(activityContext).cloneInContext(activityContext) .inflate(R.layout.user_folder_icon_normalized, null); } @@ -597,7 +605,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo * is played. */ private void animateOpen(List items, int pageNo) { - Folder openFolder = getOpen(mLauncher); + Folder openFolder = getOpen(mActivityContext); if (openFolder != null && openFolder != this) { // Close any open folder before opening a folder. openFolder.close(true); @@ -610,7 +618,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo mIsOpen = true; - DragLayer dragLayer = mLauncher.getDragLayer(); + BaseDragLayer dragLayer = mActivityContext.getDragLayer(); // Just verify that the folder hasn't already been added to the DragLayer. // There was a one-off crash where the folder had a parent already. if (getParent() == null) { @@ -724,7 +732,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo // Notify the accessibility manager that this folder "window" has disappeared and no // longer occludes the workspace items - mLauncher.getDragLayer().sendAccessibilityEvent( + mActivityContext.getDragLayer().sendAccessibilityEvent( AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); } @@ -772,7 +780,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo private void closeComplete(boolean wasAnimated) { // TODO: Clear all active animations. - DragLayer parent = (DragLayer) getParent(); + BaseDragLayer parent = (BaseDragLayer) getParent(); if (parent != null) { parent.removeView(this); } @@ -1011,7 +1019,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo private void updateItemLocationsInDatabaseBatch(boolean isBind) { FolderGridOrganizer verifier = new FolderGridOrganizer( - mLauncher.getDeviceProfile().inv).setFolderInfo(mInfo); + mActivityContext.getDeviceProfile().inv).setFolderInfo(mInfo); ArrayList items = new ArrayList<>(); int total = mInfo.contents.size(); @@ -1048,10 +1056,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } private void centerAboutIcon() { - DeviceProfile grid = mLauncher.getDeviceProfile(); - - DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams(); - DragLayer parent = mLauncher.getDragLayer(); + BaseDragLayer.LayoutParams lp = (BaseDragLayer.LayoutParams) getLayoutParams(); + BaseDragLayer parent = mActivityContext.getDragLayer(); int width = getFolderWidth(); int height = getFolderHeight(); @@ -1061,38 +1067,13 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo int centeredLeft = centerX - width / 2; int centeredTop = centerY - height / 2; - // We need to bound the folder to the currently visible workspace area - if (mLauncher.getStateManager().getState().overviewUi) { - parent.getDescendantRectRelativeToSelf(mLauncher.getOverviewPanel(), sTempRect); - } else { - mLauncher.getWorkspace().getPageAreaRelativeToDragLayer(sTempRect); - } - int left = Math.min(Math.max(sTempRect.left, centeredLeft), - sTempRect.right- width); - int top = Math.min(Math.max(sTempRect.top, centeredTop), - sTempRect.bottom - height); - - int distFromEdgeOfScreen = mLauncher.getWorkspace().getPaddingLeft() + getPaddingLeft(); - - if (grid.isPhone && (grid.availableWidthPx - width) < 4 * distFromEdgeOfScreen) { - // Center the folder if it is very close to being centered anyway, by virtue of - // filling the majority of the viewport. ie. remove it from the uncanny valley - // of centeredness. - left = (grid.availableWidthPx - width) / 2; - } else if (width >= sTempRect.width()) { - // If the folder doesn't fit within the bounds, center it about the desired bounds - left = sTempRect.left + (sTempRect.width() - width) / 2; - } - if (height >= sTempRect.height()) { - // Folder height is greater than page height, center on page - top = sTempRect.top + (sTempRect.height() - height) / 2; - } else { - // Folder height is less than page height, so bound it to the absolute open folder - // bounds if necessary - Rect folderBounds = grid.getAbsoluteOpenFolderBounds(); - left = Math.max(folderBounds.left, Math.min(left, folderBounds.right - width)); - top = Math.max(folderBounds.top, Math.min(top, folderBounds.bottom - height)); - } + 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}; + mActivityContext.updateOpenFolderPosition(inOutPosition, sTempRect, width, height); + left = inOutPosition[0]; + top = inOutPosition[1]; int folderPivotX = width / 2 + (centeredLeft - left); int folderPivotY = height / 2 + (centeredTop - top); @@ -1106,7 +1087,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo } protected int getContentAreaHeight() { - DeviceProfile grid = mLauncher.getDeviceProfile(); + DeviceProfile grid = mActivityContext.getDeviceProfile(); int maxContentAreaHeight = grid.availableHeightPx - grid.getTotalWorkspacePadding().y - mFooterHeight; int height = Math.min(maxContentAreaHeight, @@ -1384,7 +1365,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo @Override public void onAdd(WorkspaceItemInfo item, int rank) { FolderGridOrganizer verifier = new FolderGridOrganizer( - mLauncher.getDeviceProfile().inv).setFolderInfo(mInfo); + mActivityContext.getDeviceProfile().inv).setFolderInfo(mInfo); verifier.updateRankAndPos(item, rank); mLauncher.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0, item.cellX, item.cellY); @@ -1591,8 +1572,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo /** * Returns a folder which is already open or null */ - public static Folder getOpen(Launcher launcher) { - return getOpenView(launcher, TYPE_FOLDER); + public static Folder getOpen(ActivityContext activityContext) { + return getOpenView(activityContext, TYPE_FOLDER); } /** @@ -1611,7 +1592,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo @Override public boolean onControllerInterceptTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { - DragLayer dl = mLauncher.getDragLayer(); + BaseDragLayer dl = (BaseDragLayer) getParent(); if (isEditingName()) { if (!dl.isEventOverView(mFolderName, ev)) { @@ -1663,9 +1644,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo /** Returns the height of the current folder's bottom edge from the bottom of the screen. */ private int getHeightFromBottom() { - DragLayer.LayoutParams layoutParams = (DragLayer.LayoutParams) getLayoutParams(); + BaseDragLayer.LayoutParams layoutParams = (BaseDragLayer.LayoutParams) getLayoutParams(); int folderBottomPx = layoutParams.y + layoutParams.height; - int windowBottomPx = mLauncher.getDeviceProfile().heightPx; + int windowBottomPx = mActivityContext.getDeviceProfile().heightPx; return windowBottomPx - folderBottomPx; } diff --git a/src/com/android/launcher3/folder/FolderAnimationManager.java b/src/com/android/launcher3/folder/FolderAnimationManager.java index 3d72b49b44..1cac31eb18 100644 --- a/src/com/android/launcher3/folder/FolderAnimationManager.java +++ b/src/com/android/launcher3/folder/FolderAnimationManager.java @@ -39,14 +39,13 @@ import androidx.core.graphics.ColorUtils; import com.android.launcher3.BubbleTextView; import com.android.launcher3.CellLayout; -import com.android.launcher3.Launcher; import com.android.launcher3.R; import com.android.launcher3.ResourceUtils; import com.android.launcher3.ShortcutAndWidgetContainer; import com.android.launcher3.Utilities; import com.android.launcher3.anim.PropertyResetListener; -import com.android.launcher3.dragndrop.DragLayer; import com.android.launcher3.util.Themes; +import com.android.launcher3.views.BaseDragLayer; import java.util.List; @@ -69,7 +68,6 @@ public class FolderAnimationManager { private PreviewBackground mPreviewBackground; private Context mContext; - private Launcher mLauncher; private final boolean mIsOpening; @@ -92,8 +90,7 @@ public class FolderAnimationManager { mPreviewBackground = mFolderIcon.mBackground; mContext = folder.getContext(); - mLauncher = folder.mLauncher; - mPreviewVerifier = new FolderGridOrganizer(mLauncher.getDeviceProfile().inv); + mPreviewVerifier = new FolderGridOrganizer(folder.mActivityContext.getDeviceProfile().inv); mIsOpening = isOpening; @@ -114,14 +111,15 @@ public class FolderAnimationManager { * Prepares the Folder for animating between open / closed states. */ public AnimatorSet getAnimator() { - final DragLayer.LayoutParams lp = (DragLayer.LayoutParams) mFolder.getLayoutParams(); + final BaseDragLayer.LayoutParams lp = + (BaseDragLayer.LayoutParams) mFolder.getLayoutParams(); mFolderIcon.getPreviewItemManager().recomputePreviewDrawingParams(); ClippedFolderIconLayoutRule rule = mFolderIcon.getLayoutRule(); final List itemsInPreview = getPreviewIconsOnPage(0); // Match position of the FolderIcon final Rect folderIconPos = new Rect(); - float scaleRelativeToDragLayer = mLauncher.getDragLayer() + float scaleRelativeToDragLayer = mFolder.mActivityContext.getDragLayer() .getDescendantRectRelativeToSelf(mFolderIcon, folderIconPos); int scaledRadius = mPreviewBackground.getScaledRadius(); float initialSize = (scaledRadius * 2) * scaleRelativeToDragLayer; diff --git a/src/com/android/launcher3/folder/FolderIcon.java b/src/com/android/launcher3/folder/FolderIcon.java index 6477de3757..65a4fba63c 100644 --- a/src/com/android/launcher3/folder/FolderIcon.java +++ b/src/com/android/launcher3/folder/FolderIcon.java @@ -166,19 +166,19 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel mDotParams = new DotRenderer.DrawParams(); } - public static FolderIcon inflateFolderAndIcon(int resId, Launcher launcher, ViewGroup group, - FolderInfo folderInfo) { - Folder folder = Folder.fromXml(launcher); - folder.setDragController(launcher.getDragController()); + public static FolderIcon inflateFolderAndIcon(int resId, + T activityContext, ViewGroup group, FolderInfo folderInfo) { + Folder folder = Folder.fromXml(activityContext); + folder.setDragController(folder.mLauncher.getDragController()); - FolderIcon icon = inflateIcon(resId, launcher, group, folderInfo); + FolderIcon icon = inflateIcon(resId, activityContext, group, folderInfo); folder.setFolderIcon(icon); folder.bind(folderInfo); icon.setFolder(folder); - icon.setOnFocusChangeListener(launcher.getFocusHandler()); + icon.setOnFocusChangeListener(folder.mLauncher.getFocusHandler()); icon.mBackground.paddingY = icon.isInHotseat() - ? 0 : launcher.getDeviceProfile().cellYPaddingPx; + ? 0 : activityContext.getDeviceProfile().cellYPaddingPx; return icon; } diff --git a/src/com/android/launcher3/folder/FolderPagedView.java b/src/com/android/launcher3/folder/FolderPagedView.java index df3e92cf1e..0235dfac2f 100644 --- a/src/com/android/launcher3/folder/FolderPagedView.java +++ b/src/com/android/launcher3/folder/FolderPagedView.java @@ -36,7 +36,6 @@ import com.android.launcher3.BubbleTextView; import com.android.launcher3.CellLayout; import com.android.launcher3.DeviceProfile; import com.android.launcher3.InvariantDeviceProfile; -import com.android.launcher3.Launcher; import com.android.launcher3.LauncherAppState; import com.android.launcher3.PagedView; import com.android.launcher3.R; @@ -230,7 +229,7 @@ public class FolderPagedView extends PagedView { } private CellLayout createAndAddNewPage() { - DeviceProfile grid = Launcher.getLauncher(getContext()).getDeviceProfile(); + DeviceProfile grid = mFolder.mActivityContext.getDeviceProfile(); CellLayout page = mViewCache.getView(R.layout.folder_page, getContext(), this); page.setCellDimensions(grid.folderCellWidthPx, grid.folderCellHeightPx); page.getShortcutsAndWidgets().setMotionEventSplittingEnabled(false); @@ -624,7 +623,7 @@ public class FolderPagedView extends PagedView { @Override protected boolean canScroll(float absVScroll, float absHScroll) { - return AbstractFloatingView.getTopOpenViewWithType(mFolder.mLauncher, + return AbstractFloatingView.getTopOpenViewWithType(mFolder.mActivityContext, TYPE_ALL & ~TYPE_FOLDER) == null; } diff --git a/src/com/android/launcher3/views/ActivityContext.java b/src/com/android/launcher3/views/ActivityContext.java index ae459e1847..505c6cea42 100644 --- a/src/com/android/launcher3/views/ActivityContext.java +++ b/src/com/android/launcher3/views/ActivityContext.java @@ -17,7 +17,7 @@ package com.android.launcher3.views; import android.content.Context; import android.content.ContextWrapper; -import android.view.ContextThemeWrapper; +import android.graphics.Rect; import android.view.View.AccessibilityDelegate; import com.android.launcher3.DeviceProfile; @@ -49,6 +49,23 @@ public interface ActivityContext { return null; } + default Rect getFolderBoundingBox() { + return getDeviceProfile().getAbsoluteOpenFolderBounds(); + } + + /** + * After calling {@link #getFolderBoundingBox()}, we calculate a (left, top) position for a + * Folder of size width x height to be within those bounds. However, the chosen position may + * not be visually ideal (e.g. uncanny valley of centeredness), so here's a chance to update it. + * @param inOutPosition A 2-size array where the first element is the left position of the open + * folder and the second element is the top position. Should be updated in place if desired. + * @param bounds The bounds that the open folder should fit inside. + * @param width The width of the open folder. + * @param height The height of the open folder. + */ + default void updateOpenFolderPosition(int[] inOutPosition, Rect bounds, int width, int height) { + } + /** * The root view to support drag-and-drop and popup support. */ @@ -56,10 +73,10 @@ public interface ActivityContext { DeviceProfile getDeviceProfile(); - static ActivityContext lookupContext(Context context) { + static T lookupContext(Context context) { if (context instanceof ActivityContext) { - return (ActivityContext) context; - } else if (context instanceof ContextThemeWrapper) { + return (T) context; + } else if (context instanceof ContextWrapper) { return lookupContext(((ContextWrapper) context).getBaseContext()); } else { throw new IllegalArgumentException("Cannot find ActivityContext in parent tree"); From 7ba547cd2dfa8b05905fde8b77ec491cd0bc8dd1 Mon Sep 17 00:00:00 2001 From: Tony Wickham Date: Tue, 2 Feb 2021 17:12:08 -0800 Subject: [PATCH 2/6] Folder support in Taskbar - Add TaskbarActivityContext which allows shared Launcher elements to "just work" using existing generic ActivityContext. - TaskbarContainerView extends BaseDragLayer. - Inflate FolderIcon and Folder using TaskbarActivityContext to be shown in TaskbarContainerView. - Use TaskbarActivityContext's DeviceProfile to determine icon size instead of overriding in styles. This also ensures that normal BubbleTextView icons have the same size as FolderIcons. Test: Place a folder in home screen hotseat, ensure it shows up in taskbar and can be opened, and that apps inside it can be launched or dragged. Bug: 171917176 Change-Id: Ic25d2f84bcd7e3399c88989305ea565497c030d9 --- quickstep/res/values/dimens.xml | 1 + quickstep/res/values/styles.xml | 1 - .../launcher3/BaseQuickstepLauncher.java | 10 +-- .../taskbar/TaskbarActivityContext.java | 78 +++++++++++++++++++ .../taskbar/TaskbarContainerView.java | 64 ++++++++++++++- .../launcher3/taskbar/TaskbarController.java | 60 +++++++++++++- .../launcher3/taskbar/TaskbarView.java | 49 +++++++++--- src/com/android/launcher3/BubbleTextView.java | 2 +- src/com/android/launcher3/DeviceProfile.java | 2 +- src/com/android/launcher3/folder/Folder.java | 5 ++ .../android/launcher3/folder/FolderIcon.java | 6 ++ .../launcher3/views/BaseDragLayer.java | 12 ++- 12 files changed, 265 insertions(+), 25 deletions(-) create mode 100644 quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java diff --git a/quickstep/res/values/dimens.xml b/quickstep/res/values/dimens.xml index 68c3851bf9..a0e87cfcbc 100644 --- a/quickstep/res/values/dimens.xml +++ b/quickstep/res/values/dimens.xml @@ -130,4 +130,5 @@ 14dp 1dp 24dp + 16dp diff --git a/quickstep/res/values/styles.xml b/quickstep/res/values/styles.xml index 5a353f0a59..df089f6738 100644 --- a/quickstep/res/values/styles.xml +++ b/quickstep/res/values/styles.xml @@ -89,6 +89,5 @@ \ No newline at end of file diff --git a/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java b/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java index edcd0a203a..d1fa2fd3ef 100644 --- a/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java +++ b/quickstep/src/com/android/launcher3/BaseQuickstepLauncher.java @@ -30,7 +30,6 @@ import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.os.CancellationSignal; -import android.view.LayoutInflater; import android.view.View; import androidx.annotation.Nullable; @@ -43,7 +42,7 @@ import com.android.launcher3.proxy.StartActivityParams; import com.android.launcher3.statehandlers.BackButtonAlphaHandler; import com.android.launcher3.statehandlers.DepthController; import com.android.launcher3.statemanager.StateManager.StateHandler; -import com.android.launcher3.taskbar.TaskbarContainerView; +import com.android.launcher3.taskbar.TaskbarActivityContext; import com.android.launcher3.taskbar.TaskbarController; import com.android.launcher3.taskbar.TaskbarStateHandler; import com.android.launcher3.uioverrides.RecentsViewStateController; @@ -207,6 +206,7 @@ public abstract class BaseQuickstepLauncher extends Launcher mActionsView.updateVerticalMargin(SysUINavigationMode.getMode(this)); addTaskbarIfNecessary(); + addOnDeviceProfileChangeListener(newDp -> addTaskbarIfNecessary()); } @Override @@ -223,9 +223,9 @@ public abstract class BaseQuickstepLauncher extends Launcher mTaskbarController = null; } if (FeatureFlags.ENABLE_TASKBAR.get() && mDeviceProfile.isTablet) { - TaskbarContainerView taskbarContainer = (TaskbarContainerView) LayoutInflater.from(this) - .inflate(R.layout.taskbar, null, false); - mTaskbarController = new TaskbarController(this, taskbarContainer); + TaskbarActivityContext taskbarActivityContext = new TaskbarActivityContext(this); + mTaskbarController = new TaskbarController(this, + taskbarActivityContext.getTaskbarContainerView()); mTaskbarController.init(); } } diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java new file mode 100644 index 0000000000..06372fe22f --- /dev/null +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarActivityContext.java @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.launcher3.taskbar; + +import android.content.ContextWrapper; +import android.graphics.Rect; +import android.view.LayoutInflater; + +import com.android.launcher3.BaseQuickstepLauncher; +import com.android.launcher3.DeviceProfile; +import com.android.launcher3.R; +import com.android.launcher3.views.ActivityContext; +import com.android.launcher3.views.BaseDragLayer; + +/** + * The {@link ActivityContext} with which we inflate Taskbar-related Views. This allows UI elements + * that are used by both Launcher and Taskbar (such as Folder) to reference a generic + * ActivityContext and BaseDragLayer instead of the Launcher activity and its DragLayer. + */ +public class TaskbarActivityContext extends ContextWrapper implements ActivityContext { + + private final DeviceProfile mDeviceProfile; + private final LayoutInflater mLayoutInflater; + private final TaskbarContainerView mTaskbarContainerView; + + public TaskbarActivityContext(BaseQuickstepLauncher launcher) { + super(launcher); + mDeviceProfile = launcher.getDeviceProfile().copy(this); + float taskbarIconSize = getResources().getDimension(R.dimen.taskbar_icon_size); + float iconScale = taskbarIconSize / mDeviceProfile.iconSizePx; + mDeviceProfile.updateIconSize(iconScale, getResources()); + + mLayoutInflater = LayoutInflater.from(this).cloneInContext(this); + + mTaskbarContainerView = (TaskbarContainerView) mLayoutInflater + .inflate(R.layout.taskbar, null, false); + } + + public TaskbarContainerView getTaskbarContainerView() { + return mTaskbarContainerView; + } + + /** + * @return A LayoutInflater to use in this Context. Views inflated with this LayoutInflater will + * be able to access this TaskbarActivityContext via ActivityContext.lookupContext(). + */ + public LayoutInflater getLayoutInflater() { + return mLayoutInflater; + } + + @Override + public BaseDragLayer getDragLayer() { + return mTaskbarContainerView; + } + + @Override + public DeviceProfile getDeviceProfile() { + return mDeviceProfile; + } + + @Override + public Rect getFolderBoundingBox() { + return mTaskbarContainerView.getFolderBoundingBox(); + } +} diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarContainerView.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarContainerView.java index 3b361c4a38..ddd0d15442 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarContainerView.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarContainerView.java @@ -19,19 +19,29 @@ import static com.android.systemui.shared.system.ViewTreeObserverWrapper.InsetsI import static com.android.systemui.shared.system.ViewTreeObserverWrapper.InsetsInfo.TOUCHABLE_INSETS_REGION; import android.content.Context; +import android.graphics.Rect; import android.util.AttributeSet; -import android.widget.FrameLayout; +import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import com.android.launcher3.R; import com.android.launcher3.anim.AlphaUpdateListener; +import com.android.launcher3.util.TouchController; +import com.android.launcher3.views.BaseDragLayer; import com.android.systemui.shared.system.ViewTreeObserverWrapper; /** * Top-level ViewGroup that hosts the TaskbarView as well as Views created by it such as Folder. */ -public class TaskbarContainerView extends FrameLayout { +public class TaskbarContainerView extends BaseDragLayer { + + private final int[] mTempLoc = new int[2]; + private final int mFolderMargin; + + // Initialized in TaskbarController constructor. + private TaskbarController.TaskbarContainerViewCallbacks mControllerCallbacks; // Initialized in init. private TaskbarView mTaskbarView; @@ -52,12 +62,23 @@ public class TaskbarContainerView extends FrameLayout { public TaskbarContainerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); + super(context, attrs, 1 /* alphaChannelCount */); + mFolderMargin = getResources().getDimensionPixelSize(R.dimen.taskbar_folder_margin); + } + + protected void construct(TaskbarController.TaskbarContainerViewCallbacks callbacks) { + mControllerCallbacks = callbacks; } protected void init(TaskbarView taskbarView) { mTaskbarView = taskbarView; mTaskbarInsetsComputer = createTaskbarInsetsComputer(); + recreateControllers(); + } + + @Override + public void recreateControllers() { + mControllers = new TouchController[0]; } private ViewTreeObserverWrapper.OnComputeInsetsListener createTaskbarInsetsComputer() { @@ -70,6 +91,17 @@ public class TaskbarContainerView extends FrameLayout { // We're visible again, accept touches anywhere in our bounds. insetsInfo.setTouchableInsets(TOUCHABLE_INSETS_FRAME); } + + // TaskbarContainerView provides insets to other apps based on contentInsets. These + // insets should stay consistent even if we expand TaskbarContainerView's bounds, e.g. + // to show a floating view like Folder. Thus, we set the contentInsets to be where + // mTaskbarView is, since its position never changes and insets rather than overlays. + int[] loc = mTempLoc; + mTaskbarView.getLocationInWindow(loc); + insetsInfo.contentInsets.left = loc[0]; + insetsInfo.contentInsets.top = loc[1]; + insetsInfo.contentInsets.right = getWidth() - (loc[0] + mTaskbarView.getWidth()); + insetsInfo.contentInsets.bottom = getHeight() - (loc[1] + mTaskbarView.getHeight()); }; } @@ -91,4 +123,30 @@ public class TaskbarContainerView extends FrameLayout { cleanup(); } + + @Override + protected boolean canFindActiveController() { + // Unlike super class, we want to be able to find controllers when touches occur in the + // gesture area. For example, this allows Folder to close itself when touching the Taskbar. + return true; + } + + @Override + public void onViewRemoved(View child) { + super.onViewRemoved(child); + mControllerCallbacks.onViewRemoved(); + } + + /** + * @return Bounds (in our coordinates) where an opened Folder can display. + */ + protected Rect getFolderBoundingBox() { + Rect boundingBox = new Rect(0, 0, getWidth(), getHeight() - mTaskbarView.getHeight()); + boundingBox.inset(mFolderMargin, mFolderMargin); + return boundingBox; + } + + protected TaskbarActivityContext getTaskbarActivityContext() { + return mActivity; + } } diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarController.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarController.java index 260428dbc2..ab05fbf036 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarController.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarController.java @@ -34,11 +34,15 @@ import android.view.WindowManager; import androidx.annotation.Nullable; +import com.android.launcher3.AbstractFloatingView; import com.android.launcher3.BaseQuickstepLauncher; import com.android.launcher3.LauncherState; import com.android.launcher3.QuickstepAppTransitionManagerImpl; import com.android.launcher3.R; import com.android.launcher3.anim.PendingAnimation; +import com.android.launcher3.folder.Folder; +import com.android.launcher3.folder.FolderIcon; +import com.android.launcher3.model.data.FolderInfo; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.states.StateAnimationConfig; import com.android.launcher3.touch.ItemClickHandler; @@ -81,8 +85,9 @@ public class TaskbarController { TaskbarContainerView taskbarContainerView) { mLauncher = launcher; mTaskbarContainerView = taskbarContainerView; + mTaskbarContainerView.construct(createTaskbarContainerViewCallbacks()); mTaskbarView = mTaskbarContainerView.findViewById(R.id.taskbar_view); - mTaskbarView.setCallbacks(createTaskbarViewCallbacks()); + mTaskbarView.construct(createTaskbarViewCallbacks()); mWindowManager = mLauncher.getWindowManager(); mTaskbarSize = new Point(MATCH_PARENT, mLauncher.getResources().getDimensionPixelSize(R.dimen.taskbar_size)); @@ -110,6 +115,18 @@ public class TaskbarController { }; } + private TaskbarContainerViewCallbacks createTaskbarContainerViewCallbacks() { + return new TaskbarContainerViewCallbacks() { + @Override + public void onViewRemoved() { + if (mTaskbarContainerView.getChildCount() == 1) { + // Only TaskbarView remains. + setTaskbarWindowFullscreen(false); + } + } + }; + } + private TaskbarViewCallbacks createTaskbarViewCallbacks() { return new TaskbarViewCallbacks() { @Override @@ -120,9 +137,29 @@ public class TaskbarController { Task task = (Task) tag; ActivityManagerWrapper.getInstance().startActivityFromRecents(task.key, ActivityOptions.makeBasic()); + } else if (tag instanceof FolderInfo) { + FolderIcon folderIcon = (FolderIcon) view; + Folder folder = folderIcon.getFolder(); + + setTaskbarWindowFullscreen(true); + + mTaskbarContainerView.post(() -> { + folder.animateOpen(); + + folder.iterateOverItems((itemInfo, itemView) -> { + itemView.setOnClickListener(getItemOnClickListener()); + itemView.setOnLongClickListener(getItemOnLongClickListener()); + // To play haptic when dragging, like other Taskbar items do. + itemView.setHapticFeedbackEnabled(true); + return false; + }); + }); } else { ItemClickHandler.INSTANCE.onClick(view); } + + AbstractFloatingView.closeAllOpenViews( + mTaskbarContainerView.getTaskbarActivityContext()); }; } @@ -344,6 +381,20 @@ public class TaskbarController { return mTaskbarContainerView.getWindowId().equals(v.getWindowId()); } + /** + * Updates the TaskbarContainer to MATCH_PARENT vs original Taskbar size. + */ + private void setTaskbarWindowFullscreen(boolean fullscreen) { + if (fullscreen) { + mWindowLayoutParams.width = MATCH_PARENT; + mWindowLayoutParams.height = MATCH_PARENT; + } else { + mWindowLayoutParams.width = mTaskbarSize.x; + mWindowLayoutParams.height = mTaskbarSize.y; + } + mWindowManager.updateViewLayout(mTaskbarContainerView, mWindowLayoutParams); + } + /** * Contains methods that TaskbarStateHandler can call to interface with TaskbarController. */ @@ -360,6 +411,13 @@ public class TaskbarController { void updateTaskbarVisibilityAlpha(float alpha); } + /** + * Contains methods that TaskbarContainerView can call to interface with TaskbarController. + */ + protected interface TaskbarContainerViewCallbacks { + void onViewRemoved(); + } + /** * Contains methods that TaskbarView can call to interface with TaskbarController. */ diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java index d8f3bb595e..df77f8778e 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java @@ -22,7 +22,6 @@ import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.DragEvent; -import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; @@ -32,10 +31,14 @@ import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import com.android.launcher3.AbstractFloatingView; import com.android.launcher3.BubbleTextView; import com.android.launcher3.R; +import com.android.launcher3.folder.FolderIcon; +import com.android.launcher3.model.data.FolderInfo; import com.android.launcher3.model.data.ItemInfo; import com.android.launcher3.model.data.WorkspaceItemInfo; +import com.android.launcher3.views.ActivityContext; import com.android.systemui.shared.recents.model.Task; /** @@ -51,6 +54,9 @@ public class TaskbarView extends LinearLayout { private final RectF mDelegateSlopBounds = new RectF(); private final int[] mTempOutLocation = new int[2]; + // Initialized in TaskbarController constructor. + private TaskbarController.TaskbarViewCallbacks mControllerCallbacks; + // Initialized in init(). private int mHotseatStartIndex; private int mHotseatEndIndex; @@ -58,8 +64,6 @@ public class TaskbarView extends LinearLayout { private int mRecentsStartIndex; private int mRecentsEndIndex; - private TaskbarController.TaskbarViewCallbacks mControllerCallbacks; - // Delegate touches to the closest view if within mIconTouchSize. private boolean mDelegateTargeted; private View mDelegateView; @@ -90,7 +94,7 @@ public class TaskbarView extends LinearLayout { mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } - protected void setCallbacks(TaskbarController.TaskbarViewCallbacks taskbarViewCallbacks) { + protected void construct(TaskbarController.TaskbarViewCallbacks taskbarViewCallbacks) { mControllerCallbacks = taskbarViewCallbacks; } @@ -130,17 +134,37 @@ public class TaskbarView extends LinearLayout { // Replace any Hotseat views with the appropriate type if it's not already that type. final int expectedLayoutResId; + boolean isFolder = false; + boolean needsReinflate = false; if (hotseatItemInfo != null && hotseatItemInfo.isPredictedItem()) { expectedLayoutResId = R.layout.taskbar_predicted_app_icon; + } else if (hotseatItemInfo instanceof FolderInfo) { + expectedLayoutResId = R.layout.folder_icon; + isFolder = true; + // Unlike for BubbleTextView, we can't reapply a new FolderInfo after inflation, so + // if the info changes we need to reinflate. This should only happen if a new folder + // is dragged to the position that another folder previously existed. + needsReinflate = hotseatView != null && hotseatView.getTag() != hotseatItemInfo; } else { expectedLayoutResId = R.layout.taskbar_app_icon; } - if (hotseatView == null || hotseatView.getSourceLayoutResId() != expectedLayoutResId) { + if (hotseatView == null || hotseatView.getSourceLayoutResId() != expectedLayoutResId + || needsReinflate) { removeView(hotseatView); - BubbleTextView btv = (BubbleTextView) inflate(expectedLayoutResId); - LayoutParams lp = new LayoutParams(btv.getIconSize(), btv.getIconSize()); + TaskbarActivityContext activityContext = + ActivityContext.lookupContext(getContext()); + if (isFolder) { + FolderInfo folderInfo = (FolderInfo) hotseatItemInfo; + FolderIcon folderIcon = FolderIcon.inflateFolderAndIcon(expectedLayoutResId, + activityContext, this, folderInfo); + folderIcon.setTextVisible(false); + hotseatView = folderIcon; + } else { + hotseatView = inflate(expectedLayoutResId); + } + int iconSize = activityContext.getDeviceProfile().iconSizePx; + LayoutParams lp = new LayoutParams(iconSize, iconSize); lp.setMargins(mItemMarginLeftRight, 0, mItemMarginLeftRight, 0); - hotseatView = btv; addView(hotseatView, hotseatIndex, lp); } @@ -153,6 +177,11 @@ public class TaskbarView extends LinearLayout { hotseatView.setOnClickListener(mControllerCallbacks.getItemOnClickListener()); hotseatView.setOnLongClickListener( mControllerCallbacks.getItemOnLongClickListener()); + } else if (isFolder) { + hotseatView.setVisibility(VISIBLE); + hotseatView.setOnClickListener(mControllerCallbacks.getItemOnClickListener()); + hotseatView.setOnLongClickListener( + mControllerCallbacks.getItemOnLongClickListener()); } else { hotseatView.setVisibility(GONE); hotseatView.setOnClickListener(null); @@ -345,6 +374,7 @@ public class TaskbarView extends LinearLayout { switch (event.getAction()) { case DragEvent.ACTION_DRAG_STARTED: mIsDraggingItem = true; + AbstractFloatingView.closeAllOpenViews(ActivityContext.lookupContext(getContext())); return true; case DragEvent.ACTION_DRAG_ENDED: mIsDraggingItem = false; @@ -358,6 +388,7 @@ public class TaskbarView extends LinearLayout { } private View inflate(@LayoutRes int layoutResId) { - return LayoutInflater.from(getContext()).inflate(layoutResId, this, false); + TaskbarActivityContext taskbarActivityContext = ActivityContext.lookupContext(getContext()); + return taskbarActivityContext.getLayoutInflater().inflate(layoutResId, this, false); } } diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java index edc7e9bb8a..e5a4335dcd 100644 --- a/src/com/android/launcher3/BubbleTextView.java +++ b/src/com/android/launcher3/BubbleTextView.java @@ -505,7 +505,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver, * @param canvas The canvas to draw to. */ protected void drawDotIfNecessary(Canvas canvas) { - if (mDisplay == DISPLAY_TASKBAR) { + if (mActivity instanceof Launcher && ((Launcher) mActivity).isViewInTaskbar(this)) { // TODO: support notification dots in Taskbar return; } diff --git a/src/com/android/launcher3/DeviceProfile.java b/src/com/android/launcher3/DeviceProfile.java index 19915b7026..83a7d77601 100644 --- a/src/com/android/launcher3/DeviceProfile.java +++ b/src/com/android/launcher3/DeviceProfile.java @@ -375,7 +375,7 @@ public class DeviceProfile { * iconTextSizePx, iconDrawablePaddingPx, cellWidth/Height, allApps* variants, * hotseat sizes, workspaceSpringLoadedShrinkFactor, folderIconSizePx, and folderIconOffsetYPx. */ - private void updateIconSize(float scale, Resources res) { + public void updateIconSize(float scale, Resources res) { // Workspace final boolean isVerticalLayout = isVerticalBarLayout(); float invIconSizeDp = isVerticalLayout ? inv.landscapeIconSize : inv.iconSize; diff --git a/src/com/android/launcher3/folder/Folder.java b/src/com/android/launcher3/folder/Folder.java index 9efbc7dcab..504b29e75a 100644 --- a/src/com/android/launcher3/folder/Folder.java +++ b/src/com/android/launcher3/folder/Folder.java @@ -1616,6 +1616,11 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo return false; } + @Override + public boolean canInterceptEventsInSystemGestureRegion() { + return true; + } + /** * Alternative to using {@link #getClipToOutline()} as it only works with derivatives of * rounded rect. diff --git a/src/com/android/launcher3/folder/FolderIcon.java b/src/com/android/launcher3/folder/FolderIcon.java index 65a4fba63c..75d8f2296c 100644 --- a/src/com/android/launcher3/folder/FolderIcon.java +++ b/src/com/android/launcher3/folder/FolderIcon.java @@ -754,6 +754,9 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel } public void clearLeaveBehindIfExists() { + if (!(getLayoutParams() instanceof CellLayout.LayoutParams)) { + return; + } ((CellLayout.LayoutParams) getLayoutParams()).canReorder = true; if (isInHotseat()) { CellLayout cl = (CellLayout) getParent().getParent(); @@ -762,6 +765,9 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel } public void drawLeaveBehindIfExists() { + if (!(getLayoutParams() instanceof CellLayout.LayoutParams)) { + return; + } CellLayout.LayoutParams lp = (CellLayout.LayoutParams) getLayoutParams(); // While the folder is open, the position of the icon cannot change. lp.canReorder = false; diff --git a/src/com/android/launcher3/views/BaseDragLayer.java b/src/com/android/launcher3/views/BaseDragLayer.java index 15f7730fd7..1939d15776 100644 --- a/src/com/android/launcher3/views/BaseDragLayer.java +++ b/src/com/android/launcher3/views/BaseDragLayer.java @@ -206,15 +206,19 @@ public abstract class BaseDragLayer protected boolean findActiveController(MotionEvent ev) { mActiveController = null; - if ((mTouchDispatchState & (TOUCH_DISPATCHING_FROM_VIEW_GESTURE_REGION - | TOUCH_DISPATCHING_FROM_PROXY)) == 0) { - // Only look for controllers if we are not dispatching from gesture area and proxy is - // not active + if (canFindActiveController()) { mActiveController = findControllerToHandleTouch(ev); } return mActiveController != null; } + protected boolean canFindActiveController() { + // Only look for controllers if we are not dispatching from gesture area and proxy is + // not active + return (mTouchDispatchState & (TOUCH_DISPATCHING_FROM_VIEW_GESTURE_REGION + | TOUCH_DISPATCHING_FROM_PROXY)) == 0; + } + @Override public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { // Shortcuts can appear above folder From bb4de85c253baf31ff120e006941fc1cfe410047 Mon Sep 17 00:00:00 2001 From: Tony Wickham Date: Wed, 10 Feb 2021 12:35:28 -0800 Subject: [PATCH 3/6] Draw folder leave-behind when opening folder in taskbar Previously there was only support for CellLayout to draw the leave-behind. Added FolderIconParent interface so any parent can draw the leave-behind, and implement that by TaskbarView. Test: Open folder in Taskber, ensure leave-behind draws Bug: 171917176 Change-Id: I08d1d939a34f971f893994fe05cac972d165ef53 --- .../launcher3/taskbar/TaskbarView.java | 32 ++++++++++++++++- .../launcher3/ShortcutAndWidgetContainer.java | 23 +++++++++++- .../android/launcher3/folder/FolderIcon.java | 35 ++++++++++--------- 3 files changed, 72 insertions(+), 18 deletions(-) diff --git a/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java b/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java index df77f8778e..7a13b89d25 100644 --- a/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java +++ b/quickstep/src/com/android/launcher3/taskbar/TaskbarView.java @@ -17,6 +17,7 @@ package com.android.launcher3.taskbar; import android.content.Context; import android.content.res.Resources; +import android.graphics.Canvas; import android.graphics.RectF; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; @@ -44,7 +45,7 @@ import com.android.systemui.shared.recents.model.Task; /** * Hosts the Taskbar content such as Hotseat and Recent Apps. Drawn on top of other apps. */ -public class TaskbarView extends LinearLayout { +public class TaskbarView extends LinearLayout implements FolderIcon.FolderIconParent { private final ColorDrawable mBackgroundDrawable; private final int mItemMarginLeftRight; @@ -69,6 +70,8 @@ public class TaskbarView extends LinearLayout { private View mDelegateView; private boolean mIsDraggingItem; + // Only non-null when the corresponding Folder is open. + private @Nullable FolderIcon mLeaveBehindFolderIcon; public TaskbarView(@NonNull Context context) { this(context, null); @@ -387,6 +390,33 @@ public class TaskbarView extends LinearLayout { return mIsDraggingItem; } + // FolderIconParent implemented methods. + + @Override + public void drawFolderLeaveBehindForIcon(FolderIcon child) { + mLeaveBehindFolderIcon = child; + invalidate(); + } + + @Override + public void clearFolderLeaveBehind(FolderIcon child) { + mLeaveBehindFolderIcon = null; + invalidate(); + } + + // End FolderIconParent implemented methods. + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + if (mLeaveBehindFolderIcon != null) { + canvas.save(); + canvas.translate(mLeaveBehindFolderIcon.getLeft(), mLeaveBehindFolderIcon.getTop()); + mLeaveBehindFolderIcon.getFolderBackground().drawLeaveBehind(canvas); + canvas.restore(); + } + } + private View inflate(@LayoutRes int layoutResId) { TaskbarActivityContext taskbarActivityContext = ActivityContext.lookupContext(getContext()); return taskbarActivityContext.getLayoutInflater().inflate(layoutResId, this, false); diff --git a/src/com/android/launcher3/ShortcutAndWidgetContainer.java b/src/com/android/launcher3/ShortcutAndWidgetContainer.java index 1c5081cfca..eab8272431 100644 --- a/src/com/android/launcher3/ShortcutAndWidgetContainer.java +++ b/src/com/android/launcher3/ShortcutAndWidgetContainer.java @@ -26,10 +26,11 @@ import android.view.View; import android.view.ViewGroup; import com.android.launcher3.CellLayout.ContainerType; +import com.android.launcher3.folder.FolderIcon; import com.android.launcher3.views.ActivityContext; import com.android.launcher3.widget.LauncherAppWidgetHostView; -public class ShortcutAndWidgetContainer extends ViewGroup { +public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.FolderIconParent { static final String TAG = "ShortcutAndWidgetContainer"; // These are temporary variables to prevent having to allocate a new object just to @@ -228,4 +229,24 @@ public class ShortcutAndWidgetContainer extends ViewGroup { child.cancelLongPress(); } } + + @Override + public void drawFolderLeaveBehindForIcon(FolderIcon child) { + CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams(); + // While the folder is open, the position of the icon cannot change. + lp.canReorder = false; + if (mContainerType == CellLayout.HOTSEAT) { + CellLayout cl = (CellLayout) getParent(); + cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY); + } + } + + @Override + public void clearFolderLeaveBehind(FolderIcon child) { + ((CellLayout.LayoutParams) child.getLayoutParams()).canReorder = true; + if (mContainerType == CellLayout.HOTSEAT) { + CellLayout cl = (CellLayout) getParent(); + cl.clearFolderLeaveBehind(); + } + } } diff --git a/src/com/android/launcher3/folder/FolderIcon.java b/src/com/android/launcher3/folder/FolderIcon.java index 75d8f2296c..6b02021ed3 100644 --- a/src/com/android/launcher3/folder/FolderIcon.java +++ b/src/com/android/launcher3/folder/FolderIcon.java @@ -754,26 +754,14 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel } public void clearLeaveBehindIfExists() { - if (!(getLayoutParams() instanceof CellLayout.LayoutParams)) { - return; - } - ((CellLayout.LayoutParams) getLayoutParams()).canReorder = true; - if (isInHotseat()) { - CellLayout cl = (CellLayout) getParent().getParent(); - cl.clearFolderLeaveBehind(); + if (getParent() instanceof FolderIconParent) { + ((FolderIconParent) getParent()).clearFolderLeaveBehind(this); } } public void drawLeaveBehindIfExists() { - if (!(getLayoutParams() instanceof CellLayout.LayoutParams)) { - return; - } - CellLayout.LayoutParams lp = (CellLayout.LayoutParams) getLayoutParams(); - // While the folder is open, the position of the icon cannot change. - lp.canReorder = false; - if (isInHotseat()) { - CellLayout cl = (CellLayout) getParent().getParent(); - cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY); + if (getParent() instanceof FolderIconParent) { + ((FolderIconParent) getParent()).drawFolderLeaveBehindForIcon(this); } } @@ -842,4 +830,19 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel MAX_NUM_ITEMS_IN_PREVIEW); } } + + /** + * 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 + * 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. + */ + void clearFolderLeaveBehind(FolderIcon child); + } } From a9740ecc8f190af6829446d3c76f43f4188087f1 Mon Sep 17 00:00:00 2001 From: vadimt Date: Fri, 12 Feb 2021 10:08:25 -0800 Subject: [PATCH 4/6] Switching overlays more correctly Test: presubmit Bug: 180114721 Change-Id: I0d8d0c70ef34ec941e28704d06f9df5f17782155 --- .../src/com/android/quickstep/NavigationModeSwitchRule.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quickstep/tests/src/com/android/quickstep/NavigationModeSwitchRule.java b/quickstep/tests/src/com/android/quickstep/NavigationModeSwitchRule.java index 0f6671d18c..35383d2831 100644 --- a/quickstep/tests/src/com/android/quickstep/NavigationModeSwitchRule.java +++ b/quickstep/tests/src/com/android/quickstep/NavigationModeSwitchRule.java @@ -168,7 +168,7 @@ public class NavigationModeSwitchRule implements TestRule { Log.d(TAG, "setActiveOverlay: " + overlayPackage + "..."); UiDevice.getInstance(getInstrumentation()).executeShellCommand( - "cmd overlay enable-exclusive " + overlayPackage); + "cmd overlay enable-exclusive --category " + overlayPackage); if (currentSysUiNavigationMode() != expectedMode) { final CountDownLatch latch = new CountDownLatch(1); From e1a8440d78ad2437c5b69eb4df02f0a91cc4ff02 Mon Sep 17 00:00:00 2001 From: thiruram Date: Fri, 12 Feb 2021 16:02:39 -0800 Subject: [PATCH 5/6] Add @Nullable annotation to AllAppsStore.getApp. Test: Manual Bug: 180120291 Change-Id: I3f29d478e39b46e307f33f2f354720bc2915b550 --- src/com/android/launcher3/allapps/AllAppsStore.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/com/android/launcher3/allapps/AllAppsStore.java b/src/com/android/launcher3/allapps/AllAppsStore.java index 769cb5e31b..355ccadeba 100644 --- a/src/com/android/launcher3/allapps/AllAppsStore.java +++ b/src/com/android/launcher3/allapps/AllAppsStore.java @@ -21,6 +21,8 @@ import static com.android.launcher3.model.data.AppInfo.EMPTY_ARRAY; import android.view.View; import android.view.ViewGroup; +import androidx.annotation.Nullable; + import com.android.launcher3.BubbleTextView; import com.android.launcher3.model.data.AppInfo; import com.android.launcher3.model.data.ItemInfo; @@ -78,6 +80,11 @@ public class AllAppsStore { return (mModelFlags & mask) != 0; } + /** + * Returns {@link AppInfo} if any apps matches with provided {@link ComponentKey}, otherwise + * null. + */ + @Nullable public AppInfo getApp(ComponentKey key) { mTempInfo.componentName = key.componentName; mTempInfo.user = key.user; From a34af18b0efd6bfc6b1aa0f0c3b63d6751b282fc Mon Sep 17 00:00:00 2001 From: Vinit Nayak Date: Thu, 11 Feb 2021 15:48:54 -0800 Subject: [PATCH 6/6] Update System settings content observer to cache values. Existing ContentObserver will cache values and overwrite them when the value itself is modified or caller force updates. Bug: 149571513 Test: Wrote unit tests, mostly for caching logic. Not meant to test ContentObserver contract for registering an observer. Change-Id: I12835f6c2be27ce17f65a55c51c4ef85c63b4487 --- Android.bp | 1 - .../RecentsAnimationDeviceState.java | 47 ++--- .../logging/SettingsChangeLogger.java | 13 +- .../quickstep/util/RecentsOrientedState.java | 26 +-- .../launcher3/util/SettingsCacheTest.java | 115 +++++++++++ .../android/launcher3/LauncherAppState.java | 21 +- .../notification/NotificationListener.java | 19 +- .../settings/NotificationDotsPreference.java | 4 +- .../launcher3/settings/SettingsActivity.java | 35 ++-- .../util/SecureSettingsObserver.java | 104 ---------- .../android/launcher3/util/SettingsCache.java | 179 ++++++++++++++++++ tests/Android.mk | 1 - 12 files changed, 379 insertions(+), 186 deletions(-) create mode 100644 robolectric_tests/src/com/android/launcher3/util/SettingsCacheTest.java delete mode 100644 src/com/android/launcher3/util/SecureSettingsObserver.java create mode 100644 src/com/android/launcher3/util/SettingsCache.java diff --git a/Android.bp b/Android.bp index a720658f9f..9d675a4b3e 100644 --- a/Android.bp +++ b/Android.bp @@ -24,7 +24,6 @@ android_library { ], srcs: [ "tests/tapl/**/*.java", - "src/com/android/launcher3/util/SecureSettingsObserver.java", "src/com/android/launcher3/ResourceUtils.java", "src/com/android/launcher3/testing/TestProtocol.java", ], diff --git a/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java b/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java index 4301377808..f99b7e6af4 100644 --- a/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java +++ b/quickstep/src/com/android/quickstep/RecentsAnimationDeviceState.java @@ -17,14 +17,16 @@ package com.android.quickstep; import static android.content.Intent.ACTION_USER_UNLOCKED; +import static com.android.launcher3.util.SettingsCache.ONE_HANDED_ENABLED; +import static com.android.launcher3.util.SettingsCache.ONE_HANDED_SWIPE_BOTTOM_TO_NOTIFICATION_ENABLED; import static com.android.launcher3.util.DisplayController.DisplayHolder.CHANGE_ALL; import static com.android.launcher3.util.DisplayController.DisplayHolder.CHANGE_FRAME_DELAY; import static com.android.quickstep.SysUINavigationMode.Mode.NO_BUTTON; import static com.android.quickstep.SysUINavigationMode.Mode.THREE_BUTTONS; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_A11Y_BUTTON_CLICKABLE; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_A11Y_BUTTON_LONG_CLICKABLE; -import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_ALLOW_GESTURE_IGNORING_BAR_VISIBILITY; +import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_ASSIST_GESTURE_CONSTRAINED; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_BUBBLES_EXPANDED; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_GLOBAL_ACTIONS_SHOWING; import static com.android.systemui.shared.system.QuickStepContract.SYSUI_STATE_HOME_DISABLED; @@ -44,6 +46,7 @@ import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.graphics.Region; +import android.net.Uri; import android.os.Process; import android.os.SystemProperties; import android.os.UserManager; @@ -57,11 +60,11 @@ import androidx.annotation.BinderThread; import com.android.launcher3.R; import com.android.launcher3.Utilities; +import com.android.launcher3.util.SettingsCache; import com.android.launcher3.util.DisplayController; import com.android.launcher3.util.DisplayController.DisplayHolder; import com.android.launcher3.util.DisplayController.DisplayInfoChangeListener; import com.android.launcher3.util.DisplayController.Info; -import com.android.launcher3.util.SecureSettingsObserver; import com.android.quickstep.SysUINavigationMode.NavigationModeChangeListener; import com.android.quickstep.SysUINavigationMode.OneHandedModeChangeListener; import com.android.quickstep.util.NavBarPosition; @@ -177,33 +180,33 @@ public class RecentsAnimationDeviceState implements } } + SettingsCache settingsCache = SettingsCache.INSTANCE.get(mContext); if (mIsOneHandedModeSupported) { - SecureSettingsObserver oneHandedEnabledObserver = - SecureSettingsObserver.newOneHandedSettingsObserver( - mContext, enabled -> mIsOneHandedModeEnabled = enabled); - oneHandedEnabledObserver.register(); - oneHandedEnabledObserver.dispatchOnChange(); - runOnDestroy(oneHandedEnabledObserver::unregister); + Uri oneHandedUri = Settings.Secure.getUriFor(ONE_HANDED_ENABLED); + SettingsCache.OnChangeListener onChangeListener = + enabled -> mIsOneHandedModeEnabled = enabled; + settingsCache.register(oneHandedUri, onChangeListener); + settingsCache.dispatchOnChange(oneHandedUri); + runOnDestroy(() -> settingsCache.unregister(oneHandedUri, onChangeListener)); } else { mIsOneHandedModeEnabled = false; } - SecureSettingsObserver swipeBottomEnabledObserver = - SecureSettingsObserver.newSwipeToNotificationSettingsObserver( - mContext, enabled -> mIsSwipeToNotificationEnabled = enabled); - swipeBottomEnabledObserver.register(); - swipeBottomEnabledObserver.dispatchOnChange(); - runOnDestroy(swipeBottomEnabledObserver::unregister); - SecureSettingsObserver userSetupObserver = new SecureSettingsObserver( - context.getContentResolver(), - e -> mIsUserSetupComplete = e, - Settings.Secure.USER_SETUP_COMPLETE, - 0); - mIsUserSetupComplete = userSetupObserver.getValue(); + Uri swipeBottomNotificationUri = + Settings.Secure.getUriFor(ONE_HANDED_SWIPE_BOTTOM_TO_NOTIFICATION_ENABLED); + SettingsCache.OnChangeListener onChangeListener = + enabled -> mIsSwipeToNotificationEnabled = enabled; + settingsCache.register(swipeBottomNotificationUri, onChangeListener); + settingsCache.dispatchOnChange(swipeBottomNotificationUri); + runOnDestroy(() -> settingsCache.unregister(swipeBottomNotificationUri, onChangeListener)); + + Uri setupCompleteUri = Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE); + mIsUserSetupComplete = settingsCache.getValue(setupCompleteUri, 0); if (!mIsUserSetupComplete) { - userSetupObserver.register(); - runOnDestroy(userSetupObserver::unregister); + SettingsCache.OnChangeListener userSetupChangeListener = e -> mIsUserSetupComplete = e; + settingsCache.register(setupCompleteUri, userSetupChangeListener); + runOnDestroy(() -> settingsCache.unregister(setupCompleteUri, userSetupChangeListener)); } } diff --git a/quickstep/src/com/android/quickstep/logging/SettingsChangeLogger.java b/quickstep/src/com/android/quickstep/logging/SettingsChangeLogger.java index 3157865f78..f336bf5260 100644 --- a/quickstep/src/com/android/quickstep/logging/SettingsChangeLogger.java +++ b/quickstep/src/com/android/quickstep/logging/SettingsChangeLogger.java @@ -28,7 +28,7 @@ import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCH import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_NOTIFICATION_DOT_DISABLED; import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_NOTIFICATION_DOT_ENABLED; import static com.android.launcher3.model.QuickstepModelDelegate.LAST_PREDICTION_ENABLED_STATE; -import static com.android.launcher3.util.SecureSettingsObserver.newNotificationSettingsObserver; +import static com.android.launcher3.util.SettingsCache.NOTIFICATION_BADGING_URI; import android.content.Context; import android.content.SharedPreferences; @@ -43,7 +43,7 @@ import com.android.launcher3.R; import com.android.launcher3.logging.InstanceIdSequence; import com.android.launcher3.logging.StatsLogManager; import com.android.launcher3.logging.StatsLogManager.StatsLogger; -import com.android.launcher3.util.SecureSettingsObserver; +import com.android.launcher3.util.SettingsCache; import com.android.quickstep.SysUINavigationMode; import com.android.quickstep.SysUINavigationMode.Mode; import com.android.quickstep.SysUINavigationMode.NavigationModeChangeListener; @@ -77,11 +77,10 @@ public class SettingsChangeLogger implements getPrefs(context).registerOnSharedPreferenceChangeListener(this); getDevicePrefs(context).registerOnSharedPreferenceChangeListener(this); - SecureSettingsObserver dotsObserver = - newNotificationSettingsObserver(context, this::onNotificationDotsChanged); - mNotificationDotsEnabled = dotsObserver.getValue(); - dispatchUserEvent(); - + SettingsCache mSettingsCache = SettingsCache.INSTANCE.get(context); + mSettingsCache.register(NOTIFICATION_BADGING_URI, + this::onNotificationDotsChanged); + mSettingsCache.dispatchOnChange(NOTIFICATION_BADGING_URI); } private static ArrayMap loadPrefKeys(Context context) { diff --git a/quickstep/src/com/android/quickstep/util/RecentsOrientedState.java b/quickstep/src/com/android/quickstep/util/RecentsOrientedState.java index a3ee9122a7..215f05ae4c 100644 --- a/quickstep/src/com/android/quickstep/util/RecentsOrientedState.java +++ b/quickstep/src/com/android/quickstep/util/RecentsOrientedState.java @@ -23,22 +23,18 @@ import static android.view.Surface.ROTATION_180; import static android.view.Surface.ROTATION_270; import static android.view.Surface.ROTATION_90; -import static com.android.launcher3.Utilities.newContentObserver; +import static com.android.launcher3.util.SettingsCache.ROTATION_SETTING_URI; import static com.android.launcher3.states.RotationHelper.ALLOW_ROTATION_PREFERENCE_KEY; import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR; import static java.lang.annotation.RetentionPolicy.SOURCE; -import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; -import android.database.ContentObserver; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.Rect; -import android.os.Handler; -import android.provider.Settings; import android.util.Log; import android.view.MotionEvent; import android.view.OrientationEventListener; @@ -51,6 +47,7 @@ import com.android.launcher3.DeviceProfile; import com.android.launcher3.InvariantDeviceProfile; import com.android.launcher3.R; import com.android.launcher3.Utilities; +import com.android.launcher3.util.SettingsCache; import com.android.launcher3.testing.TestProtocol; import com.android.launcher3.touch.PagedOrientationHandler; import com.android.launcher3.util.WindowBounds; @@ -72,9 +69,6 @@ public final class RecentsOrientedState implements SharedPreferences.OnSharedPre private static final String TAG = "RecentsOrientedState"; private static final boolean DEBUG = false; - private ContentObserver mSystemAutoRotateObserver = - newContentObserver(new Handler(), t -> updateAutoRotateSetting()); - @Retention(SOURCE) @IntDef({ROTATION_0, ROTATION_90, ROTATION_180, ROTATION_270}) public @interface SurfaceRotation {} @@ -118,9 +112,11 @@ public final class RecentsOrientedState implements SharedPreferences.OnSharedPre | FLAG_SWIPE_UP_NOT_RUNNING; private final Context mContext; - private final ContentResolver mContentResolver; private final SharedPreferences mSharedPrefs; private final OrientationEventListener mOrientationListener; + private final SettingsCache mSettingsCache; + private final SettingsCache.OnChangeListener mRotationChangeListener = + isEnabled -> updateAutoRotateSetting(); private final Matrix mTmpMatrix = new Matrix(); @@ -138,7 +134,6 @@ public final class RecentsOrientedState implements SharedPreferences.OnSharedPre public RecentsOrientedState(Context context, BaseActivityInterface sizeStrategy, IntConsumer rotationChangeListener) { mContext = context; - mContentResolver = context.getContentResolver(); mSharedPrefs = Utilities.getPrefs(context); mOrientationListener = new OrientationEventListener(context) { @Override @@ -162,6 +157,7 @@ public final class RecentsOrientedState implements SharedPreferences.OnSharedPre mFlags |= FLAG_MULTIPLE_ORIENTATION_SUPPORTED_BY_DENSITY; } mFlags |= FLAG_SWIPE_UP_NOT_RUNNING; + mSettingsCache = SettingsCache.INSTANCE.get(mContext); initFlags(); } @@ -271,8 +267,8 @@ public final class RecentsOrientedState implements SharedPreferences.OnSharedPre } private void updateAutoRotateSetting() { - setFlag(FLAG_SYSTEM_ROTATION_ALLOWED, Settings.System.getInt(mContentResolver, - Settings.System.ACCELEROMETER_ROTATION, 1) == 1); + setFlag(FLAG_SYSTEM_ROTATION_ALLOWED, + mSettingsCache.getValue(ROTATION_SETTING_URI, 1)); } private void updateHomeRotationSetting() { @@ -295,9 +291,7 @@ public final class RecentsOrientedState implements SharedPreferences.OnSharedPre public void initListeners() { if (isMultipleOrientationSupportedByDevice()) { mSharedPrefs.registerOnSharedPreferenceChangeListener(this); - mContentResolver.registerContentObserver( - Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), - false, mSystemAutoRotateObserver); + mSettingsCache.register(ROTATION_SETTING_URI, mRotationChangeListener); } initFlags(); } @@ -308,7 +302,7 @@ public final class RecentsOrientedState implements SharedPreferences.OnSharedPre public void destroyListeners() { if (isMultipleOrientationSupportedByDevice()) { mSharedPrefs.unregisterOnSharedPreferenceChangeListener(this); - mContentResolver.unregisterContentObserver(mSystemAutoRotateObserver); + mSettingsCache.unregister(ROTATION_SETTING_URI, mRotationChangeListener); } setRotationWatcherEnabled(false); } diff --git a/robolectric_tests/src/com/android/launcher3/util/SettingsCacheTest.java b/robolectric_tests/src/com/android/launcher3/util/SettingsCacheTest.java new file mode 100644 index 0000000000..fbf4c63e65 --- /dev/null +++ b/robolectric_tests/src/com/android/launcher3/util/SettingsCacheTest.java @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.launcher3.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import android.content.Context; +import android.net.Uri; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; + +import java.util.Collections; + +@RunWith(RobolectricTestRunner.class) +public class SettingsCacheTest { + + public static final Uri KEY_SYSTEM_URI_TEST1 = Uri.parse("content://settings/system/test1"); + public static final Uri KEY_SYSTEM_URI_TEST2 = Uri.parse("content://settings/system/test2");; + + private SettingsCache.OnChangeListener mChangeListener; + private SettingsCache mSettingsCache; + + @Before + public void setup() { + mChangeListener = mock(SettingsCache.OnChangeListener.class); + Context targetContext = RuntimeEnvironment.application; + mSettingsCache = SettingsCache.INSTANCE.get(targetContext); + mSettingsCache.register(KEY_SYSTEM_URI_TEST1, mChangeListener); + } + + @Test + public void listenerCalledOnChange() { + mSettingsCache.onChange(true, KEY_SYSTEM_URI_TEST1); + verify(mChangeListener, times(1)).onSettingsChanged(true); + } + + @Test + public void getValueRespectsDefaultValue() { + // Case of key not found + boolean val = mSettingsCache.getValue(KEY_SYSTEM_URI_TEST1, 0); + assertFalse(val); + } + + @Test + public void getValueHitsCache() { + mSettingsCache.setKeyCache(Collections.singletonMap(KEY_SYSTEM_URI_TEST1, true)); + boolean val = mSettingsCache.getValue(KEY_SYSTEM_URI_TEST1, 0); + assertTrue(val); + } + + @Test + public void getValueUpdatedCache() { + // First ensure there's nothing in cache + boolean val = mSettingsCache.getValue(KEY_SYSTEM_URI_TEST1, 0); + assertFalse(val); + + mSettingsCache.setKeyCache(Collections.singletonMap(KEY_SYSTEM_URI_TEST1, true)); + val = mSettingsCache.getValue(KEY_SYSTEM_URI_TEST1, 0); + assertTrue(val); + } + + @Test + public void multipleListenersSingleKey() { + SettingsCache.OnChangeListener secondListener = mock(SettingsCache.OnChangeListener.class); + mSettingsCache.register(KEY_SYSTEM_URI_TEST1, secondListener); + + mSettingsCache.onChange(true, KEY_SYSTEM_URI_TEST1); + verify(mChangeListener, times(1)).onSettingsChanged(true); + verify(secondListener, times(1)).onSettingsChanged(true); + } + + @Test + public void singleListenerMultipleKeys() { + SettingsCache.OnChangeListener secondListener = mock(SettingsCache.OnChangeListener.class); + mSettingsCache.register(KEY_SYSTEM_URI_TEST2, secondListener); + + mSettingsCache.onChange(true, KEY_SYSTEM_URI_TEST1); + mSettingsCache.onChange(true, KEY_SYSTEM_URI_TEST2); + verify(mChangeListener, times(1)).onSettingsChanged(true); + verify(secondListener, times(1)).onSettingsChanged(true); + } + + @Test + public void sameListenerMultipleKeys() { + SettingsCache.OnChangeListener secondListener = mock(SettingsCache.OnChangeListener.class); + mSettingsCache.register(KEY_SYSTEM_URI_TEST2, mChangeListener); + + mSettingsCache.onChange(true, KEY_SYSTEM_URI_TEST1); + mSettingsCache.onChange(true, KEY_SYSTEM_URI_TEST2); + verify(mChangeListener, times(2)).onSettingsChanged(true); + verify(secondListener, times(0)).onSettingsChanged(true); + } +} diff --git a/src/com/android/launcher3/LauncherAppState.java b/src/com/android/launcher3/LauncherAppState.java index a4181c53c9..57d76005a6 100644 --- a/src/com/android/launcher3/LauncherAppState.java +++ b/src/com/android/launcher3/LauncherAppState.java @@ -17,8 +17,8 @@ package com.android.launcher3; import static com.android.launcher3.InvariantDeviceProfile.CHANGE_FLAG_ICON_PARAMS; +import static com.android.launcher3.util.SettingsCache.NOTIFICATION_BADGING_URI; import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; -import static com.android.launcher3.util.SecureSettingsObserver.newNotificationSettingsObserver; import android.content.ComponentName; import android.content.Context; @@ -37,10 +37,10 @@ import com.android.launcher3.notification.NotificationListener; import com.android.launcher3.pm.InstallSessionHelper; import com.android.launcher3.pm.InstallSessionTracker; import com.android.launcher3.pm.UserCache; +import com.android.launcher3.util.SettingsCache; import com.android.launcher3.util.MainThreadInitializedObject; import com.android.launcher3.util.Preconditions; import com.android.launcher3.util.SafeCloseable; -import com.android.launcher3.util.SecureSettingsObserver; import com.android.launcher3.util.SimpleBroadcastReceiver; import com.android.launcher3.widget.custom.CustomWidgetManager; @@ -57,8 +57,9 @@ public class LauncherAppState { private final IconCache mIconCache; private final WidgetPreviewLoader mWidgetCache; private final InvariantDeviceProfile mInvariantDeviceProfile; + private SettingsCache.OnChangeListener mNotificationSettingsChangedListener; - private SecureSettingsObserver mNotificationDotsObserver; + private SettingsCache mSettingsCache; private InstallSessionTracker mInstallSessionTracker; private SimpleBroadcastReceiver mModelChangeReceiver; private SafeCloseable mCalendarChangeTracker; @@ -108,10 +109,11 @@ public class LauncherAppState { .registerInstallTracker(mModel); // Register an observer to rebind the notification listener when dots are re-enabled. - mNotificationDotsObserver = - newNotificationSettingsObserver(mContext, this::onNotificationSettingsChanged); - mNotificationDotsObserver.register(); - mNotificationDotsObserver.dispatchOnChange(); + mSettingsCache = SettingsCache.INSTANCE.get(mContext); + mNotificationSettingsChangedListener = this::onNotificationSettingsChanged; + mSettingsCache.register(NOTIFICATION_BADGING_URI, + mNotificationSettingsChangedListener); + mSettingsCache.dispatchOnChange(NOTIFICATION_BADGING_URI); } public LauncherAppState(Context context, @Nullable String iconCacheFileName) { @@ -166,8 +168,9 @@ public class LauncherAppState { } CustomWidgetManager.INSTANCE.get(mContext).setWidgetRefreshCallback(null); - if (mNotificationDotsObserver != null) { - mNotificationDotsObserver.unregister(); + if (mSettingsCache != null) { + mSettingsCache.unregister(NOTIFICATION_BADGING_URI, + mNotificationSettingsChangedListener); } } diff --git a/src/com/android/launcher3/notification/NotificationListener.java b/src/com/android/launcher3/notification/NotificationListener.java index 059ad18971..2905dc322a 100644 --- a/src/com/android/launcher3/notification/NotificationListener.java +++ b/src/com/android/launcher3/notification/NotificationListener.java @@ -16,9 +16,9 @@ package com.android.launcher3.notification; +import static com.android.launcher3.util.SettingsCache.NOTIFICATION_BADGING_URI; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import static com.android.launcher3.util.Executors.MODEL_EXECUTOR; -import static com.android.launcher3.util.SecureSettingsObserver.newNotificationSettingsObserver; import android.annotation.TargetApi; import android.app.Notification; @@ -37,8 +37,8 @@ import androidx.annotation.AnyThread; import androidx.annotation.Nullable; import androidx.annotation.WorkerThread; +import com.android.launcher3.util.SettingsCache; import com.android.launcher3.util.PackageUserKey; -import com.android.launcher3.util.SecureSettingsObserver; import java.util.ArrayList; import java.util.Arrays; @@ -81,7 +81,8 @@ public class NotificationListener extends NotificationListenerService { /** The last notification key that was dismissed from launcher UI */ private String mLastKeyDismissedByLauncher; - private SecureSettingsObserver mNotificationDotsObserver; + private SettingsCache mSettingsCache; + private SettingsCache.OnChangeListener mNotificationSettingsChangedListener; public NotificationListener() { mWorkerHandler = new Handler(MODEL_EXECUTOR.getLooper(), this::handleWorkerMessage); @@ -207,10 +208,12 @@ public class NotificationListener extends NotificationListenerService { super.onListenerConnected(); sIsConnected = true; - mNotificationDotsObserver = - newNotificationSettingsObserver(this, this::onNotificationSettingsChanged); - mNotificationDotsObserver.register(); - mNotificationDotsObserver.dispatchOnChange(); + // Register an observer to rebind the notification listener when dots are re-enabled. + mSettingsCache = SettingsCache.INSTANCE.get(this); + mNotificationSettingsChangedListener = this::onNotificationSettingsChanged; + mSettingsCache.register(NOTIFICATION_BADGING_URI, + mNotificationSettingsChangedListener); + mSettingsCache.dispatchOnChange(NOTIFICATION_BADGING_URI); onNotificationFullRefresh(); } @@ -229,7 +232,7 @@ public class NotificationListener extends NotificationListenerService { public void onListenerDisconnected() { super.onListenerDisconnected(); sIsConnected = false; - mNotificationDotsObserver.unregister(); + mSettingsCache.unregister(NOTIFICATION_BADGING_URI, mNotificationSettingsChangedListener); onNotificationFullRefresh(); } diff --git a/src/com/android/launcher3/settings/NotificationDotsPreference.java b/src/com/android/launcher3/settings/NotificationDotsPreference.java index a91303a529..a35416915f 100644 --- a/src/com/android/launcher3/settings/NotificationDotsPreference.java +++ b/src/com/android/launcher3/settings/NotificationDotsPreference.java @@ -35,14 +35,14 @@ import androidx.preference.PreferenceViewHolder; import com.android.launcher3.R; import com.android.launcher3.notification.NotificationListener; -import com.android.launcher3.util.SecureSettingsObserver; +import com.android.launcher3.util.SettingsCache; /** * A {@link Preference} for indicating notification dots status. * Also has utility methods for updating UI based on dots status changes. */ public class NotificationDotsPreference extends Preference - implements SecureSettingsObserver.OnChangeListener { + implements SettingsCache.OnChangeListener { private boolean mWidgetFrameVisible = false; diff --git a/src/com/android/launcher3/settings/SettingsActivity.java b/src/com/android/launcher3/settings/SettingsActivity.java index 922425fca1..ac8dac5f7e 100644 --- a/src/com/android/launcher3/settings/SettingsActivity.java +++ b/src/com/android/launcher3/settings/SettingsActivity.java @@ -18,13 +18,13 @@ package com.android.launcher3.settings; import static androidx.core.view.accessibility.AccessibilityNodeInfoCompat.ACTION_ACCESSIBILITY_FOCUS; +import static com.android.launcher3.util.SettingsCache.NOTIFICATION_BADGING_URI; +import static com.android.launcher3.util.SettingsCache.NOTIFICATION_ENABLED_LISTENERS; import static com.android.launcher3.states.RotationHelper.ALLOW_ROTATION_PREFERENCE_KEY; import static com.android.launcher3.states.RotationHelper.getAllowRotationDefaultValue; -import static com.android.launcher3.util.SecureSettingsObserver.newNotificationSettingsObserver; import android.content.SharedPreferences; import android.os.Bundle; -import android.provider.Settings; import android.text.TextUtils; import androidx.annotation.NonNull; @@ -45,8 +45,8 @@ import com.android.launcher3.R; import com.android.launcher3.Utilities; import com.android.launcher3.config.FeatureFlags; import com.android.launcher3.model.WidgetsModel; +import com.android.launcher3.util.SettingsCache; import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper; -import com.android.launcher3.util.SecureSettingsObserver; /** * Settings activity for Launcher. Currently implements the following setting: Allow rotation @@ -59,8 +59,6 @@ public class SettingsActivity extends FragmentActivity private static final String FLAGS_PREFERENCE_KEY = "flag_toggler"; private static final String NOTIFICATION_DOTS_PREFERENCE_KEY = "pref_icon_badging"; - /** Hidden field Settings.Secure.ENABLED_NOTIFICATION_LISTENERS */ - private static final String NOTIFICATION_ENABLED_LISTENERS = "enabled_notification_listeners"; public static final String EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key"; public static final String EXTRA_SHOW_FRAGMENT_ARGS = ":settings:show_fragment_args"; @@ -126,10 +124,11 @@ public class SettingsActivity extends FragmentActivity */ public static class LauncherSettingsFragment extends PreferenceFragmentCompat { - private SecureSettingsObserver mNotificationDotsObserver; + private SettingsCache mSettingsCache; private String mHighLightKey; private boolean mPreferenceHighlighted = false; + private NotificationDotsPreference mNotificationSettingsChangedListener; @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { @@ -177,14 +176,16 @@ public class SettingsActivity extends FragmentActivity } // Listen to system notification dot settings while this UI is active. - mNotificationDotsObserver = newNotificationSettingsObserver( - getActivity(), (NotificationDotsPreference) preference); - mNotificationDotsObserver.register(); + mSettingsCache = SettingsCache.INSTANCE.get(getActivity()); + mNotificationSettingsChangedListener = + ((NotificationDotsPreference) preference); + mSettingsCache.register(NOTIFICATION_BADGING_URI, + (NotificationDotsPreference) mNotificationSettingsChangedListener); // Also listen if notification permission changes - mNotificationDotsObserver.getResolver().registerContentObserver( - Settings.Secure.getUriFor(NOTIFICATION_ENABLED_LISTENERS), false, - mNotificationDotsObserver); - mNotificationDotsObserver.dispatchOnChange(); + mSettingsCache.register(NOTIFICATION_ENABLED_LISTENERS, + mNotificationSettingsChangedListener); + mSettingsCache.dispatchOnChange(NOTIFICATION_BADGING_URI); + mSettingsCache.dispatchOnChange(NOTIFICATION_ENABLED_LISTENERS); return true; case ALLOW_ROTATION_PREFERENCE_KEY: @@ -251,9 +252,11 @@ public class SettingsActivity extends FragmentActivity @Override public void onDestroy() { - if (mNotificationDotsObserver != null) { - mNotificationDotsObserver.unregister(); - mNotificationDotsObserver = null; + if (mSettingsCache != null) { + mSettingsCache.unregister(NOTIFICATION_BADGING_URI, + mNotificationSettingsChangedListener); + mSettingsCache.unregister(NOTIFICATION_ENABLED_LISTENERS, + mNotificationSettingsChangedListener); } super.onDestroy(); } diff --git a/src/com/android/launcher3/util/SecureSettingsObserver.java b/src/com/android/launcher3/util/SecureSettingsObserver.java deleted file mode 100644 index 9fe72ad80a..0000000000 --- a/src/com/android/launcher3/util/SecureSettingsObserver.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.launcher3.util; - -import android.content.ContentResolver; -import android.content.Context; -import android.database.ContentObserver; -import android.os.Handler; -import android.provider.Settings; - -/** - * Utility class to listen for secure settings changes - */ -public class SecureSettingsObserver extends ContentObserver { - - /** Hidden field Settings.Secure.NOTIFICATION_BADGING */ - public static final String NOTIFICATION_BADGING = "notification_badging"; - /** Hidden field Settings.Secure.ONE_HANDED_MODE_ENABLED */ - public static final String ONE_HANDED_ENABLED = "one_handed_mode_enabled"; - /** Hidden field Settings.Secure.SWIPE_BOTTOM_TO_NOTIFICATION_ENABLED */ - public static final String ONE_HANDED_SWIPE_BOTTOM_TO_NOTIFICATION_ENABLED = - "swipe_bottom_to_notification_enabled"; - - private final ContentResolver mResolver; - private final String mKeySetting; - private final int mDefaultValue; - private final OnChangeListener mOnChangeListener; - - public SecureSettingsObserver(ContentResolver resolver, OnChangeListener listener, - String keySetting, int defaultValue) { - super(new Handler()); - - mResolver = resolver; - mOnChangeListener = listener; - mKeySetting = keySetting; - mDefaultValue = defaultValue; - } - - @Override - public void onChange(boolean selfChange) { - mOnChangeListener.onSettingsChanged(getValue()); - } - - public boolean getValue() { - return Settings.Secure.getInt(mResolver, mKeySetting, mDefaultValue) == 1; - } - - public void register() { - mResolver.registerContentObserver(Settings.Secure.getUriFor(mKeySetting), false, this); - } - - public ContentResolver getResolver() { - return mResolver; - } - - public void dispatchOnChange() { - onChange(true); - } - - public void unregister() { - mResolver.unregisterContentObserver(this); - } - - public interface OnChangeListener { - void onSettingsChanged(boolean isEnabled); - } - - public static SecureSettingsObserver newNotificationSettingsObserver(Context context, - OnChangeListener listener) { - return new SecureSettingsObserver( - context.getContentResolver(), listener, NOTIFICATION_BADGING, 1); - } - - public static SecureSettingsObserver newOneHandedSettingsObserver(Context context, - OnChangeListener listener) { - return new SecureSettingsObserver( - context.getContentResolver(), listener, ONE_HANDED_ENABLED, 0); - } - - /** - * Constructs settings observer for {@link #ONE_HANDED_SWIPE_BOTTOM_TO_NOTIFICATION_ENABLED} - * preference. - */ - public static SecureSettingsObserver newSwipeToNotificationSettingsObserver(Context context, - OnChangeListener listener) { - return new SecureSettingsObserver( - context.getContentResolver(), listener, - ONE_HANDED_SWIPE_BOTTOM_TO_NOTIFICATION_ENABLED, 1); - } -} diff --git a/src/com/android/launcher3/util/SettingsCache.java b/src/com/android/launcher3/util/SettingsCache.java new file mode 100644 index 0000000000..22b4d38891 --- /dev/null +++ b/src/com/android/launcher3/util/SettingsCache.java @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.launcher3.util; + +import static android.provider.Settings.System.ACCELEROMETER_ROTATION; + +import android.content.ContentResolver; +import android.content.Context; +import android.database.ContentObserver; +import android.net.Uri; +import android.os.Handler; +import android.provider.Settings; + +import androidx.annotation.VisibleForTesting; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * ContentObserver over Settings keys that also has a caching layer. + * Consumers can register for callbacks via {@link #register(Uri, OnChangeListener)} and + * {@link #unregister(Uri, OnChangeListener)} methods. + * + * This can be used as a normal cache without any listeners as well via the + * {@link #getValue(Uri, int)} and {@link #dispatchOnChange(Uri)} to update (and subsequently call + * get) + * + * The cache will be invalidated/updated through the normal + * {@link ContentObserver#onChange(boolean)} calls + * or can be force updated by calling {@link #dispatchOnChange(Uri)}. + * + * Cache will also be updated if a key queried is missing (even if it has no listeners registered). + */ +public class SettingsCache extends ContentObserver { + + /** Hidden field Settings.Secure.NOTIFICATION_BADGING */ + public static final Uri NOTIFICATION_BADGING_URI = + Settings.Secure.getUriFor("notification_badging"); + /** Hidden field Settings.Secure.ONE_HANDED_MODE_ENABLED */ + public static final String ONE_HANDED_ENABLED = "one_handed_mode_enabled"; + /** Hidden field Settings.Secure.SWIPE_BOTTOM_TO_NOTIFICATION_ENABLED */ + public static final String ONE_HANDED_SWIPE_BOTTOM_TO_NOTIFICATION_ENABLED = + "swipe_bottom_to_notification_enabled"; + /** Hidden field Settings.Secure.ENABLED_NOTIFICATION_LISTENERS */ + public static final Uri NOTIFICATION_ENABLED_LISTENERS = + Settings.Secure.getUriFor("enabled_notification_listeners"); + public static final Uri ROTATION_SETTING_URI = + Settings.System.getUriFor(ACCELEROMETER_ROTATION); + + private static final String SYSTEM_URI_PREFIX = Settings.System.CONTENT_URI.toString(); + + /** + * Caches the last seen value for registered keys. + */ + private Map mKeyCache = new ConcurrentHashMap<>(); + private final Map> mListenerMap = new HashMap<>(); + protected final ContentResolver mResolver; + + + /** + * Singleton instance + */ + public static MainThreadInitializedObject INSTANCE = + new MainThreadInitializedObject<>(SettingsCache::new); + + private SettingsCache(Context context) { + super(new Handler()); + mResolver = context.getContentResolver(); + } + + @Override + public void onChange(boolean selfChange, Uri uri) { + // We use default of 1, but if we're getting an onChange call, can assume a non-default + // value will exist + boolean newVal = updateValue(uri, 1 /* Effectively Unused */); + if (!mListenerMap.containsKey(uri)) { + return; + } + + for (OnChangeListener listener : mListenerMap.get(uri)) { + listener.onSettingsChanged(newVal); + } + } + + /** + * Returns the value for this classes key from the cache. If not in cache, will call + * {@link #updateValue(Uri, int)} to fetch. + */ + public boolean getValue(Uri keySetting, int defaultValue) { + if (mKeyCache.containsKey(keySetting)) { + return mKeyCache.get(keySetting); + } else { + return updateValue(keySetting, defaultValue); + } + } + + /** + * Does not de-dupe if you add same listeners for the same key multiple times. + * Unregister once complete using {@link #unregister(Uri, OnChangeListener)} + */ + public void register(Uri uri, OnChangeListener changeListener) { + if (mListenerMap.containsKey(uri)) { + mListenerMap.get(uri).add(changeListener); + } else { + CopyOnWriteArrayList l = new CopyOnWriteArrayList<>(); + l.add(changeListener); + mListenerMap.put(uri, l); + mResolver.registerContentObserver(uri, false, this); + } + } + + private boolean updateValue(Uri keyUri, int defaultValue) { + String key = keyUri.getLastPathSegment(); + boolean newVal; + if (keyUri.toString().startsWith(SYSTEM_URI_PREFIX)) { + newVal = Settings.System.getInt(mResolver, key, defaultValue) == 1; + } else { // SETTING_SECURE + newVal = Settings.Secure.getInt(mResolver, key, defaultValue) == 1; + } + + mKeyCache.put(keyUri, newVal); + return newVal; + } + + /** + * Force update a change for a given URI and have all listeners for that URI receive callbacks + * even if the value is unchanged. + */ + public void dispatchOnChange(Uri uri) { + onChange(true, uri); + } + + /** + * Call to stop receiving updates on the given {@param listener}. + * This Uri/Listener pair must correspond to the same pair called with for + * {@link #register(Uri, OnChangeListener)} + */ + public void unregister(Uri uri, OnChangeListener listener) { + List listenersToRemoveFrom = mListenerMap.get(uri); + if (!listenersToRemoveFrom.contains(listener)) { + return; + } + + listenersToRemoveFrom.remove(listener); + if (listenersToRemoveFrom.isEmpty()) { + mListenerMap.remove(uri); + } + } + + /** + * Don't use this. Ever. + * @param keyCache Cache to replace {@link #mKeyCache} + */ + @VisibleForTesting + void setKeyCache(Map keyCache) { + mKeyCache = keyCache; + } + + public interface OnChangeListener { + void onSettingsChanged(boolean isEnabled); + } +} diff --git a/tests/Android.mk b/tests/Android.mk index 3d9077d4bd..43d51fca01 100644 --- a/tests/Android.mk +++ b/tests/Android.mk @@ -32,7 +32,6 @@ else LOCAL_SRC_FILES := $(call all-java-files-under, tapl) \ ../src/com/android/launcher3/ResourceUtils.java \ - ../src/com/android/launcher3/util/SecureSettingsObserver.java \ ../src/com/android/launcher3/testing/TestProtocol.java endif