feat: Add option to clear home screen in settings (#6125)

Signed-off-by: abhixv <abhi.sharma1@hotmail.com>
This commit is contained in:
Abhishek Sharma authored and Pun Butrach committed 2026-01-10 20:51:01 +07:00
1 parent 9898749619
commit 5f3a03f4fb
1577 files changed
+112559 -80244

No files matched your search

@@ -34,8 +34,6 @@ import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import android.window.OnBackAnimationCallback;
import androidx.annotation.IntDef;
import com.android.launcher3.anim.PendingAnimation;
@@ -51,7 +49,7 @@ import java.lang.annotation.RetentionPolicy;
*/
@TargetApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
public abstract class AbstractFloatingView extends LinearLayout implements TouchController,
OnBackAnimationCallback {
OnBackPressedHandler {
@IntDef(flag = true, value = {
TYPE_COMPOSE_VIEW,
@@ -75,12 +73,12 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
TYPE_TASKBAR_ALL_APPS,
TYPE_ADD_TO_HOME_CONFIRMATION,
TYPE_TASKBAR_OVERLAY_PROXY,
TYPE_TASKBAR_PINNING_POPUP,
TYPE_PIN_IME_POPUP,
TYPE_ONE_GRID_MIGRATION_EDU,
TYPE_TASKBAR_PINNING_POPUP
})
@Retention(RetentionPolicy.SOURCE)
public @interface FloatingViewType {}
public @interface FloatingViewType {
}
public static final int TYPE_FOLDER = 1 << 0;
public static final int TYPE_ACTION_POPUP = 1 << 1;
public static final int TYPE_WIDGETS_BOTTOM_SHEET = 1 << 2;
@@ -106,10 +104,9 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
public static final int TYPE_TASKBAR_OVERLAY_PROXY = 1 << 20;
public static final int TYPE_TASKBAR_PINNING_POPUP = 1 << 21;
public static final int TYPE_PIN_IME_POPUP = 1 << 22;
public static final int TYPE_ONE_GRID_MIGRATION_EDU = 1 << 23;
// Custom compose popups
public static final int TYPE_COMPOSE_VIEW = 1 << 24;
public static final int TYPE_COMPOSE_VIEW = 1 << 23;
public static final int TYPE_ALL = TYPE_FOLDER | TYPE_ACTION_POPUP
| TYPE_WIDGETS_BOTTOM_SHEET | TYPE_WIDGET_RESIZE_FRAME | TYPE_WIDGETS_FULL_SHEET
@@ -118,34 +115,37 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
| TYPE_ICON_SURFACE | TYPE_DRAG_DROP_POPUP | TYPE_PIN_WIDGET_FROM_EXTERNAL_POPUP
| TYPE_TASKBAR_EDUCATION_DIALOG | TYPE_TASKBAR_ALL_APPS | TYPE_OPTIONS_POPUP_DIALOG
| TYPE_ADD_TO_HOME_CONFIRMATION | TYPE_TASKBAR_OVERLAY_PROXY
| TYPE_TASKBAR_PINNING_POPUP | TYPE_PIN_IME_POPUP | TYPE_ONE_GRID_MIGRATION_EDU | TYPE_COMPOSE_VIEW;
| TYPE_TASKBAR_PINNING_POPUP | TYPE_PIN_IME_POPUP | TYPE_COMPOSE_VIEW;
// Type of popups which should be kept open during launcher rebind
public static final int TYPE_REBIND_SAFE = TYPE_WIDGETS_FULL_SHEET
| TYPE_WIDGETS_BOTTOM_SHEET | TYPE_ON_BOARD_POPUP | TYPE_DISCOVERY_BOUNCE
| TYPE_ALL_APPS_EDU | TYPE_ICON_SURFACE | TYPE_TASKBAR_EDUCATION_DIALOG
| TYPE_TASKBAR_ALL_APPS | TYPE_OPTIONS_POPUP_DIALOG | TYPE_TASKBAR_OVERLAY_PROXY
| TYPE_PIN_IME_POPUP | TYPE_ONE_GRID_MIGRATION_EDU | TYPE_COMPOSE_VIEW;
| TYPE_PIN_IME_POPUP | TYPE_COMPOSE_VIEW;
/** Type of popups that should get exclusive accessibility focus. */
public static final int TYPE_ACCESSIBLE = TYPE_ALL & ~TYPE_DISCOVERY_BOUNCE & ~TYPE_LISTENER
& ~TYPE_ALL_APPS_EDU & ~TYPE_TASKBAR_ALL_APPS & ~TYPE_PIN_IME_POPUP
& ~TYPE_WIDGET_RESIZE_FRAME & ~TYPE_ONE_GRID_MIGRATION_EDU & ~TYPE_ON_BOARD_POPUP
& ~TYPE_TASKBAR_OVERLAY_PROXY;
& ~TYPE_WIDGET_RESIZE_FRAME;
// These view all have particular operation associated with swipe down interaction.
// These view all have particular operation associated with swipe down
// interaction.
public static final int TYPE_STATUS_BAR_SWIPE_DOWN_DISALLOW = TYPE_WIDGETS_BOTTOM_SHEET |
TYPE_WIDGETS_FULL_SHEET | TYPE_WIDGET_RESIZE_FRAME | TYPE_ON_BOARD_POPUP |
TYPE_DISCOVERY_BOUNCE | TYPE_TASK_MENU | TYPE_DRAG_DROP_POPUP | TYPE_COMPOSE_VIEW;
// Floating views that are exclusive to the taskbar overlay window.
public static final int TYPE_TASKBAR_OVERLAYS =
TYPE_TASKBAR_ALL_APPS | TYPE_TASKBAR_EDUCATION_DIALOG;
public static final int TYPE_TASKBAR_OVERLAYS = TYPE_TASKBAR_ALL_APPS | TYPE_TASKBAR_EDUCATION_DIALOG;
// Floating views that a TouchController should not try to intercept touches from.
// Floating views that a TouchController should not try to intercept touches
// from.
public static final int TYPE_TOUCH_CONTROLLER_NO_INTERCEPT = TYPE_ALL & ~TYPE_DISCOVERY_BOUNCE
& ~TYPE_LISTENER & ~TYPE_TASKBAR_OVERLAYS;
public static final int TYPE_ALL_EXCEPT_ON_BOARD_POPUP = TYPE_ALL & ~TYPE_ON_BOARD_POPUP
& ~TYPE_PIN_IME_POPUP;
protected boolean mIsOpen;
public AbstractFloatingView(Context context, AttributeSet attrs) {
@@ -157,7 +157,8 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
}
/**
* We need to handle touch events to prevent them from falling through to the workspace below.
* We need to handle touch events to prevent them from falling through to the
* workspace below.
*/
@SuppressLint("ClickableViewAccessibility")
@Override
@@ -177,11 +178,15 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
protected abstract void handleClose(boolean animate);
/**
* Creates a user-controlled animation to hint that the view will be closed if completed.
* @param distanceToMove The max distance that elements should move from their starting point.
* Creates a user-controlled animation to hint that the view will be closed if
* completed.
*
* @param distanceToMove The max distance that elements should move from their
* starting point.
*/
public void addHintCloseAnim(
float distanceToMove, Interpolator interpolator, PendingAnimation target) { }
float distanceToMove, Interpolator interpolator, PendingAnimation target) {
}
public final boolean isOpen() {
return mIsOpen;
@@ -238,14 +243,16 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
}
/**
* Returns whether there is at least one view of the given type where {@link #isOpen()} == true.
* Returns whether there is at least one view of the given type where
* {@link #isOpen()} == true.
*/
public static boolean hasOpenView(ActivityContext activity, @FloatingViewType int type) {
return getOpenView(activity, type) != null;
}
/**
* Returns a view matching FloatingViewType, and {@link #isOpen()} may be false (if animating
* Returns a view matching FloatingViewType, and {@link #isOpen()} may be false
* (if animating
* closed).
*/
public static <T extends AbstractFloatingView> T getAnyView(
@@ -256,8 +263,10 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
private static <T extends AbstractFloatingView> T getView(
ActivityContext activity, @FloatingViewType int type, boolean mustBeOpen) {
BaseDragLayer dragLayer = activity.getDragLayer();
if (dragLayer == null) return null;
// Iterate in reverse order. AbstractFloatingView is added later to the dragLayer,
if (dragLayer == null)
return null;
// Iterate in reverse order. AbstractFloatingView is added later to the
// dragLayer,
// and will be one of the last views.
for (int i = dragLayer.getChildCount() - 1; i >= 0; i--) {
View child = dragLayer.getChildAt(i);
@@ -294,13 +303,13 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
}
public static void closeAllOpenViewsExcept(ActivityContext activity, boolean animate,
@FloatingViewType int type) {
@FloatingViewType int type) {
closeOpenViews(activity, animate, TYPE_ALL & ~type);
activity.finishAutoCancelActionMode();
}
public static void closeAllOpenViewsExcept(ActivityContext activity,
@FloatingViewType int type) {
@FloatingViewType int type) {
closeAllOpenViewsExcept(activity, true, type);
}
-11
View File
@@ -20,8 +20,6 @@ import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import androidx.annotation.VisibleForTesting;
public class Alarm implements Runnable{
// if we reach this time and the alarm hasn't been cancelled, call the listener
private long mAlarmTriggerTime;
@@ -98,13 +96,4 @@ public class Alarm implements Runnable{
public long getLastSetTimeout() {
return mLastSetTimeout;
}
/** Simulates the alarm firing for tests. */
@VisibleForTesting
public void finishAlarm() {
if (!mAlarmPending) return;
mAlarmPending = false;
mHandler.removeCallbacks(this);
mAlarmListener.onAlarm(this);
}
}
+1 -7
View File
@@ -7,16 +7,11 @@ import android.os.Process;
import com.android.launcher3.util.ComponentKey;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import com.android.launcher3.dagger.ApplicationContext;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import app.lawnchair.preferences2.PreferenceManager2;
/**
* Utility class to filter out components from various lists
*/
@@ -24,8 +19,7 @@ public class AppFilter {
private final Set<ComponentName> mFilteredComponents;
@Inject
public AppFilter(@ApplicationContext Context context) {
public AppFilter(Context context) {
mFilteredComponents = Arrays.stream(
context.getResources().getStringArray(R.array.filtered_components))
.map(ComponentName::unflattenFromString)
@@ -49,11 +49,11 @@ import com.android.launcher3.widget.LauncherAppWidgetHostView;
import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
import com.android.launcher3.widget.PendingAppWidgetHostView;
import com.android.launcher3.widget.util.WidgetSizes;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import java.util.ArrayList;
import java.util.List;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import app.lawnchair.preferences2.PreferenceManager2;
import app.lawnchair.theme.color.tokens.ColorTokens;
import app.lawnchair.theme.drawable.DrawableTokens;
@@ -110,7 +110,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
/**
* In the two panel UI, it is not possible to resize a widget to cross its host
* {@link CellLayout}'s sibling. When this happens, we gradually reduce the opacity of the
* {@link CellLayout}'s sibling. When this happens, we gradually reduce the
* opacity of the
* sibling {@link CellLayout} from 1f to
* {@link #MIN_OPACITY_FOR_CELL_LAYOUT_DURING_INVALID_RESIZE}.
*/
@@ -141,8 +142,7 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
private int[] mWidgetViewWindowPos;
private final Rect mWidgetViewOldRect = new Rect();
private final Rect mWidgetViewNewRect = new Rect();
private final @Nullable LauncherAppWidgetHostView.CellChildViewPreLayoutListener
mCellChildViewPreLayoutListener;
private final @Nullable LauncherAppWidgetHostView.CellChildViewPreLayoutListener mCellChildViewPreLayoutListener;
private final @NonNull OnLayoutChangeListener mWidgetViewLayoutListener;
private int mXDown, mYDown;
@@ -163,14 +163,14 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
mCellChildViewPreLayoutListener = FeatureFlags.ENABLE_WIDGET_TRANSITION_FOR_RESIZING.get()
? (v, left, top, right, bottom) -> {
if (mWidgetViewWindowPos == null) {
mWidgetViewWindowPos = new int[2];
}
v.getLocationInWindow(mWidgetViewWindowPos);
mWidgetViewOldRect.set(v.getLeft(), v.getTop(), v.getRight(),
v.getBottom());
mWidgetViewNewRect.set(left, top, right, bottom);
}
if (mWidgetViewWindowPos == null) {
mWidgetViewWindowPos = new int[2];
}
v.getLocationInWindow(mWidgetViewWindowPos);
mWidgetViewOldRect.set(v.getLeft(), v.getTop(), v.getRight(),
v.getBottom());
mWidgetViewNewRect.set(left, top, right, bottom);
}
: null;
mBackgroundPadding = getResources()
@@ -186,8 +186,7 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
R.dimen.resize_frame_invalid_drag_across_two_panel_opacity_margin);
mDragLayerRelativeCoordinateHelper = new ViewGroupFocusHelper(mLauncher.getDragLayer());
mWidgetViewLayoutListener =
(v, l, t, r, b, oldL, oldT, oldR, oldB) -> setCornerRadiusFromWidget();
mWidgetViewLayoutListener = (v, l, t, r, b, oldL, oldT, oldR, oldB) -> setCornerRadiusFromWidget();
}
@Override
@@ -222,7 +221,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
boolean force = PreferenceExtensionsKt.firstBlocking(pref2.getForceWidgetResize());
boolean unlimited = PreferenceExtensionsKt.firstBlocking(pref2.getWidgetUnlimitedSize());
// If widget is not added to view hierarchy, we cannot show resize frame at correct location
// If widget is not added to view hierarchy, we cannot show resize frame at
// correct location
if (widget.getParent() == null) {
return;
}
@@ -232,14 +232,17 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
DragLayer dl = launcher.getDragLayer();
AppWidgetResizeFrame frame = (AppWidgetResizeFrame) launcher.getLayoutInflater()
.inflate(R.layout.app_widget_resize_frame, dl, false);
ImageView imageView = frame.findViewById(R.id.widget_resize_frame);
imageView.setImageDrawable(DrawableTokens.WidgetResizeFrame.resolve(launcher));
if (widget.hasEnforcedCornerRadius()) {
float enforcedCornerRadius = widget.getEnforcedCornerRadius();
Drawable d = imageView.getDrawable();
if (d instanceof GradientDrawable) {
GradientDrawable gd = (GradientDrawable) d.mutate();
gd.setCornerRadius(enforcedCornerRadius);
}
}
frame.setupForWidget(widget, cellLayout, dl, force, unlimited);
// Save widget item info as tag on resize frame; so that, the accessibility delegate can
// attach actions that typically happen on widget (e.g. resize, move) also on the resize
// frame.
frame.setTag(widget.getTag());
frame.setAccessibilityDelegate(launcher.getAccessibilityDelegate());
frame.setContentDescription(launcher.asContext().getString(R.string.widget_frame_name,
widget.getContentDescription()));
((DragLayer.LayoutParams) frame.getLayoutParams()).customPosition = true;
dl.addView(frame);
@@ -259,19 +262,11 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
}
}
/**
* Retrieves the view where accessibility actions happen.
*/
public View getViewForAccessibility() {
return mWidgetView;
}
private void setupForWidget(LauncherAppWidgetHostView widgetView, CellLayout cellLayout,
DragLayer dragLayer, boolean force, boolean unlimited) {
mCellLayout = cellLayout;
mWidgetView = widgetView;
LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo)
widgetView.getAppWidgetInfo();
LauncherAppWidgetProviderInfo info = (LauncherAppWidgetProviderInfo) widgetView.getAppWidgetInfo();
mDragLayer = dragLayer;
InvariantDeviceProfile idp = LauncherAppState.getIDP(cellLayout.getContext());
@@ -281,13 +276,12 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
} else {
resizeMode = info.resizeMode;
}
if (unlimited) {
mMinHSpan = 1;
mMinVSpan = 1;
mMaxHSpan = idp.numColumns;
mMaxVSpan = idp.numRows;
// If widget is resizable in any direction, make it resizable in both
if (resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
resizeMode = AppWidgetProviderInfo.RESIZE_BOTH;
@@ -362,8 +356,10 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
lp.cellVSpan = widgetInfo.spanY;
lp.isLockedToGrid = true;
// When we create the resize frame, we first mark all cells as unoccupied. The appropriate
// cells (same if not resized, or different) will be marked as occupied when the resize
// When we create the resize frame, we first mark all cells as unoccupied. The
// appropriate
// cells (same if not resized, or different) will be marked as occupied when the
// resize
// frame is dismissed.
mCellLayout.markCellsAsUnoccupiedForView(mWidgetView);
@@ -380,19 +376,17 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
}
public boolean beginResizeIfPointInRegion(int x, int y) {
mLeftBorderActive = (x < mTouchTargetWidth) && mHorizontalResizeActive;
mRightBorderActive = (x > getWidth() - mTouchTargetWidth) && mHorizontalResizeActive;
mTopBorderActive = (y < mTouchTargetWidth + mTopTouchRegionAdjustment)
&& mVerticalResizeActive;
mBottomBorderActive = (y > getHeight() - mTouchTargetWidth + mBottomTouchRegionAdjustment)
&& mVerticalResizeActive;
mLeftBorderActive = x < mTouchTargetWidth;
mRightBorderActive = x > getWidth() - mTouchTargetWidth;
mTopBorderActive = y < mTouchTargetWidth + mTopTouchRegionAdjustment;
mBottomBorderActive = y > getHeight() - mTouchTargetWidth + mBottomTouchRegionAdjustment;
boolean anyBordersActive = mLeftBorderActive || mRightBorderActive
|| mTopBorderActive || mBottomBorderActive;
if (anyBordersActive) {
mDragHandles[INDEX_LEFT].setAlpha(mLeftBorderActive ? 1.0f : DIMMED_HANDLE_ALPHA);
mDragHandles[INDEX_RIGHT].setAlpha(mRightBorderActive ? 1.0f :DIMMED_HANDLE_ALPHA);
mDragHandles[INDEX_RIGHT].setAlpha(mRightBorderActive ? 1.0f : DIMMED_HANDLE_ALPHA);
mDragHandles[INDEX_TOP].setAlpha(mTopBorderActive ? 1.0f : DIMMED_HANDLE_ALPHA);
mDragHandles[INDEX_BOTTOM].setAlpha(mBottomBorderActive ? 1.0f : DIMMED_HANDLE_ALPHA);
}
@@ -419,7 +413,7 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
}
/**
* Based on the deltas, we resize the frame.
* Based on the deltas, we resize the frame.
*/
public void visualizeResizeForDelta(int deltaX, int deltaY) {
mDeltaX = mDeltaXRange.clamp(deltaX);
@@ -438,6 +432,24 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
resizeWidgetIfNeeded(false);
// When the widget resizes in multi-window mode, the translation value changes
// to maintain
// a center fit. These overrides ensure the resize frame always aligns with the
// widget view.
getSnappedRectRelativeToDragLayer(sTmpRect);
if (mLeftBorderActive) {
lp.width = sTmpRect.width() + sTmpRect.left - lp.x;
}
if (mTopBorderActive) {
lp.height = sTmpRect.height() + sTmpRect.top - lp.y;
}
if (mRightBorderActive) {
lp.x = sTmpRect.left;
}
if (mBottomBorderActive) {
lp.y = sTmpRect.top;
}
// Handle invalid resize across CellLayouts in the two panel UI.
if (mCellLayout.getParent() instanceof Workspace) {
Workspace<?> workspace = (Workspace<?>) mCellLayout.getParent();
@@ -454,8 +466,7 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
// Resize from right to left.
progress = (mDragAcrossTwoPanelOpacityMargin + mDeltaX)
/ mDragAcrossTwoPanelOpacityMargin;
} else if (workspace.indexOfChild(pairedCellLayout)
> workspace.indexOfChild(mCellLayout)
} else if (workspace.indexOfChild(pairedCellLayout) > workspace.indexOfChild(mCellLayout)
&& mDeltaX > 0
&& resizeFrameBound.right > focusedCellLayoutBound.right) {
// Resize from left to right.
@@ -477,7 +488,7 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
}
/**
* Based on the current deltas, we determine if and how to resize the widget.
* Based on the current deltas, we determine if and how to resize the widget.
*/
private void resizeWidgetIfNeeded(boolean onDismiss) {
ViewGroup.LayoutParams wlp = mWidgetView.getLayoutParams();
@@ -491,7 +502,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
int hSpanInc = getSpanIncrement((mDeltaX + mDeltaXAddOn) / xThreshold - mRunningHInc);
int vSpanInc = getSpanIncrement((mDeltaY + mDeltaYAddOn) / yThreshold - mRunningVInc);
if (!onDismiss && (hSpanInc == 0 && vSpanInc == 0)) return;
if (!onDismiss && (hSpanInc == 0 && vSpanInc == 0))
return;
mDirectionVector[0] = 0;
mDirectionVector[1] = 0;
@@ -503,7 +515,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
int cellX = lp.useTmpCoords ? lp.getTmpCellX() : lp.getCellX();
int cellY = lp.useTmpCoords ? lp.getTmpCellY() : lp.getCellY();
// For each border, we bound the resizing based on the minimum width, and the maximum
// For each border, we bound the resizing based on the minimum width, and the
// maximum
// expandability.
mTempRange1.set(cellX, spanX + cellX);
int hSpanDelta = mTempRange1.applyDeltaAndBound(mLeftBorderActive, mRightBorderActive,
@@ -523,9 +536,11 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
mDirectionVector[1] = mTopBorderActive ? -1 : 1;
}
if (!onDismiss && vSpanDelta == 0 && hSpanDelta == 0) return;
if (!onDismiss && vSpanDelta == 0 && hSpanDelta == 0)
return;
// We always want the final commit to match the feedback, so we make sure to use the
// We always want the final commit to match the feedback, so we make sure to use
// the
// last used direction vector when committing the resize / reorder.
if (onDismiss) {
mDirectionVector[0] = mLastDirectionVector[0];
@@ -535,12 +550,14 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
mLastDirectionVector[1] = mDirectionVector[1];
}
// We don't want to evaluate resize if a widget was pending config activity and was already
// occupying a space on the screen. This otherwise will cause reorder algorithm evaluate a
// We don't want to evaluate resize if a widget was pending config activity and
// was already
// occupying a space on the screen. This otherwise will cause reorder algorithm
// evaluate a
// different location for the widget and cause a jump.
if (!(mWidgetView instanceof PendingAppWidgetHostView) && mCellLayout.createAreaForResize(
cellX, cellY, spanX, spanY, mWidgetView, mDirectionVector, onDismiss)) {
if (mStateAnnouncer != null && (lp.cellHSpan != spanX || lp.cellVSpan != spanY) ) {
if (mStateAnnouncer != null && (lp.cellHSpan != spanX || lp.cellVSpan != spanY)) {
mStateAnnouncer.announce(
mLauncher.getString(R.string.widget_resized, spanX, spanY));
}
@@ -563,7 +580,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// We are done with resizing the widget. Save the widget size & position to LauncherModel
// We are done with resizing the widget. Save the widget size & position to
// LauncherModel
resizeWidgetIfNeeded(true);
mLauncher.getStatsLogManager()
.logger()
@@ -586,7 +604,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
}
/**
* Returns the rect of this view when the frame is snapped around the widget, with the bounds
* Returns the rect of this view when the frame is snapped around the widget,
* with the bounds
* relative to the {@link DragLayer}.
*/
private void getSnappedRectRelativeToDragLayer(@NonNull Rect out) {
@@ -614,7 +633,10 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
afterPos[1] + mWidgetViewNewRect.height());
}
/** Returns the relative x and y values of the widget view after the layout transition */
/**
* Returns the relative x and y values of the widget view after the layout
* transition
*/
private int[] getViewPosRelativeToDragLayer() {
mDragLayer.getLocationInWindow(sDragLayerLoc);
int x = sDragLayerLoc[0];
@@ -628,12 +650,13 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
int leftOffset = mWidgetViewNewRect.left - mWidgetViewOldRect.left;
int topOffset = mWidgetViewNewRect.top - mWidgetViewOldRect.top;
return new int[] {mWidgetViewWindowPos[0] - x + leftOffset,
mWidgetViewWindowPos[1] - y + topOffset};
return new int[] { mWidgetViewWindowPos[0] - x + leftOffset,
mWidgetViewWindowPos[1] - y + topOffset };
}
private void snapToWidget(boolean animate) {
// The widget is guaranteed to be attached to the cell layout at this point, thus setting
// The widget is guaranteed to be attached to the cell layout at this point,
// thus setting
// the transition here
if (FeatureFlags.ENABLE_WIDGET_TRANSITION_FOR_RESIZING.get()
&& mWidgetView.getLayoutTransition() == null) {
@@ -649,17 +672,21 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
int newX = sTmpRect.left;
int newY = sTmpRect.top;
// We need to make sure the frame's touchable regions lie fully within the bounds of the
// DragLayer. We allow the actual handles to be clipped, but we shift the touch regions
// We need to make sure the frame's touchable regions lie fully within the
// bounds of the
// DragLayer. We allow the actual handles to be clipped, but we shift the touch
// regions
// down accordingly to provide a proper touch target.
if (newY < 0) {
// In this case we shift the touch region down to start at the top of the DragLayer
// In this case we shift the touch region down to start at the top of the
// DragLayer
mTopTouchRegionAdjustment = -newY;
} else {
mTopTouchRegionAdjustment = 0;
}
if (newY + newHeight > mDragLayer.getHeight()) {
// In this case we shift the touch region up to end at the bottom of the DragLayer
// In this case we shift the touch region up to end at the bottom of the
// DragLayer
mBottomTouchRegionAdjustment = -(newY + newHeight - mDragLayer.getHeight());
} else {
mBottomTouchRegionAdjustment = 0;
@@ -714,7 +741,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// Clear the frame and give focus to the widget host view when a directional key is pressed.
// Clear the frame and give focus to the widget host view when a directional key
// is pressed.
if (shouldConsume(keyCode)) {
close(false);
mWidgetView.requestFocus();
@@ -773,7 +801,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
if (ev.getAction() == MotionEvent.ACTION_DOWN && handleTouchDown(ev)) {
return true;
}
// Keep the resize frame open but let a click on the reconfigure button fall through to the
// Keep the resize frame open but let a click on the reconfigure button fall
// through to the
// button's OnClickListener.
if (isTouchOnReconfigureButton(ev)) {
return false;
@@ -864,7 +893,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
}
/**
* Moves either the start or end edge (but never both) by {@param delta} and sets the
* Moves either the start or end edge (but never both) by {@param delta} and
* sets the
* result in {@param out}
*/
public void applyDelta(boolean moveStart, boolean moveEnd, int delta, IntRange out) {
@@ -873,17 +903,25 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
}
/**
* Applies delta similar to {@link #applyDelta(boolean, boolean, int, IntRange)},
* Applies delta similar to
* {@link #applyDelta(boolean, boolean, int, IntRange)},
* with extra conditions.
* @param minSize minimum size after with the moving edge should not be shifted any further.
* For eg, if delta = -3 when moving the endEdge brings the size to less than
*
* @param minSize minimum size after with the moving edge should not be shifted
* any further.
* For eg, if delta = -3 when moving the endEdge brings the size
* to less than
* minSize, only delta = -2 will applied
* @param maxSize maximum size after with the moving edge should not be shifted any further.
* For eg, if delta = -3 when moving the endEdge brings the size to greater
* @param maxSize maximum size after with the moving edge should not be shifted
* any further.
* For eg, if delta = -3 when moving the endEdge brings the size
* to greater
* than maxSize, only delta = -2 will applied
* @param maxEnd The maximum value to the end edge (start edge is always restricted to 0)
* @return the amount of increase when endEdge was moves and the amount of decrease when
* the start edge was moved.
* @param maxEnd The maximum value to the end edge (start edge is always
* restricted to 0)
* @return the amount of increase when endEdge was moves and the amount of
* decrease when
* the start edge was moved.
*/
public int applyDeltaAndBound(boolean moveStart, boolean moveEnd, int delta,
int minSize, int maxSize, int maxEnd, IntRange out) {
@@ -922,12 +960,14 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
|| keyCode == KeyEvent.KEYCODE_PAGE_UP || keyCode == KeyEvent.KEYCODE_PAGE_DOWN);
}
@Nullable private ArrowTipView showReconfigurableWidgetEducationTip() {
@Nullable
private ArrowTipView showReconfigurableWidgetEducationTip() {
Rect rect = new Rect();
if (!mReconfigureButton.getGlobalVisibleRect(rect)) {
return null;
}
@Px int tipMargin = mLauncher.getResources()
@Px
int tipMargin = mLauncher.getResources()
.getDimensionPixelSize(R.dimen.widget_reconfigure_tip_top_margin);
return new ArrowTipView(mLauncher, /* isPointingUp= */ true)
.showAroundRect(
@@ -94,11 +94,6 @@ public class AutoInstallsLayout {
public static AutoInstallsLayout get(Context context, LauncherWidgetHolder appWidgetHolder,
LayoutParserCallback callback) {
// LC: c51b2a221838aefb610b7146fc4ef7cb34e5e495
if (!BuildConfig.ENABLE_AUTO_INSTALLS_LAYOUT) {
return null;
}
Partner partner = Partner.get(context.getPackageManager(), ACTION_LAUNCHER_CUSTOMIZATION);
if (partner == null) {
return null;
@@ -269,13 +264,6 @@ public class AutoInstallsLayout {
return count;
}
private void addProfileId(XmlPullParser parser) {
Long profileId = mUserTypeToSerial.get(getAttributeValue(parser, ATTR_USER_TYPE));
if (profileId != null) {
mValues.put(Favorites.PROFILE_ID, profileId);
}
}
/**
* Parses container and screenId attribute from the current tag, and puts it in
* the out.
@@ -322,6 +310,10 @@ public class AutoInstallsLayout {
convertToDistanceFromEnd(getAttributeValue(parser, ATTR_X), mColumnCount));
mValues.put(Favorites.CELLY,
convertToDistanceFromEnd(getAttributeValue(parser, ATTR_Y), mRowCount));
Long profileId = mUserTypeToSerial.get(getAttributeValue(parser, ATTR_USER_TYPE));
if (profileId != null) {
mValues.put(Favorites.PROFILE_ID, profileId);
}
TagParser tagParser = tagParserMap.get(parser.getName());
if (tagParser == null) {
@@ -397,7 +389,7 @@ public class AutoInstallsLayout {
public int parseAndAdd(XmlPullParser parser) {
final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
addProfileId(parser);
if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(className)) {
ActivityInfo info;
try {
@@ -446,7 +438,6 @@ public class AutoInstallsLayout {
public int parseAndAdd(XmlPullParser parser) {
final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
addProfileId(parser);
if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
if (LOGD)
Log.d(TAG, "Skipping invalid <favorite> with no component");
@@ -469,7 +460,7 @@ public class AutoInstallsLayout {
public int parseAndAdd(XmlPullParser parser) {
final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
final String shortcutId = getAttributeValue(parser, ATTR_SHORTCUT_ID);
addProfileId(parser);
try {
LauncherApps launcherApps = mContext.getSystemService(LauncherApps.class);
launcherApps.pinShortcuts(packageName, Collections.singletonList(shortcutId),
@@ -503,7 +494,6 @@ public class AutoInstallsLayout {
public ComponentName getComponentName(XmlPullParser parser) {
final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
addProfileId(parser);
if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
return null;
}
+22 -113
View File
@@ -16,7 +16,6 @@
package com.android.launcher3;
import static com.android.launcher3.util.DisplayController.CHANGE_ROTATION;
import static com.android.launcher3.util.FlagDebugUtils.appendFlag;
import static com.android.launcher3.util.FlagDebugUtils.formatFlagChange;
import static com.android.launcher3.util.SystemUiController.UI_STATE_FULLSCREEN_TASK;
@@ -32,34 +31,18 @@ import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.ActionMode;
import android.view.View;
import android.window.OnBackInvokedDispatcher;
import androidx.activity.ComponentActivity;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleRegistry;
import androidx.savedstate.SavedStateRegistry;
import androidx.savedstate.SavedStateRegistryController;
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.testing.TestLogging;
import com.android.launcher3.testing.shared.TestProtocol;
import com.android.launcher3.util.ActivityOptionsWrapper;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.util.DisplayController.DisplayInfoChangeListener;
import com.android.launcher3.util.DisplayController.Info;
import com.android.launcher3.util.LifecycleHelper;
import com.android.launcher3.util.RunnableList;
import com.android.launcher3.util.SystemUiController;
import com.android.launcher3.util.ViewCache;
import com.android.launcher3.util.WeakCleanupSet;
import com.android.launcher3.util.WindowBounds;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.ScrimView;
@@ -72,8 +55,7 @@ import java.util.StringJoiner;
/**
* Launcher BaseActivity
*/
public abstract class BaseActivity extends Activity implements ActivityContext,
DisplayInfoChangeListener {
public abstract class BaseActivity extends ComponentActivity implements ActivityContext {
private static final String TAG = "BaseActivity";
static final boolean DEBUG = false;
@@ -106,15 +88,11 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
private final ArrayList<MultiWindowModeChangedListener> mMultiWindowModeChangedListeners =
new ArrayList<>();
private final SavedStateRegistryController mSavedStateRegistryController =
SavedStateRegistryController.create(this);
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
private final WeakCleanupSet mCleanupSet = new WeakCleanupSet(this);
protected DeviceProfile mDeviceProfile;
protected SystemUiController mSystemUiController;
private StatsLogManager mStatsLogManager;
public static final int ACTIVITY_STATE_STARTED = 1 << 0;
public static final int ACTIVITY_STATE_RESUMED = 1 << 1;
@@ -134,6 +112,11 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
*/
public static final int ACTIVITY_STATE_USER_ACTIVE = 1 << 4;
/**
* State flag indicating if the user will be active shortly.
*/
public static final int ACTIVITY_STATE_USER_WILL_BE_ACTIVE = 1 << 5;
/**
* State flag indicating that a state transition is in progress
*/
@@ -151,10 +134,6 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
public @interface ActivityFlags {
}
// When starting an action mode, setting this tag will cause the action mode to be cancelled
// automatically when user interacts with the launcher.
public static final Object AUTO_CANCEL_ACTION_MODE = new Object();
/** Returns a human-readable string for the specified {@link ActivityFlags}. */
public static String getActivityStateString(@ActivityFlags int flags) {
StringJoiner result = new StringJoiner("|");
@@ -189,14 +168,6 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
private final RunnableList[] mEventCallbacks =
{new RunnableList(), new RunnableList(), new RunnableList(), new RunnableList()};
private ActionMode mCurrentActionMode;
public BaseActivity() {
mSavedStateRegistryController.performAttach();
registerActivityLifecycleCallbacks(
new LifecycleHelper(this, mSavedStateRegistryController, mLifecycleRegistry));
}
@Override
public ViewCache getViewCache() {
return mViewCache;
@@ -225,7 +196,7 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
public SystemUiController getSystemUiController() {
if (mSystemUiController == null) {
mSystemUiController = new SystemUiController(getWindow().getDecorView());
mSystemUiController = new SystemUiController(getWindow());
}
return mSystemUiController;
}
@@ -243,7 +214,6 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerBackDispatcher();
DisplayController.INSTANCE.get(this).addChangeListener(this);
}
@Override
@@ -291,7 +261,6 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
protected void onDestroy() {
super.onDestroy();
mEventCallbacks[EVENT_DESTROYED].executeAllAndClear();
DisplayController.INSTANCE.get(this).removeChangeListener(this);
}
@Override
@@ -350,6 +319,7 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
*/
public void setResumed() {
addActivityFlags(ACTIVITY_STATE_RESUMED | ACTIVITY_STATE_USER_ACTIVE);
removeActivityFlags(ACTIVITY_STATE_USER_WILL_BE_ACTIVE);
}
public boolean isUserActive() {
@@ -424,6 +394,15 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
mEventCallbacks[event].add(callback);
}
@Override
public Handler getMainThreadHandler() {
try {
return new Handler(Looper.getMainLooper());
} catch (Throwable t) {
return super.getMainThreadHandler();
}
}
/** Removes a previously added callback */
public void removeEventCallback(@ActivityEvent int event, Runnable callback) {
mEventCallbacks[event].remove(callback);
@@ -442,83 +421,13 @@ public abstract class BaseActivity extends Activity implements ActivityContext,
writer.println(prefix + "mForceInvisible: " + mForceInvisible);
}
@Override
public void onActionModeStarted(ActionMode mode) {
super.onActionModeStarted(mode);
mCurrentActionMode = mode;
}
@Override
public void onActionModeFinished(ActionMode mode) {
super.onActionModeFinished(mode);
mCurrentActionMode = null;
}
protected boolean isInAutoCancelActionMode() {
return mCurrentActionMode != null && AUTO_CANCEL_ACTION_MODE == mCurrentActionMode.getTag();
}
@Override
public boolean finishAutoCancelActionMode() {
if (isInAutoCancelActionMode()) {
mCurrentActionMode.finish();
return true;
}
return false;
}
@Override
@NonNull
public ActivityOptionsWrapper getActivityLaunchOptions(View v, @Nullable ItemInfo item) {
ActivityOptionsWrapper wrapper = ActivityContext.super.getActivityLaunchOptions(v, item);
addEventCallback(EVENT_RESUMED, wrapper.onEndCallback::executeAllAndDestroy);
return wrapper;
}
@Override
public ActivityOptionsWrapper makeDefaultActivityOptions(int splashScreenStyle) {
ActivityOptionsWrapper wrapper =
ActivityContext.super.makeDefaultActivityOptions(splashScreenStyle);
addEventCallback(EVENT_RESUMED, wrapper.onEndCallback::executeAllAndDestroy);
return wrapper;
}
protected WindowBounds getMultiWindowDisplaySize() {
return WindowBounds.fromWindowMetrics(getWindowManager().getCurrentWindowMetrics());
}
@Override
public void onDisplayInfoChanged(Context context, Info info, int flags) {
if ((flags & CHANGE_ROTATION) != 0 && mDeviceProfile.isVerticalBarLayout()) {
reapplyUi();
}
}
protected void reapplyUi() {}
@NonNull
@Override
public SavedStateRegistry getSavedStateRegistry() {
return mSavedStateRegistryController.getSavedStateRegistry();
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
@Override
public WeakCleanupSet getOwnerCleanupSet() {
return mCleanupSet;
}
public static <T extends BaseActivity> T fromContext(Context context) {
if (context instanceof BaseActivity) {
return (T) context;
} else if (context instanceof ContextWrapper cw) {
return fromContext(cw.getBaseContext());
} else if (context instanceof ActivityContextDelegate) {
return (T) ((ActivityContextDelegate) context).mDelegate;
} else if (context instanceof ContextWrapper) {
return fromContext(((ContextWrapper) context).getBaseContext());
} else {
throw new IllegalArgumentException("Cannot find BaseActivity in parent tree");
}
File diff suppressed because it is too large. Load diff
+28 -32
View File
@@ -42,14 +42,10 @@ import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.dragndrop.DragView;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.MSDLPlayerWrapper;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ActivityContext;
import com.google.android.msdl.data.model.MSDLToken;
import app.lawnchair.theme.color.tokens.ColorTokens;
import app.lawnchair.theme.drawable.DrawableTokens;
import com.android.launcher3.views.ActivityContext;
/**
* Implements a DropTarget.
@@ -70,13 +66,15 @@ public abstract class ButtonDropTarget extends TextView
protected final ActivityContext mActivityContext;
protected final DropTargetHandler mDropTargetHandler;
protected DropTargetBar mDropTargetBar;
private MSDLPlayerWrapper mMSDLPlayerWrapper;
/** Whether this drop target is active for the current drag */
protected boolean mActive;
/** Whether an accessible drag is in progress */
private boolean mAccessibleDrag;
/** An item must be dragged at least this many pixels before this drop target is enabled. */
/**
* An item must be dragged at least this many pixels before this drop target is
* enabled.
*/
private final int mDragDistanceThreshold;
/** The size of the drawable shown in the drop target. */
private final int mDrawableSize;
@@ -95,6 +93,7 @@ public abstract class ButtonDropTarget extends TextView
public ButtonDropTarget(Context context) {
this(context, null, 0);
}
public ButtonDropTarget(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@@ -103,7 +102,6 @@ public abstract class ButtonDropTarget extends TextView
super(context, attrs, defStyle);
mActivityContext = ActivityContext.lookupContext(context);
mDropTargetHandler = mActivityContext.getDropTargetHandler();
mMSDLPlayerWrapper = MSDLPlayerWrapper.INSTANCE.get(context);
Resources resources = getResources();
mDragDistanceThreshold = resources.getDimensionPixelSize(R.dimen.drag_distanceThreshold);
@@ -143,7 +141,8 @@ public abstract class ButtonDropTarget extends TextView
}
protected void setDrawable(int resId) {
// We do not set the drawable in the xml as that inflates two drawables corresponding to
// We do not set the drawable in the xml as that inflates two drawables
// corresponding to
// drawableLeft and drawableStart.
mDrawable = getContext().getDrawable(resId).mutate();
mDrawable.setTintList(getTextColors());
@@ -163,10 +162,6 @@ public abstract class ButtonDropTarget extends TextView
@Override
public final void onDragEnter(DragObject d) {
// Perform Haptic feedback
if (Flags.msdlFeedback()) {
mMSDLPlayerWrapper.playToken(MSDLToken.SWIPE_THRESHOLD_INDICATOR);
}
if (!mAccessibleDrag && !mTextVisible) {
// Show tooltip
hideTooltip();
@@ -245,8 +240,7 @@ public abstract class ButtonDropTarget extends TextView
@Override
public boolean isDropEnabled() {
return mActive && (mAccessibleDrag ||
mActivityContext.getDragController().getDistanceDragged()
>= mDragDistanceThreshold);
mActivityContext.getDragController().getDistanceDragged() >= mDragDistanceThreshold);
}
@Override
@@ -290,7 +284,8 @@ public abstract class ButtonDropTarget extends TextView
public abstract int getAccessibilityAction();
@Override
public void prepareAccessibilityDrop() { }
public void prepareAccessibilityDrop() {
}
public abstract void onAccessibilityDrop(View view, ItemInfo item);
@@ -365,7 +360,8 @@ public abstract class ButtonDropTarget extends TextView
}
/**
* Display button text over multiple lines when isMultiLine is true, single line otherwise.
* Display button text over multiple lines when isMultiLine is true, single line
* otherwise.
*/
public void setTextMultiLine(boolean isMultiLine) {
if (mTextMultiLine != isMultiLine) {
@@ -431,19 +427,20 @@ public abstract class ButtonDropTarget extends TextView
return !TextUtils.equals(mText, firstLine);
}
if (TextUtils.equals(mText, firstLine)) {
// When multi-line is active, if it can display as one line, then text is not truncated.
// When multi-line is active, if it can display as one line, then text is not
// truncated.
return false;
}
CharSequence secondLine =
TextUtils.ellipsize(mText.subSequence(firstLine.length(), mText.length()),
getPaint(), availableWidth, TextUtils.TruncateAt.END);
CharSequence secondLine = TextUtils.ellipsize(mText.subSequence(firstLine.length(), mText.length()),
getPaint(), availableWidth, TextUtils.TruncateAt.END);
return !(TextUtils.equals(mText.subSequence(0, firstLine.length()), firstLine)
&& TextUtils.equals(mText.subSequence(firstLine.length(), secondLine.length()),
secondLine));
secondLine));
}
/**
* Returns if the text will be clipped vertically within the provided availableHeight.
* Returns if the text will be clipped vertically within the provided
* availableHeight.
*/
@VisibleForTesting
protected boolean isTextClippedVertically(int availableHeight) {
@@ -454,22 +451,21 @@ public abstract class ButtonDropTarget extends TextView
return textHeight + getPaddingTop() + getPaddingBottom() >= availableHeight;
}
@VisibleForTesting
public void setMSDLPlayerWrapper(MSDLPlayerWrapper wrapper) {
mMSDLPlayerWrapper = wrapper;
}
/**
* Reduce the size of the text until it fits the measured width or reaches a minimum.
* Reduce the size of the text until it fits the measured width or reaches a
* minimum.
*
* The minimum size is defined by {@code R.dimen.button_drop_target_min_text_size} and
* The minimum size is defined by
* {@code R.dimen.button_drop_target_min_text_size} and
* it diminishes by intervals defined by
* {@code R.dimen.button_drop_target_resize_text_increment}
* This functionality is very similar to the option
* {@link TextView#setAutoSizeTextTypeWithDefaults(int)} but can't be used in this view because
* {@link TextView#setAutoSizeTextTypeWithDefaults(int)} but can't be used in
* this view because
* the layout width is {@code WRAP_CONTENT}.
*
* @return The biggest text size in SP that makes the text fit or if the text can't fit returns
* @return The biggest text size in SP that makes the text fit or if the text
* can't fit returns
* the min available value
*/
public float resizeTextToFit() {
+6 -46
View File
@@ -47,7 +47,6 @@ import android.view.View;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
@@ -72,7 +71,6 @@ import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.util.CellAndSpan;
import com.android.launcher3.util.GridOccupancy;
import com.android.launcher3.util.MSDLPlayerWrapper;
import com.android.launcher3.util.MultiTranslateDelegate;
import com.android.launcher3.util.ParcelableSparseArray;
import com.android.launcher3.util.Themes;
@@ -81,8 +79,6 @@ import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.widget.LauncherAppWidgetHostView;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import com.google.android.msdl.data.model.MSDLToken;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
@@ -95,7 +91,7 @@ import app.lawnchair.theme.drawable.DrawableTokens;
public class CellLayout extends ViewGroup {
private static final String TAG = "CellLayout";
private static final boolean LOGD = true;
private static final boolean LOGD = false;
/** The color of the "leave-behind" shape when a folder is opened from Hotseat. */
private static final int FOLDER_LEAVE_BEHIND_COLOR = Color.argb(160, 245, 245, 245);
@@ -175,8 +171,6 @@ public class CellLayout extends ViewGroup {
private final int[] mDragCellSpan = new int[2];
private boolean mDragging = false;
public boolean mHasOnLayoutBeenCalled = false;
private boolean mPlayDragHaptics = false;
private final TimeInterpolator mEaseOutInterpolator;
protected final ShortcutAndWidgetContainer mShortcutsAndWidgets;
@@ -214,8 +208,6 @@ public class CellLayout extends ViewGroup {
private static final Paint sPaint = new Paint();
private final MSDLPlayerWrapper mMSDLPlayerWrapper;
// Related to accessible drag and drop
DragAndDropAccessibilityDelegate mTouchHelper;
@@ -251,8 +243,6 @@ public class CellLayout extends ViewGroup {
mContainerType = a.getInteger(R.styleable.CellLayout_containerType, WORKSPACE);
a.recycle();
mMSDLPlayerWrapper = MSDLPlayerWrapper.INSTANCE.get(context);
// A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
// the user where a dragged item will land when dropped.
setWillNotDraw(false);
@@ -539,11 +529,9 @@ public class CellLayout extends ViewGroup {
for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
DelegatedCellDrawing cellDrawing = mDelegatedCellDrawings.get(i);
cellToPoint(cellDrawing.mDelegateCellX, cellDrawing.mDelegateCellY, mTempLocation);
canvas.save();
if (cellDrawing.mDelegateCellX >= 0 && cellDrawing.mDelegateCellY >= 0) {
cellToPoint(cellDrawing.mDelegateCellX, cellDrawing.mDelegateCellY, mTempLocation);
canvas.translate(mTempLocation[0], mTempLocation[1]);
}
canvas.translate(mTempLocation[0], mTempLocation[1]);
cellDrawing.drawUnderItem(canvas);
canvas.restore();
}
@@ -672,11 +660,9 @@ public class CellLayout extends ViewGroup {
for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
DelegatedCellDrawing bg = mDelegatedCellDrawings.get(i);
cellToPoint(bg.mDelegateCellX, bg.mDelegateCellY, mTempLocation);
canvas.save();
if (bg.mDelegateCellX >= 0 && bg.mDelegateCellY >= 0) {
cellToPoint(bg.mDelegateCellX, bg.mDelegateCellY, mTempLocation);
canvas.translate(mTempLocation[0], mTempLocation[1]);
}
canvas.translate(mTempLocation[0], mTempLocation[1]);
bg.drawOverItem(canvas);
canvas.restore();
}
@@ -797,12 +783,6 @@ public class CellLayout extends ViewGroup {
}
mShortcutsAndWidgets.addView(child, index, lp);
// Whenever an app is added, if Accessibility service is enabled, focus on that app.
if (mActivity instanceof Launcher) {
child.setTag(R.id.perform_a11y_action_on_launcher_state_normal_tag,
AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
}
if (markCells) markCellsAsOccupiedForView(child);
return true;
@@ -1039,7 +1019,6 @@ public class CellLayout extends ViewGroup {
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
mHasOnLayoutBeenCalled = true; // b/349929393 - is the required call to onLayout not done?
int left = getPaddingLeft();
left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
int right = r - l - getPaddingRight();
@@ -1182,10 +1161,6 @@ public class CellLayout extends ViewGroup {
DropTarget.DragObject dragObject) {
if (mDragCell[0] != cellX || mDragCell[1] != cellY || mDragCellSpan[0] != spanX
|| mDragCellSpan[1] != spanY) {
determineIfDragHapticsPlay();
if (mPlayDragHaptics && Flags.msdlFeedback()) {
mMSDLPlayerWrapper.playToken(MSDLToken.DRAG_INDICATOR_DISCRETE);
}
mDragCell[0] = cellX;
mDragCell[1] = cellY;
mDragCellSpan[0] = spanX;
@@ -1211,14 +1186,6 @@ public class CellLayout extends ViewGroup {
}
}
private void determineIfDragHapticsPlay() {
if (mDragCell[0] != -1 || mDragCell[1] != -1
|| mDragCellSpan[0] != -1 || mDragCellSpan[1] != -1) {
// The nearest cell is known and we can play haptics
mPlayDragHaptics = true;
}
}
@SuppressLint("StringFormatMatches")
public String getItemMoveDescription(int cellX, int cellY) {
if (mContainerType == HOTSEAT) {
@@ -1820,7 +1787,6 @@ public class CellLayout extends ViewGroup {
* @param child The child that is being dropped
*/
void onDropChild(View child) {
mPlayDragHaptics = false;
if (child != null) {
CellLayoutLayoutParams
lp = (CellLayoutLayoutParams) child.getLayoutParams();
@@ -1848,8 +1814,7 @@ public class CellLayout extends ViewGroup {
+ (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
final int vStartPadding = getPaddingTop();
int x = hStartPadding + (cellX * mBorderSpace.x) + (cellX * cellWidth)
+ getTranslationXForCell(cellX, cellY);
int x = hStartPadding + (cellX * mBorderSpace.x) + (cellX * cellWidth);
int y = vStartPadding + (cellY * mBorderSpace.y) + (cellY * cellHeight);
int width = cellHSpan * cellWidth + ((cellHSpan - 1) * mBorderSpace.x);
@@ -1858,11 +1823,6 @@ public class CellLayout extends ViewGroup {
resultRect.set(x, y, x + width, y + height);
}
/** Enables successors to provide an X adjustment for the cell. */
protected int getTranslationXForCell(int cellX, int cellY) {
return 0;
}
public void markCellsAsOccupiedForView(View view) {
if (view instanceof LauncherAppWidgetHostView
&& view.getTag() instanceof LauncherAppWidgetInfo) {
@@ -151,8 +151,6 @@ public class CheckLongPressHelper {
handled = mView.performLongClick();
}
if (handled) {
// Cancel any default long-press action on the view
mView.cancelLongPress();
mView.setPressed(false);
mHasPerformedLongPress = true;
}
@@ -22,7 +22,6 @@ import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCH
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
@@ -143,11 +142,8 @@ public class DeleteDropTarget extends ButtonDropTarget {
public void completeDrop(DragObject d) {
ItemInfo item = d.dragInfo;
if (canRemove(item)) {
onAccessibilityDrop(null, item);
mDropTargetHandler.onDeleteComplete(item);
} else if (mText == getResources().getText(R.string.remove_drop_target_label)) {
Log.wtf("b/379606516", "If the drop target text is 'remove', then"
+ " users should always be able to delete the item from launcher's db."
+ " Invalid drag ItemInfo: " + item);
}
}
File diff suppressed because it is too large. Load diff
@@ -18,7 +18,6 @@ package com.android.launcher3;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import com.android.launcher3.accessibility.DragViewStateAnnouncer;
import com.android.launcher3.dragndrop.DragOptions;
@@ -146,9 +145,4 @@ public interface DropTarget {
// These methods are implemented in Views
void getHitRectRelativeToDragLayer(Rect outRect);
/** Returns the drop target view. By default, the implementor class is cast to the view. */
default View getDropView() {
return (View) this;
}
}
+22 -23
View File
@@ -2,7 +2,7 @@ package com.android.launcher3
import android.content.ComponentName
import android.view.View
import com.android.launcher3.BaseActivity.EVENT_RESUMED
import com.android.launcher3.BaseDraggingActivity.EVENT_RESUMED
import com.android.launcher3.DropTarget.DragObject
import com.android.launcher3.LauncherConstants.ActivityCodes
import com.android.launcher3.SecondaryDropTarget.DeferredOnComplete
@@ -35,7 +35,8 @@ class DropTargetHandler(launcher: Launcher) {
target?.let {
deferred.mPackageName = it.packageName
mLauncher.addEventCallback(EVENT_RESUMED) { deferred.onLauncherResume() }
} ?: deferred.sendFailure()
}
?: deferred.sendFailure()
}
}
}
@@ -46,10 +47,19 @@ class DropTargetHandler(launcher: Launcher) {
mLauncher.appWidgetHolder.startConfigActivity(
mLauncher,
widgetId,
ActivityCodes.REQUEST_RECONFIGURE_APPWIDGET,
ActivityCodes.REQUEST_RECONFIGURE_APPWIDGET
)
}
fun dismissPrediction(
announcement: CharSequence,
onActionClicked: Runnable,
onDismiss: Runnable?
) {
mLauncher.dragLayer.announceForAccessibility(announcement)
Snackbar.show(mLauncher, R.string.item_removed, R.string.undo, onDismiss, onActionClicked)
}
fun getViewUnderDrag(info: ItemInfo): View? {
return if (
info is LauncherAppWidgetInfo &&
@@ -65,17 +75,10 @@ class DropTargetHandler(launcher: Launcher) {
}
fun onDeleteComplete(item: ItemInfo) {
removeItemAndStripEmptyScreens(null /* view */, item)
AbstractFloatingView.closeOpenViews(
mLauncher,
false,
AbstractFloatingView.TYPE_WIDGET_RESIZE_FRAME,
)
var pageItem: ItemInfo = item
if (item.container >= 0) {
mLauncher.workspace.getViewByItemId(item.container)?.let {
pageItem = it.tag as ItemInfo
}
if (item.container <= 0) {
val v = mLauncher.workspace.getHomescreenIconByItemId(item.container)
v?.let { pageItem = v.tag as ItemInfo }
}
val pageIds =
if (pageItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP)
@@ -92,12 +95,16 @@ class DropTargetHandler(launcher: Launcher) {
R.string.item_removed,
R.string.undo,
mLauncher.modelWriter::commitDelete,
onUndoClicked,
onUndoClicked
)
}
fun onAccessibilityDelete(view: View?, item: ItemInfo, announcement: CharSequence) {
removeItemAndStripEmptyScreens(view, item)
// Remove the item from launcher and the db, we can ignore the containerInfo in this call
// because we already remove the drag view from the folder (if the drag originated from
// a folder) in Folder.beginDrag()
mLauncher.removeItem(view, item, true /* deleteFromDb */, "removed by accessibility drop")
mLauncher.workspace.stripEmptyScreens()
mLauncher.dragLayer.announceForAccessibility(announcement)
}
@@ -108,12 +115,4 @@ class DropTargetHandler(launcher: Launcher) {
fun onClick(buttonDropTarget: ButtonDropTarget) {
mLauncher.accessibilityDelegate.handleAccessibleDrop(buttonDropTarget, null, null)
}
private fun removeItemAndStripEmptyScreens(view: View?, item: ItemInfo) {
// Remove the item from launcher and the db, we can ignore the containerInfo in this call
// because we already remove the drag view from the folder (if the drag originated from
// a folder) in Folder.beginDrag()
mLauncher.removeItem(view, item, true /* deleteFromDb */, "removed by accessibility drop")
mLauncher.workspace.stripEmptyScreens()
}
}
@@ -25,23 +25,24 @@ import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.android.app.animation.Interpolators;
import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.views.RecyclerViewFastScroller;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import app.lawnchair.preferences2.PreferenceManager2;
/**
* A base {@link RecyclerView}, which does the following:
* <ul>
* <li> NOT intercept a touch unless the scrolling velocity is below a predefined threshold.
* <li> Enable fast scroller.
* <li>NOT intercept a touch unless the scrolling velocity is below a predefined
* threshold.
* <li>Enable fast scroller.
* </ul>
*/
public abstract class FastScrollRecyclerView extends RecyclerView {
public abstract class FastScrollRecyclerView extends RecyclerView {
protected RecyclerViewFastScroller mScrollbar;
@@ -62,12 +63,9 @@ public abstract class FastScrollRecyclerView extends RecyclerView {
pref2 = PreferenceManager2.getInstance(context);
}
public void bindFastScrollbar(RecyclerViewFastScroller scrollbar,
RecyclerViewFastScroller.FastScrollerLocation location) {
public void bindFastScrollbar(RecyclerViewFastScroller scrollbar) {
mScrollbar = scrollbar;
mScrollbar.setRecyclerView(this);
mScrollbar.setFastScrollerLocation(location);
scrollToTop();
onUpdateScrollbar(0);
}
@@ -115,7 +113,7 @@ public abstract class FastScrollRecyclerView extends RecyclerView {
/**
* Returns the available scroll height:
* AvailableScrollHeight = Total height of the all items - last page height
* AvailableScrollHeight = Total height of the all items - last page height
*/
protected int getAvailableScrollHeight() {
// AvailableScrollHeight = Total height of the all items - first page height
@@ -126,15 +124,17 @@ public abstract class FastScrollRecyclerView extends RecyclerView {
/**
* Returns the available scroll bar height:
* AvailableScrollBarHeight = Total height of the visible view - thumb height
* AvailableScrollBarHeight = Total height of the visible view - thumb height
*/
protected int getAvailableScrollBarHeight() {
return getScrollbarTrackHeight() - mScrollbar.getThumbHeight();
}
/**
* Updates the scrollbar thumb offset to match the visible scroll of the recycler view. It does
* this by mapping the available scroll area of the recycler view to the available space for the
* Updates the scrollbar thumb offset to match the visible scroll of the
* recycler view. It does
* this by mapping the available scroll area of the recycler view to the
* available space for the
* scroll bar.
*
* @param scrollY the current scroll y
@@ -147,11 +147,12 @@ public abstract class FastScrollRecyclerView extends RecyclerView {
return;
}
// Calculate the current scroll position, the scrollY of the recycler view accounts for the
// view padding, while the scrollBarY is drawn right up to the background padding (ignoring
// Calculate the current scroll position, the scrollY of the recycler view
// accounts for the
// view padding, while the scrollBarY is drawn right up to the background
// padding (ignoring
// padding)
int scrollBarY =
(int) (((float) scrollY / availableScrollHeight) * getAvailableScrollBarHeight());
int scrollBarY = (int) (((float) scrollY / availableScrollHeight) * getAvailableScrollBarHeight());
// Calculate the position and size of the scroll bar
mScrollbar.setThumbOffsetY(scrollBarY);
@@ -159,6 +160,7 @@ public abstract class FastScrollRecyclerView extends RecyclerView {
/**
* Returns whether the view itself will handle the touch event or not.
*
* @param ev MotionEvent in {@param eventSource}
*/
public boolean shouldContainerScroll(MotionEvent ev, View eventSource) {
@@ -171,7 +173,8 @@ public abstract class FastScrollRecyclerView extends RecyclerView {
return false;
}
// IF scroller is at the very top OR there is no scroll bar because there is probably not
// IF scroller is at the very top OR there is no scroll bar because there is
// probably not
// enough items to scroll, THEN it's okay for the container to be pulled down.
return computeVerticalScrollOffset() == 0;
}
@@ -185,28 +188,25 @@ public abstract class FastScrollRecyclerView extends RecyclerView {
/**
* Maps the touch (from 0..1) to the adapter position that should be visible.
* <p>Override in each subclass of this base class.
* <p>
* Override in each subclass of this base class.
*/
public abstract CharSequence scrollToPositionAtProgress(float touchFraction);
/**
* Updates the bounds for the scrollbar.
* <p>Override in each subclass of this base class.
* <p>
* Override in each subclass of this base class.
*/
public abstract void onUpdateScrollbar(int dy);
/**
* Return the fast scroll letter list view in the A-Z list.
* <p>
* Override in each subclass of this base class.
*/
public ConstraintLayout getLetterList() {
return null;
public void onFastScrollCompleted() {
}
/**
* <p>Override in each subclass of this base class.
*/
public void onFastScrollCompleted() {}
@Override
public void onScrollStateChanged(int state) {
super.onScrollStateChanged(state);
@@ -221,7 +221,8 @@ public abstract class FastScrollRecyclerView extends RecyclerView {
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
if (isLayoutSuppressed()) info.setScrollable(false);
if (isLayoutSuppressed())
info.setScrollable(false);
}
/**
@@ -19,13 +19,10 @@ import static android.content.Intent.EXTRA_COMPONENT_NAME;
import static android.content.Intent.EXTRA_USER;
import static com.android.launcher3.AbstractFloatingView.TYPE_ICON_SURFACE;
import static com.android.launcher3.Utilities.ATLEAST_Q;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
@@ -74,9 +71,7 @@ public class GestureNavContract {
@Nullable SurfaceControl surfaceControl) {
Bundle result = new Bundle();
result.putParcelable(EXTRA_ICON_POSITION, position);
if (ATLEAST_Q) {
result.putParcelable(EXTRA_ICON_SURFACE, surfaceControl);
}
result.putParcelable(EXTRA_ICON_SURFACE, surfaceControl);
if (sMessageReceiver == null) {
sMessageReceiver = new StaticMessageReceiver();
}
+66 -151
View File
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications copyright 2025 Lawnchair
* Modifications copyright 2022 Lawnchair
*/
package com.android.launcher3;
@@ -40,27 +40,10 @@ import android.view.ViewDebug;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import com.android.launcher3.ShortcutAndWidgetContainer.TranslationProvider;
import com.android.launcher3.celllayout.CellLayoutLayoutParams;
import com.android.launcher3.taskbar.BlurredBitmapDrawable;
import com.android.launcher3.util.HorizontalInsettableView;
import com.android.launcher3.util.MultiPropertyFactory;
import com.android.launcher3.util.MultiPropertyFactory.MultiProperty;
import com.android.launcher3.util.MultiTranslateDelegate;
import com.android.launcher3.util.MultiValueAlpha;
import com.android.launcher3.views.ActivityContext;
import android.graphics.drawable.Drawable;
import java.io.PrintWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import com.hoko.blur.HokoBlur;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import app.lawnchair.hotseat.DisabledHotseat;
import app.lawnchair.hotseat.HotseatMode;
import app.lawnchair.hotseat.LawnchairHotseat;
@@ -68,30 +51,16 @@ import app.lawnchair.preferences.PreferenceManager;
import app.lawnchair.preferences2.PreferenceManager2;
import app.lawnchair.theme.drawable.DrawableTokens;
import com.android.launcher3.util.HorizontalInsettableView;
import com.android.launcher3.util.MultiTranslateDelegate;
import com.android.launcher3.views.ActivityContext;
import android.graphics.drawable.Drawable;
/**
* View class that represents the bottom row of the home screen.
*/
public class Hotseat extends CellLayout implements Insettable {
public static final int ALPHA_CHANNEL_TASKBAR_ALIGNMENT = 0;
public static final int ALPHA_CHANNEL_PREVIEW_RENDERER = 1;
public static final int ALPHA_CHANNEL_TASKBAR_STASH = 2;
public static final int ALPHA_CHANNEL_CHANNELS_COUNT = 3;
@Retention(RetentionPolicy.RUNTIME)
@IntDef({ALPHA_CHANNEL_TASKBAR_ALIGNMENT, ALPHA_CHANNEL_PREVIEW_RENDERER,
ALPHA_CHANNEL_TASKBAR_STASH})
public @interface HotseatQsbAlphaId {
}
public static final int ICONS_TRANSLATION_X_NAV_BAR_ALIGNMENT = 0;
public static final int ICONS_TRANSLATION_X_CHANNELS_COUNT = 1;
@Retention(RetentionPolicy.RUNTIME)
@IntDef({ICONS_TRANSLATION_X_NAV_BAR_ALIGNMENT})
public @interface IconsTranslationX {
}
// Ratio of empty space, qsb should take up to appear visually centered.
public static final float QSB_CENTER_FACTOR = .325f;
private static final int BUBBLE_BAR_ADJUSTMENT_ANIMATION_DURATION_MS = 250;
@@ -100,12 +69,6 @@ public class Hotseat extends CellLayout implements Insettable {
private boolean mHasVerticalHotseat;
private Workspace<?> mWorkspace;
private boolean mSendTouchToWorkspace;
private final MultiValueAlpha mIconsAlphaChannels;
private final MultiValueAlpha mQsbAlphaChannels;
private @Nullable MultiProperty mQsbTranslationX;
private final MultiPropertyFactory mIconsTranslationXFactory;
private final View mQsb;
@@ -142,48 +105,28 @@ public class Hotseat extends CellLayout implements Insettable {
mQsb = LayoutInflater.from(context).inflate(layoutId, this, false);
addView(mQsb);
mIconsAlphaChannels = new MultiValueAlpha(getShortcutsAndWidgets(),
ALPHA_CHANNEL_CHANNELS_COUNT);
if (mQsb instanceof Reorderable qsbReorderable) {
mQsbTranslationX = qsbReorderable.getTranslateDelegate()
.getTranslationX(MultiTranslateDelegate.INDEX_NAV_BAR_ANIM);
}
mIconsTranslationXFactory = new MultiPropertyFactory<>(getShortcutsAndWidgets(),
VIEW_TRANSLATE_X, ICONS_TRANSLATION_X_CHANNELS_COUNT, Float::sum);
mQsbAlphaChannels = new MultiValueAlpha(mQsb, ALPHA_CHANNEL_CHANNELS_COUNT);
setUpBackground();
}
private void setUpBackground() {
if(!preferenceManager.getHotseatBG().get()) return;
var bgColor = PreferenceExtensionsKt.firstBlocking(preferenceManager2.getHotseatBackgroundColor());
var transparency = preferenceManager.getHotseatBGAlpha().get();
var alphaValue = (transparency * 255) / 100;
var baseColor = bgColor.getColorPreferenceEntry().getLightColor().invoke(getContext());
var baseColor = bgColor.getColorPreferenceEntry().getLightColor().invoke(mContext);
var finalColor = Color.argb(alphaValue, Color.red(baseColor), Color.green(baseColor), Color.blue(baseColor));
int insetHorizontalLeft = preferenceManager.getHotseatBGHorizontalInsetLeft().get();
int insetHorizontalRight = preferenceManager.getHotseatBGHorizontalInsetRight().get();
int insetVerticalTop = preferenceManager.getHotseatBGVerticalInsetTop().get();
int insetVerticalBottom = preferenceManager.getHotseatBGVerticalInsetBottom().get();
InsetDrawable bg = new InsetDrawable(DrawableTokens.BgCellLayout.resolve(getContext()),
insetHorizontalLeft, insetVerticalTop, insetHorizontalRight, insetVerticalBottom);
insetHorizontalLeft, insetVerticalTop, insetHorizontalRight, insetVerticalBottom);
bg.setTint(finalColor);
setBackground(bg);
}
/** Provides translation X for hotseat icons for the channel. */
public MultiProperty getIconsTranslationX(@IconsTranslationX int channelId) {
return mIconsTranslationXFactory.get(channelId);
}
/** Provides translation X for hotseat Qsb. */
@Nullable
public MultiProperty getQsbTranslationX() {
return mQsbTranslationX;
}
/**
* Returns orientation specific cell X given invariant order in the hotseat
*/
@@ -211,9 +154,13 @@ public class Hotseat extends CellLayout implements Insettable {
DeviceProfile dp = mActivity.getDeviceProfile();
if (bubbleBarEnabled) {
if (dp.shouldAdjustHotseatForBubbleBar(getContext(), hasBubbles)) {
getShortcutsAndWidgets().setTranslationProvider(
cellX -> dp.getHotseatAdjustedTranslation(getContext(), cellX));
float adjustedBorderSpace = dp.getHotseatAdjustedBorderSpaceForBubbleBar(getContext());
if (hasBubbles && Float.compare(adjustedBorderSpace, 0f) != 0) {
getShortcutsAndWidgets().setTranslationProvider(child -> {
int index = getShortcutsAndWidgets().indexOfChild(child);
float borderSpaceDelta = adjustedBorderSpace - dp.hotseatBorderSpace;
return dp.iconSizePx + index * borderSpaceDelta;
});
if (mQsb instanceof HorizontalInsettableView) {
HorizontalInsettableView insettableQsb = (HorizontalInsettableView) mQsb;
final float insetFraction = (float) dp.iconSizePx / dp.hotseatQsbWidth;
@@ -240,52 +187,57 @@ public class Hotseat extends CellLayout implements Insettable {
/**
* Adjust the hotseat icons for the bubble bar.
*
* <p>When the bubble bar becomes visible, if needed, this method animates the hotseat icons
* to reduce the spacing between them and make room for the bubble bar. The QSB width is
* <p>
* When the bubble bar becomes visible, if needed, this method animates the
* hotseat icons
* to reduce the spacing between them and make room for the bubble bar. The QSB
* width is
* animated as well to align with the hotseat icons.
*
* <p>When the bubble bar goes away, any adjustments that were previously made are reversed.
* <p>
* When the bubble bar goes away, any adjustments that were previously made are
* reversed.
*/
public void adjustForBubbleBar(boolean isBubbleBarVisible) {
DeviceProfile dp = mActivity.getDeviceProfile();
boolean shouldAdjust = isBubbleBarVisible
&& dp.shouldAdjustHotseatOrQsbForBubbleBar(getContext());
boolean shouldAdjustHotseat = shouldAdjust
&& dp.shouldAlignBubbleBarWithHotseat();
float adjustedBorderSpace = dp.getHotseatAdjustedBorderSpaceForBubbleBar(getContext());
if (Float.compare(adjustedBorderSpace, 0f) == 0) {
return;
}
ShortcutAndWidgetContainer icons = getShortcutsAndWidgets();
AnimatorSet animatorSet = new AnimatorSet();
float borderSpaceDelta = adjustedBorderSpace - dp.hotseatBorderSpace;
// update the translation provider for future layout passes of hotseat icons.
if (shouldAdjustHotseat) {
icons.setTranslationProvider(
cellX -> dp.getHotseatAdjustedTranslation(getContext(), cellX));
if (isBubbleBarVisible) {
icons.setTranslationProvider(child -> {
int index = icons.indexOfChild(child);
return dp.iconSizePx + index * borderSpaceDelta;
});
} else {
icons.setTranslationProvider(null);
}
AnimatorSet animatorSet = new AnimatorSet();
for (int i = 0; i < icons.getChildCount(); i++) {
View child = icons.getChildAt(i);
if (child.getLayoutParams() instanceof CellLayoutLayoutParams lp) {
float tx = shouldAdjustHotseat
? dp.getHotseatAdjustedTranslation(getContext(), lp.getCellX()) : 0;
if (child instanceof Reorderable) {
MultiTranslateDelegate mtd = ((Reorderable) child).getTranslateDelegate();
animatorSet.play(
mtd.getTranslationX(INDEX_BUBBLE_ADJUSTMENT_ANIM).animateToValue(tx));
} else {
animatorSet.play(ObjectAnimator.ofFloat(child, VIEW_TRANSLATE_X, tx));
}
float tx = isBubbleBarVisible ? dp.iconSizePx + i * borderSpaceDelta : 0;
if (child instanceof Reorderable) {
MultiTranslateDelegate mtd = ((Reorderable) child).getTranslateDelegate();
animatorSet.play(
mtd.getTranslationX(INDEX_BUBBLE_ADJUSTMENT_ANIM).animateToValue(tx));
} else {
animatorSet.play(ObjectAnimator.ofFloat(child, VIEW_TRANSLATE_X, tx));
}
}
//TODO(b/381109832) refactor & simplify adjustment logic
boolean shouldAdjustQsb =
shouldAdjustHotseat || (shouldAdjust && dp.shouldAlignBubbleBarWithQSB());
if (mQsb instanceof HorizontalInsettableView horizontalInsettableQsb) {
final float currentInsetFraction = horizontalInsettableQsb.getHorizontalInsets();
final float targetInsetFraction = shouldAdjustQsb
? (float) dp.iconSizePx / dp.hotseatQsbWidth : 0;
ValueAnimator qsbAnimator =
ValueAnimator.ofFloat(currentInsetFraction, targetInsetFraction);
if (mQsb instanceof HorizontalInsettableView) {
HorizontalInsettableView horizontalInsettableQsb = (HorizontalInsettableView) mQsb;
ValueAnimator qsbAnimator = ValueAnimator.ofFloat(0f, 1f);
qsbAnimator.addUpdateListener(animation -> {
float insetFraction = (float) animation.getAnimatedValue();
float fraction = qsbAnimator.getAnimatedFraction();
float insetFraction = isBubbleBarVisible
? (float) dp.iconSizePx * fraction / dp.hotseatQsbWidth
: (float) dp.iconSizePx * (1 - fraction) / dp.hotseatQsbWidth;
horizontalInsettableQsb.setHorizontalInsets(insetFraction);
});
animatorSet.play(qsbAnimator);
@@ -293,13 +245,6 @@ public class Hotseat extends CellLayout implements Insettable {
animatorSet.setDuration(BUBBLE_BAR_ADJUSTMENT_ANIMATION_DURATION_MS).start();
}
@Override
protected int getTranslationXForCell(int cellX, int cellY) {
TranslationProvider translationProvider = getShortcutsAndWidgets().getTranslationProvider();
if (translationProvider == null) return 0;
return (int) translationProvider.getTranslationX(cellX);
}
@Override
public void setInsets(Rect insets) {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) getLayoutParams();
@@ -320,6 +265,7 @@ public class Hotseat extends CellLayout implements Insettable {
lp.gravity = Gravity.BOTTOM;
lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
lp.height = grid.hotseatBarSizePx;
lp.topMargin = grid.hotseatBarBottomSpacePx;
}
Rect padding = grid.getHotseatLayoutPadding(getContext());
@@ -335,8 +281,10 @@ public class Hotseat extends CellLayout implements Insettable {
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// We allow horizontal workspace scrolling from within the Hotseat. We do this by delegating
// touch intercept the Workspace, and if it intercepts, delegating touch to the Workspace
// We allow horizontal workspace scrolling from within the Hotseat. We do this
// by delegating
// touch intercept the Workspace, and if it intercepts, delegating touch to the
// Workspace
// for the remainder of the this input stream.
int yThreshold = getMeasuredHeight() - getPaddingBottom();
if (mWorkspace != null && ev.getY() <= yThreshold) {
@@ -368,14 +316,7 @@ public class Hotseat extends CellLayout implements Insettable {
DeviceProfile dp = mActivity.getDeviceProfile();
// LC: Fix weird sizing with hotseatQsbWidth being 0 on phone
int width;
if (dp.isQsbInline) {
width = dp.hotseatQsbWidth;
} else {
width = getShortcutsAndWidgets().getMeasuredWidth();
}
int width = getShortcutsAndWidgets().getMeasuredWidth();
mQsb.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dp.hotseatQsbHeight, MeasureSpec.EXACTLY));
}
@@ -402,27 +343,21 @@ public class Hotseat extends CellLayout implements Insettable {
}
/**
* Sets the alpha value of the specified alpha channel of just our ShortcutAndWidgetContainer.
* Sets the alpha value of just our ShortcutAndWidgetContainer.
*/
public void setIconsAlpha(float alpha, @HotseatQsbAlphaId int channelId) {
getIconsAlpha(channelId).setValue(alpha);
public void setIconsAlpha(float alpha) {
getShortcutsAndWidgets().setAlpha(alpha);
}
/**
* Sets the alpha value of just our QSB.
*/
public void setQsbAlpha(float alpha, @HotseatQsbAlphaId int channelId) {
getQsbAlpha(channelId).setValue(alpha);
public void setQsbAlpha(float alpha) {
mQsb.setAlpha(alpha);
}
/** Returns the alpha channel for ShortcutAndWidgetContainer */
public MultiProperty getIconsAlpha(@HotseatQsbAlphaId int channelId) {
return mIconsAlphaChannels.get(channelId);
}
/** Returns the alpha channel for Qsb */
public MultiProperty getQsbAlpha(@HotseatQsbAlphaId int channelId) {
return mQsbAlphaChannels.get(channelId);
public float getIconsAlpha() {
return getShortcutsAndWidgets().getAlpha();
}
/**
@@ -432,24 +367,4 @@ public class Hotseat extends CellLayout implements Insettable {
return mQsb;
}
/** Dumps the Hotseat internal state */
public void dump(String prefix, PrintWriter writer) {
writer.println(prefix + "Hotseat:");
mIconsAlphaChannels.dump(
prefix + "\t",
writer,
"mIconsAlphaChannels",
"ALPHA_CHANNEL_TASKBAR_ALIGNMENT",
"ALPHA_CHANNEL_PREVIEW_RENDERER",
"ALPHA_CHANNEL_TASKBAR_STASH");
mQsbAlphaChannels.dump(
prefix + "\t",
writer,
"mQsbAlphaChannels",
"ALPHA_CHANNEL_TASKBAR_ALIGNMENT",
"ALPHA_CHANNEL_PREVIEW_RENDERER",
"ALPHA_CHANNEL_TASKBAR_STASH"
);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -17,51 +17,14 @@ package com.android.launcher3;
import android.app.Application;
import com.android.launcher3.dagger.DaggerLauncherAppComponent;
import com.android.launcher3.dagger.LauncherAppComponent;
import com.android.launcher3.dagger.LauncherBaseAppComponent;
import com.android.launcher3.util.TraceHelper;
/**
* Main application class for Launcher
*/
public class LauncherApplication extends Application {
private volatile LauncherBaseAppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
MainProcessInitializer.initialize(this);
}
public LauncherAppComponent getAppComponent() {
if (mAppComponent == null) {
synchronized (this) {
// Check for null again, as it may have been assigned on a different thread. This
// avoids holding synchronization locks everytime.
if (mAppComponent == null) {
// Initialize the dagger component on demand as content providers can get
// accessed before the Launcher application (b/36917845#comment4)
initDaggerComponent(DaggerLauncherAppComponent.builder()
.iconsDbName(LauncherFiles.APP_ICONS_DB));
}
}
}
// Since supertype setters will return a supertype.builder and @Component.Builder types
// must not have any generic types.
// We need to cast mAppComponent to {@link LauncherAppComponent} since appContext()
// method is defined in the super class LauncherBaseComponent#Builder.
return (LauncherAppComponent) mAppComponent;
}
/**
* Init with the desired dagger component.
*/
public void initDaggerComponent(LauncherBaseAppComponent.Builder componentBuilder) {
mAppComponent = componentBuilder
.appContext(this)
.setSafeModeEnabled(TraceHelper.allowIpcs(
"isSafeMode", () -> getPackageManager().isSafeMode()))
.build();
}
}
@@ -1,7 +1,5 @@
package com.android.launcher3;
import static com.android.launcher3.LauncherPrefs.NO_DB_FILES_RESTORED;
import android.app.backup.BackupAgent;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
@@ -12,13 +10,10 @@ import com.android.launcher3.provider.RestoreDbTask;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
public class LauncherBackupAgent extends BackupAgent {
private static final String TAG = "LauncherBackupAgent";
private static final String DB_FILE_PREFIX = "launcher";
private static final String DB_FILE_SUFFIX = ".db";
@Override
public void onCreate() {
@@ -52,34 +47,7 @@ public class LauncherBackupAgent extends BackupAgent {
@Override
public void onRestoreFinished() {
RestoreDbTask.setPending(this);
FileLog.d(TAG, "onRestoreFinished: set pending for RestoreDbTask");
markIfFilesWereNotActuallyRestored();
}
/**
* When restore is finished, we check to see if any db files were successfully restored. If not,
* our restore will fail later, but will report a different cause. This is important to split
* out the metric failures that are launcher's fault, and those that are due to bugs in the
* backup/restore code itself.
*/
private void markIfFilesWereNotActuallyRestored() {
File directory = new File(getDatabasePath(InvariantDeviceProfile.INSTANCE.get(this).dbFile)
.getParent());
if (!directory.exists()) {
FileLog.e(TAG, "restore failed as target database directory doesn't exist");
} else {
// Check for any db file that was restored, and collect as list
String fileNames = Arrays.stream(directory.listFiles())
.map(File::getName)
.filter(n -> n.startsWith(DB_FILE_PREFIX) && n.endsWith(DB_FILE_SUFFIX))
.collect(Collectors.joining(", "));
if (fileNames.isBlank()) {
FileLog.e(TAG, "no database files were successfully restored");
LauncherPrefs.get(this).putSync(NO_DB_FILES_RESTORED.to(true));
} else {
FileLog.d(TAG, "database files successfully restored: " + fileNames);
}
}
RestoreDbTask.setPending(this);
}
}
@@ -67,8 +67,5 @@ public class LauncherConstants {
static final String RUNTIME_STATE_WIDGET_PANEL = "launcher.widget_panel";
// Type int[]
static final String RUNTIME_STATE_CURRENT_SCREEN_IDS = "launcher.current_screen_ids";
// Type: boolean
public static final String RUNTIME_STATE_RECREATE_TO_UPDATE_THEME =
"launcher.recreate_to_update_theme";
}
}
+1 -13
View File
@@ -16,17 +16,11 @@ public class LauncherFiles {
private static final String XML = ".xml";
public static final String LAUNCHER_DB = "launcher.db";
public static final String LAUNCHER_5_BY_8_DB = "launcher_5_by_8.db";
public static final String LAUNCHER_6_BY_5_DB = "launcher_6_by_5.db";
public static final String LAUNCHER_4_BY_5_DB = "launcher_4_by_5.db";
public static final String LAUNCHER_4_BY_6_DB = "launcher_4_by_6.db";
public static final String LAUNCHER_4_BY_7_DB = "launcher_4_by_7.db";
public static final String LAUNCHER_5_BY_6_DB = "launcher_5_by_6.db";
public static final String LAUNCHER_4_BY_4_DB = "launcher_4_by_4.db";
public static final String LAUNCHER_3_BY_3_DB = "launcher_3_by_3.db";
public static final String LAUNCHER_2_BY_2_DB = "launcher_2_by_2.db";
public static final String LAUNCHER_7_BY_3_DB = "launcher_7_by_3.db";
public static final String LAUNCHER_8_BY_3_DB = "launcher_8_by_3.db";
public static final String BACKUP_DB = "backup.db";
public static final String SHARED_PREFERENCES_KEY = "com.android.launcher3.prefs";
public static final String MANAGED_USER_PREFERENCES_KEY =
@@ -39,17 +33,11 @@ public class LauncherFiles {
public static final List<String> GRID_DB_FILES = Collections.unmodifiableList(Arrays.asList(
LAUNCHER_DB,
LAUNCHER_5_BY_8_DB,
LAUNCHER_6_BY_5_DB,
LAUNCHER_4_BY_5_DB,
LAUNCHER_4_BY_6_DB,
LAUNCHER_4_BY_7_DB,
LAUNCHER_5_BY_6_DB,
LAUNCHER_4_BY_4_DB,
LAUNCHER_3_BY_3_DB,
LAUNCHER_2_BY_2_DB,
LAUNCHER_7_BY_3_DB,
LAUNCHER_8_BY_3_DB));
LAUNCHER_2_BY_2_DB));
public static final List<String> OTHER_FILES = Collections.unmodifiableList(Arrays.asList(
BACKUP_DB,
+97 -120
View File
@@ -18,54 +18,46 @@ package com.android.launcher3
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import androidx.annotation.VisibleForTesting
import com.android.launcher3.BuildConfigs.WIDGET_ON_FIRST_SCREEN
import com.android.launcher3.GridType.Companion.GRID_TYPE_ANY
import com.android.launcher3.InvariantDeviceProfile.GRID_NAME_PREFS_KEY
import com.android.launcher3.InvariantDeviceProfile.NON_FIXED_LANDSCAPE_GRID_NAME_PREFS_KEY
import com.android.launcher3.LauncherFiles.DEVICE_PREFERENCES_KEY
import com.android.launcher3.LauncherFiles.SHARED_PREFERENCES_KEY
import com.android.launcher3.dagger.ApplicationContext
import com.android.launcher3.dagger.LauncherAppComponent
import com.android.launcher3.dagger.LauncherAppSingleton
import com.android.launcher3.model.DeviceGridState
import com.android.launcher3.pm.InstallSessionHelper
import com.android.launcher3.provider.RestoreDbTask
import com.android.launcher3.provider.RestoreDbTask.FIRST_LOAD_AFTER_RESTORE_KEY
import com.android.launcher3.settings.SettingsActivity
import com.android.launcher3.states.RotationHelper
import com.android.launcher3.util.DaggerSingletonObject
import com.android.launcher3.util.DisplayController
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import com.android.launcher3.util.MainThreadInitializedObject
import com.android.launcher3.util.SafeCloseable
import com.android.launcher3.util.Themes
/**
* Manages Launcher [SharedPreferences] through [Item] instances.
* Use same context for shared preferences, so that we use a single cached instance
*
* TODO(b/262721340): Replace all direct SharedPreference refs with LauncherPrefs / Item methods.
*/
@LauncherAppSingleton
open class LauncherPrefs
@Inject
constructor(@ApplicationContext private val encryptedContext: Context) {
class LauncherPrefs(private val encryptedContext: Context) : SafeCloseable {
private val deviceProtectedStorageContext =
encryptedContext.createDeviceProtectedStorageContext()
private val deviceProtectedSharedPrefs: SharedPreferences by lazy {
encryptedContext
.createDeviceProtectedStorageContext()
.getSharedPreferences(BOOT_AWARE_PREFS_KEY, MODE_PRIVATE)
}
private val bootAwarePrefs
get() =
deviceProtectedStorageContext.getSharedPreferences(BOOT_AWARE_PREFS_KEY, MODE_PRIVATE)
open protected fun getSharedPrefs(item: Item): SharedPreferences =
item.run {
if (encryptionType == EncryptionType.DEVICE_PROTECTED) deviceProtectedSharedPrefs
else encryptedContext.getSharedPreferences(sharedPrefFile, MODE_PRIVATE)
}
private val Item.encryptedPrefs
get() = encryptedContext.getSharedPreferences(sharedPrefFile, MODE_PRIVATE)
/** Returns the value with type [T] for [item]. */
private fun chooseSharedPreferences(item: Item): SharedPreferences =
if (item.encryptionType == EncryptionType.DEVICE_PROTECTED) bootAwarePrefs
else item.encryptedPrefs
/** Wrapper around `getInner` for a `ContextualItem` */
fun <T> get(item: ContextualItem<T>): T =
getInner(item, item.defaultValueFromContext(encryptedContext))
/** Returns the value with type [T] for [item]. */
/** Wrapper around `getInner` for an `Item` */
fun <T> get(item: ConstantItem<T>): T = getInner(item, item.defaultValue)
/**
@@ -75,19 +67,19 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
*/
@Suppress("IMPLICIT_CAST_TO_ANY", "UNCHECKED_CAST")
private fun <T> getInner(item: Item, default: T): T {
val sp = getSharedPrefs(item)
return when {
item.type == String::class.java -> sp.getString(item.sharedPrefKey, default as? String)
item.type == Boolean::class.java || item.type == java.lang.Boolean::class.java ->
sp.getBoolean(item.sharedPrefKey, default as Boolean)
item.type == Int::class.java || item.type == java.lang.Integer::class.java ->
sp.getInt(item.sharedPrefKey, default as Int)
item.type == Float::class.java || item.type == java.lang.Float::class.java ->
sp.getFloat(item.sharedPrefKey, default as Float)
item.type == Long::class.java || item.type == java.lang.Long::class.java ->
sp.getLong(item.sharedPrefKey, default as Long)
Set::class.java.isAssignableFrom(item.type) ->
sp.getStringSet(item.sharedPrefKey, default as? Set<String>)
val sp = chooseSharedPreferences(item)
return when (item.type) {
String::class.java -> sp.getString(item.sharedPrefKey, default as? String)
Boolean::class.java,
java.lang.Boolean::class.java -> sp.getBoolean(item.sharedPrefKey, default as Boolean)
Int::class.java,
java.lang.Integer::class.java -> sp.getInt(item.sharedPrefKey, default as Int)
Float::class.java,
java.lang.Float::class.java -> sp.getFloat(item.sharedPrefKey, default as Float)
Long::class.java,
java.lang.Long::class.java -> sp.getLong(item.sharedPrefKey, default as Long)
Set::class.java -> sp.getStringSet(item.sharedPrefKey, default as? Set<String>)
else ->
throw IllegalArgumentException(
"item type: ${item.type}" + " is not compatible with sharedPref methods"
@@ -131,10 +123,24 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
private fun prepareToPutValues(
updates: Array<out Pair<Item, Any>>
): List<SharedPreferences.Editor> {
val updatesPerPrefFile = updates.groupBy { getSharedPrefs(it.first) }.toMap()
val updatesPerPrefFile =
updates
.filter { it.first.encryptionType != EncryptionType.DEVICE_PROTECTED }
.groupBy { it.first.encryptedPrefs }
.toMutableMap()
return updatesPerPrefFile.map { (sharedPref, itemList) ->
sharedPref.edit().apply { itemList.forEach { (item, value) -> putValue(item, value) } }
val bootAwareUpdates =
updates.filter { it.first.encryptionType == EncryptionType.DEVICE_PROTECTED }
if (bootAwareUpdates.isNotEmpty()) {
updatesPerPrefFile[bootAwarePrefs] = bootAwareUpdates
}
return updatesPerPrefFile.map { prefToItemValueList ->
prefToItemValueList.key.edit().apply {
prefToItemValueList.value.forEach { itemToValue: Pair<Item, Any> ->
putValue(itemToValue.first, itemToValue.second)
}
}
}
}
@@ -144,22 +150,21 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
* types of Item values.
*/
@Suppress("UNCHECKED_CAST")
internal fun SharedPreferences.Editor.putValue(
private fun SharedPreferences.Editor.putValue(
item: Item,
value: Any?,
value: Any?
): SharedPreferences.Editor =
when {
item.type == String::class.java -> putString(item.sharedPrefKey, value as? String)
item.type == Boolean::class.java || item.type == java.lang.Boolean::class.java ->
putBoolean(item.sharedPrefKey, value as Boolean)
item.type == Int::class.java || item.type == java.lang.Integer::class.java ->
putInt(item.sharedPrefKey, value as Int)
item.type == Float::class.java || item.type == java.lang.Float::class.java ->
putFloat(item.sharedPrefKey, value as Float)
item.type == Long::class.java || item.type == java.lang.Long::class.java ->
putLong(item.sharedPrefKey, value as Long)
Set::class.java.isAssignableFrom(item.type) ->
putStringSet(item.sharedPrefKey, value as? Set<String>)
when (item.type) {
String::class.java -> putString(item.sharedPrefKey, value as? String)
Boolean::class.java,
java.lang.Boolean::class.java -> putBoolean(item.sharedPrefKey, value as Boolean)
Int::class.java,
java.lang.Integer::class.java -> putInt(item.sharedPrefKey, value as Int)
Float::class.java,
java.lang.Float::class.java -> putFloat(item.sharedPrefKey, value as Float)
Long::class.java,
java.lang.Long::class.java -> putLong(item.sharedPrefKey, value as Long)
Set::class.java -> putStringSet(item.sharedPrefKey, value as? Set<String>)
else ->
throw IllegalArgumentException(
"item type: ${item.type} is not compatible with sharedPref methods"
@@ -171,9 +176,9 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
* `SharedPreferences` files associated with the provided list of items. The listener will need
* to filter update notifications so they don't activate for non-relevant updates.
*/
fun addListener(listener: LauncherPrefChangeListener, vararg items: Item) {
fun addListener(listener: OnSharedPreferenceChangeListener, vararg items: Item) {
items
.map { getSharedPrefs(it) }
.map { chooseSharedPreferences(it) }
.distinct()
.forEach { it.registerOnSharedPreferenceChangeListener(listener) }
}
@@ -182,10 +187,10 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
* Stops the listener from getting notified of any more updates to any of the
* `SharedPreferences` files associated with any of the provided list of [Item].
*/
fun removeListener(listener: LauncherPrefChangeListener, vararg items: Item) {
fun removeListener(listener: OnSharedPreferenceChangeListener, vararg items: Item) {
// If a listener is not registered to a SharedPreference, unregistering it does nothing
items
.map { getSharedPrefs(it) }
.map { chooseSharedPreferences(it) }
.distinct()
.forEach { it.unregisterOnSharedPreferenceChangeListener(listener) }
}
@@ -196,7 +201,7 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
*/
fun has(vararg items: Item): Boolean {
items
.groupBy { getSharedPrefs(it) }
.groupBy { chooseSharedPreferences(it) }
.forEach { (prefs, itemsSublist) ->
if (!itemsSublist.none { !prefs.contains(it.sharedPrefKey) }) return false
}
@@ -220,7 +225,16 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
* .apply() or .commit()
*/
private fun prepareToRemove(items: Array<out Item>): List<SharedPreferences.Editor> {
val itemsPerFile = items.groupBy { getSharedPrefs(it) }.toMap()
val itemsPerFile =
items
.filter { it.encryptionType != EncryptionType.DEVICE_PROTECTED }
.groupBy { it.encryptedPrefs }
.toMutableMap()
val bootAwareUpdates = items.filter { it.encryptionType == EncryptionType.DEVICE_PROTECTED }
if (bootAwareUpdates.isNotEmpty()) {
itemsPerFile[bootAwarePrefs] = bootAwareUpdates
}
return itemsPerFile.map { (prefs, items) ->
prefs.edit().also { editor ->
@@ -229,19 +243,25 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
}
}
override fun close() {}
companion object {
@VisibleForTesting const val BOOT_AWARE_PREFS_KEY = "boot_aware_prefs"
@JvmField val INSTANCE = DaggerSingletonObject(LauncherAppComponent::getLauncherPrefs)
@JvmField var INSTANCE = MainThreadInitializedObject { LauncherPrefs(it) }
@JvmStatic fun get(context: Context): LauncherPrefs = INSTANCE.get(context)
const val TASKBAR_PINNING_KEY = "TASKBAR_PINNING_KEY"
const val TASKBAR_PINNING_DESKTOP_MODE_KEY = "TASKBAR_PINNING_DESKTOP_MODE_KEY"
const val SHOULD_SHOW_SMARTSPACE_KEY = "SHOULD_SHOW_SMARTSPACE_KEY"
@JvmField
val ICON_STATE = nonRestorableItem("pref_icon_shape_path", "", EncryptionType.ENCRYPTED)
@JvmField
val ENABLE_TWOLINE_ALLAPPS_TOGGLE = backedUpItem("pref_enable_two_line_toggle", false)
@JvmField
val THEMED_ICONS = backedUpItem(Themes.KEY_THEMED_ICONS, false, EncryptionType.ENCRYPTED)
@JvmField val PROMISE_ICON_IDS = backedUpItem(InstallSessionHelper.PROMISE_ICON_IDS, "")
@JvmField val WORK_EDU_STEP = backedUpItem("showed_work_profile_edu", 0)
@JvmField
@@ -262,44 +282,37 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
backedUpItem(
DeviceGridState.KEY_DEVICE_TYPE,
InvariantDeviceProfile.TYPE_PHONE,
EncryptionType.ENCRYPTED,
EncryptionType.ENCRYPTED
)
@JvmField
val DB_FILE = backedUpItem(DeviceGridState.KEY_DB_FILE, "", EncryptionType.ENCRYPTED)
@JvmField
val GRID_TYPE =
backedUpItem(DeviceGridState.KEY_GRID_TYPE, GRID_TYPE_ANY, EncryptionType.ENCRYPTED)
@JvmField
val SHOULD_SHOW_SMARTSPACE =
backedUpItem(
SHOULD_SHOW_SMARTSPACE_KEY,
WIDGET_ON_FIRST_SCREEN,
EncryptionType.DEVICE_PROTECTED,
EncryptionType.DEVICE_PROTECTED
)
@JvmField
val RESTORE_DEVICE =
backedUpItem(
RestoreDbTask.RESTORED_DEVICE_TYPE,
InvariantDeviceProfile.TYPE_PHONE,
EncryptionType.ENCRYPTED,
EncryptionType.ENCRYPTED
)
@JvmField
val NO_DB_FILES_RESTORED =
nonRestorableItem("no_db_files_restored", false, EncryptionType.DEVICE_PROTECTED)
@JvmField
val IS_FIRST_LOAD_AFTER_RESTORE =
nonRestorableItem(FIRST_LOAD_AFTER_RESTORE_KEY, false, EncryptionType.ENCRYPTED)
@JvmField val APP_WIDGET_IDS = backedUpItem(RestoreDbTask.APPWIDGET_IDS, "")
@JvmField val OLD_APP_WIDGET_IDS = backedUpItem(RestoreDbTask.APPWIDGET_OLD_IDS, "")
@JvmField
val GRID_NAME =
ConstantItem(
GRID_NAME_PREFS_KEY,
"idp_grid_name",
isBackedUp = true,
defaultValue = null,
encryptionType = EncryptionType.ENCRYPTED,
type = String::class.java,
type = String::class.java
)
@JvmField
val ALLOW_ROTATION =
@@ -307,19 +320,6 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
RotationHelper.getAllowRotationDefaultValue(DisplayController.INSTANCE.get(it).info)
}
@JvmField
val FIXED_LANDSCAPE_MODE = backedUpItem(SettingsActivity.FIXED_LANDSCAPE_MODE, false)
@JvmField
val NON_FIXED_LANDSCAPE_GRID_NAME =
ConstantItem(
NON_FIXED_LANDSCAPE_GRID_NAME_PREFS_KEY,
isBackedUp = true,
defaultValue = null,
encryptionType = EncryptionType.ENCRYPTED,
type = String::class.java,
)
// Preferences for widget configurations
@JvmField
val RECONFIGURABLE_WIDGET_EDUCATION_TIP_SEEN =
@@ -329,7 +329,7 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
fun <T> backedUpItem(
sharedPrefKey: String,
defaultValue: T,
encryptionType: EncryptionType = EncryptionType.ENCRYPTED,
encryptionType: EncryptionType = EncryptionType.ENCRYPTED
): ConstantItem<T> =
ConstantItem(sharedPrefKey, isBackedUp = true, defaultValue, encryptionType)
@@ -338,21 +338,21 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
sharedPrefKey: String,
type: Class<out T>,
encryptionType: EncryptionType = EncryptionType.ENCRYPTED,
defaultValueFromContext: (c: Context) -> T,
defaultValueFromContext: (c: Context) -> T
): ContextualItem<T> =
ContextualItem(
sharedPrefKey,
isBackedUp = true,
defaultValueFromContext,
encryptionType,
type,
type
)
@JvmStatic
fun <T> nonRestorableItem(
sharedPrefKey: String,
defaultValue: T,
encryptionType: EncryptionType = EncryptionType.ENCRYPTED,
encryptionType: EncryptionType = EncryptionType.ENCRYPTED
): ConstantItem<T> =
ConstantItem(sharedPrefKey, isBackedUp = false, defaultValue, encryptionType)
@@ -362,7 +362,7 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
// Use application context for shared preferences, so we use single cached instance
return context.applicationContext.getSharedPreferences(
SHARED_PREFERENCES_KEY,
MODE_PRIVATE,
MODE_PRIVATE
)
}
@@ -372,7 +372,7 @@ constructor(@ApplicationContext private val encryptedContext: Context) {
// Use application context for shared preferences, so we use a single cached instance
return context.applicationContext.getSharedPreferences(
DEVICE_PREFERENCES_KEY,
MODE_PRIVATE,
MODE_PRIVATE
)
}
}
@@ -395,7 +395,7 @@ data class ConstantItem<T>(
val defaultValue: T,
override val encryptionType: EncryptionType,
// The default value can be null. If so, the type needs to be explicitly stated, or else NPE
override val type: Class<out T> = defaultValue!!::class.java,
override val type: Class<out T> = defaultValue!!::class.java
) : Item() {
fun get(c: Context): T = LauncherPrefs.get(c).get(this)
@@ -406,7 +406,7 @@ data class ContextualItem<T>(
override val isBackedUp: Boolean,
private val defaultSupplier: (c: Context) -> T,
override val encryptionType: EncryptionType,
override val type: Class<out T>,
override val type: Class<out T>
) : Item() {
private var default: T? = null
@@ -424,26 +424,3 @@ enum class EncryptionType {
ENCRYPTED,
DEVICE_PROTECTED,
}
/**
* LauncherPrefs which delegates all lookup to [prefs] but uses the real prefs for initial values
*/
class ProxyPrefs(context: Context, private val prefs: SharedPreferences) : LauncherPrefs(context) {
private val copiedPrefs = ConcurrentHashMap<SharedPreferences, Boolean>()
override fun getSharedPrefs(item: Item): SharedPreferences {
val originalPrefs = super.getSharedPrefs(item)
// Copy all existing values, when the pref is accessed for the first time
copiedPrefs.computeIfAbsent(originalPrefs) { op ->
val editor = prefs.edit()
op.all.forEach { (key, value) ->
if (value != null) {
editor.putValue(backedUpItem(key, value), value)
}
}
editor.commit()
}
return prefs
}
}
+49 -82
View File
@@ -24,47 +24,35 @@ import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.model.ModelDbController;
import com.android.launcher3.util.LayoutImportExportHelper;
import com.android.launcher3.widget.LauncherWidgetHolder;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.ToIntFunction;
public class LauncherProvider extends ContentProvider {
private static final String TAG = "LauncherProvider";
// Method API For Provider#call method.
private static final String METHOD_EXPORT_LAYOUT_XML = "EXPORT_LAYOUT_XML";
private static final String METHOD_IMPORT_LAYOUT_XML = "IMPORT_LAYOUT_XML";
private static final String KEY_RESULT = "KEY_RESULT";
private static final String KEY_LAYOUT = "KEY_LAYOUT";
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
/**
* $ adb shell dumpsys activity provider com.android.launcher3
*/
@Override
public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
LauncherModel model = LauncherAppState.INSTANCE.get(getContext()).getModel();
if (model.isModelLoaded()) {
model.dumpState("", fd, writer, args);
}
LauncherAppState.INSTANCE.executeIfCreated(appState -> {
if (appState.getModel().isModelLoaded()) {
appState.getModel().dumpState("", fd, writer, args);
}
});
}
@Override
@@ -79,20 +67,24 @@ public class LauncherProvider extends ContentProvider {
@Override
public String getType(Uri uri) {
if (TextUtils.isEmpty(parseUri(uri, null, null).first)) {
return "vnd.android.cursor.dir/" + Favorites.TABLE_NAME;
SqlArguments args = new SqlArguments(uri, null, null);
if (TextUtils.isEmpty(args.where)) {
return "vnd.android.cursor.dir/" + args.table;
} else {
return "vnd.android.cursor.item/" + Favorites.TABLE_NAME;
return "vnd.android.cursor.item/" + args.table;
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Pair<String, String[]> args = parseUri(uri, selection, selectionArgs);
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(args.table);
Cursor[] result = new Cursor[1];
executeControllerTask(controller -> {
result[0] = controller.query(projection, args.first, args.second, sortOrder);
result[0] = controller.query(args.table, projection, args.where, args.args, sortOrder);
return 0;
});
return result[0];
@@ -109,7 +101,7 @@ public class LauncherProvider extends ContentProvider {
// attempt allocate and bind the widget.
Integer itemType = values.getAsInteger(Favorites.ITEM_TYPE);
if (itemType != null
&& itemType == Favorites.ITEM_TYPE_APPWIDGET
&& itemType.intValue() == Favorites.ITEM_TYPE_APPWIDGET
&& !values.containsKey(Favorites.APPWIDGET_ID)) {
ComponentName cn = ComponentName.unflattenFromString(
@@ -136,7 +128,8 @@ public class LauncherProvider extends ContentProvider {
}
}
return controller.insert(values);
SqlArguments args = new SqlArguments(uri);
return controller.insert(args.table, values);
});
return rowId < 0 ? null : ContentUris.withAppendedId(uri, rowId);
@@ -144,51 +137,14 @@ public class LauncherProvider extends ContentProvider {
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
Pair<String, String[]> args = parseUri(uri, selection, selectionArgs);
return executeControllerTask(c -> c.delete(args.first, args.second));
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
return executeControllerTask(c -> c.delete(args.table, args.where, args.args));
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Pair<String, String[]> args = parseUri(uri, selection, selectionArgs);
return executeControllerTask(c -> c.update(values, args.first, args.second));
}
@Override
public Bundle call(String method, String arg, Bundle extras) {
Bundle b = new Bundle();
// The caller must have the read or write permission for this content provider to
// access the "call" method at all. We also enforce the appropriate per-method permissions.
switch(method) {
case METHOD_EXPORT_LAYOUT_XML:
if (getContext().checkCallingOrSelfPermission(getReadPermission())
!= PackageManager.PERMISSION_GRANTED) {
throw new SecurityException("Caller doesn't have read permission");
}
CompletableFuture<String> resultFuture = LayoutImportExportHelper.INSTANCE
.exportModelDbAsXmlFuture(getContext());
try {
b.putString(KEY_LAYOUT, resultFuture.get());
b.putString(KEY_RESULT, SUCCESS);
} catch (ExecutionException | InterruptedException e) {
b.putString(KEY_RESULT, FAILURE);
}
return b;
case METHOD_IMPORT_LAYOUT_XML:
if (getContext().checkCallingOrSelfPermission(getWritePermission())
!= PackageManager.PERMISSION_GRANTED) {
throw new SecurityException("Caller doesn't have write permission");
}
LayoutImportExportHelper.INSTANCE.importModelFromXml(getContext(), arg);
b.putString(KEY_RESULT, SUCCESS);
return b;
default:
return null;
}
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
return executeControllerTask(c -> c.update(args.table, values, args.where, args.args));
}
private int executeControllerTask(ToIntFunction<ModelDbController> task) {
@@ -209,24 +165,35 @@ public class LauncherProvider extends ContentProvider {
}
}
/**
* Parses the uri and returns the where and arg clause.
*
* Note: This should be called on the binder thread (before posting on any executor) so that
* any parsing error gets propagated to the caller.
*/
private static Pair<String, String[]> parseUri(Uri url, String where, String[] args) {
switch (url.getPathSegments().size()) {
case 1 -> {
return Pair.create(where, args);
static class SqlArguments {
public final String table;
public final String where;
public final String[] args;
SqlArguments(Uri url, String where, String[] args) {
if (url.getPathSegments().size() == 1) {
this.table = url.getPathSegments().get(0);
this.where = where;
this.args = args;
} else if (url.getPathSegments().size() != 2) {
throw new IllegalArgumentException("Invalid URI: " + url);
} else if (!TextUtils.isEmpty(where)) {
throw new UnsupportedOperationException("WHERE clause not supported: " + url);
} else {
this.table = url.getPathSegments().get(0);
this.where = "_id=" + ContentUris.parseId(url);
this.args = null;
}
case 2 -> {
if (!TextUtils.isEmpty(where)) {
throw new UnsupportedOperationException("WHERE clause not supported: " + url);
}
return Pair.create("_id=" + ContentUris.parseId(url), null);
}
SqlArguments(Uri url) {
if (url.getPathSegments().size() == 1) {
table = url.getPathSegments().get(0);
where = null;
args = null;
} else {
throw new IllegalArgumentException("Invalid URI: " + url);
}
default -> throw new IllegalArgumentException("Invalid URI: " + url);
}
}
}
+13 -25
View File
@@ -16,16 +16,14 @@ import android.view.ViewDebug;
import android.view.WindowInsets;
import com.android.launcher3.graphics.SysUiScrim;
import com.android.launcher3.statemanager.StatefulContainer;
import com.android.launcher3.statemanager.StatefulActivity;
import com.hoko.blur.HokoBlur;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import com.android.launcher3.util.window.WindowManagerProxy;
import com.android.launcher3.views.ActivityContext;
import java.util.Collections;
import java.util.List;
import com.hoko.blur.HokoBlur;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import app.lawnchair.preferences.PreferenceManager;
import app.lawnchair.preferences2.PreferenceManager2;
import app.lawnchair.util.FileAccessManager;
@@ -35,11 +33,10 @@ public class LauncherRootView extends InsettableFrameLayout {
private final Rect mTempRect = new Rect();
private final StatefulContainer mStatefulContainer;
private final StatefulActivity mActivity;
@ViewDebug.ExportedProperty(category = "launcher")
private static final List<Rect> SYSTEM_GESTURE_EXCLUSION_RECT =
Collections.singletonList(new Rect());
private static final List<Rect> SYSTEM_GESTURE_EXCLUSION_RECT = Collections.singletonList(new Rect());
private WindowStateListener mWindowStateListener;
@ViewDebug.ExportedProperty(category = "launcher")
@@ -54,7 +51,7 @@ public class LauncherRootView extends InsettableFrameLayout {
public LauncherRootView(Context context, AttributeSet attrs) {
super(context, attrs);
mStatefulContainer = ActivityContext.lookupContext(context);
mActivity = StatefulActivity.fromContext(context);
mSysUiScrim = new SysUiScrim(this);
pref = PreferenceManager.getInstance(context);
@@ -70,7 +67,7 @@ public class LauncherRootView extends InsettableFrameLayout {
}
private void setUpBlur(Context context) {
var display = mStatefulContainer.getDeviceProfile();
var display = mActivity.getDeviceProfile();
int width = display.widthPx;
int height = display.heightPx;
@@ -120,23 +117,19 @@ public class LauncherRootView extends InsettableFrameLayout {
private void handleSystemWindowInsets(Rect insets) {
// Update device profile before notifying the children.
mStatefulContainer.getDeviceProfile().updateInsets(insets);
mActivity.getDeviceProfile().updateInsets(insets);
boolean resetState = !insets.equals(mInsets);
setInsets(insets);
if (resetState) {
mStatefulContainer.getStateManager().reapplyState(true /* cancelCurrentAnimation */);
mActivity.getStateManager().reapplyState(true /* cancelCurrentAnimation */);
}
}
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
mStatefulContainer.handleConfigurationChanged(
mStatefulContainer.asContext().getResources().getConfiguration());
return updateInsets(insets);
}
mActivity.handleConfigurationChanged(mActivity.getResources().getConfiguration());
private WindowInsets updateInsets(WindowInsets insets) {
insets = WindowManagerProxy.INSTANCE.get(getContext())
.normalizeWindowInsets(getContext(), insets, mTempRect);
handleSystemWindowInsets(mTempRect);
@@ -145,7 +138,8 @@ public class LauncherRootView extends InsettableFrameLayout {
@Override
public void setInsets(Rect insets) {
// If the insets haven't changed, this is a no-op. Avoid unnecessary layout caused by
// If the insets haven't changed, this is a no-op. Avoid unnecessary layout
// caused by
// modifying child layout params.
if (!insets.equals(mInsets)) {
super.setInsets(insets);
@@ -154,11 +148,7 @@ public class LauncherRootView extends InsettableFrameLayout {
}
public void dispatchInsets() {
if (isAttachedToWindow()) {
updateInsets(getRootWindowInsets());
} else {
mStatefulContainer.getDeviceProfile().updateInsets(mInsets);
}
mActivity.getDeviceProfile().updateInsets(mInsets);
super.setInsets(mInsets);
}
@@ -191,8 +181,6 @@ public class LauncherRootView extends InsettableFrameLayout {
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
SYSTEM_GESTURE_EXCLUSION_RECT.get(0).set(l, t, r, b);
setDisallowBackGesture(mDisallowBackGesture);
mSysUiScrim.setSize(r - l, b - t);
}
@@ -16,18 +16,11 @@
package com.android.launcher3;
import static android.util.Base64.NO_PADDING;
import static android.util.Base64.NO_WRAP;
import static com.android.launcher3.icons.cache.CacheLookupFlag.DEFAULT_LOOKUP_FLAG;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;
import android.util.Base64;
import androidx.annotation.NonNull;
import com.android.launcher3.icons.cache.CacheLookupFlag;
import com.android.launcher3.model.data.ItemInfo;
import java.util.LinkedHashMap;
@@ -413,28 +406,14 @@ public class LauncherSettings {
public static String getColumns(long profileId) {
return String.join(", ", getColumnsToTypes(profileId).keySet());
}
/**
* Lookup flag to be used for items which are visible on the home screen
*/
public static final CacheLookupFlag DESKTOP_ICON_FLAG = DEFAULT_LOOKUP_FLAG;
}
/**
* Launcher settings
*/
public static final class Settings {
public static final String LAYOUT_PROVIDER_KEY = "launcher3.layout.provider";
public static final String LAYOUT_DIGEST_KEY = "launcher3.layout.provider.blob";
public static final String LAYOUT_DIGEST_LABEL = "launcher-layout";
public static final String LAYOUT_DIGEST_TAG = "ignore";
public static final String BLOB_KEY_PREFIX = "blob://";
/**
* Creates a key to be used for {@link #LAYOUT_PROVIDER_KEY}
* @param digest byte[] representing the message digest for the blob handle
*/
public static String createBlobProviderKey(byte[] digest) {
return BLOB_KEY_PREFIX + Base64.encodeToString(digest, NO_WRAP | NO_PADDING);
}
}
}
+4 -11
View File
@@ -72,7 +72,6 @@ public abstract class LauncherState implements BaseState<LauncherState> {
public static final int WORKSPACE_PAGE_INDICATOR = 1 << 5;
public static final int SPLIT_PLACHOLDER_VIEW = 1 << 6;
public static final int FLOATING_SEARCH_BAR = 1 << 7;
public static final int ADD_DESK_BUTTON = 1 << 8;
// Flag indicating workspace has multiple pages visible.
public static final int FLAG_MULTI_PAGE = BaseState.getFlag(0);
@@ -121,7 +120,7 @@ public abstract class LauncherState implements BaseState<LauncherState> {
LAUNCHER_STATE_HOME,
FLAG_DISABLE_RESTORE | FLAG_WORKSPACE_ICONS_CAN_BE_DRAGGED | FLAG_HAS_SYS_UI_SCRIM) {
@Override
public int getTransitionDuration(ActivityContext context, boolean isToState) {
public int getTransitionDuration(Context context, boolean isToState) {
// Arbitrary duration, when going to NORMAL we use the state we're coming from instead.
return 0;
}
@@ -356,7 +355,7 @@ public abstract class LauncherState implements BaseState<LauncherState> {
public final <DEVICE_PROFILE_CONTEXT extends Context & ActivityContext>
float getDepth(DEVICE_PROFILE_CONTEXT context) {
return getDepth(context,
ActivityContext.lookupContext(context).getDeviceProfile().isMultiWindowMode);
BaseDraggingActivity.fromContext(context).getDeviceProfile().isMultiWindowMode);
}
/**
@@ -386,14 +385,8 @@ public abstract class LauncherState implements BaseState<LauncherState> {
}
public PageAlphaProvider getWorkspacePageAlphaProvider(Launcher launcher) {
DeviceProfile dp = launcher.getDeviceProfile();
boolean shouldFadeAdjacentScreens = (this == NORMAL || this == HINT_STATE)
&& dp.shouldFadeAdjacentWorkspaceScreens();
// Avoid showing adjacent screens behind handheld All Apps sheet.
if (Flags.allAppsSheetForHandheld() && dp.isPhone && this == ALL_APPS) {
shouldFadeAdjacentScreens = true;
}
if (!shouldFadeAdjacentScreens) {
if ((this != NORMAL && this != HINT_STATE)
|| !launcher.getDeviceProfile().shouldFadeAdjacentWorkspaceScreens()) {
return DEFAULT_ALPHA_PROVIDER;
}
final int centerPage = launcher.getWorkspace().getNextPage();
+42 -26
View File
@@ -11,12 +11,12 @@ import com.android.launcher3.Utilities.SHOULD_SHOW_FIRST_PAGE_WIDGET
import com.android.launcher3.WorkspaceLayoutManager.FIRST_SCREEN_ID
import com.android.launcher3.allapps.AllAppsStore
import com.android.launcher3.config.FeatureFlags
import com.android.launcher3.debug.TestEventEmitter
import com.android.launcher3.debug.TestEventEmitter.TestEvent
import com.android.launcher3.model.BgDataModel
import com.android.launcher3.model.StringCache
import com.android.launcher3.model.data.AppInfo
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.model.data.LauncherAppWidgetInfo
import com.android.launcher3.model.data.WorkspaceItemInfo
import com.android.launcher3.popup.PopupContainerWithArrow
import com.android.launcher3.util.ComponentKey
import com.android.launcher3.util.IntArray as LIntArray
@@ -59,7 +59,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
AbstractFloatingView.closeOpenViews(
launcher,
true,
AbstractFloatingView.TYPE_ALL and AbstractFloatingView.TYPE_REBIND_SAFE.inv(),
AbstractFloatingView.TYPE_ALL and AbstractFloatingView.TYPE_REBIND_SAFE.inv()
)
workspaceLoading = true
@@ -74,7 +74,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
TAG,
"startBinding: " +
"hotseat layout was vertical: ${launcher.hotseat?.isHasVerticalHotseat}" +
" and is setting to ${launcher.deviceProfile.isVerticalBarLayout}",
" and is setting to ${launcher.deviceProfile.isVerticalBarLayout}"
)
launcher.hotseat?.resetLayout(launcher.deviceProfile.isVerticalBarLayout)
TraceHelper.INSTANCE.endSection()
@@ -86,16 +86,18 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
pendingTasks: RunnableList,
onCompleteSignal: RunnableList,
workspaceItemCount: Int,
isBindSync: Boolean,
isBindSync: Boolean
) {
Trace.endAsyncSection(
TraceEvents.DISPLAY_WORKSPACE_TRACE_METHOD_NAME,
TraceEvents.DISPLAY_WORKSPACE_TRACE_COOKIE,
)
if (Utilities.ATLEAST_S) {
Trace.endAsyncSection(
TraceEvents.DISPLAY_WORKSPACE_TRACE_METHOD_NAME,
TraceEvents.DISPLAY_WORKSPACE_TRACE_COOKIE
)
}
synchronouslyBoundPages = boundPages
pagesToBindSynchronously = LIntSet()
clearPendingBinds()
if (!launcher.isInState(LauncherState.ALL_APPS) && !Flags.enableWorkspaceInflation()) {
if (!launcher.isInState(LauncherState.ALL_APPS)) {
launcher.appsView.appsStore.enableDeferUpdates(AllAppsStore.DEFER_UPDATES_NEXT_DRAW)
pendingTasks.add {
launcher.appsView.appsStore.disableDeferUpdates(
@@ -145,16 +147,15 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
// Cache one page worth of icons
launcher.viewCache.setCacheSize(
R.layout.folder_application,
deviceProfile.numFolderColumns * deviceProfile.numFolderRows,
deviceProfile.numFolderColumns * deviceProfile.numFolderRows
)
launcher.viewCache.setCacheSize(R.layout.folder_page, 2)
TraceHelper.INSTANCE.endSection()
launcher.workspace.removeExtraEmptyScreen(/* stripEmptyScreens= */ true)
launcher.workspace.pageIndicator.setPauseScroll(
/*pause=*/ false,
deviceProfile.isTwoPanels,
deviceProfile.isTwoPanels
)
TestEventEmitter.sendEvent(TestEvent.WORKSPACE_FINISH_LOADING)
}
/**
@@ -178,7 +179,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
val snackbar =
AbstractFloatingView.getOpenView<AbstractFloatingView>(
launcher,
AbstractFloatingView.TYPE_SNACKBAR,
AbstractFloatingView.TYPE_SNACKBAR
)
snackbar?.post { snackbar.close(true) }
}
@@ -187,7 +188,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
override fun bindAllApplications(
apps: Array<AppInfo?>?,
flags: Int,
packageUserKeytoUidMap: Map<PackageUserKey?, Int?>?,
packageUserKeytoUidMap: Map<PackageUserKey?, Int?>?
) {
Preconditions.assertUIThread()
val hadWorkApps = launcher.appsView.shouldShowTabs()
@@ -213,13 +214,29 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
launcher.appsView.appsStore.updateProgressBar(app)
}
override fun bindWidgetsRestored(widgets: ArrayList<LauncherAppWidgetInfo?>?) {
launcher.workspace.widgetsRestored(widgets)
}
/**
* Some shortcuts were updated in the background. Implementation of the method from
* LauncherModel.Callbacks.
*
* @param updated list of shortcuts which have changed.
*/
override fun bindWorkspaceItemsChanged(updated: List<WorkspaceItemInfo?>) {
if (updated.isNotEmpty()) {
launcher.workspace.updateWorkspaceItems(updated, launcher)
PopupContainerWithArrow.dismissInvalidPopup(launcher)
}
}
/**
* Update the state of a package, typically related to install state. Implementation of the
* method from LauncherModel.Callbacks.
*/
override fun bindItemsUpdated(updates: Set<ItemInfo>) {
launcher.workspace.updateContainerItems(updates, launcher)
PopupContainerWithArrow.dismissInvalidPopup(launcher)
override fun bindRestoreItemsChange(updates: HashSet<ItemInfo?>?) {
launcher.workspace.updateRestoreItems(updates, launcher)
}
/**
@@ -234,8 +251,8 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
PopupContainerWithArrow.dismissInvalidPopup(launcher)
}
override fun bindAllWidgets(allWidgets: List<WidgetsListBaseEntry>) {
launcher.widgetPickerDataProvider.setWidgets(allWidgets)
override fun bindAllWidgets(allWidgets: List<WidgetsListBaseEntry?>?) {
launcher.popupDataProvider.allWidgets = allWidgets
}
/** Returns the ids of the workspaces to bind. */
@@ -284,15 +301,14 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
}
val widgetsListBaseEntry: WidgetsListBaseEntry =
launcher.widgetPickerDataProvider.get().allWidgets.firstOrNull {
item: WidgetsListBaseEntry ->
launcher.popupDataProvider.allWidgets.firstOrNull { item: WidgetsListBaseEntry ->
item.mPkgItem.packageName == BuildConfig.APPLICATION_ID
} ?: return
val info =
PendingAddWidgetInfo(
widgetsListBaseEntry.mWidgets[0].widgetInfo,
LauncherSettings.Favorites.CONTAINER_DESKTOP,
LauncherSettings.Favorites.CONTAINER_DESKTOP
)
launcher.addPendingItem(
info,
@@ -300,14 +316,14 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
WorkspaceLayoutManager.FIRST_SCREEN_ID,
intArrayOf(0, 0),
info.spanX,
info.spanY,
info.spanY
)
}
override fun bindScreens(orderedScreenIds: LIntArray) {
launcher.workspace.pageIndicator.setPauseScroll(
/*pause=*/ true,
launcher.deviceProfile.isTwoPanels,
launcher.deviceProfile.isTwoPanels
)
val firstScreenPosition = 0
if (
@@ -334,7 +350,7 @@ class ModelCallbacks(private var launcher: Launcher) : BgDataModel.Callbacks {
override fun bindAppsAdded(
newScreens: LIntArray?,
addNotAnimated: java.util.ArrayList<ItemInfo?>?,
addAnimated: java.util.ArrayList<ItemInfo?>?,
addAnimated: java.util.ArrayList<ItemInfo?>?
) {
// Add the new screens
if (newScreens != null) {
@@ -18,6 +18,8 @@ package com.android.launcher3;
import static android.view.MotionEvent.CLASSIFICATION_TWO_FINGER_SWIPE;
import static com.android.launcher3.config.FeatureFlags.ENABLE_TRACKPAD_GESTURE;
import android.annotation.TargetApi;
import android.os.Build;
import android.view.MotionEvent;
@@ -33,12 +35,14 @@ public class MotionEventsUtils {
@TargetApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
public static boolean isTrackpadScroll(MotionEvent event) {
return event.getClassification() == CLASSIFICATION_TWO_FINGER_SWIPE;
return ENABLE_TRACKPAD_GESTURE.get()
&& event.getClassification() == CLASSIFICATION_TWO_FINGER_SWIPE;
}
@TargetApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
public static boolean isTrackpadMultiFingerSwipe(MotionEvent event) {
return Utilities.ATLEAST_U && event.getClassification() == CLASSIFICATION_MULTI_FINGER_SWIPE;
return Utilities.ATLEAST_U && ENABLE_TRACKPAD_GESTURE.get ( )
&& event.getClassification ( ) == CLASSIFICATION_MULTI_FINGER_SWIPE;
}
public static boolean isTrackpadThreeFingerSwipe(MotionEvent event) {
+6 -19
View File
@@ -17,7 +17,6 @@
package com.android.launcher3;
import static com.android.app.animation.Interpolators.SCROLL;
import static com.android.launcher3.RemoveAnimationSettingsTracker.WINDOW_ANIMATION_SCALE_URI;
import static com.android.launcher3.compat.AccessibilityManagerCompat.isAccessibilityEnabled;
import static com.android.launcher3.compat.AccessibilityManagerCompat.isObservedEventType;
import static com.android.launcher3.testing.shared.TestProtocol.SCROLL_FINISHED_MESSAGE;
@@ -34,6 +33,7 @@ import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InputDevice;
@@ -723,14 +723,12 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
}
/**
* Run the given `callback` immediately once {@code mPageScrolls} has been initialized,
* otherwise queue the callback to `mOnPageScrollsInitializedCallbacks`.
* Queues the given callback to be run once {@code mPageScrolls} has been initialized.
*/
public void runOnPageScrollsInitialized(Runnable callback) {
mOnPageScrollsInitializedCallbacks.add(callback);
if (isPageScrollsInitialized()) {
callback.run();
} else {
mOnPageScrollsInitializedCallbacks.add(callback);
onPageScrollsInitialized();
}
}
@@ -1478,15 +1476,6 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
mEdgeGlowLeft.onFlingVelocity(velocity);
mEdgeGlowRight.onFlingVelocity(velocity);
}
// Detect if user tries to swipe to -1 page but gets disallowed by checking if there was
// left-over values in mEdgeGlowLeft (or mEdgeGlowRight in RLT).
final int layoutDir = getLayoutDirection();
if ((mEdgeGlowLeft.getDistance() > 0 && layoutDir == LAYOUT_DIRECTION_LTR)
|| (mEdgeGlowRight.getDistance() > 0 && layoutDir == LAYOUT_DIRECTION_RTL)) {
onDisallowSwipeToMinusOnePage();
}
mEdgeGlowLeft.onRelease(ev);
mEdgeGlowRight.onRelease(ev);
// End any intermediate reordering states
@@ -1511,8 +1500,6 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
return true;
}
protected void onDisallowSwipeToMinusOnePage() {}
protected void onNotSnappingToPageInFreeScroll() { }
/**
@@ -1769,8 +1756,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
}
if (FeatureFlags.IS_STUDIO_BUILD && !Utilities.isRunningInTestHarness()) {
duration *= RemoveAnimationSettingsTracker.INSTANCE.get(getContext()).getValue(
WINDOW_ANIMATION_SCALE_URI);
duration *= Settings.Global.getFloat(getContext().getContentResolver(),
Settings.Global.WINDOW_ANIMATION_SCALE, 1);
}
whichPage = validateNewPage(whichPage);
@@ -7,6 +7,7 @@ import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.INVALID;
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.RECONFIGURE;
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.UNINSTALL;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_DISMISS_PREDICTION_UNDO;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_DROPPED_ON_DONT_SUGGEST;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_DROPPED_ON_UNINSTALL;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_UNINSTALL_CANCELLED;
@@ -22,6 +23,7 @@ import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.UserHandle;
@@ -34,6 +36,7 @@ import android.widget.Toast;
import androidx.annotation.Nullable;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.logging.InstanceId;
@@ -43,7 +46,7 @@ import com.android.launcher3.logging.StatsLogManager.StatsLogger;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.util.ApplicationInfoWrapper;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
import java.net.URISyntaxException;
@@ -239,7 +242,8 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
@Override
public void completeDrop(final DragObject d) {
ComponentName target = performDropAction(getViewUnderDrag(d.dragInfo), d.dragInfo);
ComponentName target = performDropAction(getViewUnderDrag(d.dragInfo), d.dragInfo,
d.logInstanceId);
mDropTargetHandler.onSecondaryTargetCompleteDrop(target, d);
}
@@ -271,7 +275,7 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
* Performs the drop action and returns the target component for the dragObject or null if
* the action was not performed.
*/
protected ComponentName performDropAction(View view, ItemInfo info) {
protected ComponentName performDropAction(View view, ItemInfo info, InstanceId instanceId) {
if (mCurrentAccessibilityAction == RECONFIGURE) {
int widgetId = getReconfigurableWidgetId(view);
if (widgetId != INVALID_APPWIDGET_ID) {
@@ -279,6 +283,21 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
}
return null;
}
if (mCurrentAccessibilityAction == DISMISS_PREDICTION) {
if (FeatureFlags.ENABLE_DISMISS_PREDICTION_UNDO.get()) {
CharSequence announcement = getContext().getString(R.string.item_removed);
mDropTargetHandler
.dismissPrediction(announcement, () -> {
}, () -> {
mStatsLogManager.logger()
.withInstanceId(instanceId)
.withItemInfo(info)
.log(LAUNCHER_DISMISS_PREDICTION_UNDO);
});
}
return null;
}
return performUninstall(getContext(), getUninstallTarget(getContext(), info), info);
}
@@ -303,19 +322,19 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
.setData(Uri.fromParts("package", cn.getPackageName(), cn.getClassName()))
.putExtra(Intent.EXTRA_USER, info.user);
context.startActivity(i);
FileLog.d(TAG, "start uninstall activity from drop target " + cn.getPackageName());
FileLog.d(TAG, "start uninstall activity " + cn.getPackageName());
return cn;
} catch (URISyntaxException e) {
Log.e(TAG, "Failed to parse intent to start drop target uninstall activity for"
+ " item=" + info);
Log.e(TAG, "Failed to parse intent to start uninstall activity for item=" + info);
return null;
}
}
@Override
public void onAccessibilityDrop(View view, ItemInfo item) {
doLog(new InstanceIdSequence().newInstanceId(), item);
performDropAction(view, item);
InstanceId instanceId = new InstanceIdSequence().newInstanceId();
doLog(instanceId, item);
performDropAction(view, item, instanceId);
}
/**
@@ -342,8 +361,9 @@ public class SecondaryDropTarget extends ButtonDropTarget implements OnAlarmList
}
public void onLauncherResume() {
if (new ApplicationInfoWrapper(mContext, mPackageName, mDragObject.dragInfo.user)
.getInfo() == null) {
// We use MATCH_UNINSTALLED_PACKAGES as the app can be on SD card as well.
if (PackageManagerHelper.INSTANCE.get(mContext).getApplicationInfo(mPackageName,
mDragObject.dragInfo.user, PackageManager.MATCH_UNINSTALLED_PACKAGES) == null) {
mDragObject.dragSource = mOriginal;
mOriginal.onDropCompleted(SecondaryDropTarget.this, mDragObject, true);
mStatsLogManager.logger().withInstanceId(mDragObject.logInstanceId)
@@ -58,7 +58,7 @@ public class SessionCommitReceiver extends BroadcastReceiver {
@WorkerThread
private static void processIntent(Context context, Intent intent) {
UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
if (!isEnabled(context, user)) {
if (!isEnabled(context)) {
// User has decided to not add icons on homescreen.
return;
}
@@ -71,21 +71,17 @@ public class SessionCommitReceiver extends BroadcastReceiver {
}
InstallSessionHelper packageInstallerCompat = InstallSessionHelper.INSTANCE.get(context);
boolean alreadyAddedPromiseIcon =
packageInstallerCompat.promiseIconAddedForId(info.getSessionId());
boolean alreadyAddedPromiseIcon = packageInstallerCompat.promiseIconAddedForId(info.getSessionId());
if (TextUtils.isEmpty(info.getAppPackageName())
|| info.getInstallReason() != PackageManager.INSTALL_REASON_USER
|| alreadyAddedPromiseIcon) {
FileLog.d(LOG,
String.format(Locale.ENGLISH,
"Removing unneeded PromiseIcon for package: %s"
+ ", install reason: %d,"
"Removing PromiseIcon for package: %s, install reason: %d,"
+ " alreadyAddedPromiseIcon: %s",
info.getAppPackageName(),
info.getInstallReason(),
alreadyAddedPromiseIcon
)
);
info.getAppPackageName(),
info.getInstallReason(),
alreadyAddedPromiseIcon));
packageInstallerCompat.removePromiseIconId(info.getSessionId());
return;
}
@@ -99,19 +95,9 @@ public class SessionCommitReceiver extends BroadcastReceiver {
.queueItem(info.getAppPackageName(), user);
}
/**
* Returns whether adding Installed App Icons to home screen is allowed or not.
* Not allowed when:
* - User belongs to {@link com.android.launcher3.util.UserIconInfo.TYPE_PRIVATE} or
* - Home Settings preference to add App Icons on Home Screen is set as disabled
*/
public static boolean isEnabled(Context context, UserHandle user) {
if (Flags.privateSpaceRestrictItemDrag()
&& PreferenceExtensionsKt.firstBlocking(PreferenceManager2.getInstance(context).getLockHomeScreen())
&& user != null
&& UserCache.getInstance(context).getUserInfo(user).isPrivate()) {
public static boolean isEnabled(Context context) {
if (PreferenceExtensionsKt.firstBlocking(PreferenceManager2.getInstance(context).getLockHomeScreen()))
return false;
}
return LauncherPrefs.getPrefs(context).getBoolean(ADD_ICON_PREFERENCE_KEY, true);
return Utilities.getPrefs(context).getBoolean(ADD_ICON_PREFERENCE_KEY, true);
}
}
@@ -69,7 +69,6 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
private final ActivityContext mActivity;
private boolean mInvertIfRtl = false;
public boolean mHasOnLayoutBeenCalled = false;
private final PreferenceManager2 mPreferenceManager2;
@Nullable
@@ -218,7 +217,6 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Trace.beginSection("ShortcutAndWidgetConteiner#onLayout");
mHasOnLayoutBeenCalled = true; // b/349929393 - is the required call to onLayout not done?
int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
@@ -267,7 +265,7 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
}
child.layout(childLeft, childTop, childLeft + lp.width, childTop + lp.height);
if (mTranslationProvider != null) {
final float tx = mTranslationProvider.getTranslationX(lp.getCellX());
final float tx = mTranslationProvider.getTranslationX(child);
if (child instanceof Reorderable) {
((Reorderable) child).getTranslateDelegate()
.getTranslationX(INDEX_BUBBLE_ADJUSTMENT_ANIM)
@@ -349,13 +347,8 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
mTranslationProvider = provider;
}
/** Returns the current {@link TranslationProvider translation provider}. */
public @Nullable TranslationProvider getTranslationProvider() {
return mTranslationProvider;
}
/** Provides translation values to apply when laying out child views. */
public interface TranslationProvider {
float getTranslationX(int cellX);
interface TranslationProvider {
float getTranslationX(View child);
}
}
+213 -260
View File
@@ -16,9 +16,10 @@
package com.android.launcher3;
import static android.graphics.drawable.AdaptiveIconDrawable.getExtraInsetFraction;
import static com.android.launcher3.BuildConfigs.WIDGET_ON_FIRST_SCREEN;
import static com.android.launcher3.Flags.enableSmartspaceAsAWidget;
import static com.android.launcher3.graphics.ShapeDelegate.DEFAULT_PATH_SIZE;
import static com.android.launcher3.icons.BitmapInfo.FLAG_THEMED;
import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_BOTTOM_OR_RIGHT;
import static com.android.launcher3.util.SplitConfigurationOptions.STAGE_POSITION_TOP_OR_LEFT;
@@ -30,25 +31,30 @@ import android.app.ActivityOptions;
import android.app.Person;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
import android.content.pm.ResolveInfo;
import android.content.pm.ShortcutInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BlendMode;
import android.graphics.BlendModeColorFilter;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.InsetDrawable;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.DeadObjectException;
@@ -78,13 +84,11 @@ import androidx.annotation.WorkerThread;
import androidx.core.graphics.ColorUtils;
import com.android.launcher3.dragndrop.FolderAdaptiveIcon;
import com.android.launcher3.graphics.ThemeManager;
import com.android.launcher3.graphics.TintedDrawableSpan;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.CacheableShortcutCachingLogic;
import com.android.launcher3.icons.CacheableShortcutInfo;
import com.android.launcher3.icons.IconThemeController;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.icons.ShortcutCachingLogic;
import com.android.launcher3.icons.ThemedIconDrawable;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.pm.ShortcutConfigActivityInfo;
@@ -96,6 +100,7 @@ import com.android.launcher3.util.FlagOp;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.SplitConfigurationOptions.SplitPositionOption;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.widget.PendingAddShortcutInfo;
@@ -104,8 +109,9 @@ import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import app.lawnchair.icons.ExtendedBitmapDrawable;
import app.lawnchair.preferences.PreferenceManager;
@@ -117,7 +123,8 @@ public final class Utilities {
private static final String TAG = "Launcher.Utilities";
private static final String TRIM_PATTERN = "(^\\h+|\\h+$)";
private static final Pattern sTrimPattern = Pattern
.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$");
private static final Matrix sMatrix = new Matrix();
private static final Matrix sInverseMatrix = new Matrix();
@@ -140,50 +147,42 @@ public final class Utilities {
@ChecksSdkIntAtLeast(api = VERSION_CODES.S)
public static final boolean ATLEAST_S = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S;
@ChecksSdkIntAtLeast(api = VERSION_CODES.S_V2)
public static final boolean ATLEAST_S_V2 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S_V2;
@ChecksSdkIntAtLeast(api = VERSION_CODES.TIRAMISU, codename = "T")
public static final boolean ATLEAST_T = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU;
public static final boolean ATLEAST_S_V2 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S_V2;
@ChecksSdkIntAtLeast(api = VERSION_CODES.UPSIDE_DOWN_CAKE, codename = "U")
public static final boolean ATLEAST_U = Build.VERSION.SDK_INT >= VERSION_CODES.UPSIDE_DOWN_CAKE;
@ChecksSdkIntAtLeast(api = VERSION_CODES.VANILLA_ICE_CREAM, codename = "V")
public static final boolean ATLEAST_V = Build.VERSION.SDK_INT
>= VERSION_CODES.VANILLA_ICE_CREAM;
@ChecksSdkIntAtLeast(api = VERSION_CODES.BAKLAVA)
public static final boolean ATLEAST_BAKLAVA = Build.VERSION.SDK_INT >= VERSION_CODES.BAKLAVA;
@ChecksSdkIntAtLeast(api = 36, codename = "BAKLAVA_1")
public static final boolean ATLEAST_BAKLAVA_1 =
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA)
&& (Build.VERSION.SDK_INT_FULL >= 3600001); // pE-TODO(): Why Build.VERSION_CODES_FULL.BAKLAVA_1 failed?
public static final boolean ATLEAST_V = Build.VERSION.SDK_INT >= VERSION_CODES.VANILLA_ICE_CREAM;
/**
* Set on a motion event dispatched from the nav bar. See {@link MotionEvent#setEdgeFlags(int)}.
* Set on a motion event dispatched from the nav bar. See
* {@link MotionEvent#setEdgeFlags(int)}.
*/
public static final int EDGE_NAV_BAR = 1 << 8;
/**
* Indicates if the device has a debug build. Should only be used to store additional info or
* Indicates if the device has a debug build. Should only be used to store
* additional info or
* add extra logging and not for changing the app behavior.
*
* @deprecated Use {@link BuildConfig#IS_DEBUG_DEVICE} directly
*/
@Deprecated
public static final boolean IS_DEBUG_DEVICE = false;
public static final boolean IS_DEBUG_DEVICE = true;
public static final int TRANSLATE_UP = 0;
public static final int TRANSLATE_DOWN = 1;
public static final int TRANSLATE_LEFT = 2;
public static final int TRANSLATE_RIGHT = 3;
public static final boolean SHOULD_SHOW_FIRST_PAGE_WIDGET =
enableSmartspaceAsAWidget() && WIDGET_ON_FIRST_SCREEN;
public static final boolean SHOULD_SHOW_FIRST_PAGE_WIDGET = WIDGET_ON_FIRST_SCREEN;
@IntDef({TRANSLATE_UP, TRANSLATE_DOWN, TRANSLATE_LEFT, TRANSLATE_RIGHT})
public @interface AdjustmentDirection{}
@IntDef({ TRANSLATE_UP, TRANSLATE_DOWN, TRANSLATE_LEFT, TRANSLATE_RIGHT })
public @interface AdjustmentDirection {
}
/**
* Returns true if theme is dark.
@@ -203,6 +202,11 @@ public final class Utilities {
return nightMode == Configuration.UI_MODE_NIGHT_YES;
}
public static boolean isDevelopersOptionsEnabled(Context context) {
return Settings.Global.getInt(context.getApplicationContext().getContentResolver(),
Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
}
public static Drawable loadFullDrawableWithoutTheme(Context context, ItemInfo info,
int width, int height, Object[] outObj) {
ActivityContext activity = ActivityContext.lookupContext(context);
@@ -219,7 +223,7 @@ public final class Utilities {
return activityInfo == null ? null
: LauncherAppState.getInstance(context)
.getIconProvider().getIcon(
activityInfo.getActivityInfo(), activity.getDeviceProfile().inv.fillResIconDpi);
activityInfo, activity.getDeviceProfile().inv.fillResIconDpi);
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
List<ShortcutInfo> si = ShortcutKey.fromItemInfo(info)
.buildRequest(context)
@@ -228,9 +232,8 @@ public final class Utilities {
return null;
} else {
outObj[0] = si.get(0);
BitmapInfo bi = CacheableShortcutCachingLogic.INSTANCE.loadIcon(
context, appState.getIconCache(), new CacheableShortcutInfo(si.get(0), context));
return bi.newIcon(context);
return ShortcutCachingLogic.getIcon(context, si.get(0),
appState.getInvariantDeviceProfile().fillResIconDpi);
}
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
FolderAdaptiveIcon icon = FolderAdaptiveIcon.createFolderAdaptiveIcon(
@@ -258,15 +261,10 @@ public final class Utilities {
sIsRunningInTestHarness = true;
}
/** Disables running test in test harness mode */
public static void disableRunningInTestHarnessForTests() {
sIsRunningInTestHarness = false;
}
public static boolean isPropertyEnabled(String propertyName) {
return Log.isLoggable(propertyName, Log.VERBOSE);
}
public static boolean showStyleWallpapers(Context context) {
return existsStyleWallpapers(context) || existsStyleWallpapersAlt(context);
}
@@ -284,16 +282,22 @@ public final class Utilities {
}
/**
* Given a coordinate relative to the descendant, find the coordinate in a parent view's
* Given a coordinate relative to the descendant, find the coordinate in a
* parent view's
* coordinates.
*
* @param descendant The descendant to which the passed coordinate is relative.
* @param ancestor The root view to make the coordinates relative to.
* @param coord The coordinate that we want mapped.
* @param includeRootScroll Whether or not to account for the scroll of the descendant:
* sometimes this is relevant as in a child's coordinates within the descendant.
* @return The factor by which this descendant is scaled relative to this DragLayer. Caution
* this scale factor is assumed to be equal in X and Y, and so if at any point this
* @param descendant The descendant to which the passed coordinate is
* relative.
* @param ancestor The root view to make the coordinates relative to.
* @param coord The coordinate that we want mapped.
* @param includeRootScroll Whether or not to account for the scroll of the
* descendant:
* sometimes this is relevant as in a child's
* coordinates within the descendant.
* @return The factor by which this descendant is scaled relative to this
* DragLayer. Caution
* this scale factor is assumed to be equal in X and Y, and so if at any
* point this
* assumption fails, we will need to return a pair of scale factors.
*/
public static float getDescendantCoordRelativeToAncestor(
@@ -303,24 +307,30 @@ public final class Utilities {
}
/**
* Given a coordinate relative to the descendant, find the coordinate in a parent view's
* Given a coordinate relative to the descendant, find the coordinate in a
* parent view's
* coordinates.
*
* @param descendant The descendant to which the passed coordinate is relative.
* @param ancestor The root view to make the coordinates relative to.
* @param coord The coordinate that we want mapped.
* @param includeRootScroll Whether or not to account for the scroll of the descendant:
* sometimes this is relevant as in a child's coordinates within the descendant.
* @param ignoreTransform If true, view transform is ignored
* @return The factor by which this descendant is scaled relative to this DragLayer. Caution
* this scale factor is assumed to be equal in X and Y, and so if at any point this
* @param descendant The descendant to which the passed coordinate is
* relative.
* @param ancestor The root view to make the coordinates relative to.
* @param coord The coordinate that we want mapped.
* @param includeRootScroll Whether or not to account for the scroll of the
* descendant:
* sometimes this is relevant as in a child's
* coordinates within the descendant.
* @param ignoreTransform If true, view transform is ignored
* @return The factor by which this descendant is scaled relative to this
* DragLayer. Caution
* this scale factor is assumed to be equal in X and Y, and so if at any
* point this
* assumption fails, we will need to return a pair of scale factors.
*/
public static float getDescendantCoordRelativeToAncestor(View descendant, View ancestor,
float[] coord, boolean includeRootScroll, boolean ignoreTransform) {
float scale = 1.0f;
View v = descendant;
while(v != ancestor && v != null) {
while (v != ancestor && v != null) {
// For TextViews, scroll has a meaning which relates to the text position
// which is very strange... ignore the scroll.
if (v != descendant || includeRootScroll) {
@@ -343,10 +353,12 @@ public final class Utilities {
*
* see {@link com.android.launcher3.dragndrop.DragLayer}.
*
* @param viewBounds Bounds of the view wanted in drag layer coordinates, relative to the view
* itself. eg. (0, 0, view.getWidth, view.getHeight)
* @param viewBounds Bounds of the view wanted in drag layer coordinates,
* relative to the view
* itself. eg. (0, 0, view.getWidth, view.getHeight)
* @param ignoreTransform If true, view transform is ignored
* @param outRect The out rect where we return the bounds of {@param view} in drag layer coords.
* @param outRect The out rect where we return the bounds of
* {@param view} in drag layer coords.
*/
public static void getBoundsForViewInDragLayer(BaseDragLayer dragLayer, View view,
Rect viewBounds, boolean ignoreTransform, float[] recycle, RectF outRect) {
@@ -366,24 +378,24 @@ public final class Utilities {
}
/**
* Similar to {@link #mapCoordInSelfToDescendant(View descendant, View root, float[] coord)}
* Similar to
* {@link #mapCoordInSelfToDescendant(View descendant, View root, float[] coord)}
* but accepts a Rect instead of float[].
*/
public static void mapRectInSelfToDescendant(View descendant, View root, Rect rect) {
float[] coords = new float[]{rect.left, rect.top, rect.right, rect.bottom};
float[] coords = new float[] { rect.left, rect.top, rect.right, rect.bottom };
mapCoordInSelfToDescendant(descendant, root, coords);
rect.set((int) coords[0], (int) coords[1], (int) coords[2], (int) coords[3]);
}
/**
* Inverse of {@link #getDescendantCoordRelativeToAncestor(View, View, float[], boolean)}.
* Inverse of
* {@link #getDescendantCoordRelativeToAncestor(View, View, float[], boolean)}.
*/
public static void mapCoordInSelfToDescendant(View descendant, View root, float[] coord) {
sMatrix.reset();
//TODO(b/307488755) when implemented this check should be removed
if (!Objects.equals(descendant.getWindowId(), root.getWindowId())) {
if (descendant == null || root == null || coord == null || coord.length < 2)
return;
}
sMatrix.reset();
View v = descendant;
while (v != root) {
sMatrix.postTranslate(-v.getScrollX(), -v.getScrollY());
@@ -414,8 +426,10 @@ public final class Utilities {
/**
* Utility method to determine whether the given point, in local coordinates,
* is inside the view, where the area of the view is expanded by the slop factor.
* This method is called while processing touch-move events to determine if the event
* is inside the view, where the area of the view is expanded by the slop
* factor.
* This method is called while processing touch-move events to determine if the
* event
* is still within the view.
*/
public static boolean pointInView(View v, float localX, float localY, float slop) {
@@ -428,7 +442,8 @@ public final class Utilities {
}
/**
* Similar to {@link #scaleRectAboutCenter(Rect, float)} except this allows different scales
* Similar to {@link #scaleRectAboutCenter(Rect, float)} except this allows
* different scales
* for X and Y
*/
public static void scaleRectFAboutCenter(RectF r, float scaleX, float scaleY) {
@@ -470,8 +485,8 @@ public final class Utilities {
/**
* Sets the x and y pivots for scaling from one Rect to another.
*
* @param src the source rectangle to scale from.
* @param dst the destination rectangle to scale to.
* @param src the source rectangle to scale from.
* @param dst the destination rectangle to scale to.
* @param outPivot the pivots set for scaling from src to dst.
*/
public static void getPivotsForScalingRectToRect(Rect src, Rect dst, PointF outPivot) {
@@ -482,35 +497,14 @@ public final class Utilities {
outPivot.y = dst.top + dst.height() * pivotYPct;
}
/**
* Scales a {@code RectF} in place about a specified pivot point.
*
* <p>This method modifies the given {@code RectF} directly to scale it proportionally
* by the given {@code scale}, while preserving its center at the specified
* {@code (pivotX, pivotY)} coordinates.
*
* @param rectF the {@code RectF} to scale, modified directly.
* @param pivotX the x-coordinate of the pivot point about which to scale.
* @param pivotY the y-coordinate of the pivot point about which to scale.
* @param scale the factor by which to scale the rectangle. Values less than 1 will
* shrink the rectangle, while values greater than 1 will enlarge it.
*/
public static void scaleRectFAboutPivot(RectF rectF, float pivotX, float pivotY, float scale) {
rectF.offset(-pivotX, -pivotY);
rectF.left *= scale;
rectF.top *= scale;
rectF.right *= scale;
rectF.bottom *= scale;
rectF.offset(pivotX, pivotY);
}
/**
* Maps t from one range to another range.
* @param t The value to map.
*
* @param t The value to map.
* @param fromMin The lower bound of the range that t is being mapped from.
* @param fromMax The upper bound of the range that t is being mapped from.
* @param toMin The lower bound of the range that t is being mapped to.
* @param toMax The upper bound of the range that t is being mapped to.
* @param toMin The lower bound of the range that t is being mapped to.
* @param toMax The upper bound of the range that t is being mapped to.
* @return The mapped value of t.
*/
public static float mapToRange(float t, float fromMin, float fromMax, float toMin, float toMax,
@@ -523,25 +517,6 @@ public final class Utilities {
return mapRange(interpolator.getInterpolation(progress), toMin, toMax);
}
/**
* Maps t from one range to another range.
* @param t The value to map.
* @param fromMin The lower bound of the range that t is being mapped from.
* @param fromMax The upper bound of the range that t is being mapped from.
* @param toMin The lower bound of the range that t is being mapped to.
* @param toMax The upper bound of the range that t is being mapped to.
* @return The mapped value of t.
*/
public static int mapToRange(int t, int fromMin, int fromMax, int toMin, int toMax,
Interpolator interpolator) {
if (fromMin == fromMax || toMin == toMax) {
Log.e(TAG, "mapToRange: range has 0 length");
return toMin;
}
float progress = getProgress(t, fromMin, fromMax);
return (int) mapRange(interpolator.getInterpolation(progress), toMin, toMax);
}
/** Bounds t between a lower and upper bound and maps the result to a range. */
public static float mapBoundToRange(float t, float lowerBound, float upperBound,
float toMin, float toMax, Interpolator interpolator) {
@@ -558,7 +533,8 @@ public final class Utilities {
}
/**
* Trims the string, removing all whitespace at the beginning and end of the string.
* Trims the string, removing all whitespace at the beginning and end of the
* string.
* Non-breaking whitespaces are also removed.
*/
@NonNull
@@ -566,7 +542,11 @@ public final class Utilities {
if (s == null) {
return "";
}
return s.toString().replaceAll(TRIM_PATTERN, "").trim();
// Just strip any sequence of whitespace or java space characters from the
// beginning and end
Matcher m = sTrimPattern.matcher(s);
return m.replaceAll("$1");
}
/**
@@ -583,7 +563,9 @@ public final class Utilities {
return res.getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
}
/** Converts a pixel value (px) to scale pixel value (SP) for the current device. */
/**
* Converts a pixel value (px) to scale pixel value (SP) for the current device.
*/
public static float pxToSp(float size) {
return size / Resources.getSystem().getDisplayMetrics().scaledDensity;
}
@@ -637,7 +619,8 @@ public final class Utilities {
/**
* Ensures that a value is within given bounds. Specifically:
* If value is less than lowerBound, return lowerBound; else if value is greater than upperBound,
* If value is less than lowerBound, return lowerBound; else if value is greater
* than upperBound,
* return upperBound; else return value unchanged.
*/
public static int boundToRange(int value, int lowerBound, int upperBound) {
@@ -661,7 +644,8 @@ public final class Utilities {
/**
* Wraps a message with a TTS span, so that a different message is spoken than
* what is getting displayed.
* @param msg original message
*
* @param msg original message
* @param ttsMsg message to be spoken
*/
public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
@@ -676,8 +660,10 @@ public final class Utilities {
*/
public static CharSequence prefixTextWithIcon(Context context, int iconRes, CharSequence msg) {
// Update the hint to contain the icon.
// Prefix the original hint with two spaces. The first space gets replaced by the icon
// using span. The second space is used for a singe space character between the hint
// Prefix the original hint with two spaces. The first space gets replaced by
// the icon
// using span. The second space is used for a singe space character between the
// hint
// and the icon.
SpannableString spanned = new SpannableString(" " + msg);
spanned.setSpan(new TintedDrawableSpan(context, iconRes),
@@ -699,7 +685,8 @@ public final class Utilities {
}
/**
* Utility method to post a runnable on the handler, skipping the synchronization barriers.
* Utility method to post a runnable on the handler, skipping the
* synchronization barriers.
*/
public static void postAsyncCallback(Handler handler, Runnable callback) {
Message msg = Message.obtain(handler, callback);
@@ -708,7 +695,8 @@ public final class Utilities {
}
/**
* Utility method to allow background activity launch for the provided activity options
* Utility method to allow background activity launch for the provided activity
* options
*/
public static ActivityOptions allowBGLaunch(ActivityOptions options) {
if (ATLEAST_V) {
@@ -719,15 +707,8 @@ public final class Utilities {
}
/**
* Utility method to know if a device's primary language is English.
*/
public static boolean isEnglishLanguage(Context context) {
return context.getResources().getConfiguration().locale.getLanguage()
.equals(Locale.ENGLISH.getLanguage());
}
/**
* Returns the full drawable for info as multiple layers of AdaptiveIconDrawable. The second
* Returns the full drawable for info as multiple layers of
* AdaptiveIconDrawable. The second
* drawable in the Pair is the badge used with the icon.
*
* @param useTheme If true, will theme icons when applicable
@@ -735,19 +716,19 @@ public final class Utilities {
@SuppressLint("UseCompatLoadingForDrawables")
@Nullable
@WorkerThread
public static <T extends Context & ActivityContext> Pair<AdaptiveIconDrawable, Drawable>
getFullDrawable(T context, ItemInfo info, int width, int height, boolean useTheme) {
public static <T extends Context & ActivityContext> Pair<AdaptiveIconDrawable, Drawable> getFullDrawable(T context,
ItemInfo info, int width, int height, boolean useTheme) {
useTheme &= Themes.isThemedIconEnabled(context);
LauncherAppState appState = LauncherAppState.getInstance(context);
Drawable mainIcon = null;
Drawable badge = null;
if ((info instanceof ItemInfoWithIcon iiwi) && !iiwi.getMatchingLookupFlag().useLowRes()) {
badge = iiwi.bitmap.getBadgeDrawable(context, useTheme, getIconShapeOrNull(context));
if ((info instanceof ItemInfoWithIcon iiwi) && !iiwi.usingLowResIcon()) {
badge = iiwi.bitmap.getBadgeDrawable(context, useTheme);
}
if (info instanceof PendingAddShortcutInfo) {
ShortcutConfigActivityInfo activityInfo =
((PendingAddShortcutInfo) info).getActivityInfo(context);
ShortcutConfigActivityInfo activityInfo = ((PendingAddShortcutInfo) info).getActivityInfo(context);
mainIcon = activityInfo.getFullResIcon(appState.getIconCache());
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
LauncherActivityInfo activityInfo = context.getSystemService(LauncherApps.class)
@@ -755,7 +736,8 @@ public final class Utilities {
if (activityInfo == null) {
return null;
}
mainIcon = appState.getIconCache().getFullResIcon(activityInfo.getActivityInfo());
mainIcon = appState.getIconProvider().getIcon(
activityInfo, appState.getInvariantDeviceProfile().fillResIconDpi);
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
List<ShortcutInfo> siList = ShortcutKey.fromItemInfo(info)
.buildRequest(context)
@@ -764,16 +746,12 @@ public final class Utilities {
return null;
} else {
ShortcutInfo si = siList.get(0);
mainIcon = CacheableShortcutInfo.getIcon(context, si,
mainIcon = ShortcutCachingLogic.getIcon(context, si,
appState.getInvariantDeviceProfile().fillResIconDpi);
// Only fetch badge if the icon is on workspace
if (info.id != ItemInfo.NO_ID && badge == null) {
badge = appState.getIconCache().getShortcutInfoBadge(si).newIcon(
context,
ThemeManager.INSTANCE.get(context).isIconThemeEnabled()
? FLAG_THEMED : 0,
getIconShapeOrNull(context)
);
badge = appState.getIconCache().getShortcutInfoBadge(si)
.newIcon(context, FLAG_THEMED);
}
}
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
@@ -782,16 +760,19 @@ public final class Utilities {
if (icon == null) {
return null;
}
mainIcon = icon;
mainIcon = icon;
badge = icon.getBadge();
}
if (useTheme && mainIcon instanceof BitmapInfo.Extender) {
mainIcon = ((BitmapInfo.Extender) mainIcon).getThemedDrawable(context);
}
if (mainIcon == null) {
return null;
}
AdaptiveIconDrawable result;
// Lawnchair-TODO-Merge: From LC, maybe heavily affected by L3, Allow 3p icon
if (ExtendedBitmapDrawable.isFromIconPack(mainIcon) || (!PreferenceManager.INSTANCE.get(context).getWrapAdaptiveIcons().get() && info.itemType != LauncherSettings.Favorites.ITEM_TYPE_FOLDER))
return null;
if (mainIcon instanceof AdaptiveIconDrawable aid) {
@@ -799,35 +780,49 @@ public final class Utilities {
} else {
// Wrap the main icon in AID
try (LauncherIcons li = LauncherIcons.obtain(context)) {
result = li.wrapToAdaptiveIcon(mainIcon);
result = li.wrapToAdaptiveIcon(mainIcon, null);
}
}
if (result == null) {
return null;
}
// Inject theme icon drawable
if (ATLEAST_T && useTheme) {
IconThemeController themeController =
ThemeManager.INSTANCE.get(context).getThemeController();
if (themeController != null) {
AdaptiveIconDrawable themed = themeController.createThemedAdaptiveIcon(
context,
result,
info instanceof ItemInfoWithIcon iiwi ? iiwi.bitmap : null);
if (themed != null) {
result = themed;
// Inject monochrome icon drawable
if (useTheme) {
result.mutate();
int[] colors = ThemedIconDrawable.getColors(context);
Drawable mono = null;
if (ATLEAST_T) {
mono = result.getMonochrome();
}
if (mono != null) {
mono.setTint(colors[1]);
} else if (info instanceof ItemInfoWithIcon iiwi) {
// Inject a previously generated monochrome icon
Bitmap monoBitmap = iiwi.bitmap.getMono();
if (monoBitmap != null) {
// Use BitmapDrawable instead of FastBitmapDrawable so that the colorState is
// preserved in constantState
mono = new BitmapDrawable(monoBitmap);
if (ATLEAST_Q) {
mono.setColorFilter(new BlendModeColorFilter(colors[1], BlendMode.SRC_IN));
}
// Inset the drawable according to the AdaptiveIconDrawable layers
mono = new InsetDrawable(mono, getExtraInsetFraction() / 2);
}
}
if (mono != null) {
result = new AdaptiveIconDrawable(new ColorDrawable(colors[0]), mono);
}
}
if (badge == null) {
badge = BitmapInfo.LOW_RES_INFO.withFlags(
UserCache.INSTANCE.get(context)
.getUserInfo(info.user)
.applyBitmapInfoFlags(FlagOp.NO_OP)
)
.getBadgeDrawable(context, useTheme, getIconShapeOrNull(context));
.applyBitmapInfoFlags(FlagOp.NO_OP))
.getBadgeDrawable(context, useTheme);
if (badge == null) {
badge = new ColorDrawable(Color.TRANSPARENT);
}
@@ -845,54 +840,11 @@ public final class Utilities {
}
/**
* Rotates `inOutBounds` by `delta` 90-degree increments. Rotation is visually CW. Parent
* sizes represent the "space" that will rotate carrying inOutBounds along with it to determine
* Rotates `inOutBounds` by `delta` 90-degree increments. Rotation is visually
* CCW. Parent
* sizes represent the "space" that will rotate carrying inOutBounds along with
* it to determine
* the final bounds.
*
* As an example if this is the input:
* +-------------+
* | +-----+ |
* | | | |
* | +-----+ |
* | |
* | |
* | |
* +-------------+
* This would be case delta % 4 == 0:
* +-------------+
* | +-----+ |
* | | | |
* | +-----+ |
* | |
* | |
* | |
* +-------------+
* This would be case delta % 4 == 1:
* +----------------+
* | +--+ |
* | | | |
* | | | |
* | +--+ |
* | |
* +----------------+
* This would be case delta % 4 == 2: // This is case was reverted to previous behaviour which
* doesn't match the illustration due to b/353965234
* +-------------+
* | |
* | |
* | |
* | +-----+ |
* | | | |
* | +-----+ |
* +-------------+
* This would be case delta % 4 == 3:
* +----------------+
* | +--+ |
* | | | |
* | | | |
* | +--+ |
* | |
* +----------------+
*/
public static void rotateBounds(Rect inOutBounds, int parentWidth, int parentHeight,
int delta) {
@@ -921,9 +873,10 @@ public final class Utilities {
}
/**
* Make a color filter that blends a color into the destination based on a scalable amout.
* Make a color filter that blends a color into the destination based on a
* scalable amout.
*
* @param color to blend in.
* @param color to blend in.
* @param tintAmount [0-1] 0 no tinting, 1 full color.
* @return ColorFilter for tinting, or {@code null} if no filter is needed.
*/
@@ -932,7 +885,8 @@ public final class Utilities {
return null;
}
return new LightingColorFilter(
// This isn't blending in white, its making a multiplication mask for the base color
// This isn't blending in white, its making a multiplication mask for the base
// color
ColorUtils.blendARGB(Color.WHITE, 0, tintAmount),
ColorUtils.blendARGB(0, color, tintAmount));
}
@@ -944,7 +898,8 @@ public final class Utilities {
}
/**
* Returns a list of screen-splitting options depending on the device orientation (split top for
* Returns a list of screen-splitting options depending on the device
* orientation (split top for
* portrait, split right for landscape)
*/
public static List<SplitPositionOption> getSplitPositionOptions(
@@ -959,37 +914,61 @@ public final class Utilities {
splitIconRes,
R.string.recent_task_option_split_screen,
stagePosition,
STAGE_TYPE_MAIN
));
STAGE_TYPE_MAIN));
}
/** Logs the Scale and Translate properties of a matrix. Ignores skew and perspective. */
/**
* Logs the Scale and Translate properties of a matrix. Ignores skew and
* perspective.
*/
public static void logMatrix(String label, Matrix matrix) {
float[] matrixValues = new float[9];
matrix.getValues(matrixValues);
Log.d(label, String.format("%s: %s\nscale (x,y) = (%f, %f)\ntranslate (x,y) = (%f, %f)",
label, matrix, matrixValues[Matrix.MSCALE_X], matrixValues[Matrix.MSCALE_Y],
matrixValues[Matrix.MTRANS_X], matrixValues[Matrix.MTRANS_Y]
));
matrixValues[Matrix.MTRANS_X], matrixValues[Matrix.MTRANS_Y]));
}
public static SharedPreferences getPrefs(Context context) {
// Use application context for shared preferences, so that we use a single
// cached instance
return context.getApplicationContext().getSharedPreferences(
LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
}
public static SharedPreferences getDevicePrefs(Context context) {
// Use application context for shared preferences, so that we use a single
// cached instance
return context.getApplicationContext().getSharedPreferences(
LauncherFiles.DEVICE_PREFERENCES_KEY, Context.MODE_PRIVATE);
}
/**
* Translates the {@code targetView} so that it overlaps with {@code exclusionBounds} as little
* Translates the {@code targetView} so that it overlaps with
* {@code exclusionBounds} as little
* as possible, while remaining within {@code inclusionBounds}.
* <p>
* {@code inclusionBounds} will always take precedence over {@code exclusionBounds}, so if
* {@code targetView} needs to be translated outside of {@code inclusionBounds} to fully fix an
* overlap with {@code exclusionBounds}, then {@code targetView} will only be translated up to
* {@code inclusionBounds} will always take precedence over
* {@code exclusionBounds}, so if
* {@code targetView} needs to be translated outside of {@code inclusionBounds}
* to fully fix an
* overlap with {@code exclusionBounds}, then {@code targetView} will only be
* translated up to
* the border of {@code inclusionBounds}.
* <p>
* Note: {@code targetViewBounds}, {@code inclusionBounds} and {@code exclusionBounds} must all
* Note: {@code targetViewBounds}, {@code inclusionBounds} and
* {@code exclusionBounds} must all
* be in relation to the same reference point on screen.
* <p>
* @param targetView the view being translated
* @param targetViewBounds the bounds of the {@code targetView}
* @param inclusionBounds the bounds the {@code targetView} absolutely must stay within
* @param exclusionBounds the bounds to try to move the {@code targetView} away from
* @param adjustmentDirection the translation direction that should be attempted to fix an
*
* @param targetView the view being translated
* @param targetViewBounds the bounds of the {@code targetView}
* @param inclusionBounds the bounds the {@code targetView} absolutely must
* stay within
* @param exclusionBounds the bounds to try to move the {@code targetView}
* away from
* @param adjustmentDirection the translation direction that should be attempted
* to fix an
* overlap
*/
public static void translateOverlappingView(
@@ -998,9 +977,6 @@ public final class Utilities {
@NonNull Rect inclusionBounds,
@NonNull Rect exclusionBounds,
@AdjustmentDirection int adjustmentDirection) {
if (!Rect.intersects(targetViewBounds, exclusionBounds)) {
return;
}
switch (adjustmentDirection) {
case TRANSLATE_RIGHT:
targetView.setTranslationX(Math.min(
@@ -1036,8 +1012,10 @@ public final class Utilities {
}
/**
* Does a depth-first search through the View hierarchy starting at root, to find a view that
* matches the predicate. Returns null if no View was found. View has a findViewByPredicate
* Does a depth-first search through the View hierarchy starting at root, to
* find a view that
* matches the predicate. Returns null if no View was found. View has a
* findViewByPredicate
* member function but it is currently a @hide API.
*/
@Nullable
@@ -1057,29 +1035,4 @@ public final class Utilities {
}
return null;
}
/**
* Returns current icon shape to use for badges if flag is on, otherwise null.
*/
@Nullable
public static Path getIconShapeOrNull(Context context) {
if (Flags.enableLauncherIconShapes()) {
return ThemeManager.INSTANCE.get(context)
.getIconShape()
.getPath(DEFAULT_PATH_SIZE);
} else {
return null;
}
}
/**
* Logs with DEBUG priority if the current device is a debug device.
*
* <p>Debug devices by default include -eng and -userdebug builds, but not -user builds.
*/
public static void debugLog(String tag, String message) {
if (false) {
Log.d(tag, message);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,89 @@
/*
* Copyright (C) 2016 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.accessibility;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.OnHierarchyChangeListener;
import androidx.annotation.Nullable;
import com.android.launcher3.CellLayout;
import com.android.launcher3.DropTarget.DragObject;
import com.android.launcher3.Launcher;
import com.android.launcher3.dragndrop.DragController.DragListener;
import com.android.launcher3.dragndrop.DragOptions;
import java.util.function.Function;
/**
* Utility listener to enable/disable accessibility drag flags for a ViewGroup
* containing CellLayouts
*/
public class AccessibleDragListenerAdapter implements DragListener, OnHierarchyChangeListener {
private final ViewGroup mViewGroup;
private final Function<CellLayout, DragAndDropAccessibilityDelegate> mDelegateFactory;
/**
* @param parent the viewgroup containing all the children
* @param delegateFactory function to create no delegates
*/
public AccessibleDragListenerAdapter(ViewGroup parent,
Function<CellLayout, DragAndDropAccessibilityDelegate> delegateFactory) {
mViewGroup = parent;
mDelegateFactory = delegateFactory;
}
@Override
public void onDragStart(DragObject dragObject, DragOptions options) {
mViewGroup.setOnHierarchyChangeListener(this);
enableAccessibleDrag(true, dragObject);
}
@Override
public void onDragEnd() {
mViewGroup.setOnHierarchyChangeListener(null);
enableAccessibleDrag(false, null);
Launcher.getLauncher(mViewGroup.getContext()).getDragController().removeDragListener(this);
}
@Override
public void onChildViewAdded(View parent, View child) {
if (parent == mViewGroup) {
setEnableForLayout((CellLayout) child, true);
}
}
@Override
public void onChildViewRemoved(View parent, View child) {
if (parent == mViewGroup) {
setEnableForLayout((CellLayout) child, false);
}
}
protected void enableAccessibleDrag(boolean enable, @Nullable DragObject dragObject) {
for (int i = 0; i < mViewGroup.getChildCount(); i++) {
setEnableForLayout((CellLayout) mViewGroup.getChildAt(i), enable);
}
}
protected final void setEnableForLayout(CellLayout layout, boolean enable) {
layout.setDragAndDropAccessibilityDelegate(enable ? mDelegateFactory.apply(layout) : null);
}
}
@@ -29,9 +29,9 @@ import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.customview.widget.ExploreByTouchHelper;
import com.android.launcher3.CellLayout;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.dragndrop.DragLayer;
import java.util.List;
@@ -47,17 +47,16 @@ public abstract class DragAndDropAccessibilityDelegate extends ExploreByTouchHel
protected final CellLayout mView;
protected final Context mContext;
protected final ActivityContext mActivityContext;
protected final LauncherAccessibilityDelegate mDelegate;
protected final BaseDragLayer<?> mDragLayer;
protected final DragLayer mDragLayer;
public DragAndDropAccessibilityDelegate(CellLayout forView) {
super(forView);
mView = forView;
mContext = mView.getContext();
mActivityContext = ActivityContext.lookupContext(mContext);
mDelegate = (LauncherAccessibilityDelegate) mActivityContext.getAccessibilityDelegate();
mDragLayer = mActivityContext.getDragLayer();
Launcher launcher = Launcher.getLauncher(mContext);
mDelegate = launcher.getAccessibilityDelegate();
mDragLayer = launcher.getDragLayer();
}
@Override
@@ -24,8 +24,6 @@ import android.view.accessibility.AccessibilityEvent;
import androidx.annotation.Nullable;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.AppWidgetResizeFrame;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.ButtonDropTarget;
import com.android.launcher3.CellLayout;
@@ -50,7 +48,6 @@ import com.android.launcher3.model.data.WorkspaceItemFactory;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.popup.ArrowPopup;
import com.android.launcher3.popup.PopupContainerWithArrow;
import com.android.launcher3.shortcuts.DeepShortcutView;
import com.android.launcher3.touch.ItemLongClickListener;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
@@ -83,7 +80,6 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
protected static final int MOVE_TO_WORKSPACE = R.id.action_move_to_workspace;
protected static final int RESIZE = R.id.action_resize;
public static final int DEEP_SHORTCUTS = R.id.action_deep_shortcuts;
public static final int CLOSE = R.id.action_close;
public LauncherAccessibilityDelegate(Launcher launcher) {
super(launcher);
@@ -106,19 +102,13 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
RESIZE, R.string.action_resize, KeyEvent.KEYCODE_R));
mActions.put(DEEP_SHORTCUTS, new LauncherAction(DEEP_SHORTCUTS,
R.string.action_deep_shortcut, KeyEvent.KEYCODE_S));
mActions.put(CLOSE, new LauncherAction(CLOSE,
R.string.action_close, KeyEvent.KEYCODE_X));
}
private static boolean isNotInShortcutMenu(@Nullable View view) {
return view == null || !(view.getParent() instanceof DeepShortcutView);
}
@Override
protected void getSupportedActions(View host, ItemInfo item, List<LauncherAction> out) {
// If the request came from keyboard, do not add custom shortcuts as that is already
// exposed as a direct shortcut
if (isNotInShortcutMenu(host) && ShortcutUtil.supportsShortcuts(item)) {
if (ShortcutUtil.supportsShortcuts(item)) {
out.add(mActions.get(DEEP_SHORTCUTS));
}
@@ -141,10 +131,6 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
}
}
if (host instanceof AppWidgetResizeFrame) {
out.add(mActions.get(CLOSE));
}
if (supportAddToWorkSpace(item)) {
out.add(mActions.get(ADD_TO_WORKSPACE));
}
@@ -191,30 +177,22 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
}
return dragCondition != null;
} else if (action == MOVE) {
final View itemView = (host instanceof AppWidgetResizeFrame)
? ((AppWidgetResizeFrame) host).getViewForAccessibility()
: host;
return beginAccessibleDrag(itemView, item, fromKeyboard);
return beginAccessibleDrag(host, item, fromKeyboard);
} else if (action == ADD_TO_WORKSPACE) {
return addToWorkspace(item, true /*accessibility*/, null /*finishCallback*/);
} else if (action == MOVE_TO_WORKSPACE) {
return moveToWorkspace(item);
} else if (action == RESIZE) {
final View itemView = (host instanceof AppWidgetResizeFrame)
? ((AppWidgetResizeFrame) host).getViewForAccessibility()
: host;
final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) item;
List<OptionItem> actions = getSupportedResizeActions(itemView, info);
List<OptionItem> actions = getSupportedResizeActions(host, info);
Rect pos = new Rect();
mContext.getDragLayer().getDescendantRectRelativeToSelf(itemView, pos);
mContext.getDragLayer().getDescendantRectRelativeToSelf(host, pos);
ArrowPopup popup = OptionsPopupView.show(mContext, new RectF(pos), actions, false);
popup.requestFocus();
popup.addOnCloseCallback(() -> {
itemView.requestFocus();
itemView.sendAccessibilityEvent(TYPE_VIEW_FOCUSED);
itemView.performAccessibilityAction(ACTION_ACCESSIBILITY_FOCUS, null);
AbstractFloatingView.closeOpenViews(mContext, /* animate= */ false,
AbstractFloatingView.TYPE_WIDGET_RESIZE_FRAME);
host.requestFocus();
host.sendAccessibilityEvent(TYPE_VIEW_FOCUSED);
host.performAccessibilityAction(ACTION_ACCESSIBILITY_FOCUS, null);
});
return true;
} else if (action == DEEP_SHORTCUTS) {
@@ -222,11 +200,6 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
: (host instanceof BubbleTextHolder
? ((BubbleTextHolder) host).getBubbleText() : null);
return btv != null && PopupContainerWithArrow.showForIcon(btv) != null;
} else if (action == CLOSE) {
if (host instanceof AppWidgetResizeFrame) {
AbstractFloatingView.closeOpenViews(mContext, /* animate= */ false,
AbstractFloatingView.TYPE_WIDGET_RESIZE_FRAME);
}
} else {
for (ButtonDropTarget dropTarget : mContext.getDropTargetBar().getDropTargets()) {
if (dropTarget.supportsAccessibilityDrop(item, host)
@@ -241,10 +214,6 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
private List<OptionItem> getSupportedResizeActions(View host, LauncherAppWidgetInfo info) {
List<OptionItem> actions = new ArrayList<>();
if (host instanceof AppWidgetResizeFrame) {
return getSupportedResizeActions(
((AppWidgetResizeFrame) host).getViewForAccessibility(), info);
}
AppWidgetProviderInfo providerInfo = ((LauncherAppWidgetHostView) host).getAppWidgetInfo();
if (providerInfo == null) {
return actions;
@@ -330,6 +299,7 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
info.spanX, info.spanY);
host.requestLayout();
mContext.getModelWriter().updateItemInDatabase(info);
announceConfirmation(mContext.getString(R.string.widget_resized, info.spanX, info.spanY));
return true;
}
@@ -429,11 +399,6 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
*/
public boolean addToWorkspace(ItemInfo item, boolean accessibility,
@Nullable Consumer<Boolean> finishCallback) {
// Dismiss widget resize frame if it is showing. The frame marks its cells as unoccupied
// while it is showing, so findSpaceOnWorkspace may try to use those cells.
AbstractFloatingView.closeOpenViews(mContext, /* animate= */ false,
AbstractFloatingView.TYPE_WIDGET_RESIZE_FRAME);
final int[] coordinates = new int[2];
final int screenId = findSpaceOnWorkspace(item, coordinates);
if (screenId == -1) {
@@ -450,6 +415,7 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
screenId, coordinates[0], coordinates[1]);
bindItem(info, accessibility, finishCallback);
announceConfirmation(R.string.item_added_to_workspace);
} else if (item instanceof PendingAddItemInfo) {
PendingAddItemInfo info = (PendingAddItemInfo) item;
if (info instanceof PendingAddWidgetInfo widgetInfo
@@ -519,7 +485,7 @@ public class LauncherAccessibilityDelegate extends BaseAccessibilityDelegate<Lau
Folder folder = Folder.getOpen(mContext);
folder.close(true);
WorkspaceItemInfo info = (WorkspaceItemInfo) item;
folder.removeFolderContent(false, info);
folder.getInfo().remove(info, false);
final int[] coordinates = new int[2];
final int screenId = findSpaceOnWorkspace(item, coordinates);
@@ -24,6 +24,7 @@ import android.view.View;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.R;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.DeepShortcutView;
@@ -66,6 +67,7 @@ public class ShortcutMenuAccessibilityDelegate extends LauncherAccessibilityDele
screenId, coordinates[0], coordinates[1]);
mContext.bindItems(Collections.singletonList(info), true);
AbstractFloatingView.closeAllOpenViews(mContext);
announceConfirmation(R.string.item_added_to_workspace);
}));
return true;
}
@@ -114,7 +114,9 @@ public class WorkspaceAccessibilityHelper extends DragAndDropAccessibilityDelega
LauncherAccessibilityDelegate.DragInfo dragInfo = mDelegate.getDragInfo();
View child = mView.getChildAt(x, y);
if (child != null && child != dragInfo.item) {
if (child == null || child == dragInfo.item) {
return mContext.getString(R.string.item_moved);
} else {
ItemInfo info = (ItemInfo) child.getTag();
if (Folder.willAccept(info)) {
return mContext.getString(R.string.folder_created);
File diff suppressed because it is too large. Load diff
@@ -15,8 +15,6 @@
*/
package com.android.launcher3.allapps;
import static android.view.HapticFeedbackConstants.CLOCK_TICK;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
@@ -73,7 +71,6 @@ public class AllAppsFastScrollHelper {
@Override
protected int getVerticalSnapPreference() {
mRv.performHapticFeedback(CLOCK_TICK);
return SNAP_TO_ANY;
}
@@ -30,6 +30,7 @@ import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.R;
import com.android.launcher3.config.FeatureFlags;
@@ -135,12 +136,6 @@ public class AllAppsGridAdapter<T extends Context & ActivityContext> extends
getRowsNotForAccessibility(mApps.getAdapterItems().size() - 1);
}
@Override
public int getColumnCountForAccessibility(RecyclerView.Recycler recycler,
RecyclerView.State state) {
return mAppsPerRow;
}
@Override
public void onInitializeAccessibilityNodeInfoForItem(RecyclerView.Recycler recycler,
RecyclerView.State state, View host, AccessibilityNodeInfoCompat info) {
@@ -15,9 +15,8 @@
*/
package com.android.launcher3.allapps;
import static androidx.constraintlayout.widget.ConstraintSet.MATCH_CONSTRAINT;
import static androidx.constraintlayout.widget.ConstraintSet.WRAP_CONTENT;
import static com.android.launcher3.config.FeatureFlags.ALL_APPS_GONE_VISIBILITY;
import static com.android.launcher3.config.FeatureFlags.ENABLE_ALL_APPS_RV_PREINFLATION;
import static com.android.launcher3.logger.LauncherAtom.ContainerInfo;
import static com.android.launcher3.logger.LauncherAtom.SearchResultContainer;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ALLAPPS_PERSONAL_SCROLLED_DOWN;
@@ -37,29 +36,22 @@ import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.core.util.Consumer;
import androidx.recyclerview.widget.RecyclerView;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.ExtendedEditText;
import com.android.launcher3.FastScrollRecyclerView;
import com.android.launcher3.Flags;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.views.ActivityContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
@@ -74,7 +66,6 @@ public class AllAppsRecyclerView extends FastScrollRecyclerView {
protected final int mNumAppsPerRow;
private final AllAppsFastScrollHelper mFastScrollHelper;
private int mCumulativeVerticalScroll;
private ConstraintLayout mLetterList;
public AlphabeticalAppsList<?> mApps;
@@ -122,11 +113,13 @@ public class AllAppsRecyclerView extends FastScrollRecyclerView {
// all apps.
int maxPoolSizeForAppIcons = grid.getMaxAllAppsRowCount()
* grid.numShownAllAppsColumns;
// If we set all apps' hidden visibility to GONE and enable pre-inflation, we want to
// preinflate one page of all apps icons plus [PREINFLATE_ICONS_ROW_COUNT] rows +
// [EXTRA_ICONS_COUNT]. Thus we need to bump the max pool size of app icons accordingly.
maxPoolSizeForAppIcons +=
PREINFLATE_ICONS_ROW_COUNT * grid.numShownAllAppsColumns + EXTRA_ICONS_COUNT;
if (ALL_APPS_GONE_VISIBILITY.get() && ENABLE_ALL_APPS_RV_PREINFLATION.get()) {
// If we set all apps' hidden visibility to GONE and enable pre-inflation, we want to
// preinflate one page of all apps icons plus [PREINFLATE_ICONS_ROW_COUNT] rows +
// [EXTRA_ICONS_COUNT]. Thus we need to bump the max pool size of app icons accordingly.
maxPoolSizeForAppIcons +=
PREINFLATE_ICONS_ROW_COUNT * grid.numShownAllAppsColumns + EXTRA_ICONS_COUNT;
}
if (hasWorkProfile) {
maxPoolSizeForAppIcons *= 2;
}
@@ -245,9 +238,6 @@ public class AllAppsRecyclerView extends FastScrollRecyclerView {
return;
}
if (Flags.letterFastScroller() && !mScrollbar.isDraggingThumb()) {
setLettersToScrollLayout(mApps.getFastScrollerSections());
}
// Only show the scrollbar if there is height to be scrolled
int availableScrollBarHeight = getAvailableScrollBarHeight();
int availableScrollHeight = getAvailableScrollHeight();
@@ -329,80 +319,6 @@ public class AllAppsRecyclerView extends FastScrollRecyclerView {
return false;
}
public void setLettersToScrollLayout(
List<AlphabeticalAppsList.FastScrollSectionInfo> fastScrollSections) {
if (fastScrollSections.isEmpty()) {
return;
}
if (mLetterList != null) {
mLetterList.removeAllViews();
}
Context context = getContext();
ActivityAllAppsContainerView<?> allAppsContainerView =
ActivityContext.lookupContext(context).getAppsView();
mLetterList = allAppsContainerView.getFastScrollerLetterList();
mLetterList.setPadding(0, getScrollBarTop(), 0, getScrollBarMarginBottom());
List<LetterListTextView> textViews = new ArrayList<>();
for (int i = 0; i < fastScrollSections.size(); i++) {
AlphabeticalAppsList.FastScrollSectionInfo sectionInfo = fastScrollSections.get(i);
LetterListTextView textView =
(LetterListTextView) LayoutInflater.from(context).inflate(
R.layout.fast_scroller_letter_list_text_view, mLetterList, false);
int viewId = View.generateViewId();
textView.apply(sectionInfo /* FastScrollSectionInfo */, viewId /* viewId */);
sectionInfo.setId(viewId);
if (i == fastScrollSections.size() - 1) {
// The last section info is just a duplicate so that user can scroll to the bottom.
textView.setVisibility(INVISIBLE);
}
textViews.add(textView);
mLetterList.addView(textView);
}
// Need to add an extra textview to be aligned.
LetterListTextView lastLetterListTextView = new LetterListTextView(context);
int currentId = View.generateViewId();
lastLetterListTextView.setId(currentId);
lastLetterListTextView.setVisibility(INVISIBLE);
textViews.add(lastLetterListTextView);
mLetterList.addView(lastLetterListTextView);
constraintTextViewsVertically(mLetterList, textViews);
mLetterList.setVisibility(VISIBLE);
// Set the alpha to 0 to avoid the letter list being shown when it shouldn't be.
mLetterList.setAlpha(0);
}
private void constraintTextViewsVertically(ConstraintLayout constraintLayout,
List<LetterListTextView> textViews) {
ConstraintSet chain = new ConstraintSet();
chain.clone(constraintLayout);
for (int i = 0; i < textViews.size(); i++) {
LetterListTextView currentView = textViews.get(i);
if (i == 0) {
chain.connect(currentView.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID,
ConstraintSet.TOP);
} else {
chain.connect(currentView.getId(), ConstraintSet.TOP, textViews.get(i-1).getId(),
ConstraintSet.BOTTOM);
}
chain.connect(currentView.getId(), ConstraintSet.START, constraintLayout.getId(),
ConstraintSet.START);
chain.connect(currentView.getId(), ConstraintSet.END, constraintLayout.getId(),
ConstraintSet.END);
}
int[] viewIds = textViews.stream().mapToInt(TextView::getId).toArray();
float[] weights = new float[textViews.size()];
Arrays.fill(weights,1); // fill with 1 for equal weights
chain.createVerticalChain(constraintLayout.getId(), ConstraintSet.TOP,
constraintLayout.getId(), ConstraintSet.BOTTOM, viewIds, weights,
ConstraintSet.CHAIN_SPREAD);
chain.applyTo(constraintLayout);
}
@Override
public ConstraintLayout getLetterList() {
return mLetterList;
}
private void logCumulativeVerticalScroll() {
ActivityContext context = ActivityContext.lookupContext(getContext());
StatsLogManager mgr = context.getStatsLogManager();
@@ -15,12 +15,13 @@
*/
package com.android.launcher3.allapps;
import static com.android.launcher3.config.FeatureFlags.ENABLE_ALL_APPS_RV_PREINFLATION;
import static com.android.launcher3.model.data.AppInfo.COMPONENT_KEY_COMPARATOR;
import static com.android.launcher3.model.data.AppInfo.EMPTY_ARRAY;
import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_SHOW_DOWNLOAD_PROGRESS_MASK;
import android.content.Context;
import android.os.UserHandle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
@@ -41,7 +42,6 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
@@ -54,7 +54,6 @@ import java.util.function.Predicate;
*/
public class AllAppsStore<T extends Context & ActivityContext> {
private static final String TAG = "AllAppsStore";
// Defer updates flag used to defer all apps updates to the next draw.
public static final int DEFER_UPDATES_NEXT_DRAW = 1 << 0;
// Defer updates flag used to defer all apps updates by a test's request.
@@ -111,14 +110,13 @@ public class AllAppsStore<T extends Context & ActivityContext> {
public void setApps(@Nullable AppInfo[] apps, int flags, Map<PackageUserKey, Integer> map,
boolean shouldPreinflate) {
mApps = apps == null ? EMPTY_ARRAY : apps;
Log.d(TAG, "setApps: apps.length=" + mApps.length);
mModelFlags = flags;
notifyUpdate();
mPackageUserKeytoUidMap = map;
// Preinflate all apps RV when apps has changed, which can happen after
// unlocking screen,
// rotating screen, or downloading/upgrading apps.
if (shouldPreinflate) {
if (shouldPreinflate && ENABLE_ALL_APPS_RV_PREINFLATION.get()) {
mAllAppsRecyclerViewPool.preInflateAllAppsViewHolders(mContext);
}
}
@@ -173,12 +171,10 @@ public class AllAppsStore<T extends Context & ActivityContext> {
public void enableDeferUpdates(int flag) {
mDeferUpdatesFlags |= flag;
Log.d(TAG, "enableDeferUpdates: " + flag + " mDeferUpdatesFlags=" + mDeferUpdatesFlags);
}
public void disableDeferUpdates(int flag) {
mDeferUpdatesFlags &= ~flag;
Log.d(TAG, "disableDeferUpdates: " + flag + " mDeferUpdatesFlags=" + mDeferUpdatesFlags);
if (mDeferUpdatesFlags == 0 && mUpdatePending) {
notifyUpdate();
mUpdatePending = false;
@@ -187,9 +183,6 @@ public class AllAppsStore<T extends Context & ActivityContext> {
public void disableDeferUpdatesSilently(int flag) {
mDeferUpdatesFlags &= ~flag;
Log.d(TAG, "disableDeferUpdatesSilently: " + flag
+ " mDeferUpdatesFlags=" + mDeferUpdatesFlags);
}
public int getDeferUpdatesFlags() {
@@ -198,11 +191,9 @@ public class AllAppsStore<T extends Context & ActivityContext> {
private void notifyUpdate() {
if (mDeferUpdatesFlags != 0) {
Log.d(TAG, "notifyUpdate: deferring update");
mUpdatePending = true;
return;
}
Log.d(TAG, "notifyUpdate: notifying listeners");
for (OnUpdateListener listener : mUpdateListeners) {
listener.onAppsUpdated();
}
@@ -251,7 +242,11 @@ public class AllAppsStore<T extends Context & ActivityContext> {
public void updateProgressBar(AppInfo app) {
updateAllIcons((child) -> {
if (child.getTag() == app) {
child.applyFromApplicationInfo(app);
if ((app.runtimeStatusFlags & FLAG_SHOW_DOWNLOAD_PROGRESS_MASK) == 0) {
child.applyFromApplicationInfo(app);
} else {
child.applyProgressLevel();
}
}
});
}
@@ -280,15 +275,8 @@ public class AllAppsStore<T extends Context & ActivityContext> {
public void dump(String prefix, PrintWriter writer) {
writer.println(prefix + "\tAllAppsStore Apps[] size: " + mApps.length);
for (int i = 0; i < mApps.length; i++) {
writer.println(String.format(Locale.getDefault(),
"%s\tPackage index, name, class, description, bitmap flag: %d/%s:%s, %s, %s+%s",
prefix,
i,
mApps[i].componentName.getPackageName(),
mApps[i].componentName.getClassName(),
mApps[i].contentDescription,
Integer.toBinaryString(mApps[i].bitmap.flags),
Integer.toBinaryString(mApps[i].bitmap.creationFlags)));
writer.println(String.format("%s\tPackage index and name: %d/%s", prefix, i,
mApps[i].componentName.getPackageName()));
}
}
}
@@ -16,6 +16,7 @@
package com.android.launcher3.allapps;
import static com.android.app.animation.Interpolators.DECELERATE_1_7;
import static com.android.app.animation.Interpolators.INSTANT;
import static com.android.app.animation.Interpolators.LINEAR;
import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
@@ -27,6 +28,7 @@ import static com.android.launcher3.UtilitiesKt.CLIP_CHILDREN_FALSE_MODIFIER;
import static com.android.launcher3.UtilitiesKt.modifyAttributesOnViewTree;
import static com.android.launcher3.UtilitiesKt.restoreAttributesOnViewTree;
import static com.android.launcher3.anim.PropertySetter.NO_ANIM_PROPERTY_SETTER;
import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_BOTTOM_SHEET_FADE;
import static com.android.launcher3.states.StateAnimationConfig.ANIM_ALL_APPS_FADE;
import static com.android.launcher3.states.StateAnimationConfig.ANIM_VERTICAL_PROGRESS;
import static com.android.launcher3.util.SystemUiController.FLAG_DARK_NAV;
@@ -34,8 +36,8 @@ import static com.android.launcher3.util.SystemUiController.FLAG_LIGHT_NAV;
import static com.android.launcher3.util.SystemUiController.UI_STATE_ALL_APPS;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.util.FloatProperty;
import android.view.HapticFeedbackConstants;
import android.view.View;
@@ -44,28 +46,28 @@ import android.view.animation.Interpolator;
import androidx.annotation.FloatRange;
import androidx.annotation.Nullable;
import com.android.app.animation.Interpolators;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
import com.android.launcher3.Flags;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimatedFloat;
import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.anim.PropertySetter;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.statemanager.StateManager.StateHandler;
import com.android.launcher3.states.StateAnimationConfig;
import com.android.launcher3.touch.AllAppsSwipeController;
import com.android.launcher3.util.MSDLPlayerWrapper;
import com.android.launcher3.util.MultiPropertyFactory;
import com.android.launcher3.util.MultiPropertyFactory.MultiProperty;
import com.android.launcher3.util.MultiValueAlpha;
import com.android.launcher3.util.ScrollableLayoutManager;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.VibratorWrapper;
import com.android.launcher3.views.ScrimView;
import com.google.android.msdl.data.model.MSDLToken;
/**
* Handles AllApps view transition.
* 1) Slides all apps view using direct manipulation
@@ -73,88 +75,90 @@ import com.google.android.msdl.data.model.MSDLToken;
* <p/>
* Algorithm:
* If release velocity > THRES1, snap according to the direction of movement.
* If release velocity < THRES1, snap according to either top or bottom depending on whether it's
* If release velocity < THRES1, snap according to either top or bottom
* depending on whether it's
* closer to top or closer to the page indicator.
*/
public class AllAppsTransitionController
implements StateHandler<LauncherState>, OnDeviceProfileChangeListener {
// This constant should match the second derivative of the animator interpolator.
// This constant should match the second derivative of the animator
// interpolator.
public static final float INTERP_COEFF = 1.7f;
public static final int REVERT_SWIPE_ALL_APPS_TO_HOME_ANIMATION_DURATION_MS = 200;
private static final float NAV_BAR_COLOR_FORCE_UPDATE_THRESHOLD = 0.1f;
private static final float SWIPE_DRAG_COMMIT_THRESHOLD =
1 - AllAppsSwipeController.ALL_APPS_STATE_TRANSITION_MANUAL;
private static final float SWIPE_DRAG_COMMIT_THRESHOLD = 1
- AllAppsSwipeController.ALL_APPS_STATE_TRANSITION_MANUAL;
public static final FloatProperty<AllAppsTransitionController> ALL_APPS_PROGRESS =
new FloatProperty<AllAppsTransitionController>("allAppsProgress") {
public static final FloatProperty<AllAppsTransitionController> ALL_APPS_PROGRESS = new FloatProperty<AllAppsTransitionController>(
"allAppsProgress") {
@Override
public Float get(AllAppsTransitionController controller) {
return controller.mProgress;
}
@Override
public Float get(AllAppsTransitionController controller) {
return controller.mProgress;
}
@Override
public void setValue(AllAppsTransitionController controller, float progress) {
controller.setProgress(progress);
}
};
@Override
public void setValue(AllAppsTransitionController controller, float progress) {
controller.setProgress(progress);
}
};
private static final float ALL_APPS_PULL_BACK_TRANSLATION_DEFAULT = 0f;
public static final FloatProperty<AllAppsTransitionController> ALL_APPS_PULL_BACK_TRANSLATION =
new FloatProperty<AllAppsTransitionController>("allAppsPullBackTranslation") {
public static final FloatProperty<AllAppsTransitionController> ALL_APPS_PULL_BACK_TRANSLATION = new FloatProperty<AllAppsTransitionController>(
"allAppsPullBackTranslation") {
@Override
public Float get(AllAppsTransitionController controller) {
if (controller.mShouldShowAllAppsOnSheet) {
return controller.mAppsView.getActiveRecyclerView().getTranslationY();
} else {
return controller.getAppsViewPullbackTranslationY().getValue();
}
}
@Override
public Float get(AllAppsTransitionController controller) {
if (controller.mIsTablet) {
return controller.mAppsView.getActiveRecyclerView().getTranslationY();
} else {
return controller.getAppsViewPullbackTranslationY().getValue();
}
}
@Override
public void setValue(AllAppsTransitionController controller, float translation) {
if (controller.mShouldShowAllAppsOnSheet) {
controller.mAppsView.getActiveRecyclerView().setTranslationY(translation);
controller.getAppsViewPullbackTranslationY().setValue(
ALL_APPS_PULL_BACK_TRANSLATION_DEFAULT);
} else {
controller.getAppsViewPullbackTranslationY().setValue(translation);
controller.mAppsView.getActiveRecyclerView().setTranslationY(
ALL_APPS_PULL_BACK_TRANSLATION_DEFAULT);
}
}
};
@Override
public void setValue(AllAppsTransitionController controller, float translation) {
if (controller.mIsTablet) {
controller.mAppsView.getActiveRecyclerView().setTranslationY(translation);
controller.getAppsViewPullbackTranslationY().setValue(
ALL_APPS_PULL_BACK_TRANSLATION_DEFAULT);
} else {
controller.getAppsViewPullbackTranslationY().setValue(translation);
controller.mAppsView.getActiveRecyclerView().setTranslationY(
ALL_APPS_PULL_BACK_TRANSLATION_DEFAULT);
}
}
};
private static final float ALL_APPS_PULL_BACK_ALPHA_DEFAULT = 1f;
public static final FloatProperty<AllAppsTransitionController> ALL_APPS_PULL_BACK_ALPHA =
new FloatProperty<AllAppsTransitionController>("allAppsPullBackAlpha") {
public static final FloatProperty<AllAppsTransitionController> ALL_APPS_PULL_BACK_ALPHA = new FloatProperty<AllAppsTransitionController>(
"allAppsPullBackAlpha") {
@Override
public Float get(AllAppsTransitionController controller) {
if (controller.mShouldShowAllAppsOnSheet) {
return controller.mAppsView.getActiveRecyclerView().getAlpha();
} else {
return controller.getAppsViewPullbackAlpha().getValue();
}
}
@Override
public Float get(AllAppsTransitionController controller) {
if (controller.mIsTablet) {
return controller.mAppsView.getActiveRecyclerView().getAlpha();
} else {
return controller.getAppsViewPullbackAlpha().getValue();
}
}
@Override
public void setValue(AllAppsTransitionController controller, float alpha) {
if (controller.mShouldShowAllAppsOnSheet) {
controller.mAppsView.getActiveRecyclerView().setAlpha(alpha);
controller.getAppsViewPullbackAlpha().setValue(
ALL_APPS_PULL_BACK_ALPHA_DEFAULT);
} else {
controller.getAppsViewPullbackAlpha().setValue(alpha);
controller.mAppsView.getActiveRecyclerView().setAlpha(
ALL_APPS_PULL_BACK_ALPHA_DEFAULT);
}
}
};
@Override
public void setValue(AllAppsTransitionController controller, float alpha) {
if (controller.mIsTablet) {
controller.mAppsView.getActiveRecyclerView().setAlpha(alpha);
controller.getAppsViewPullbackAlpha().setValue(
ALL_APPS_PULL_BACK_ALPHA_DEFAULT);
} else {
controller.getAppsViewPullbackAlpha().setValue(alpha);
controller.mAppsView.getActiveRecyclerView().setAlpha(
ALL_APPS_PULL_BACK_ALPHA_DEFAULT);
}
}
};
private static final int INDEX_APPS_VIEW_PROGRESS = 0;
private static final int INDEX_APPS_VIEW_PULLBACK = 1;
@@ -166,41 +170,45 @@ public class AllAppsTransitionController
private final AnimatedFloat mAllAppScale = new AnimatedFloat(this::onScaleProgressChanged);
private final int mNavScrimFlag;
@Nullable private Animator.AnimatorListener mAllAppsSearchBackAnimationListener;
@Nullable
private Animator.AnimatorListener mAllAppsSearchBackAnimationListener;
private boolean mIsVerticalLayout;
private boolean mShouldShowAllAppsOnSheet;
// Animation in this class is controlled by a single variable {@link mProgress}.
// Visually, it represents top y coordinate of the all apps container if multiplied with
// Visually, it represents top y coordinate of the all apps container if
// multiplied with
// {@link mShiftRange}.
// When {@link mProgress} is 0, all apps container is pulled up.
// When {@link mProgress} is 1, all apps container is pulled down.
private float mShiftRange; // changes depending on the orientation
private float mProgress; // [0, 1], mShiftRange * mProgress = shiftCurrent
private float mShiftRange; // changes depending on the orientation
private float mProgress; // [0, 1], mShiftRange * mProgress = shiftCurrent
private ScrimView mScrimView;
private MultiValueAlpha mAppsViewAlpha;
private MultiPropertyFactory<View> mAppsViewTranslationY;
private boolean mIsTablet;
private boolean mHasScaleEffect;
private final MSDLPlayerWrapper mMSDLPlayerWrapper;
private final VibratorWrapper mVibratorWrapper;
public AllAppsTransitionController(Launcher l) {
mLauncher = l;
DeviceProfile dp = mLauncher.getDeviceProfile();
mProgress = 1f;
mIsVerticalLayout = dp.isVerticalBarLayout();
mShouldShowAllAppsOnSheet = dp.shouldShowAllAppsOnSheet();
mIsTablet = dp.isTablet;
mNavScrimFlag = Themes.getAttrBoolean(l, R.attr.isMainColorDark)
? FLAG_DARK_NAV : FLAG_LIGHT_NAV;
? FLAG_DARK_NAV
: FLAG_LIGHT_NAV;
setShiftRange(dp.allAppsShiftRange);
mAllAppScale.value = 1;
mLauncher.addOnDeviceProfileChangeListener(this);
mMSDLPlayerWrapper = MSDLPlayerWrapper.INSTANCE.get(mLauncher.getApplicationContext());
mVibratorWrapper = VibratorWrapper.INSTANCE.get(mLauncher.getApplicationContext());
}
public float getShiftRange() {
@@ -217,21 +225,22 @@ public class AllAppsTransitionController
mLauncher.getWorkspace().getPageIndicator().setTranslationY(0);
}
mShouldShowAllAppsOnSheet = dp.shouldShowAllAppsOnSheet();
mIsTablet = dp.isTablet;
}
/**
* Note this method should not be called outside this class. This is public because it is used
* Note this method should not be called outside this class. This is public
* because it is used
* in xml-based animations which also handle updating the appropriate UI.
*
* @param progress value between 0 and 1, 0 shows all apps and 1 shows workspace
* @see #setState(LauncherState)
* @see #setStateWithAnimation(LauncherState, StateAnimationConfig, PendingAnimation)
* @see #setStateWithAnimation(LauncherState, StateAnimationConfig,
* PendingAnimation)
*/
public void setProgress(float progress) {
mProgress = progress;
boolean fromBackground =
mLauncher.getStateManager().getCurrentStableState() == BACKGROUND_APP;
boolean fromBackground = mLauncher.getStateManager().getCurrentStableState() == BACKGROUND_APP;
// Allow apps panel to shift the full screen if coming from another app.
float shiftRange = fromBackground ? mLauncher.getDeviceProfile().heightPx : mShiftRange;
getAppsViewProgressTranslationY().setValue(mProgress * shiftRange);
@@ -264,7 +273,8 @@ public class AllAppsTransitionController
}
/**
* Sets the vertical transition progress to {@param state} and updates all the dependent UI
* Sets the vertical transition progress to {@param state} and updates all the
* dependent UI
* accordingly.
*/
@Override
@@ -280,9 +290,10 @@ public class AllAppsTransitionController
return;
}
float deceleratedProgress = Interpolators.BACK_GESTURE.getInterpolation(backProgress);
float scaleProgress = ScrollableLayoutManager.PREDICTIVE_BACK_MIN_SCALE
+ (1 - ScrollableLayoutManager.PREDICTIVE_BACK_MIN_SCALE)
* (1 - backProgress);
* (1 - deceleratedProgress);
mAllAppScale.updateValue(scaleProgress);
}
@@ -290,16 +301,18 @@ public class AllAppsTransitionController
private void onScaleProgressChanged() {
final float scaleProgress = mAllAppScale.value;
SCALE_PROPERTY.set(mLauncher.getAppsView(), scaleProgress);
if (!mLauncher.getAppsView().isSearching()
|| !mLauncher.getDeviceProfile().shouldShowAllAppsOnSheet()) {
if (!mLauncher.getAppsView().isSearching() || !mLauncher.getDeviceProfile().isTablet) {
mLauncher.getScrimView().setScrimHeaderScale(scaleProgress);
}
AllAppsRecyclerView rv = mLauncher.getAppsView().getActiveRecyclerView();
// Disable view clipping from all apps' RecyclerView up to all apps view during scale
// animation, and vice versa. The goal is to display extra roll(s) app icons (rendered in
// {@link AppsGridLayoutManager#calculateExtraLayoutSpace}) during scale animation.
// Disable view clipping from all apps' RecyclerView up to all apps view during
// scale
// animation, and vice versa. The goal is to display extra roll(s) app icons
// (rendered in
// {@link AppsGridLayoutManager#calculateExtraLayoutSpace}) during scale
// animation.
boolean hasScaleEffect = scaleProgress < 1f;
if (hasScaleEffect != mHasScaleEffect) {
mHasScaleEffect = hasScaleEffect;
@@ -313,13 +326,17 @@ public class AllAppsTransitionController
}
}
/** Set {@link Animator.AnimatorListener} for scaling all apps scale to 1 animation. */
/**
* Set {@link Animator.AnimatorListener} for scaling all apps scale to 1
* animation.
*/
public void setAllAppsSearchBackAnimationListener(Animator.AnimatorListener listener) {
mAllAppsSearchBackAnimationListener = listener;
}
/**
* Animate all apps view to 1f scale. This is called when backing (exiting) from all apps
* Animate all apps view to 1f scale. This is called when backing (exiting) from
* all apps
* search view to all apps view.
*/
public void animateAllAppsToNoScale() {
@@ -335,12 +352,16 @@ public class AllAppsTransitionController
}
/**
* Creates an animation which updates the vertical transition progress and updates all the
* Creates an animation which updates the vertical transition progress and
* updates all the
* dependent UI using various animation events
*
* This method also dictates where along the progress the haptics should be played. As the user
* scrolls up from workspace or down from AllApps, a drag haptic is being played until the
* commit point where it plays a commit haptic. Where we play the haptics differs when going
* This method also dictates where along the progress the haptics should be
* played. As the user
* scrolls up from workspace or down from AllApps, a drag haptic is being played
* until the
* commit point where it plays a commit haptic. Where we play the haptics
* differs when going
* from workspace -> allApps and vice versa.
*/
@Override
@@ -356,6 +377,22 @@ public class AllAppsTransitionController
});
}
if (FeatureFlags.ENABLE_PREMIUM_HAPTICS_ALL_APPS.get() && config.isUserControlled()
&& Utilities.ATLEAST_S) {
if (toState == ALL_APPS) {
builder.addOnFrameListener(
new VibrationAnimatorUpdateListener(this, mVibratorWrapper,
SWIPE_DRAG_COMMIT_THRESHOLD, 1));
} else {
builder.addOnFrameListener(
new VibrationAnimatorUpdateListener(this, mVibratorWrapper,
0, SWIPE_DRAG_COMMIT_THRESHOLD));
}
builder.addEndListener((unused) -> {
mVibratorWrapper.cancelVibrate();
});
}
float targetProgress = toState.getVerticalProgress(mLauncher);
if (Float.compare(mProgress, targetProgress) == 0) {
setAlphas(toState, config, builder);
@@ -367,28 +404,15 @@ public class AllAppsTransitionController
Interpolator verticalProgressInterpolator = config.getInterpolator(ANIM_VERTICAL_PROGRESS,
config.isUserControlled() ? LINEAR : DECELERATE_1_7);
Animator anim = createSpringAnimation(mProgress, targetProgress);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(Animator animation) {
setProgress(targetProgress);
}
});
anim.setInterpolator(verticalProgressInterpolator);
builder.add(anim);
setAlphas(toState, config, builder);
// This controls both haptics for tapping on QSB and going to all apps.
if (ALL_APPS.equals(toState) && mLauncher.isInState(NORMAL)) {
if (Flags.msdlFeedback()) {
if (config.isUserControlled()) {
mMSDLPlayerWrapper.playToken(MSDLToken.SWIPE_THRESHOLD_INDICATOR);
} else {
mMSDLPlayerWrapper.playToken(MSDLToken.TAP_HIGH_EMPHASIS);
}
} else {
mLauncher.getAppsView().performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
}
if (ALL_APPS.equals(toState) && mLauncher.isInState(NORMAL) &&
!FeatureFlags.ENABLE_PREMIUM_HAPTICS_ALL_APPS.get()) {
mLauncher.getAppsView().performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
}
}
@@ -409,6 +433,10 @@ public class AllAppsTransitionController
setter.setFloat(getAppsViewPullbackAlpha(), MultiPropertyFactory.MULTI_PROPERTY_VALUE,
hasAllAppsContent ? 1 : 0, allAppsFade);
setter.setFloat(mLauncher.getAppsView(),
ActivityAllAppsContainerView.BOTTOM_SHEET_ALPHA, hasAllAppsContent ? 1 : 0,
config.getInterpolator(ANIM_ALL_APPS_BOTTOM_SHEET_FADE, INSTANT));
boolean shouldProtectHeader = !config.hasAnimationFlag(StateAnimationConfig.SKIP_SCRIM)
&& (ALL_APPS == state || mLauncher.getStateManager().getState() == ALL_APPS);
mScrimView.setDrawingController(shouldProtectHeader ? mAppsView : null);
@@ -422,7 +450,8 @@ public class AllAppsTransitionController
mAppsView = appsView;
mAppsView.setScrimView(scrimView);
mAppsViewAlpha = new MultiValueAlpha(mAppsView, APPS_VIEW_INDEX_COUNT, View.GONE);
mAppsViewAlpha = new MultiValueAlpha(mAppsView, APPS_VIEW_INDEX_COUNT,
FeatureFlags.ALL_APPS_GONE_VISIBILITY.get() ? View.GONE : View.INVISIBLE);
mAppsViewAlpha.setUpdateVisibility(true);
mAppsViewTranslationY = new MultiPropertyFactory<>(
mAppsView, VIEW_TRANSLATE_Y, APPS_VIEW_INDEX_COUNT, Float::sum);
@@ -434,4 +463,49 @@ public class AllAppsTransitionController
public void setShiftRange(float shiftRange) {
mShiftRange = shiftRange;
}
/**
* This VibrationAnimatorUpdateListener class takes in four parameters, a
* controller, start
* threshold, end threshold, and a Vibrator wrapper. We use the progress given
* by the controller
* as it gives an accurate progress that dictates where the vibrator should
* vibrate.
* Note: once the user begins a gesture and does the commit haptic, there should
* not be anymore
* haptics played for that gesture.
*/
private static class VibrationAnimatorUpdateListener implements
ValueAnimator.AnimatorUpdateListener {
private final VibratorWrapper mVibratorWrapper;
private final AllAppsTransitionController mController;
private final float mStartThreshold;
private final float mEndThreshold;
private boolean mHasCommitted;
VibrationAnimatorUpdateListener(AllAppsTransitionController controller,
VibratorWrapper vibratorWrapper, float startThreshold,
float endThreshold) {
mController = controller;
mVibratorWrapper = vibratorWrapper;
mStartThreshold = startThreshold;
mEndThreshold = endThreshold;
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (mHasCommitted) {
return;
}
float currentProgress = AllAppsTransitionController.ALL_APPS_PROGRESS.get(mController);
if (currentProgress > mStartThreshold && currentProgress < mEndThreshold) {
mVibratorWrapper.vibrateForDragTexture();
} else if (!(currentProgress == 0 || currentProgress == 1)) {
// This check guards against committing at the location of the start of the
// gesture
mVibratorWrapper.vibrateForDragCommit();
mHasCommitted = true;
}
}
}
}
@@ -17,15 +17,9 @@
*/
package com.android.launcher3.allapps;
import static android.multiuser.Flags.enableMovingContentIntoPrivateSpace;
import static com.android.launcher3.Utilities.ATLEAST_BAKLAVA;
import static com.android.launcher3.allapps.BaseAllAppsAdapter.VIEW_TYPE_BOTTOM_VIEW_TO_SCROLL_TO;
import static com.android.launcher3.allapps.BaseAllAppsAdapter.VIEW_TYPE_MASK_PRIVATE_SPACE_HEADER;
import static com.android.launcher3.allapps.SectionDecorationInfo.ROUND_BOTTOM_LEFT;
import static com.android.launcher3.allapps.SectionDecorationInfo.ROUND_BOTTOM_RIGHT;
import static com.android.launcher3.allapps.SectionDecorationInfo.ROUND_NOTHING;
import static com.android.launcher3.icons.BitmapInfo.FLAG_NO_BADGE;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_PRIVATE_SPACE_PREINSTALLED_APPS_COUNT;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_PRIVATE_SPACE_USER_INSTALLED_APPS_COUNT;
@@ -33,7 +27,6 @@ import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
@@ -47,7 +40,6 @@ import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.LabelComparator;
import com.android.launcher3.views.ActivityContext;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@@ -67,7 +59,6 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
AllAppsStore.OnUpdateListener {
public static final String TAG = "AlphabeticalAppsList";
public static final String PRIVATE_SPACE_PACKAGE = "com.android.privatespace";
private final WorkProfileManager mWorkProviderManager;
@@ -83,17 +74,11 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
public final CharSequence sectionName;
// The item position
public final int position;
// The view id associated with this section
public int id = -1;
public FastScrollSectionInfo(CharSequence sectionName, int position) {
this.sectionName = sectionName;
this.position = position;
}
public void setId(int id) {
this.id = id;
}
}
private final T mActivityContext;
@@ -115,7 +100,6 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
// The of ordered component names as a result of a search query
private final ArrayList<AdapterItem> mSearchResults = new ArrayList<>();
private final SpannableString mPrivateProfileAppScrollerBadge;
private final SpannableString mPrivateProfileDividerBadge;
private BaseAllAppsAdapter<T> mAdapter;
private AppInfoComparator mAppNameComparator;
private int mNumAppsPerRowAllApps;
@@ -134,14 +118,9 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
mAllAppsStore.addUpdateListener(this);
}
mPrivateProfileAppScrollerBadge = new SpannableString(" ");
mPrivateProfileAppScrollerBadge.setSpan(new ImageSpan(context, Flags.letterFastScroller()
? R.drawable.ic_private_profile_letter_list_fast_scroller_badge :
mPrivateProfileAppScrollerBadge.setSpan(new ImageSpan(context,
R.drawable.ic_private_profile_app_scroller_badge, ImageSpan.ALIGN_CENTER),
0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPrivateProfileDividerBadge = new SpannableString(" ");
mPrivateProfileDividerBadge.setSpan(new ImageSpan(context,
R.drawable.ic_private_profile_divider_badge, ImageSpan.ALIGN_CENTER),
0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
/** Set the number of apps per row when device profile changes. */
@@ -297,7 +276,6 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
List<AdapterItem> oldItems = new ArrayList<>(mAdapterItems);
// Prepare to update the list of sections, filtered apps, etc.
mFastScrollerSections.clear();
Log.d(TAG, "Clearing FastScrollerSections.");
mAdapterItems.clear();
mAccessibilityResultsCount = 0;
@@ -319,22 +297,12 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
mFastScrollerSections.add(new FastScrollSectionInfo(
mActivityContext.getResources().getString(
R.string.work_profile_edu_section), 0));
Log.d(TAG, "Adding FastScrollSection for work edu card.");
}
position = addAppsWithSections(mApps, position);
}
if (Flags.enablePrivateSpace()) {
position = addPrivateSpaceItems(position);
}
if (!mFastScrollerSections.isEmpty()) {
// After all the adapterItems are added, add a view to the bottom so that user can
// scroll all the way down.
mAdapterItems.add(new AdapterItem(VIEW_TYPE_BOTTOM_VIEW_TO_SCROLL_TO));
mFastScrollerSections.add(new FastScrollSectionInfo(
mFastScrollerSections.get(mFastScrollerSections.size() - 1).sectionName,
position++));
Log.d(TAG, "Adding FastScrollSection duplicate to scroll to the bottom.");
}
}
mAccessibilityResultsCount = (int) mAdapterItems.stream()
.filter(AdapterItem::isCountedForAccessibility).count();
@@ -378,7 +346,6 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
&& !mPrivateApps.isEmpty()) {
// Always add PS Header if Space is present and visible.
position = mPrivateProviderManager.addPrivateSpaceHeader(mAdapterItems);
Log.d(TAG, "Adding FastScrollSection for Private Space header. ");
mFastScrollerSections.add(new FastScrollSectionInfo(
mPrivateProfileAppScrollerBadge, position));
int privateSpaceState = mPrivateProviderManager.getCurrentState();
@@ -396,36 +363,12 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
}
private int addPrivateSpaceApps(int position) {
/* LC-Note: Fix for missing flags and account for NCDFE */
boolean enableMovingContentIntoPrivateSpace = false;
if (ATLEAST_BAKLAVA) {
try {
/* LC-Note: Some devices (Android 16 QPR) doesn't have or expose this flag to user.
* Let's assume no, because (the flags) enableMovingContentIntoPrivateSpace seems
* to be False for R8 by default.
* */
enableMovingContentIntoPrivateSpace = enableMovingContentIntoPrivateSpace();
} catch (NoClassDefFoundError e) {
/* LC-Ignored: we already set it false by default. */
}
}
// Add Install Apps Button first.
if (!ATLEAST_BAKLAVA) {
// LC: Baklava added a new behavior for the PS app button. (enableMovingContentIntoPrivateSpace)
if (Flags.privateSpaceAppInstallerButton() && !enableMovingContentIntoPrivateSpace) {
mPrivateProviderManager.addPrivateSpaceInstallAppButton(mAdapterItems);
position++;
}
} else {
if (Flags.privateSpaceAppInstallerButton()) {
mPrivateProviderManager.addPrivateSpaceInstallAppButton(mAdapterItems);
position++;
}
if (Flags.privateSpaceAppInstallerButton()) {
mPrivateProviderManager.addPrivateSpaceInstallAppButton(mAdapterItems);
position++;
}
// Split of private space apps into user-installed and system apps.
Map<Boolean, List<AppInfo>> split = mPrivateApps.stream()
.collect(Collectors.partitioningBy(mPrivateProviderManager
@@ -449,40 +392,10 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
// Add system apps separator.
if (Flags.privateSpaceSysAppsSeparation()) {
position = mPrivateProviderManager.addSystemAppsDivider(mAdapterItems);
if (Flags.letterFastScroller()) {
FastScrollSectionInfo sectionInfo =
new FastScrollSectionInfo(mPrivateProfileDividerBadge, position);
mFastScrollerSections.add(sectionInfo);
}
}
// Add system apps.
position = addAppsWithSections(split.get(false), position);
if (enableMovingContentIntoPrivateSpace) {
// Look for the private space app via package and move it after header.
int headerIndex = -1;
int privateSpaceAppIndex = -1;
for (int i = 0; i < mAdapterItems.size(); i++) {
BaseAllAppsAdapter.AdapterItem currentItem = mAdapterItems.get(i);
if (currentItem.viewType == VIEW_TYPE_MASK_PRIVATE_SPACE_HEADER) {
headerIndex = i;
}
if (currentItem.itemInfo != null && Objects.equals(
currentItem.itemInfo.getTargetPackage(), PRIVATE_SPACE_PACKAGE)) {
currentItem.itemInfo.bitmap = mPrivateProviderManager.preparePSBitmapInfo();
currentItem.itemInfo.bitmap.creationFlags |= FLAG_NO_BADGE;
currentItem.itemInfo.contentDescription =
mPrivateProviderManager.getPsAppContentDesc();
privateSpaceAppIndex = i;
}
}
if (headerIndex != -1 && privateSpaceAppIndex != -1) {
BaseAllAppsAdapter.AdapterItem movedItem =
mAdapterItems.remove(privateSpaceAppIndex);
// Move the icon after the header.
mAdapterItems.add(headerIndex + 1, movedItem);
}
}
return position;
}
@@ -494,14 +407,14 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
hasPrivateApps = appList.stream().
allMatch(mPrivateProviderManager.getItemInfoMatcher());
}
Log.d(TAG, "Adding apps with sections. HasPrivateApps: " + hasPrivateApps);
for (int i = 0; i < appList.size(); i++) {
AppInfo info = appList.get(i);
// Apply decorator to private apps.
if (hasPrivateApps) {
mAdapterItems.add(AdapterItem.asAppWithDecorationInfo(info,
new SectionDecorationInfo(mActivityContext,
getRoundRegions(i, appList.size()), true /* decorateTogether */)));
new SectionDecorationInfo(mActivityContext.getApplicationContext(),
getRoundRegions(i, appList.size()),
true /* decorateTogether */)));
} else {
mAdapterItems.add(AdapterItem.asApp(info));
}
@@ -509,14 +422,9 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
String sectionName = info.sectionName;
// Create a new section if the section names do not match
if (!sectionName.equals(lastSectionName)) {
Log.d(TAG, "addAppsWithSections: adding sectionName: " + sectionName
+ " with appInfoTitle: " + info.title);
lastSectionName = sectionName;
boolean usePrivateAppScrollerBadge = !Flags.letterFastScroller() && hasPrivateApps;
FastScrollSectionInfo sectionInfo = new FastScrollSectionInfo(
usePrivateAppScrollerBadge ?
mPrivateProfileAppScrollerBadge : sectionName, position);
mFastScrollerSections.add(sectionInfo);
mFastScrollerSections.add(new FastScrollSectionInfo(hasPrivateApps ?
mPrivateProfileAppScrollerBadge : sectionName, position));
}
position++;
}
@@ -578,13 +486,6 @@ public class AlphabeticalAppsList<T extends Context & ActivityContext> implement
return mPrivateProviderManager;
}
public void dump(String prefix, PrintWriter writer) {
writer.println(prefix + "SectionInfo[] size: " + mFastScrollerSections.size());
for (int i = 0; i < mFastScrollerSections.size(); i++) {
writer.println("\tFastScrollSection: " + mFastScrollerSections.get(i).sectionName);
}
}
private static class MyDiffCallback extends DiffUtil.Callback {
private final List<AdapterItem> mOldList;
@@ -26,7 +26,6 @@ import static com.android.launcher3.allapps.UserProfileManager.STATE_DISABLED;
import static com.android.launcher3.allapps.UserProfileManager.STATE_ENABLED;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
@@ -41,11 +40,15 @@ import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.Flags;
import com.android.launcher3.LauncherPrefs;
import com.android.launcher3.R;
import com.android.launcher3.allapps.search.SearchAdapterProvider;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ActivityContext;
/**
@@ -62,27 +65,28 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
public static final int VIEW_TYPE_ICON = 1 << 1;
// The message shown when there are no filtered results
public static final int VIEW_TYPE_EMPTY_SEARCH = 1 << 2;
// A divider that separates the apps list and the search market button
public static final int VIEW_TYPE_ALL_APPS_DIVIDER = 1 << 3;
public static final int VIEW_TYPE_WORK_EDU_CARD = 1 << 4;
// The message to continue to a market search when there are no filtered results
public static final int VIEW_TYPE_SEARCH_MARKET = 1 << 3;
// A divider that separates the apps list and the search market button
public static final int VIEW_TYPE_ALL_APPS_DIVIDER = 1 << 4;
public static final int VIEW_TYPE_WORK_DISABLED_CARD = 1 << 5;
public static final int VIEW_TYPE_PRIVATE_SPACE_HEADER = 1 << 6;
public static final int VIEW_TYPE_PRIVATE_SPACE_SYS_APPS_DIVIDER = 1 << 7;
public static final int VIEW_TYPE_BOTTOM_VIEW_TO_SCROLL_TO = 1 << 8;
public static final int NEXT_ID = 9;
public static final int VIEW_TYPE_WORK_EDU_CARD = 1 << 8;
// LC-Feature: Folder support in All Apps, can be any ID
public static final int VIEW_TYPE_FOLDER = 1 << 10;
public static final int VIEW_TYPE_FOLDER = 1 << 9;
public static final int NEXT_ID = 10;
// Common view type masks
public static final int VIEW_TYPE_MASK_DIVIDER = VIEW_TYPE_ALL_APPS_DIVIDER;
public static final int VIEW_TYPE_MASK_ICON = VIEW_TYPE_FOLDER | VIEW_TYPE_ICON;
public static final int VIEW_TYPE_MASK_ICON = VIEW_TYPE_ICON | VIEW_TYPE_FOLDER;
public static final int VIEW_TYPE_MASK_PRIVATE_SPACE_HEADER =
VIEW_TYPE_PRIVATE_SPACE_HEADER;
public static final int VIEW_TYPE_MASK_PRIVATE_SPACE_SYS_APPS_DIVIDER =
VIEW_TYPE_PRIVATE_SPACE_SYS_APPS_DIVIDER;
public static final int VIEW_TYPE_MASK_PRIVATE_SPACE_HEADER = VIEW_TYPE_PRIVATE_SPACE_HEADER;
public static final int VIEW_TYPE_MASK_PRIVATE_SPACE_SYS_APPS_DIVIDER = VIEW_TYPE_PRIVATE_SPACE_SYS_APPS_DIVIDER;
protected final SearchAdapterProvider<?> mAdapterProvider;
@@ -96,32 +100,36 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
}
}
/** Sets the number of apps to be displayed in one row of the all apps screen. */
/**
* Sets the number of apps to be displayed in one row of the all apps screen.
*/
public abstract void setAppsPerRow(int appsPerRow);
/**
* Info about a particular adapter item (can be either section or app)
*/
public static class AdapterItem {
/** Common properties */
// The type of this item
public final int viewType;
public int viewType;
// The row that this item shows up on
public int rowIndex;
// The index of this app in the row
public int rowAppIndex;
// The associated ItemInfoWithIcon for the item
public AppInfo itemInfo = null;
public AppInfo itemInfo = new AppInfo();
public FolderInfo folderInfo = new FolderInfo();
// Private App Decorator
public SectionDecorationInfo decorationInfo = null;
public AdapterItem(int viewType) {
this.viewType = viewType;
}
// LC-Feature: Folder support in All Apps
public FolderInfo folderInfo = new FolderInfo();
/**
* Factory method for AppIcon AdapterItem
*/
@@ -130,6 +138,12 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
item.itemInfo = appInfo;
return item;
}
public static AdapterItem asFolder(FolderInfo folderInfo) {
AdapterItem item = new AdapterItem(VIEW_TYPE_FOLDER);
item.folderInfo = folderInfo;
return item;
}
public static AdapterItem asAppWithDecorationInfo(AppInfo appInfo,
SectionDecorationInfo decorationInfo) {
@@ -138,12 +152,6 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
return item;
}
public static AdapterItem asFolder(FolderInfo folderInfo) {
AdapterItem item = new AdapterItem(VIEW_TYPE_FOLDER);
item.folderInfo = folderInfo;
return item;
}
protected boolean isCountedForAccessibility() {
return viewType == VIEW_TYPE_ICON || viewType == VIEW_TYPE_FOLDER;
}
@@ -156,7 +164,8 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
}
/**
* This is called only if {@link #isSameAs} returns true to check if the contents are same
* This is called only if {@link #isSameAs} returns true to check if the
* contents are same
* as well. Returning true will prevent redrawing of thee item.
*/
public boolean isContentSame(AdapterItem other) {
@@ -178,8 +187,9 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
}
protected final T mActivityContext;
protected final AlphabeticalAppsList<T> mApps;
// The text to show when there are no search results and no market search handler.
public final AlphabeticalAppsList<T> mApps;
// The text to show when there are no search results and no market search
// handler.
protected int mAppsPerRow;
protected final LayoutInflater mLayoutInflater;
@@ -214,7 +224,9 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
return isViewType(viewType, VIEW_TYPE_MASK_PRIVATE_SPACE_HEADER);
}
/** Checks if the passed viewType represents private space system apps divider. */
/**
* Checks if the passed viewType represents private space system apps divider.
*/
public static boolean isPrivateSpaceSysAppsDividerView(int viewType) {
return isViewType(viewType, VIEW_TYPE_MASK_PRIVATE_SPACE_SYS_APPS_DIVIDER);
}
@@ -232,8 +244,8 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case VIEW_TYPE_ICON:
int layout = mActivityContext.getDeviceProfile().inv.enableTwoLinesInAllApps
? R.layout.all_apps_icon_twoline : R.layout.all_apps_icon;
int layout = !FeatureFlags.twoLineAllApps(parent.getContext()) ? R.layout.all_apps_icon
: R.layout.all_apps_icon_twoline;
BubbleTextView icon = (BubbleTextView) mLayoutInflater.inflate(
layout, parent, false);
icon.setLongPressTimeoutFactor(1f);
@@ -241,8 +253,7 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
icon.setOnClickListener(mOnIconClickListener);
icon.setOnLongClickListener(mOnIconLongClickListener);
// Ensure the all apps icon height matches the workspace icons in portrait mode.
icon.getLayoutParams().height =
mActivityContext.getDeviceProfile().allAppsCellHeightPx;
icon.getLayoutParams().height = mActivityContext.getDeviceProfile().allAppsCellHeightPx;
return new ViewHolder(icon);
case VIEW_TYPE_EMPTY_SEARCH:
return new ViewHolder(mLayoutInflater.inflate(R.layout.all_apps_empty_search,
@@ -259,10 +270,7 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
case VIEW_TYPE_PRIVATE_SPACE_HEADER:
return new ViewHolder(mLayoutInflater.inflate(
R.layout.private_space_header, parent, false));
case VIEW_TYPE_BOTTOM_VIEW_TO_SCROLL_TO:
return new ViewHolder(new View(mActivityContext));
case VIEW_TYPE_FOLDER:
// LC-Feature: Folder support in All Apps
FrameLayout fl = new FrameLayout(mActivityContext);
ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
@@ -272,7 +280,7 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
if (mAdapterProvider.isViewSupported(viewType)) {
return mAdapterProvider.onCreateViewHolder(mLayoutInflater, parent, viewType);
}
throw new RuntimeException("Unexpected view type" + viewType);
throw new RuntimeException("Unexpected view type : " + viewType);
}
}
@@ -291,22 +299,15 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
// Set the alpha of the private space icon to 0 upon expanding the header so the
// alpha can animate -> 1. This should only be in effect when doing a
// transitioning between Locked/Unlocked state.
boolean isPrivateSpaceItem =
privateProfileManager.isPrivateSpaceItem(adapterItem);
boolean isPrivateSpaceItem = privateProfileManager.isPrivateSpaceItem(adapterItem);
if (icon.getAlpha() == 0 || icon.getAlpha() == 1) {
icon.setAlpha(isPrivateSpaceItem
&& privateProfileManager.isStateTransitioning()
&& (privateProfileManager.isScrolling() ||
privateProfileManager.getReadyToAnimate())
privateProfileManager.getReadyToAnimate())
&& privateProfileManager.getCurrentState() == STATE_ENABLED
? 0 : 1);
Log.d(TAG, "onBindViewHolder: "
+ "isPrivateSpaceItem: " + isPrivateSpaceItem
+ " isStateTransitioning: " + privateProfileManager.isStateTransitioning()
+ " isScrolling: " + privateProfileManager.isScrolling()
+ " readyToAnimate: " + privateProfileManager.getReadyToAnimate()
+ " currentState: " + privateProfileManager.getCurrentState()
+ " currentAlpha: " + icon.getAlpha());
? 0
: 1);
}
// Views can still be bounded before the app list is updated hence showing icons
// after collapsing.
@@ -335,17 +336,15 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
if (mApps.getPrivateProfileManager().getCurrentState() == STATE_DISABLED) {
roundRegions |= (ROUND_BOTTOM_LEFT | ROUND_BOTTOM_RIGHT);
}
adapterItem.decorationInfo =
new SectionDecorationInfo(mActivityContext, roundRegions,
false /* decorateTogether */);
adapterItem.decorationInfo = new SectionDecorationInfo(mActivityContext, roundRegions,
false /* decorateTogether */);
break;
case VIEW_TYPE_PRIVATE_SPACE_SYS_APPS_DIVIDER:
adapterItem = mApps.getAdapterItems().get(position);
adapterItem.decorationInfo = mApps.getPrivateProfileManager().getCurrentState()
== STATE_DISABLED ? null : new SectionDecorationInfo(mActivityContext,
ROUND_NOTHING, true /* decorateTogether */);
adapterItem.decorationInfo = mApps.getPrivateProfileManager().getCurrentState() == STATE_DISABLED ? null
: new SectionDecorationInfo(mActivityContext,
ROUND_NOTHING, true /* decorateTogether */);
break;
case VIEW_TYPE_BOTTOM_VIEW_TO_SCROLL_TO:
case VIEW_TYPE_ALL_APPS_DIVIDER:
case VIEW_TYPE_WORK_DISABLED_CARD:
// nothing to do
@@ -354,12 +353,10 @@ public abstract class BaseAllAppsAdapter<T extends Context & ActivityContext> ex
((WorkEduCard) holder.itemView).setPosition(position);
break;
case VIEW_TYPE_FOLDER:
// LC: Caddy/Folder in allapps 86b2b025a4f23a068818274020f37ad6d5268363
FolderInfo folderInfo = mApps.getAdapterItems().get(position).folderInfo;
ViewGroup container = (ViewGroup) holder.itemView;
container.removeAllViews();
container.addView(
FolderIcon.inflateFolderAndIcon(R.layout.all_apps_folder_icon, mActivityContext,
container.addView(FolderIcon.inflateFolderAndIcon(R.layout.all_apps_folder_icon, mActivityContext,
container, folderInfo));
break;
default:
@@ -15,8 +15,6 @@
*/
package com.android.launcher3.allapps;
import static com.android.launcher3.allapps.FloatingHeaderRow.NO_ROWS;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Point;
@@ -32,10 +30,10 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.android.launcher3.Flags;
import com.android.launcher3.Insettable;
import com.android.launcher3.R;
import com.android.launcher3.allapps.ActivityAllAppsContainerView.AdapterHolder;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.util.PluginManagerWrapper;
import com.android.launcher3.views.ActivityContext;
import com.android.systemui.plugins.AllAppsRow;
@@ -109,16 +107,14 @@ public class FloatingHeaderView extends LinearLayout implements
private boolean mFloatingRowsCollapsed;
// Total height of all current floating rows. Collapsed rows == 0 height.
private int mFloatingRowsHeight;
// Offset of search bar. Adds to the floating view height when multi-line is supported.
private int mSearchBarOffset = 0;
// This is initialized once during inflation and stays constant after that. Fixed views
// cannot be added or removed dynamically.
private FloatingHeaderRow[] mFixedRows = NO_ROWS;
private FloatingHeaderRow[] mFixedRows = FloatingHeaderRow.NO_ROWS;
// Array of all fixed rows and plugin rows. This is initialized every time a plugin is
// enabled or disabled, and represent the current set of all rows.
private FloatingHeaderRow[] mAllRows = NO_ROWS;
private FloatingHeaderRow[] mAllRows = FloatingHeaderRow.NO_ROWS;
private final PreferenceManager2 pref2;
@@ -188,10 +184,6 @@ public class FloatingHeaderView extends LinearLayout implements
@Override
public void onPluginConnected(AllAppsRow allAppsRowPlugin, Context context) {
if (mPluginRows.containsKey(allAppsRowPlugin)) {
// Plugin has already been connected
return;
}
PluginHeaderRow headerRow = new PluginHeaderRow(allAppsRowPlugin, this);
addView(headerRow.mView, indexOfChild(mTabLayout));
mPluginRows.put(allAppsRowPlugin, headerRow);
@@ -212,20 +204,9 @@ public class FloatingHeaderView extends LinearLayout implements
}
}
/**
* Offset floating rows height by search bar
*/
void updateSearchBarOffset(int offset) {
mSearchBarOffset = offset;
onHeightUpdated();
}
@Override
public void onPluginDisconnected(AllAppsRow plugin) {
PluginHeaderRow row = mPluginRows.get(plugin);
if (row == null) {
return;
}
removeView(row.mView);
mPluginRows.remove(plugin);
recreateAllRowsArray();
@@ -234,12 +215,15 @@ public class FloatingHeaderView extends LinearLayout implements
@Override
public View getFocusedChild() {
for (FloatingHeaderRow row : mAllRows) {
if (row.hasVisibleContent() && row.isVisible()) {
return row.getFocusedChild();
if (FeatureFlags.ENABLE_DEVICE_SEARCH.get()) {
for (FloatingHeaderRow row : mAllRows) {
if (row.hasVisibleContent() && row.isVisible()) {
return row.getFocusedChild();
}
}
return null;
}
return null;
return super.getFocusedChild();
}
void setup(AllAppsRecyclerView mainRV, AllAppsRecyclerView workRV, SearchRecyclerView searchRV,
@@ -280,18 +264,9 @@ public class FloatingHeaderView extends LinearLayout implements
mTabLayout.setVisibility(mTabsHidden ? GONE : visibility);
}
/** Returns whether search bar has multi-line support, and is currently in multi-line state. */
private boolean isSearchBarMultiline() {
return Flags.multilineSearchBar() && mSearchBarOffset > 0;
}
private void updateExpectedHeight() {
updateFloatingRowsHeight();
mMaxTranslation = 0;
boolean shouldAddSearchBarHeight = isSearchBarMultiline() && !Flags.floatingSearchBar();
if (shouldAddSearchBarHeight) {
mMaxTranslation += mSearchBarOffset;
}
if (mFloatingRowsCollapsed) {
return;
}
@@ -21,7 +21,6 @@ import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.VisibleForTesting;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.android.launcher3.R;
@@ -54,21 +53,13 @@ public class FloatingMaskView extends ConstraintLayout {
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
setParameters((ViewGroup.MarginLayoutParams) getLayoutParams(),
mActivityContext.getAppsView().getActiveRecyclerView());
}
@VisibleForTesting
void setParameters(ViewGroup.MarginLayoutParams lp, AllAppsRecyclerView recyclerView) {
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) getLayoutParams();
AllAppsRecyclerView allAppsContainerView =
mActivityContext.getAppsView().getActiveRecyclerView();
if (lp != null) {
lp.rightMargin = recyclerView.getPaddingRight();
lp.leftMargin = recyclerView.getPaddingLeft();
getBottomBox().setMinimumHeight(recyclerView.getPaddingBottom());
lp.rightMargin = allAppsContainerView.getPaddingRight();
lp.leftMargin = allAppsContainerView.getPaddingLeft();
mBottomBox.setMinimumHeight(allAppsContainerView.getPaddingBottom());
}
}
@VisibleForTesting
ImageView getBottomBox() {
return mBottomBox;
}
}
@@ -41,11 +41,11 @@ import static com.android.launcher3.util.SettingsCache.PRIVATE_SPACE_HIDE_WHEN_L
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Trace;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.Log;
@@ -67,7 +67,6 @@ import com.android.launcher3.BuildConfig;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Flags;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimatedPropertySetter;
import com.android.launcher3.anim.PropertySetter;
import com.android.launcher3.icons.BitmapInfo;
@@ -91,16 +90,14 @@ import java.util.function.Predicate;
* logic in the Personal tab.
*/
public class PrivateProfileManager extends UserProfileManager {
private static final String TAG = "PrivateProfileManager";
private static final int EXPAND_COLLAPSE_DURATION = 400;
private static final int EXPAND_COLLAPSE_DURATION = 800;
private static final int SETTINGS_OPACITY_DURATION = 400;
private static final int TEXT_UNLOCK_OPACITY_DURATION = 300;
private static final int TEXT_LOCK_OPACITY_DURATION = 50;
private static final int APP_OPACITY_DURATION = 400;
private static final int MASK_VIEW_DURATION = 200;
private static final int APP_OPACITY_DELAY = 400;
private static final int PILL_TRANSITION_DELAY = 400;
private static final int SETTINGS_AND_LOCK_GROUP_TRANSITION_DELAY = 400;
private static final int SETTINGS_OPACITY_DELAY = 400;
private static final int LOCK_TEXT_OPACITY_DELAY = 500;
private static final int MASK_VIEW_DELAY = 400;
@@ -110,8 +107,6 @@ public class PrivateProfileManager extends UserProfileManager {
private final Predicate<UserHandle> mPrivateProfileMatcher;
private final int mPsHeaderHeight;
private final int mFloatingMaskViewCornerRadius;
private final int mLockTextMarginStart;
private final int mLockTextMarginEnd;
private final RecyclerView.OnScrollListener mOnIdleScrollListener =
new RecyclerView.OnScrollListener() {
@Override
@@ -136,13 +131,7 @@ public class PrivateProfileManager extends UserProfileManager {
private Runnable mOnPSHeaderAdded;
@Nullable
private RelativeLayout mPSHeader;
@Nullable
private TextView mLockText;
@Nullable
private PrivateSpaceSettingsButton mPrivateSpaceSettingsButton;
@Nullable
private ConstraintLayout mFloatingMaskView;
private final String mPrivateSpaceAppContentDesc;
private final String mLockedStateContentDesc;
private final String mUnLockedStateContentDesc;
@@ -158,18 +147,12 @@ public class PrivateProfileManager extends UserProfileManager {
UI_HELPER_EXECUTOR.post(() -> initializeInBackgroundThread(appContext));
mPsHeaderHeight = mAllApps.getContext().getResources().getDimensionPixelSize(
R.dimen.ps_header_height);
mPrivateSpaceAppContentDesc = mAllApps.getContext()
.getString(R.string.ps_app_content_description);
mLockedStateContentDesc = mAllApps.getContext()
.getString(R.string.ps_container_lock_button_content_description);
mUnLockedStateContentDesc = mAllApps.getContext()
.getString(R.string.ps_container_unlock_button_content_description);
mFloatingMaskViewCornerRadius = mAllApps.getContext().getResources().getDimensionPixelSize(
R.dimen.ps_floating_mask_corner_radius);
mLockTextMarginStart = mAllApps.getContext().getResources().getDimensionPixelSize(
R.dimen.ps_lock_icon_text_margin_start_expanded);
mLockTextMarginEnd = mAllApps.getContext().getResources().getDimensionPixelSize(
R.dimen.ps_lock_icon_text_margin_end_expanded);
}
/** Adds Private Space Header to the layout. */
@@ -190,11 +173,15 @@ public class PrivateProfileManager extends UserProfileManager {
/** Adds Private Space install app button to the layout. */
public void addPrivateSpaceInstallAppButton(List<BaseAllAppsAdapter.AdapterItem> adapterItems) {
Context context = mAllApps.getContext();
// Prepare bitmapInfo
Intent.ShortcutIconResource shortcut = Intent.ShortcutIconResource.fromContext(
context, com.android.launcher3.R.drawable.private_space_install_app_icon);
BitmapInfo bitmapInfo = LauncherIcons.obtain(context).createIconBitmap(shortcut);
PrivateSpaceInstallAppButtonInfo itemInfo = new PrivateSpaceInstallAppButtonInfo();
itemInfo.title = context.getResources().getString(R.string.ps_add_button_label);
itemInfo.intent = mAppInstallerIntent;
itemInfo.bitmap = preparePSBitmapInfo();
itemInfo.bitmap = bitmapInfo;
itemInfo.contentDescription = context.getResources().getString(
com.android.launcher3.R.string.ps_add_button_content_description);
itemInfo.runtimeStatusFlags |= FLAG_NOT_PINNABLE;
@@ -223,21 +210,13 @@ public class PrivateProfileManager extends UserProfileManager {
}
}
BitmapInfo preparePSBitmapInfo() {
Context context = mAllApps.getContext();
Intent.ShortcutIconResource shortcut = Intent.ShortcutIconResource.fromContext(
context, com.android.launcher3.R.drawable.private_space_install_app_icon);
return LauncherIcons.obtain(context).createIconBitmap(shortcut);
}
/**
* Resets the current state of Private Profile, w.r.t. to Launcher. The decorator should only
* be applied upon expand before animating. When collapsing, reset() will remove the decorator
* when animation is not running.
*/
public void reset() {
Trace.beginSection("PrivateProfileManager#reset");
// Ensure the state of the header view is what it should be before animating.
// Ensure the state of the header views is what it should be before animating.
updateView();
getMainRecyclerView().setChildAttachedConsumer(null);
int previousState = getCurrentState();
@@ -256,7 +235,6 @@ public class PrivateProfileManager extends UserProfileManager {
executeLock();
}
addPrivateSpaceDecorator(updatedState);
Trace.endSection();
}
/** Returns whether or not Private Space Settings Page is available. */
@@ -311,11 +289,30 @@ public class PrivateProfileManager extends UserProfileManager {
}
}
@Override
public void setQuietMode(boolean enable) {
setQuietMode(enable, mAllApps.mActivityContext);
UI_HELPER_EXECUTOR.post(() ->
mUserCache.getUserProfiles()
.stream()
.filter(getUserMatcher())
.findFirst()
.ifPresent(userHandle -> setQuietModeSafely(enable, userHandle)));
mReadyToAnimate = true;
}
/**
* Sets Quiet Mode for Private Profile.
* If {@link SecurityException} is thrown, prompts the user to set this launcher as HOME app.
*/
private void setQuietModeSafely(boolean enable, UserHandle userHandle) {
try {
mUserManager.requestQuietModeEnabled(enable, userHandle);
} catch (SecurityException ex) {
ApiWrapper.INSTANCE.get(mAllApps.mActivityContext)
.assignDefaultHomeRole(mAllApps.mActivityContext);
}
}
/**
* Expand the private space after the app list has been added and updated from
* {@link AlphabeticalAppsList#onAppsUpdated()}
@@ -330,9 +327,7 @@ public class PrivateProfileManager extends UserProfileManager {
/** Collapses the private space before the app list has been updated. */
void executeLock() {
Trace.beginSection("PrivateProfileManager#executeLock");
MAIN_EXECUTOR.execute(() -> updatePrivateStateAnimator(false));
Trace.endSection();
}
void setAnimationRunning(boolean isAnimationRunning) {
@@ -366,12 +361,19 @@ public class PrivateProfileManager extends UserProfileManager {
/** Add Private Space Header view elements based upon {@link UserProfileState} */
public void bindPrivateSpaceHeaderViewElements(RelativeLayout parent) {
mPSHeader = parent;
Log.d(TAG, "bindPrivateSpaceHeaderViewElements: " + "Binding private space.");
updateView();
if (mOnPSHeaderAdded != null) {
MAIN_EXECUTOR.execute(mOnPSHeaderAdded);
mOnPSHeaderAdded = null;
}
// Set the transition duration for the settings and lock button to animate.
ViewGroup settingAndLockGroup = mPSHeader.findViewById(R.id.settingsAndLockGroup);
if (mReadyToAnimate) {
enableLayoutTransition(settingAndLockGroup);
} else {
// Ensure any unwanted animations to not happen.
settingAndLockGroup.setLayoutTransition(null);
}
updateView();
}
/** Update the states of the views that make up the header at the state it is called in. */
@@ -379,16 +381,12 @@ public class PrivateProfileManager extends UserProfileManager {
if (mPSHeader == null) {
return;
}
Trace.beginSection("PrivateProfileManager#updateView");
Log.d(TAG, "bindPrivateSpaceHeaderViewElements: " + "Updating view with state: "
+ getCurrentState());
mPSHeader.setAlpha(1);
ViewGroup lockPill = mPSHeader.findViewById(R.id.ps_lock_unlock_button);
assert lockPill != null;
mLockText = lockPill.findViewById(R.id.lock_text);
assert mLockText != null;
mPrivateSpaceSettingsButton = mPSHeader.findViewById(R.id.ps_settings_button);
assert mPrivateSpaceSettingsButton != null;
TextView lockText = lockPill.findViewById(R.id.lock_text);
PrivateSpaceSettingsButton settingsButton = mPSHeader.findViewById(R.id.ps_settings_button);
assert settingsButton != null;
//Add image for private space transitioning view
ImageView transitionView = mPSHeader.findViewById(R.id.ps_transition_image);
assert transitionView != null;
@@ -399,19 +397,12 @@ public class PrivateProfileManager extends UserProfileManager {
// Remove header from accessibility target when enabled.
mPSHeader.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
if (!mReadyToAnimate) {
// Don't set visibilities when animating as the animation will handle it.
mLockText.setVisibility(VISIBLE);
mLockText.setAlpha(1);
mLockText.setHorizontallyScrolling(false);
mPrivateSpaceSettingsButton.setVisibility(
isPrivateSpaceSettingsAvailable() ? VISIBLE : GONE);
mPrivateSpaceSettingsButton.setClickable(isPrivateSpaceSettingsAvailable());
}
lockText.setVisibility(VISIBLE);
lockPill.setVisibility(VISIBLE);
lockPill.setOnClickListener(view -> lockingAction(/* lock */ true));
lockPill.setContentDescription(mUnLockedStateContentDesc);
settingsButton.setVisibility(isPrivateSpaceSettingsAvailable() ? VISIBLE : GONE);
transitionView.setVisibility(GONE);
}
case STATE_DISABLED -> {
@@ -421,15 +412,12 @@ public class PrivateProfileManager extends UserProfileManager {
mPSHeader.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
mPSHeader.setContentDescription(mLockedStateContentDesc);
mLockText.setVisibility(GONE);
mLockText.setAlpha(0);
mLockText.setHorizontallyScrolling(false);
lockText.setVisibility(GONE);
lockPill.setVisibility(VISIBLE);
lockPill.setOnClickListener(view -> lockingAction(/* lock */ false));
lockPill.setContentDescription(mLockedStateContentDesc);
mPrivateSpaceSettingsButton.setVisibility(GONE);
mPrivateSpaceSettingsButton.setClickable(false);
settingsButton.setVisibility(GONE);
transitionView.setVisibility(GONE);
}
case STATE_TRANSITION -> {
@@ -437,8 +425,6 @@ public class PrivateProfileManager extends UserProfileManager {
lockPill.setVisibility(GONE);
}
}
mPSHeader.invalidate();
Trace.endSection();
}
/** Sets the enablement of the profile when header or button is clicked. */
@@ -478,8 +464,7 @@ public class PrivateProfileManager extends UserProfileManager {
break;
}
// Make the private space apps gone to "collapse".
if ((mFloatingMaskView == null && isPrivateSpaceItem(currentItem)) ||
currentItem.viewType == VIEW_TYPE_PRIVATE_SPACE_SYS_APPS_DIVIDER) {
if (mFloatingMaskView == null && isPrivateSpaceItem(currentItem)) {
RecyclerView.ViewHolder viewHolder =
allAppsRecyclerView.findViewHolderForAdapterPosition(i);
if (viewHolder != null) {
@@ -606,51 +591,6 @@ public class PrivateProfileManager extends UserProfileManager {
return alphaAnim;
}
private ValueAnimator animatePillTransition(boolean isExpanding) {
if (mLockText == null) {
return new ValueAnimator().setDuration(0);
}
mLockText.measure(0,0);
int currentWidth = mLockText.getWidth();
int fullWidth = mLockText.getMeasuredWidth();
float from = isExpanding ? 0 : currentWidth;
float to = isExpanding ? fullWidth : 0;
ValueAnimator pillAnim = ObjectAnimator.ofFloat(from, to);
pillAnim.setStartDelay(isExpanding ? PILL_TRANSITION_DELAY : 0);
pillAnim.setDuration(EXPAND_COLLAPSE_DURATION);
pillAnim.setInterpolator(Interpolators.STANDARD);
pillAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float translation = (float) valueAnimator.getAnimatedValue();
float translationFraction = translation / fullWidth;
ViewGroup.MarginLayoutParams layoutParams =
(ViewGroup.MarginLayoutParams) mLockText.getLayoutParams();
layoutParams.width = (int) translation;
layoutParams.setMarginStart((int) (mLockTextMarginStart * translationFraction));
layoutParams.setMarginEnd((int) (mLockTextMarginEnd * translationFraction));
mLockText.setLayoutParams(layoutParams);
mLockText.requestLayout();
}
});
pillAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
if (!isExpanding) {
mLockText.setVisibility(GONE);
}
mLockText.setHorizontallyScrolling(false);
}
@Override
public void onAnimationStart(Animator animator) {
mLockText.setHorizontallyScrolling(true);
mLockText.setVisibility(VISIBLE);
}
});
return pillAnim;
}
/**
* Using PropertySetter{@link PropertySetter}, we can update the view's attributes within an
* animation. At the moment, collapsing, setting alpha changes, and animating the text is done
@@ -662,23 +602,33 @@ public class PrivateProfileManager extends UserProfileManager {
}
if (mPSHeader == null) {
mOnPSHeaderAdded = () -> updatePrivateStateAnimator(expand);
// Set animation to true, because onBind will be called after this return where we want
// the views to be updated accordingly so animation can happen.
setAnimationRunning(true);
setAnimationRunning(false);
return;
}
attachFloatingMaskView(expand);
AnimatorSet animatorSet = new AnimatedPropertySetter().buildAnim();
ViewGroup settingsAndLockGroup = mPSHeader.findViewById(R.id.settingsAndLockGroup);
if (settingsAndLockGroup.getLayoutTransition() == null) {
// Set a new transition if the current ViewGroup does not already contain one as each
// transition should only happen once when applied.
enableLayoutTransition(settingsAndLockGroup);
}
settingsAndLockGroup.getLayoutTransition().setStartDelay(
LayoutTransition.CHANGING,
expand ? SETTINGS_AND_LOCK_GROUP_TRANSITION_DELAY : NO_DELAY);
PropertySetter headerSetter = new AnimatedPropertySetter();
headerSetter.add(updateSettingsGearAlpha(expand));
headerSetter.add(updateLockTextAlpha(expand));
AnimatorSet animatorSet = headerSetter.buildAnim();
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
Log.d(TAG, "updatePrivateStateAnimator: Private space animation expanding: "
+ expand);
mStatsLogManager.logger().sendToInteractionJankMonitor(
expand
? LAUNCHER_PRIVATE_SPACE_UNLOCK_ANIMATION_BEGIN
: LAUNCHER_PRIVATE_SPACE_LOCK_ANIMATION_BEGIN,
mAllApps.getActiveRecyclerView());
// Animate the collapsing of the text at the same time while updating lock button.
mPSHeader.findViewById(R.id.lock_text).setVisibility(expand ? VISIBLE : GONE);
setAnimationRunning(true);
}
@@ -696,18 +646,11 @@ public class PrivateProfileManager extends UserProfileManager {
? LAUNCHER_PRIVATE_SPACE_UNLOCK_ANIMATION_END
: LAUNCHER_PRIVATE_SPACE_LOCK_ANIMATION_END,
mAllApps.getActiveRecyclerView());
Log.d(TAG, "updatePrivateStateAnimator: lockText visibility: "
+ mLockText.getVisibility() + " lockTextAlpha: " + mLockText.getAlpha());
Log.d(TAG, "updatePrivateStateAnimator: settingsCog visibility: "
+ mPrivateSpaceSettingsButton.getVisibility()
+ " settingsCogAlpha: " + mPrivateSpaceSettingsButton.getAlpha());
if (!expand) {
mAllApps.mAH.get(MAIN).mRecyclerView.removeItemDecoration(
mPrivateAppsSectionDecorator);
// Call onAppsUpdated() because it may be canceled when this animation occurs.
if (!Utilities.isRunningInTestHarness()) {
mAllApps.getPersonalAppList().onAppsUpdated();
}
mAllApps.getPersonalAppList().onAppsUpdated();
if (isPrivateSpaceHidden()) {
// TODO (b/325455879): Figure out if we can avoid this.
getMainRecyclerView().getAdapter().notifyDataSetChanged();
@@ -715,24 +658,16 @@ public class PrivateProfileManager extends UserProfileManager {
}
}));
if (expand) {
animatorSet.playTogether(updateSettingsGearAlpha(true),
updateLockTextAlpha(true),
animateAlphaOfIcons(true),
animatePillTransition(true),
animatorSet.playTogether(animateAlphaOfIcons(true),
translateFloatingMaskView(false));
} else {
AnimatorSet parallelSet = new AnimatorSet();
parallelSet.playTogether(updateSettingsGearAlpha(false),
updateLockTextAlpha(false),
animateAlphaOfIcons(false),
animatePillTransition(false));
if (isPrivateSpaceHidden()) {
animatorSet.playSequentially(parallelSet,
animatorSet.playSequentially(animateAlphaOfIcons(false),
animateAlphaOfPrivateSpaceContainer(),
animateCollapseAnimation());
} else {
animatorSet.playSequentially(translateFloatingMaskView(true),
parallelSet,
animateAlphaOfIcons(false),
animateCollapseAnimation());
}
}
@@ -763,7 +698,7 @@ public class PrivateProfileManager extends UserProfileManager {
/** Fades out the private space container. */
private ValueAnimator translateFloatingMaskView(boolean animateIn) {
if (!Flags.privateSpaceAddFloatingMaskView() || mFloatingMaskView == null) {
return new ValueAnimator().setDuration(0);
return new ValueAnimator();
}
// Translate base on the height amount. Translates out on expand and in on collapse.
float floatingMaskViewHeight = getFloatingMaskViewHeight();
@@ -775,19 +710,38 @@ public class PrivateProfileManager extends UserProfileManager {
alphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
if (mFloatingMaskView == null) {
return;
}
mFloatingMaskView.setTranslationY((float) valueAnimator.getAnimatedValue());
}
});
return alphaAnim;
}
/** Animates the layout changes when the text of the button becomes visible/gone. */
private void enableLayoutTransition(ViewGroup settingsAndLockGroup) {
LayoutTransition settingsAndLockTransition = new LayoutTransition();
settingsAndLockTransition.enableTransitionType(LayoutTransition.CHANGING);
settingsAndLockTransition.setDuration(EXPAND_COLLAPSE_DURATION);
settingsAndLockTransition.setInterpolator(LayoutTransition.CHANGING,
Interpolators.STANDARD);
settingsAndLockTransition.addTransitionListener(new LayoutTransition.TransitionListener() {
@Override
public void startTransition(LayoutTransition transition, ViewGroup viewGroup,
View view, int i) {
}
@Override
public void endTransition(LayoutTransition transition, ViewGroup viewGroup,
View view, int i) {
settingsAndLockGroup.setLayoutTransition(null);
mReadyToAnimate = false;
}
});
settingsAndLockGroup.setLayoutTransition(settingsAndLockTransition);
}
/** Change the settings gear alpha when expanded or collapsed. */
private ValueAnimator updateSettingsGearAlpha(boolean expand) {
if (mPrivateSpaceSettingsButton == null || !isPrivateSpaceSettingsAvailable()) {
return new ValueAnimator().setDuration(0);
if (mPSHeader == null) {
return new ValueAnimator();
}
float from = expand ? 0 : 1;
float to = expand ? 1 : 0;
@@ -798,29 +752,16 @@ public class PrivateProfileManager extends UserProfileManager {
settingsAlphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
mPrivateSpaceSettingsButton.setAlpha((float) valueAnimator.getAnimatedValue());
}
});
settingsAlphaAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animator) {
mPrivateSpaceSettingsButton.setVisibility(VISIBLE);
mPrivateSpaceSettingsButton.setClickable(false);
}
@Override
public void onAnimationEnd(Animator animator) {
if (expand) {
mPrivateSpaceSettingsButton.setClickable(true);
}
mPSHeader.findViewById(R.id.ps_settings_button)
.setAlpha((float) valueAnimator.getAnimatedValue());
}
});
return settingsAlphaAnim;
}
private ValueAnimator updateLockTextAlpha(boolean expand) {
if (mLockText == null) {
return new ValueAnimator().setDuration(0);
if (mPSHeader == null) {
return new ValueAnimator();
}
float from = expand ? 0 : 1;
float to = expand ? 1 : 0;
@@ -831,7 +772,8 @@ public class PrivateProfileManager extends UserProfileManager {
alphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
mLockText.setAlpha((float) valueAnimator.getAnimatedValue());
mPSHeader.findViewById(R.id.lock_text).setAlpha(
(float) valueAnimator.getAnimatedValue());
}
});
return alphaAnim;
@@ -843,7 +785,6 @@ public class PrivateProfileManager extends UserProfileManager {
ActivityAllAppsContainerView<?>.AdapterHolder mainAdapterHolder = mAllApps.mAH.get(MAIN);
List<BaseAllAppsAdapter.AdapterItem> adapterItems =
mainAdapterHolder.mAppsList.getAdapterItems();
Trace.beginSection("PrivateProfileManager#expandPrivateSpace");
if (Flags.enablePrivateSpace() && Flags.privateSpaceAnimation()
&& mAllApps.isPersonalTab()) {
// Animate the text and settings icon.
@@ -853,7 +794,6 @@ public class PrivateProfileManager extends UserProfileManager {
getPsHeaderHeight(), deviceProfile.allAppsCellHeightPx);
updatePrivateStateAnimator(true);
}
Trace.endSection();
}
private void exitSearchAndExpand() {
@@ -871,22 +811,8 @@ public class PrivateProfileManager extends UserProfileManager {
if (!Flags.privateSpaceAddFloatingMaskView()) {
return;
}
// Use getLocationOnScreen() as simply checking for mPSHeader.getBottom() is only relative
// to its parent.
int[] psHeaderLocation = new int[2];
mPSHeader.getLocationOnScreen(psHeaderLocation);
int psHeaderBottomY = psHeaderLocation[1] + mPsHeaderHeight;
// Calculate the topY of the floatingMaskView as if it was added.
int floatingMaskViewBottomBoxTopY =
(int) (mAllApps.getBottom() - getMainRecyclerView().getPaddingBottom());
// Don't attach if the header will be clipped by the floating mask view.
if (psHeaderBottomY > floatingMaskViewBottomBoxTopY) {
mFloatingMaskView = null;
return;
}
mFloatingMaskView = (FloatingMaskView) mAllApps.getLayoutInflater().inflate(
R.layout.private_space_mask_view, mAllApps, false);
assert mFloatingMaskView != null;
mAllApps.addView(mFloatingMaskView);
// Translate off the screen first if its collapsing so this header view isn't visible to
// user when animation starts.
@@ -944,10 +870,6 @@ public class PrivateProfileManager extends UserProfileManager {
return mPsHeaderHeight;
}
String getPsAppContentDesc() {
return mPrivateSpaceAppContentDesc;
}
boolean isPrivateSpaceItem(BaseAllAppsAdapter.AdapterItem item) {
return getItemInfoMatcher().test(item.itemInfo) || item.decorationInfo != null
|| (item.itemInfo instanceof PrivateSpaceInstallAppButtonInfo);
@@ -25,8 +25,10 @@ import android.graphics.drawable.InsetDrawable;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import com.android.launcher3.R;
import com.android.launcher3.util.Themes;
public class SectionDecorationHandler {
@@ -59,8 +61,10 @@ public class SectionDecorationHandler {
mContext = context;
mFillAlpha = fillAlpha;
mFocusColor = context.getColor(R.color.materialColorSurfaceBright); // UX recommended
mFillColor = context.getColor(R.color.materialColorSurfaceContainerHigh); // UX recommended
mFocusColor = ContextCompat.getColor(context,
R.color.material_color_surface_bright); // UX recommended
mFillColor = ContextCompat.getColor(context,
R.color.material_color_surface_container_high); // UX recommended
mIsTopLeftRound = isTopLeftRound;
mIsTopRightRound = isTopRightRound;
@@ -16,12 +16,8 @@
package com.android.launcher3.allapps;
import static com.android.launcher3.Utilities.ATLEAST_P;
import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.UserHandle;
import android.os.UserManager;
@@ -30,7 +26,6 @@ import androidx.annotation.IntDef;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.util.ApiWrapper;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -74,28 +69,14 @@ public abstract class UserProfileManager {
}
/** Sets quiet mode as enabled/disabled for the profile type. */
protected void setQuietMode(boolean enabled, Context context) {
protected void setQuietMode(boolean enabled) {
UI_HELPER_EXECUTOR.post(() ->
mUserCache.getUserProfiles()
.stream()
.filter(getUserMatcher())
.findFirst()
.ifPresent(userHandle ->
setQuietModeSafely(enabled, userHandle, context)));
}
/**
* Sets Quiet Mode for Private Profile.
* If {@link SecurityException} is thrown, prompts the user to set this launcher as HOME app.
*/
private void setQuietModeSafely(boolean enable, UserHandle userHandle, Context context) {
try {
if (ATLEAST_P) {
mUserManager.requestQuietModeEnabled(enable, userHandle);
}
} catch (SecurityException ex) {
ApiWrapper.INSTANCE.get(context).assignDefaultHomeRole(context);
}
mUserManager.requestQuietModeEnabled(enabled, userHandle)));
}
/** Sets current state for the profile type. */
@@ -20,7 +20,6 @@ import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCH
import android.content.Context;
import android.content.res.Configuration;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
@@ -39,9 +38,7 @@ import app.lawnchair.theme.color.tokens.ColorTokens;
*/
public class WorkPausedCard extends LinearLayout implements View.OnClickListener {
private static final String TAG = "WorkPausedCard";
private final ActivityContext mActivityContext;
private Button mBtn;
public WorkPausedCard(Context context) {
this(context, null, 0);
@@ -59,17 +56,7 @@ public class WorkPausedCard extends LinearLayout implements View.OnClickListener
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mBtn = findViewById(R.id.enable_work_apps);
mBtn.setOnClickListener(this);
updateStringFromCache();
}
public void updateStringFromCache() {
StringCache cache = mActivityContext.getStringCache();
if (cache != null) {
setWorkProfilePausedResources();
}
setWorkProfilePausedResources();
}
public void setWorkProfilePausedResources() {
@@ -91,7 +78,7 @@ public class WorkPausedCard extends LinearLayout implements View.OnClickListener
@Override
public void onClick(View view) {
Log.d(TAG, "WorkPausedCard clicked.");
setEnabled(false);
mActivityContext.getAppsView().getWorkManager().setWorkProfileEnabled(true);
mActivityContext.getStatsLogManager().logger().log(LAUNCHER_TURN_ON_WORK_APPS_TAP);
}
@@ -26,6 +26,7 @@ import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_HAS_SHORTCU
import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_QUIET_MODE_CHANGE_PERMISSION;
import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_QUIET_MODE_ENABLED;
import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_WORK_PROFILE_QUIET_MODE_ENABLED;
import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
import android.os.UserHandle;
import android.os.UserManager;
@@ -50,7 +51,8 @@ import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* Companion class for {@link ActivityAllAppsContainerView} to manage work tab and personal tab
* Companion class for {@link ActivityAllAppsContainerView} to manage work tab
* and personal tab
* related
* logic based on {@link UserProfileState}?
*/
@@ -58,7 +60,7 @@ public class WorkProfileManager extends UserProfileManager
implements PersonalWorkSlidingTabStrip.OnActivePageChangedListener {
private static final String TAG = "WorkProfileManager";
private final ActivityAllAppsContainerView<?> mAllApps;
private WorkUtilityView mWorkUtilityView;
private WorkModeSwitch mWorkModeSwitch;
private final Predicate<UserHandle> mWorkProfileMatcher;
public WorkProfileManager(
@@ -74,26 +76,39 @@ public class WorkProfileManager extends UserProfileManager
*/
public void setWorkProfileEnabled(boolean enabled) {
updateCurrentState(STATE_TRANSITION);
setQuietMode(!enabled, mAllApps.mActivityContext);
UI_HELPER_EXECUTOR.post(() -> {
for (UserHandle userProfile : mUserManager.getUserProfiles()) {
if (android.os.Process.myUserHandle().equals(userProfile)) {
continue;
}
// https://github.com/LawnchairLauncher/lawnchair/issues/3145
try {
mUserManager.requestQuietModeEnabled(!enabled, userProfile);
} catch (RuntimeException e) {
Log.e(TAG, "Failed to set quiet mode for user " + userProfile, e);
}
}
});
}
@Override
public void onActivePageChanged(int page) {
updateWorkUtilityViews(page);
updateWorkFAB(page);
}
private void updateWorkUtilityViews(int page) {
if (mWorkUtilityView != null) {
private void updateWorkFAB(int page) {
if (mWorkModeSwitch != null) {
if (page == MAIN || page == SEARCH) {
mWorkUtilityView.animateVisibility(false);
mWorkModeSwitch.animateVisibility(false);
} else if (page == WORK && getCurrentState() == STATE_ENABLED) {
mWorkUtilityView.animateVisibility(true);
mWorkModeSwitch.animateVisibility(true);
}
}
}
/**
* Requests work profile state from {@link AllAppsStore} and updates work profile related views
* Requests work profile state from {@link AllAppsStore} and updates work
* profile related views
*/
public void reset() {
int quietModeFlag;
@@ -104,10 +119,10 @@ public class WorkProfileManager extends UserProfileManager
}
boolean isEnabled = !mAllApps.getAppsStore().hasModelFlag(quietModeFlag);
updateCurrentState(isEnabled ? STATE_ENABLED : STATE_DISABLED);
if (mWorkUtilityView != null) {
if (mWorkModeSwitch != null) {
// reset the position of the button and clear IME insets.
mWorkUtilityView.getImeInsets().setEmpty();
mWorkUtilityView.updateTranslationY();
mWorkModeSwitch.getImeInsets().setEmpty();
mWorkModeSwitch.updateTranslationY();
}
}
@@ -116,54 +131,56 @@ public class WorkProfileManager extends UserProfileManager
if (getAH() != null) {
getAH().mAppsList.updateAdapterItems();
}
if (mWorkUtilityView != null) {
updateWorkUtilityViews(mAllApps.getCurrentPage());
if (mWorkModeSwitch != null) {
updateWorkFAB(mAllApps.getCurrentPage());
}
if (getCurrentState() == STATE_ENABLED) {
attachWorkUtilityViews();
attachWorkModeSwitch();
} else if (getCurrentState() == STATE_DISABLED) {
detachWorkUtilityViews();
detachWorkModeSwitch();
}
}
/**
* Creates and attaches for profile toggle button to {@link ActivityAllAppsContainerView}
* Creates and attaches for profile toggle button to
* {@link ActivityAllAppsContainerView}
*/
public boolean attachWorkUtilityViews() {
public boolean attachWorkModeSwitch() {
if (!mAllApps.getAppsStore().hasModelFlag(
FLAG_HAS_SHORTCUT_PERMISSION | FLAG_QUIET_MODE_CHANGE_PERMISSION)) {
Log.e(TAG, "unable to attach work mode switch; Missing required permissions");
return false;
}
if (mWorkUtilityView == null) {
mWorkUtilityView = (WorkUtilityView) mAllApps.getLayoutInflater().inflate(
R.layout.work_mode_utility_view, mAllApps, false);
if (mWorkModeSwitch == null) {
mWorkModeSwitch = (WorkModeSwitch) mAllApps.getLayoutInflater().inflate(
R.layout.work_mode_fab, mAllApps, false);
}
if (mWorkUtilityView.getParent() == null) {
mAllApps.addView(mWorkUtilityView);
if (mWorkModeSwitch.getParent() == null) {
mAllApps.addView(mWorkModeSwitch);
}
if (mAllApps.getCurrentPage() != WORK) {
mWorkUtilityView.animateVisibility(false);
mWorkModeSwitch.animateVisibility(false);
}
if (getAH() != null) {
getAH().applyPadding();
}
mWorkUtilityView.getWorkFAB().setOnClickListener(this::onWorkFabClicked);
mWorkModeSwitch.setOnClickListener(this::onWorkFabClicked);
return true;
}
/**
* Removes work profile toggle button from {@link ActivityAllAppsContainerView}
*/
public void detachWorkUtilityViews() {
if (mWorkUtilityView != null && mWorkUtilityView.getParent() == mAllApps) {
mAllApps.removeView(mWorkUtilityView);
public void detachWorkModeSwitch() {
if (mWorkModeSwitch != null && mWorkModeSwitch.getParent() == mAllApps) {
mAllApps.removeView(mWorkModeSwitch);
}
mWorkUtilityView = null;
mWorkModeSwitch = null;
}
@Nullable
public WorkUtilityView getWorkUtilityView() {
return mWorkUtilityView;
public WorkModeSwitch getWorkModeSwitch() {
return mWorkModeSwitch;
}
private ActivityAllAppsContainerView.AdapterHolder getAH() {
@@ -182,11 +199,12 @@ public class WorkProfileManager extends UserProfileManager
}
/**
* Adds work profile specific adapter items to adapterItems and returns number of items added
* Adds work profile specific adapter items to adapterItems and returns number
* of items added
*/
public int addWorkItems(ArrayList<AdapterItem> adapterItems) {
if (getCurrentState() == WorkProfileManager.STATE_DISABLED) {
//add disabled card here.
// add disabled card here.
adapterItems.add(new AdapterItem(VIEW_TYPE_WORK_DISABLED_CARD));
} else if (getCurrentState() == WorkProfileManager.STATE_ENABLED && !isEduSeen()) {
adapterItems.add(new AdapterItem(VIEW_TYPE_WORK_EDU_CARD));
@@ -199,8 +217,7 @@ public class WorkProfileManager extends UserProfileManager
}
private void onWorkFabClicked(View view) {
if (getCurrentState() == STATE_ENABLED && mWorkUtilityView.isEnabled()) {
Log.d(TAG, "Work FAB clicked.");
if (getCurrentState() == STATE_ENABLED && mWorkModeSwitch.isEnabled()) {
logEvents(LAUNCHER_TURN_OFF_WORK_APPS_TAP);
setWorkProfileEnabled(false);
}
@@ -209,16 +226,18 @@ public class WorkProfileManager extends UserProfileManager
public RecyclerView.OnScrollListener newScrollListener() {
return new RecyclerView.OnScrollListener() {
int totalDelta = 0;
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState){
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
totalDelta = 0;
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
WorkUtilityView fab = getWorkUtilityView();
if (fab == null){
WorkModeSwitch fab = getWorkModeSwitch();
if (fab == null) {
return;
}
totalDelta = Utilities.boundToRange(totalDelta,
@@ -22,6 +22,8 @@ import android.text.TextWatcher;
import android.text.style.SuggestionSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
@@ -29,6 +31,7 @@ import android.widget.TextView.OnEditorActionListener;
import com.android.launcher3.ExtendedEditText;
import com.android.launcher3.Utilities;
import com.android.launcher3.allapps.BaseAllAppsAdapter.AdapterItem;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.search.SearchAlgorithm;
import com.android.launcher3.search.SearchCallback;
import com.android.launcher3.views.ActivityContext;
@@ -37,7 +40,8 @@ import com.android.launcher3.views.ActivityContext;
* An interface to a search box that AllApps can command.
*/
public class AllAppsSearchBarController
implements TextWatcher, OnEditorActionListener, ExtendedEditText.OnBackKeyListener {
implements TextWatcher, OnEditorActionListener, ExtendedEditText.OnBackKeyListener,
OnFocusChangeListener {
private static final String TAG = "AllAppsSearchBarController";
protected ActivityContext mLauncher;
@@ -65,6 +69,7 @@ public class AllAppsSearchBarController
mInput.addTextChangedListener(this);
mInput.setOnEditorActionListener(this);
mInput.setOnBackKeyListener(this);
mInput.addOnFocusChangeListener(this);
mSearchAlgorithm = searchAlgorithm;
}
@@ -117,14 +122,8 @@ public class AllAppsSearchBarController
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || (
actionId == EditorInfo.IME_NULL && event != null
&& event.getAction() == KeyEvent.ACTION_DOWN)) {
if (actionId == EditorInfo.IME_NULL) {
Log.i(TAG, "User pressed ENTER key");
} else {
Log.i(TAG, "User tapped ime search button");
}
if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO) {
Log.i(TAG, "User tapped ime search button");
// selectFocusedView should return SearchTargetEvent that is passed onto onClick
return mLauncher.getAppsView().getMainAdapterProvider().launchHighlightedItem();
}
@@ -142,6 +141,13 @@ public class AllAppsSearchBarController
return false;
}
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus && !FeatureFlags.ENABLE_DEVICE_SEARCH.get()) {
mInput.hideKeyboard();
}
}
/**
* Resets the search bar state.
*/
@@ -149,8 +155,8 @@ public class AllAppsSearchBarController
mCallback.clearSearchResult();
mInput.reset();
mInput.clearFocus();
mInput.hideKeyboard();
mQuery = null;
mInput.removeOnFocusChangeListener(this);
}
/**
@@ -20,7 +20,6 @@ import static com.android.launcher3.LauncherAnimUtils.VIEW_BACKGROUND_COLOR;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
@@ -122,31 +121,19 @@ public class AnimatedPropertySetter extends PropertySetter {
* Adds a listener to be run on every frame of the animation
*/
public void addOnFrameListener(ValueAnimator.AnimatorUpdateListener listener) {
getProgressAnimator().addUpdateListener(listener);
if (mProgressAnimator == null) {
mProgressAnimator = ValueAnimator.ofFloat(0, 1);
}
mProgressAnimator.addUpdateListener(listener);
}
@Override
public void addEndListener(Consumer<Boolean> listener) {
getProgressAnimator().addListener(AnimatorListeners.forEndCallback(listener));
}
/**
* Add a callback to run on progress start.
*/
public void addStartListener(Runnable listener) {
getProgressAnimator().addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
listener.run();
}
});
}
private ValueAnimator getProgressAnimator() {
if (mProgressAnimator == null) {
mProgressAnimator = ValueAnimator.ofFloat(0, 1);
}
return mProgressAnimator;
mProgressAnimator.addListener(AnimatorListeners.forEndCallback(listener));
}
/**
@@ -106,7 +106,11 @@ public class PendingAnimation extends AnimatedPropertySetter {
/** If trace is enabled, add counter to trace animation progress. */
public void logAnimationProgressToTrace(String counterName) {
// LC: No-op
if (Trace.isEnabled()) {
super.addOnFrameListener(
animation -> Trace.setCounter(
counterName, (long) (animation.getAnimatedFraction() * 100)));
}
}
/**
@@ -18,12 +18,10 @@ package com.android.launcher3.apppairs;
import static com.android.launcher3.BubbleTextView.DISPLAY_FOLDER;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.FloatProperty;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.FrameLayout;
@@ -56,26 +54,6 @@ import java.util.function.Predicate;
public class AppPairIcon extends FrameLayout implements DraggableView, Reorderable {
private static final String TAG = "AppPairIcon";
// The duration of the scaling animation on hover enter/exit.
private static final int HOVER_SCALE_DURATION = 150;
// The default scale of the icon when not hovered.
private static final Float HOVER_SCALE_DEFAULT = 1f;
// The max scale of the icon when hovered.
private static final Float HOVER_SCALE_MAX = 1.1f;
// Animates the scale of the icon background on hover.
private static final FloatProperty<AppPairIcon> HOVER_SCALE_PROPERTY =
new FloatProperty<>("hoverScale") {
@Override
public void setValue(AppPairIcon view, float scale) {
view.mIconGraphic.setHoverScale(scale);
}
@Override
public Float get(AppPairIcon view) {
return view.mIconGraphic.getHoverScale();
}
};
// A view that holds the app pair icon graphic.
private AppPairIconGraphic mIconGraphic;
// A view that holds the app pair's title.
@@ -272,14 +250,4 @@ public class AppPairIcon extends FrameLayout implements DraggableView, Reorderab
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public void onHoverChanged(boolean hovered) {
super.onHoverChanged(hovered);
ObjectAnimator
.ofFloat(this, HOVER_SCALE_PROPERTY,
hovered ? HOVER_SCALE_MAX : HOVER_SCALE_DEFAULT)
.setDuration(HOVER_SCALE_DURATION)
.start();
}
}
@@ -26,7 +26,6 @@ import android.os.Build;
import androidx.annotation.NonNull;
import com.android.launcher3.Utilities;
import com.android.launcher3.icons.FastBitmapDrawable;
/**
@@ -129,18 +128,6 @@ public class AppPairIconDrawable extends Drawable {
height - (mP.getStandardIconPadding() + mP.getOuterPadding())
);
// Scale each background from its center edge closest to the center channel.
Utilities.scaleRectFAboutPivot(
leftSide,
leftSide.left + leftSide.width(),
leftSide.top + leftSide.centerY(),
mP.getHoverScale());
Utilities.scaleRectFAboutPivot(
rightSide,
rightSide.left,
rightSide.top + rightSide.centerY(),
mP.getHoverScale());
drawCustomRoundedRect(canvas, leftSide, new float[]{
mP.getBigRadius(), mP.getBigRadius(),
mP.getSmallRadius(), mP.getSmallRadius(),
@@ -176,18 +163,6 @@ public class AppPairIconDrawable extends Drawable {
height - (mP.getStandardIconPadding() + mP.getOuterPadding())
);
// Scale each background from its center edge closest to the center channel.
Utilities.scaleRectFAboutPivot(
topSide,
topSide.left + topSide.centerX(),
topSide.top + topSide.height(),
mP.getHoverScale());
Utilities.scaleRectFAboutPivot(
bottomSide,
bottomSide.left + bottomSide.centerX(),
bottomSide.top,
mP.getHoverScale());
drawCustomRoundedRect(canvas, topSide, new float[]{
mP.getBigRadius(), mP.getBigRadius(),
mP.getBigRadius(), mP.getBigRadius(),
@@ -64,8 +64,6 @@ class AppPairIconDrawingParams(val context: Context, container: Int) {
var isLeftRightSplit: Boolean = true
// The background paint color (based on container).
var bgColor: Int = 0
// The scale of the icon background while hovered.
var hoverScale: Float = 1f
init {
val activity: ActivityContext = ActivityContext.lookupContext(context)
@@ -27,6 +27,7 @@ import com.android.launcher3.DeviceProfile
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener
import com.android.launcher3.icons.BitmapInfo
import com.android.launcher3.model.data.AppPairInfo
import com.android.launcher3.util.Themes
import com.android.launcher3.views.ActivityContext
/**
@@ -45,11 +46,12 @@ constructor(context: Context, attrs: AttributeSet? = null) :
@JvmStatic
fun composeDrawable(
appPairInfo: AppPairInfo,
p: AppPairIconDrawingParams,
p: AppPairIconDrawingParams
): AppPairIconDrawable {
// Generate new icons, using themed flag since the icon is drawn on homescreen
val appIcon1 = appPairInfo.getFirstApp().newIcon(p.context, BitmapInfo.FLAG_THEMED)
val appIcon2 = appPairInfo.getSecondApp().newIcon(p.context, BitmapInfo.FLAG_THEMED)
// Generate new icons, using themed flag if needed.
val flags = if (Themes.isThemedIconEnabled(p.context)) BitmapInfo.FLAG_THEMED else 0
val appIcon1 = appPairInfo.getFirstApp().newIcon(p.context, flags)
val appIcon2 = appPairInfo.getSecondApp().newIcon(p.context, flags)
appIcon1.setBounds(0, 0, p.memberIconSize.toInt(), p.memberIconSize.toInt())
appIcon2.setBounds(0, 0, p.memberIconSize.toInt(), p.memberIconSize.toInt())
@@ -123,7 +125,7 @@ constructor(context: Context, attrs: AttributeSet? = null) :
((parentIcon.width - drawParams.backgroundSize) / 2).toInt(),
// y-coordinate in parent's coordinate system
(parentIcon.paddingTop + drawParams.standardIconPadding + drawParams.outerPadding)
.toInt(),
.toInt()
)
}
@@ -137,15 +139,4 @@ constructor(context: Context, attrs: AttributeSet? = null) :
super.dispatchDraw(canvas)
drawable.draw(canvas)
}
/** Sets the scale of the icon background while hovered. */
fun setHoverScale(scale: Float) {
drawParams.hoverScale = scale
redraw()
}
/** Gets the scale of the icon background while hovered. */
fun getHoverScale(): Float {
return drawParams.hoverScale
}
}
@@ -16,52 +16,32 @@ open class LauncherRestoreEventLogger : ResourceBasedOverride {
@Retention(AnnotationRetention.SOURCE)
@StringDef(
RestoreError.PROFILE_DELETED,
RestoreError.MISSING_INFO,
RestoreError.MISSING_WIDGET_PROVIDER,
RestoreError.OVERLAPPING_ITEM,
RestoreError.INVALID_WIDGET_SIZE,
RestoreError.INVALID_WIDGET_CONTAINER,
RestoreError.INVALID_LOCATION,
RestoreError.SHORTCUT_NOT_FOUND,
RestoreError.APP_NO_TARGET_PACKAGE,
RestoreError.APP_NO_DB_INTENT,
RestoreError.APP_NO_LAUNCH_INTENT,
RestoreError.APP_NOT_RESTORED_OR_INSTALLING,
RestoreError.APP_NOT_INSTALLED_EXTERNAL_MEDIA,
RestoreError.APP_NOT_INSTALLED,
RestoreError.WIDGETS_DISABLED,
RestoreError.PROFILE_NOT_RESTORED,
RestoreError.WIDGET_REMOVED,
RestoreError.DATABASE_FILE_NOT_RESTORED,
RestoreError.GRID_MIGRATION_FAILURE,
RestoreError.NO_SEARCH_WIDGET,
RestoreError.INVALID_WIDGET_ID,
RestoreError.OTHER_WIDGET_INFLATION_FAIL,
RestoreError.UNSPECIFIED_WIDGET_INFLATION_RESULT,
RestoreError.UNRESTORED_PENDING_WIDGET,
RestoreError.INVALID_CUSTOM_WIDGET_ID,
RestoreError.INVALID_WIDGET_ID
)
annotation class RestoreError {
companion object {
const val PROFILE_DELETED = "user_profile_deleted"
const val MISSING_INFO = "missing_information_when_loading"
const val MISSING_WIDGET_PROVIDER = "missing_widget_provider"
const val OVERLAPPING_ITEM = "overlapping_item"
const val INVALID_WIDGET_SIZE = "invalid_widget_size"
const val INVALID_WIDGET_CONTAINER = "invalid_widget_container"
const val INVALID_LOCATION = "invalid_size_or_location"
const val SHORTCUT_NOT_FOUND = "shortcut_not_found"
const val APP_NO_TARGET_PACKAGE = "app_no_target_package"
const val APP_NO_DB_INTENT = "app_no_db_intent"
const val APP_NO_LAUNCH_INTENT = "app_no_launch_intent"
const val APP_NOT_RESTORED_OR_INSTALLING = "app_not_restored_or_installed"
const val APP_NOT_INSTALLED_EXTERNAL_MEDIA = "app_not_installed_external_media"
const val APP_NOT_INSTALLED = "app_not_installed"
const val WIDGETS_DISABLED = "widgets_disabled"
const val PROFILE_NOT_RESTORED = "profile_not_restored"
const val DATABASE_FILE_NOT_RESTORED = "db_file_not_restored"
const val WIDGET_REMOVED = "widget_not_found"
const val GRID_MIGRATION_FAILURE = "grid_migration_failed"
const val NO_SEARCH_WIDGET = "no_search_widget"
const val INVALID_WIDGET_ID = "invalid_widget_id"
const val OTHER_WIDGET_INFLATION_FAIL = "other_widget_fail"
const val UNSPECIFIED_WIDGET_INFLATION_RESULT = "unspecified_widget_inflation_result"
const val UNRESTORED_PENDING_WIDGET = "unrestored_pending_widget"
const val INVALID_CUSTOM_WIDGET_ID = "invalid_custom_widget_id"
}
}
@@ -72,7 +52,7 @@ open class LauncherRestoreEventLogger : ResourceBasedOverride {
return ResourceBasedOverride.Overrides.getObject(
LauncherRestoreEventLogger::class.java,
context,
R.string.launcher_restore_event_logger_class,
R.string.launcher_restore_event_logger_class
)
}
}
@@ -137,7 +117,7 @@ open class LauncherRestoreEventLogger : ResourceBasedOverride {
open fun logFavoritesItemsRestoreFailed(
favoritesId: Int,
count: Int,
@RestoreError error: String?,
@RestoreError error: String?
) {
// no-op
}
@@ -22,6 +22,7 @@ import com.android.launcher3.CellLayout;
import com.android.launcher3.Utilities;
import com.android.launcher3.util.CellAndSpan;
import com.android.launcher3.util.GridOccupancy;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import java.util.ArrayList;
import java.util.Comparator;
@@ -29,8 +30,6 @@ import java.util.List;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
/**
* Contains the logic of a reorder.
*
@@ -133,7 +132,6 @@ public class ReorderAlgorithm {
ArrayList<View> intersectingViews = new ArrayList<>();
Rect occupiedRect = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
// Lawnchair: Widget overlap
if (PreferenceExtensionsKt.firstBlocking(mCellLayout.pref.getAllowWidgetOverlap())) {
solution.intersectingViews = new ArrayList<>(intersectingViews);
return true;
@@ -153,14 +151,16 @@ public class ReorderAlgorithm {
// and not by the views hash which is "random".
// The views are sorted twice, once for the X position and a second time for the Y position
// to ensure same order everytime.
Comparator<View> comparator = Comparator.comparing(
(View view) -> ((CellLayoutLayoutParams) view.getLayoutParams()).getCellX()
Comparator comparator = Comparator.comparing(
view -> ((CellLayoutLayoutParams) ((View) view).getLayoutParams()).getCellX()
).thenComparing(
(View view) -> ((CellLayoutLayoutParams) view.getLayoutParams()).getCellY()
view -> ((CellLayoutLayoutParams) ((View) view).getLayoutParams()).getCellY()
);
List<View> views = solution.map.keySet().stream()
.sorted(comparator)
.filter(View.class::isInstance)
.map(View.class::cast)
.collect(Collectors.toList());
views.sort(comparator);
for (View child : views) {
if (child == ignoreView) continue;
CellAndSpan c = solution.map.get(child);
@@ -3,7 +3,6 @@ package com.android.launcher3.compat;
import android.content.Context;
import android.icu.text.AlphabeticIndex;
import android.os.LocaleList;
import android.util.Log;
import androidx.annotation.NonNull;
@@ -13,9 +12,6 @@ import java.util.Locale;
public class AlphabeticIndexCompat {
// TODO(b/336947811): Set to false after root causing is done.
private static final boolean DEBUG = true;
private static final String TAG = "AlphabeticIndexCompat";
private static final String MID_DOT = "\u2219";
private final String mDefaultMiscLabel;
@@ -53,9 +49,6 @@ public class AlphabeticIndexCompat {
public String computeSectionName(@NonNull CharSequence cs) {
String s = Utilities.trim(cs);
String sectionName = mBaseIndex.getBucket(mBaseIndex.getBucketIndex(s)).getLabel();
if (DEBUG) {
Log.d(TAG, "computeSectionName: cs: " + cs + " sectionName: " + sectionName);
}
if (Utilities.trim(sectionName).isEmpty() && s.length() > 0) {
int c = s.codePointAt(0);
boolean startsWithDigit = Character.isDigit(c);
+418 -202
View File
@@ -18,232 +18,448 @@ package com.android.launcher3.config;
import static com.android.launcher3.config.FeatureFlags.BooleanFlag.DISABLED;
import static com.android.launcher3.config.FeatureFlags.BooleanFlag.ENABLED;
import static com.android.wm.shell.Flags.enableTaskbarNavbarUnification;
import static com.android.wm.shell.Flags.enableTaskbarOnPhones;
import android.content.Context;
import android.content.res.Resources;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.Utilities;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import com.android.launcher3.BuildConfig;
import com.android.launcher3.Flags;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import app.lawnchair.preferences2.PreferenceManager2;
/**
* Defines a set of flags used to control various launcher behaviors.
* <p>
* <p>All the flags should be defined here with appropriate default values.
* <p>
* All the flags should be defined here with appropriate default values.
*/
public final class FeatureFlags {
private FeatureFlags() { }
/**
* True when the build has come from Android Studio and is being used for local debugging.
* @deprecated Use {@link BuildConfig#IS_STUDIO_BUILD} directly
*/
@Deprecated
public static final boolean IS_STUDIO_BUILD = false;
/**
* Enable moving the QSB on the 0th screen of the workspace. This is not a configuration feature
* and should be modified at a project level.
* @deprecated Use {@link BuildConfig#QSB_ON_FIRST_SCREEN} directly
*/
@Deprecated
public static final boolean QSB_ON_FIRST_SCREEN = true;
/**
* Feature flag to handle define config changes dynamically instead of killing the process.
* <p>
*
* To add a new flag that can be toggled through the flags UI:
* <p>
* Declare a new ToggleableFlag below. Give it a unique key (e.g. "QSB_ON_FIRST_SCREEN"),
* and set a default value for the flag. This will be the default value on Debug builds.
* <p>
*/
// TODO(Block 6): Clean up flags
public static final BooleanFlag SECONDARY_DRAG_N_DROP_TO_PIN = getDebugFlag(270395140,
"SECONDARY_DRAG_N_DROP_TO_PIN", DISABLED,
"Enable dragging and dropping to pin apps within secondary display");
// TODO(Block 8): Clean up flags
// TODO(Block 9): Clean up flags
public static final BooleanFlag MULTI_SELECT_EDIT_MODE = getDebugFlag(270709220,
"MULTI_SELECT_EDIT_MODE", DISABLED, "Enable new multi-select edit mode "
+ "for home screen");
// TODO(Block 11): Clean up flags
public static final BooleanFlag FOLDABLE_SINGLE_PAGE = getDebugFlag(270395274,
"FOLDABLE_SINGLE_PAGE", DISABLED, "Use a single page for the workspace");
// TODO(Block 12): Clean up flags
public static final BooleanFlag ENABLE_MULTI_INSTANCE = getDebugFlag(270396680,
"ENABLE_MULTI_INSTANCE", DISABLED,
"Enables creation and filtering of multiple task instances in overview");
// TODO(Block 13): Clean up flags
public static final BooleanFlag ENABLE_DEVICE_SEARCH_PERFORMANCE_LOGGING = getReleaseFlag(
270391397, "ENABLE_DEVICE_SEARCH_PERFORMANCE_LOGGING", DISABLED,
"Allows on device search in all apps logging");
// TODO(Block 14): Cleanup flags
public static final BooleanFlag NOTIFY_CRASHES = getDebugFlag(270393108, "NOTIFY_CRASHES",
DISABLED, "Sends a notification whenever launcher encounters an uncaught exception.");
public static final boolean ENABLE_TASKBAR_NAVBAR_UNIFICATION =
enableTaskbarNavbarUnification() && (!isPhone() || enableTaskbarOnPhones());
private static boolean isPhone() {
final boolean isPhone;
int foldedDeviceStatesId = Resources.getSystem().getIdentifier(
"config_foldedDeviceStates", "array", "android");
if (foldedDeviceStatesId != 0) {
isPhone = Resources.getSystem().getIntArray(foldedDeviceStatesId).length == 0;
} else {
isPhone = true;
private FeatureFlags() {
}
return isPhone;
}
// Aconfig migration complete for ENABLE_TASKBAR_NO_RECREATION.
public static final BooleanFlag ENABLE_TASKBAR_NO_RECREATION = getDebugFlag(299193589,
"ENABLE_TASKBAR_NO_RECREATION", DISABLED,
"Enables taskbar with no recreation from lifecycle changes of TaskbarActivityContext.");
public static boolean enableTaskbarNoRecreate() {
return ENABLE_TASKBAR_NO_RECREATION.get() || Flags.enableTaskbarNoRecreate()
public static boolean showFlagTogglerUi(Context context) {
return Utilities.isDevelopersOptionsEnabled(context);
}
/**
* True when the build has come from Android Studio and is being used for local
* debugging.
*
* @deprecated Use {@link BuildConfig#IS_STUDIO_BUILD} directly
*/
@Deprecated
public static final boolean IS_STUDIO_BUILD = false;
/**
* Enable moving the QSB on the 0th screen of the workspace. This is not a
* configuration feature
* and should be modified at a project level.
*
* @deprecated Use {@link BuildConfig#QSB_ON_FIRST_SCREEN} directly
*/
@Deprecated
public static boolean topQsbOnFirstScreenEnabled(Context context) {
PreferenceManager2 preferenceManager2 = PreferenceManager2.getInstance(context);
return PreferenceExtensionsKt.firstBlocking(preferenceManager2.getEnableSmartspace());
}
public static boolean showDotPagination(Context context) {
PreferenceManager2 preferenceManager2 = PreferenceManager2.getInstance(context);
return PreferenceExtensionsKt.firstBlocking(preferenceManager2.getEnableDotPagination());
}
public static boolean showMaterialUPopup(Context context) {
PreferenceManager2 preferenceManager2 = PreferenceManager2.getInstance(context);
return PreferenceExtensionsKt.firstBlocking(preferenceManager2.getEnableMaterialUPopUp());
}
public static boolean twoLineAllApps(Context context) {
PreferenceManager2 preferenceManager2 = PreferenceManager2.getInstance(context);
return PreferenceExtensionsKt.firstBlocking(preferenceManager2.getTwoLineAllApps());
}
/**
* Feature flag to handle define config changes dynamically instead of killing
* the process.
* <p>
*
* To add a new flag that can be toggled through the flags UI:
* <p>
* Declare a new ToggleableFlag below. Give it a unique key (e.g.
* "QSB_ON_FIRST_SCREEN"),
* and set a default value for the flag. This will be the default value on Debug
* builds.
* <p>
*/
// TODO(Block 1): Clean up flags
public static final BooleanFlag ENABLE_ONE_SEARCH_MOTION = getReleaseFlag(270394223,
"ENABLE_ONE_SEARCH_MOTION", ENABLED, "Enables animations in OneSearch.");
public static final BooleanFlag ENABLE_SEARCH_RESULT_BACKGROUND_DRAWABLES = getReleaseFlag(
270394041, "ENABLE_SEARCH_RESULT_BACKGROUND_DRAWABLES", ENABLED,
"Enable option to replace decorator-based search result backgrounds with drawables");
public static final BooleanFlag ENABLE_SEARCH_RESULT_LAUNCH_TRANSITION = getReleaseFlag(
270394392, "ENABLE_SEARCH_RESULT_LAUNCH_TRANSITION", ENABLED,
"Enable option to launch search results using the new view container transitions");
// TODO(Block 2): Clean up flags
public static final BooleanFlag ENABLE_MULTI_DISPLAY_PARTIAL_DEPTH = getDebugFlag(270395073,
"ENABLE_MULTI_DISPLAY_PARTIAL_DEPTH", DISABLED,
"Allow bottom sheet depth to be smaller than 1 for multi-display devices.");
// TODO(Block 3): Clean up flags
public static final BooleanFlag ENABLE_DISMISS_PREDICTION_UNDO = getDebugFlag(270394476,
"ENABLE_DISMISS_PREDICTION_UNDO", DISABLED,
"Show an 'Undo' snackbar when users dismiss a predicted hotseat item");
public static final BooleanFlag CONTINUOUS_VIEW_TREE_CAPTURE = getDebugFlag(270395171,
"CONTINUOUS_VIEW_TREE_CAPTURE", DISABLED, "Capture View tree every frame");
public static final BooleanFlag ENABLE_WORKSPACE_LOADING_OPTIMIZATION = getDebugFlag(251502424,
"ENABLE_WORKSPACE_LOADING_OPTIMIZATION", DISABLED,
"load the current workspace screen visible to the user before the rest rather than "
+ "loading all of them at once.");
public static final BooleanFlag CHANGE_MODEL_DELEGATE_LOADING_ORDER = getDebugFlag(251502424,
"CHANGE_MODEL_DELEGATE_LOADING_ORDER", ENABLED,
"changes the timing of the loading and binding of delegate items during "
+ "data preparation for loading the home screen");
// TODO(Block 4): Cleanup flags
public static final BooleanFlag ENABLE_FLOATING_SEARCH_BAR = getReleaseFlag(268388460,
"ENABLE_FLOATING_SEARCH_BAR", DISABLED,
"Allow search bar to persist and animate across states, and attach to"
+ " the keyboard from the bottom of the screen");
public static final BooleanFlag ENABLE_ALL_APPS_FROM_OVERVIEW = getDebugFlag(275132633,
"ENABLE_ALL_APPS_FROM_OVERVIEW", DISABLED,
"Allow entering All Apps from Overview (e.g. long swipe up from app)");
public static final BooleanFlag ENABLE_SHOW_KEYBOARD_OPTION_IN_ALL_APPS = getReleaseFlag(
270394468, "ENABLE_SHOW_KEYBOARD_OPTION_IN_ALL_APPS", ENABLED,
"Enable option to show keyboard when going to all-apps");
// TODO(Block 5): Clean up flags
public static final BooleanFlag ENABLE_TWOLINE_DEVICESEARCH = getDebugFlag(201388851,
"ENABLE_TWOLINE_DEVICESEARCH", DISABLED,
"Enable two line label for icons with labels on device search.");
public static final BooleanFlag ENABLE_ICON_IN_TEXT_HEADER = getDebugFlag(270395143,
"ENABLE_ICON_IN_TEXT_HEADER", DISABLED, "Show icon in textheader");
public static final BooleanFlag ENABLE_PREMIUM_HAPTICS_ALL_APPS = getDebugFlag(270396358,
"ENABLE_PREMIUM_HAPTICS_ALL_APPS", DISABLED,
"Enables haptics opening/closing All apps");
// TODO(Block 6): Clean up flags
public static final BooleanFlag ENABLE_ALL_APPS_SEARCH_IN_TASKBAR = getDebugFlag(270393900,
"ENABLE_ALL_APPS_SEARCH_IN_TASKBAR", ENABLED,
"Enables Search box in Taskbar All Apps.");
public static final BooleanFlag SECONDARY_DRAG_N_DROP_TO_PIN = getDebugFlag(270395140,
"SECONDARY_DRAG_N_DROP_TO_PIN", DISABLED,
"Enable dragging and dropping to pin apps within secondary display");
// TODO(Block 8): Clean up flags
// TODO(Block 9): Clean up flags
public static final BooleanFlag MULTI_SELECT_EDIT_MODE = getDebugFlag(270709220,
"MULTI_SELECT_EDIT_MODE", DISABLED, "Enable new multi-select edit mode "
+ "for home screen");
// TODO(Block 11): Clean up flags
public static final BooleanFlag ENABLE_TWO_PANEL_HOME = getDebugFlag(270392643,
"ENABLE_TWO_PANEL_HOME", ENABLED,
"Uses two panel on home screen. Only applicable on large screen devices.");
public static final BooleanFlag FOLDABLE_WORKSPACE_REORDER = getDebugFlag(270395070,
"FOLDABLE_WORKSPACE_REORDER", DISABLED,
"In foldables, when reordering the icons and widgets, is now going to use both sides");
public static final BooleanFlag FOLDABLE_SINGLE_PAGE = getDebugFlag(270395274,
"FOLDABLE_SINGLE_PAGE", DISABLED, "Use a single page for the workspace");
public static final BooleanFlag ENABLE_PARAMETRIZE_REORDER = getDebugFlag(289420844,
"ENABLE_PARAMETRIZE_REORDER", DISABLED,
"Enables generating the reorder using a set of parameters");
// TODO(Block 12): Clean up flags
public static final BooleanFlag ENABLE_MULTI_INSTANCE = getDebugFlag(270396680,
"ENABLE_MULTI_INSTANCE", DISABLED,
"Enables creation and filtering of multiple task instances in overview");
// TODO(Block 13): Clean up flags
public static final BooleanFlag ENABLE_DEVICE_SEARCH_PERFORMANCE_LOGGING = getReleaseFlag(
270391397, "ENABLE_DEVICE_SEARCH_PERFORMANCE_LOGGING", DISABLED,
"Allows on device search in all apps logging");
// TODO(Block 14): Cleanup flags
public static final BooleanFlag NOTIFY_CRASHES = getDebugFlag(270393108, "NOTIFY_CRASHES",
DISABLED, "Sends a notification whenever launcher encounters an uncaught exception.");
public static final boolean ENABLE_TASKBAR_NAVBAR_UNIFICATION = !isPhone();
private static boolean isPhone() {
final boolean isPhone;
int foldedDeviceStatesId = Resources.getSystem().getIdentifier(
"config_foldedDeviceStates", "array", "android");
if (foldedDeviceStatesId != 0) {
isPhone = Resources.getSystem().getIntArray(foldedDeviceStatesId).length == 0;
} else {
isPhone = true;
}
return isPhone;
}
// Aconfig migration complete for ENABLE_TASKBAR_NO_RECREATION.
public static final BooleanFlag ENABLE_TASKBAR_NO_RECREATION = getDebugFlag(299193589,
"ENABLE_TASKBAR_NO_RECREATION", DISABLED,
"Enables taskbar with no recreation from lifecycle changes of TaskbarActivityContext.");
public static boolean enableTaskbarNoRecreate() {
return ENABLE_TASKBAR_NO_RECREATION.get() || Flags.enableTaskbarNoRecreate()
// Task bar pinning and task bar nav bar unification are both dependent on
// ENABLE_TASKBAR_NO_RECREATION. We want to turn ENABLE_TASKBAR_NO_RECREATION on
// when either of the dependent features is turned on.
|| enableTaskbarPinning() || ENABLE_TASKBAR_NAVBAR_UNIFICATION;
}
// TODO(Block 16): Clean up flags
// When enabled the promise icon is visible in all apps while installation an app.
public static final BooleanFlag PROMISE_APPS_IN_ALL_APPS = getDebugFlag(270390012,
"PROMISE_APPS_IN_ALL_APPS", DISABLED, "Add promise icon in all-apps");
// Aconfig migration complete for ENABLE_EXPANDING_PAUSE_WORK_BUTTON.
public static final BooleanFlag ENABLE_EXPANDING_PAUSE_WORK_BUTTON = getDebugFlag(270390779,
"ENABLE_EXPANDING_PAUSE_WORK_BUTTON", DISABLED,
"Expand and collapse pause work button while scrolling");
public static final BooleanFlag INJECT_FALLBACK_APP_CORPUS_RESULTS = getReleaseFlag(270391706,
"INJECT_FALLBACK_APP_CORPUS_RESULTS", DISABLED,
"Inject fallback app corpus result when AiAi fails to return it.");
// TODO(Block 17): Clean up flags
// Aconfig migration complete for ENABLE_TASKBAR_PINNING.
private static final BooleanFlag ENABLE_TASKBAR_PINNING = getDebugFlag(296231746,
"ENABLE_TASKBAR_PINNING", DISABLED,
"Enables taskbar pinning to allow user to switch between transient and persistent "
+ "taskbar flavors");
public static boolean enableTaskbarPinning() {
return ENABLE_TASKBAR_PINNING.get() || Flags.enableTaskbarPinning();
}
// TODO(Block 20): Clean up flags
// Aconfig migration complete for ENABLE_HOME_TRANSITION_LISTENER.
public static final BooleanFlag ENABLE_HOME_TRANSITION_LISTENER = getDebugFlag(306053414,
"ENABLE_HOME_TRANSITION_LISTENER", DISABLED,
"Enables launcher to listen to all transitions that include home activity.");
public static boolean enableHomeTransitionListener() {
return ENABLE_HOME_TRANSITION_LISTENER.get() || Flags.enableHomeTransitionListener();
}
// TODO(Block 21): Clean up flags
public static final BooleanFlag ENABLE_APP_ICON_FOR_INLINE_SHORTCUTS = getDebugFlag(270395087,
"ENABLE_APP_ICON_IN_INLINE_SHORTCUTS", DISABLED, "Show app icon for inline shortcut");
// TODO(Block 22): Clean up flags
public static final BooleanFlag ENABLE_WIDGET_TRANSITION_FOR_RESIZING = getDebugFlag(268553314,
"ENABLE_WIDGET_TRANSITION_FOR_RESIZING", ENABLED,
"Enable widget transition animation when resizing the widgets");
// TODO(Block 27): Clean up flags
public static final BooleanFlag ENABLE_OVERLAY_CONNECTION_OPTIM = getDebugFlag(270392629,
"ENABLE_OVERLAY_CONNECTION_OPTIM", DISABLED,
"Enable optimizing overlay service connection");
/**
* Enables region sampling for text color: Needs system health assessment before turning on
*/
public static final BooleanFlag ENABLE_REGION_SAMPLING = getDebugFlag(270391669,
"ENABLE_REGION_SAMPLING", DISABLED,
"Enable region sampling to determine color of text on screen.");
public static final BooleanFlag ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS =
getDebugFlag(270393096, "ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS",
DISABLED, "Always use hardware optimization for folder animations.");
public static final BooleanFlag SEPARATE_RECENTS_ACTIVITY = getDebugFlag(270392980,
"SEPARATE_RECENTS_ACTIVITY", DISABLED,
"Uses a separate recents activity instead of using the integrated recents+Launcher UI");
public static final BooleanFlag USE_LOCAL_ICON_OVERRIDES = getDebugFlag(270394973,
"USE_LOCAL_ICON_OVERRIDES", ENABLED,
"Use inbuilt monochrome icons if app doesn't provide one");
// TODO(Block 29): Clean up flags
// Aconfig migration complete for ENABLE_ALL_APPS_BUTTON_IN_HOTSEAT.
public static final BooleanFlag ENABLE_ALL_APPS_BUTTON_IN_HOTSEAT = getDebugFlag(270393897,
"ENABLE_ALL_APPS_BUTTON_IN_HOTSEAT", DISABLED,
"Enables displaying the all apps button in the hotseat.");
public static boolean enableAllAppsButtonInHotseat() {
return ENABLE_ALL_APPS_BUTTON_IN_HOTSEAT.get() || Flags.enableAllAppsButtonInHotseat();
}
// TODO(Block 30): Clean up flags
public static final BooleanFlag USE_SEARCH_REQUEST_TIMEOUT_OVERRIDES = getDebugFlag(270395010,
"USE_SEARCH_REQUEST_TIMEOUT_OVERRIDES", DISABLED,
"Use local overrides for search request timeout");
// TODO(Block 31): Clean up flags
// TODO(Block 32): Clean up flags
// Aconfig migration complete for ENABLE_RESPONSIVE_WORKSPACE.
@VisibleForTesting
public static final BooleanFlag ENABLE_RESPONSIVE_WORKSPACE = getDebugFlag(241386436,
"ENABLE_RESPONSIVE_WORKSPACE", ENABLED,
"Enables new workspace grid calculations method.");
public static boolean enableResponsiveWorkspace() {
return ENABLE_RESPONSIVE_WORKSPACE.get() || Flags.enableResponsiveWorkspace();
}
public static BooleanFlag getDebugFlag(
int bugId, String key, BooleanFlag flagState, String description) {
return flagState;
}
public static BooleanFlag getReleaseFlag(
int bugId, String key, BooleanFlag flagState, String description) {
return flagState;
}
/**
* Enabled state for a flag
*/
public enum BooleanFlag {
ENABLED(true),
DISABLED(false);
private final boolean mValue;
BooleanFlag(boolean value) {
mValue = value;
|| enableTaskbarPinning() || ENABLE_TASKBAR_NAVBAR_UNIFICATION;
}
public boolean get() {
return mValue;
// TODO(Block 16): Clean up flags
// When enabled the promise icon is visible in all apps while installation an
// app.
public static final BooleanFlag PROMISE_APPS_IN_ALL_APPS = getDebugFlag(270390012,
"PROMISE_APPS_IN_ALL_APPS", DISABLED, "Add promise icon in all-apps");
public static final BooleanFlag KEYGUARD_ANIMATION = getDebugFlag(270390904,
"KEYGUARD_ANIMATION", DISABLED,
"Enable animation for keyguard going away on wallpaper");
public static final BooleanFlag ENABLE_DEVICE_SEARCH = getReleaseFlag(270390907,
"ENABLE_DEVICE_SEARCH", ENABLED, "Allows on device search in all apps");
public static final BooleanFlag ENABLE_HIDE_HEADER = getReleaseFlag(270390930,
"ENABLE_HIDE_HEADER", ENABLED, "Hide header on keyboard before typing in all apps");
// Aconfig migration complete for ENABLE_EXPANDING_PAUSE_WORK_BUTTON.
public static final BooleanFlag ENABLE_EXPANDING_PAUSE_WORK_BUTTON = getDebugFlag(270390779,
"ENABLE_EXPANDING_PAUSE_WORK_BUTTON", DISABLED,
"Expand and collapse pause work button while scrolling");
// Aconfig migration complete for ENABLE_TWOLINE_ALLAPPS.
public static final BooleanFlag ENABLE_TWOLINE_ALLAPPS = getDebugFlag(270390937,
"ENABLE_TWOLINE_ALLAPPS", DISABLED, "Enables two line label inside all apps.");
public static final BooleanFlag IME_STICKY_SNACKBAR_EDU = getDebugFlag(270391693,
"IME_STICKY_SNACKBAR_EDU", ENABLED, "Show sticky IME edu in AllApps");
public static final BooleanFlag FOLDER_NAME_MAJORITY_RANKING = getDebugFlag(270391638,
"FOLDER_NAME_MAJORITY_RANKING", ENABLED,
"Suggests folder names based on majority based ranking.");
public static final BooleanFlag INJECT_FALLBACK_APP_CORPUS_RESULTS = getReleaseFlag(270391706,
"INJECT_FALLBACK_APP_CORPUS_RESULTS", DISABLED,
"Inject fallback app corpus result when AiAi fails to return it.");
// TODO(Block 17): Clean up flags
// Aconfig migration complete for ENABLE_TASKBAR_PINNING.
private static final BooleanFlag ENABLE_TASKBAR_PINNING = getDebugFlag(296231746,
"ENABLE_TASKBAR_PINNING", DISABLED,
"Enables taskbar pinning to allow user to switch between transient and persistent "
+ "taskbar flavors");
// TODO(Block 18): Clean up flags
public static final BooleanFlag ENABLE_LAUNCH_FROM_STAGED_APP = getDebugFlag(270395567,
"ENABLE_LAUNCH_FROM_STAGED_APP", ENABLED,
"Enable the ability to tap a staged app during split select to launch it in full "
+ "screen");
public static boolean enableTaskbarPinning() {
return ENABLE_TASKBAR_PINNING.get() || Flags.enableTaskbarPinning();
}
// Aconfig migration complete for ENABLE_APP_PAIRS.
public static final BooleanFlag ENABLE_APP_PAIRS = getDebugFlag(274189428,
"ENABLE_APP_PAIRS", DISABLED,
"Enables the ability to create and save app pairs on the Home screen for easy"
+ " split screen launching.");
public static boolean enableAppPairs() {
return ENABLE_APP_PAIRS.get() || com.android.wm.shell.Flags.enableAppPairs();
}
// TODO(Block 19): Clean up flags
public static final BooleanFlag SCROLL_TOP_TO_RESET = getReleaseFlag(270395177,
"SCROLL_TOP_TO_RESET", ENABLED,
"Bring up IME and focus on input when scroll to top if 'Always show keyboard'"
+ " is enabled or in prefix state");
public static final BooleanFlag ENABLE_SEARCH_UNINSTALLED_APPS = getReleaseFlag(270395269,
"ENABLE_SEARCH_UNINSTALLED_APPS", ENABLED, "Search uninstalled app results.");
// TODO(Block 20): Clean up flags
public static final BooleanFlag ENABLE_SCRIM_FOR_APP_LAUNCH = getDebugFlag(270393276,
"ENABLE_SCRIM_FOR_APP_LAUNCH", DISABLED, "Enables scrim during app launch animation.");
public static final BooleanFlag ENABLE_BACK_SWIPE_HOME_ANIMATION = getDebugFlag(270393426,
"ENABLE_BACK_SWIPE_HOME_ANIMATION", ENABLED,
"Enables home animation to icon when user swipes back.");
public static final BooleanFlag ENABLE_DYNAMIC_TASKBAR_THRESHOLDS = getDebugFlag(294252473,
"ENABLE_DYNAMIC_TASKBAR_THRESHOLDS", ENABLED,
"Enables taskbar thresholds that scale based on screen size.");
// Aconfig migration complete for ENABLE_HOME_TRANSITION_LISTENER.
public static final BooleanFlag ENABLE_HOME_TRANSITION_LISTENER = getDebugFlag(306053414,
"ENABLE_HOME_TRANSITION_LISTENER", DISABLED,
"Enables launcher to listen to all transitions that include home activity.");
public static boolean enableHomeTransitionListener() {
return ENABLE_HOME_TRANSITION_LISTENER.get() || Flags.enableHomeTransitionListener();
}
// TODO(Block 21): Clean up flags
public static final BooleanFlag ENABLE_APP_ICON_FOR_INLINE_SHORTCUTS = getDebugFlag(270395087,
"ENABLE_APP_ICON_IN_INLINE_SHORTCUTS", DISABLED, "Show app icon for inline shortcut");
// TODO(Block 22): Clean up flags
public static final BooleanFlag RECEIVE_UNFOLD_EVENTS_FROM_SYSUI = getDebugFlag(270397209,
"RECEIVE_UNFOLD_EVENTS_FROM_SYSUI", ENABLED,
"Enables receiving unfold animation events from sysui instead of calculating "
+ "them in launcher process using hinge sensor values.");
public static final BooleanFlag ENABLE_WIDGET_TRANSITION_FOR_RESIZING = getDebugFlag(268553314,
"ENABLE_WIDGET_TRANSITION_FOR_RESIZING", ENABLED,
"Enable widget transition animation when resizing the widgets");
public static final BooleanFlag PREEMPTIVE_UNFOLD_ANIMATION_START = getDebugFlag(270397209,
"PREEMPTIVE_UNFOLD_ANIMATION_START", ENABLED,
"Enables starting the unfold animation preemptively when unfolding, without"
+ "waiting for SystemUI and then merging the SystemUI progress whenever we "
+ "start receiving the events");
// TODO(Block 25): Clean up flags
public static final BooleanFlag ENABLE_NEW_GESTURE_NAV_TUTORIAL = getDebugFlag(270396257,
"ENABLE_NEW_GESTURE_NAV_TUTORIAL", ENABLED,
"Enable the redesigned gesture navigation tutorial");
// TODO(Block 26): Clean up flags
public static final BooleanFlag ENABLE_WIDGET_HOST_IN_BACKGROUND = getDebugFlag(270394384,
"ENABLE_WIDGET_HOST_IN_BACKGROUND", ENABLED,
"Enable background widget updates listening for widget holder");
// TODO(Block 27): Clean up flags
public static final BooleanFlag ENABLE_OVERLAY_CONNECTION_OPTIM = getDebugFlag(270392629,
"ENABLE_OVERLAY_CONNECTION_OPTIM", DISABLED,
"Enable optimizing overlay service connection");
/**
* Enables region sampling for text color: Needs system health assessment before
* turning on
*/
public static final BooleanFlag ENABLE_REGION_SAMPLING = getDebugFlag(270391669,
"ENABLE_REGION_SAMPLING", DISABLED,
"Enable region sampling to determine color of text on screen.");
public static final BooleanFlag ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS = getDebugFlag(270393096,
"ALWAYS_USE_HARDWARE_OPTIMIZATION_FOR_FOLDER_ANIMATIONS",
DISABLED, "Always use hardware optimization for folder animations.");
public static final BooleanFlag SEPARATE_RECENTS_ACTIVITY = getDebugFlag(270392980,
"SEPARATE_RECENTS_ACTIVITY", DISABLED,
"Uses a separate recents activity instead of using the integrated recents+Launcher UI");
public static final BooleanFlag ENABLE_ENFORCED_ROUNDED_CORNERS = getReleaseFlag(270393258,
"ENABLE_ENFORCED_ROUNDED_CORNERS", ENABLED,
"Enforce rounded corners on all App Widgets");
public static final BooleanFlag USE_LOCAL_ICON_OVERRIDES = getDebugFlag(270394973,
"USE_LOCAL_ICON_OVERRIDES", ENABLED,
"Use inbuilt monochrome icons if app doesn't provide one");
// Aconfig migration complete for ENABLE_SPLIT_FROM_WORKSPACE_TO_WORKSPACE.
public static final BooleanFlag ENABLE_SPLIT_FROM_WORKSPACE_TO_WORKSPACE = getDebugFlag(
270393453, "ENABLE_SPLIT_FROM_WORKSPACE_TO_WORKSPACE", DISABLED,
"Enable initiating split screen from workspace to workspace.");
public static boolean enableSplitContextually() {
return ENABLE_SPLIT_FROM_WORKSPACE_TO_WORKSPACE.get() ||
com.android.wm.shell.Flags.enableSplitContextual();
}
public static final BooleanFlag ENABLE_TRACKPAD_GESTURE = getDebugFlag(271010401,
"ENABLE_TRACKPAD_GESTURE", ENABLED, "Enables trackpad gesture.");
// TODO(Block 29): Clean up flags
public static final BooleanFlag ENABLE_ALL_APPS_BUTTON_IN_HOTSEAT = getDebugFlag(270393897,
"ENABLE_ALL_APPS_BUTTON_IN_HOTSEAT", DISABLED,
"Enables displaying the all apps button in the hotseat.");
public static final BooleanFlag ENABLE_KEYBOARD_QUICK_SWITCH = getDebugFlag(270396844,
"ENABLE_KEYBOARD_QUICK_SWITCH", ENABLED, "Enables keyboard quick switching");
public static final BooleanFlag ENABLE_KEYBOARD_TASKBAR_TOGGLE = getDebugFlag(281726846,
"ENABLE_KEYBOARD_TASKBAR_TOGGLE", ENABLED,
"Enables keyboard taskbar stash toggling");
// TODO(Block 30): Clean up flags
public static final BooleanFlag USE_SEARCH_REQUEST_TIMEOUT_OVERRIDES = getDebugFlag(270395010,
"USE_SEARCH_REQUEST_TIMEOUT_OVERRIDES", DISABLED,
"Use local overrides for search request timeout");
// TODO(Block 31)
public static final BooleanFlag ENABLE_SPLIT_LAUNCH_DATA_REFACTOR = getDebugFlag(279494325,
"ENABLE_SPLIT_LAUNCH_DATA_REFACTOR", DISABLED,
"Use refactored split launching code path");
// TODO(Block 32): Empty block
// TODO(Block 32): Clean up flags
// Aconfig migration complete for ENABLE_RESPONSIVE_WORKSPACE.
@VisibleForTesting
public static final BooleanFlag ENABLE_RESPONSIVE_WORKSPACE = getDebugFlag(241386436,
"ENABLE_RESPONSIVE_WORKSPACE", ENABLED,
"Enables new workspace grid calculations method.");
public static boolean enableResponsiveWorkspace() {
return ENABLE_RESPONSIVE_WORKSPACE.get() || Flags.enableResponsiveWorkspace();
}
// TODO(Block 33): Clean up flags
public static final BooleanFlag ENABLE_ALL_APPS_RV_PREINFLATION = getDebugFlag(288161355,
"ENABLE_ALL_APPS_RV_PREINFLATION", ENABLED,
"Enables preinflating all apps icons to avoid scrolling jank.");
public static final BooleanFlag ALL_APPS_GONE_VISIBILITY = getDebugFlag(291651514,
"ALL_APPS_GONE_VISIBILITY", ENABLED,
"Set all apps container view's hidden visibility to GONE instead of INVISIBLE.");
public static BooleanFlag getDebugFlag(
int bugId, String key, BooleanFlag flagState, String description) {
return flagState;
}
public static BooleanFlag getReleaseFlag(
int bugId, String key, BooleanFlag flagState, String description) {
return flagState;
}
/**
* Enabled state for a flag
*/
public enum BooleanFlag {
ENABLED(true),
DISABLED(false);
private final boolean mValue;
BooleanFlag(boolean value) {
mValue = value;
}
public boolean get() {
return mValue;
}
}
}
}
@@ -30,10 +30,6 @@ public class FolderDotInfo extends DotInfo {
private int mNumNotifications;
public void reset() {
mNumNotifications = 0;
}
public void addDotInfo(DotInfo dotToAdd) {
if (dotToAdd == null) {
return;
@@ -43,6 +39,15 @@ public class FolderDotInfo extends DotInfo {
mNumNotifications, MIN_COUNT, DotInfo.MAX_COUNT);
}
public void subtractDotInfo(DotInfo dotToSubtract) {
if (dotToSubtract == null) {
return;
}
mNumNotifications -= dotToSubtract.getNotificationKeys().size();
mNumNotifications = Utilities.boundToRange(
mNumNotifications, MIN_COUNT, DotInfo.MAX_COUNT);
}
@Override
public int getNotificationCount() {
return mNumNotifications;
@@ -68,7 +68,7 @@ import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.PackageItemInfo;
import com.android.launcher3.pm.PinRequestHelper;
import com.android.launcher3.util.ApiWrapper;
import com.android.launcher3.util.ApplicationInfoWrapper;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.SystemUiController;
import com.android.launcher3.views.AbstractSlideInView;
import com.android.launcher3.views.BaseDragLayer;
@@ -164,8 +164,8 @@ public class AddItemActivity extends BaseActivity
finish();
return;
}
ApplicationInfo info = new ApplicationInfoWrapper(
this, targetApp.packageName, targetApp.user).getInfo();
ApplicationInfo info = PackageManagerHelper.INSTANCE.get(this)
.getApplicationInfo(targetApp.packageName, targetApp.user, 0);
if (info == null) {
finish();
return;
@@ -281,7 +281,7 @@ public class AddItemActivity extends BaseActivity
new PinShortcutRequestActivityInfo(mRequest, this);
mWidgetCell.getWidgetView().setTag(new PendingAddShortcutInfo(shortcutInfo));
applyWidgetItemAsync(
() -> new WidgetItem(shortcutInfo, mApp.getIconCache()));
() -> new WidgetItem(shortcutInfo, mApp.getIconCache(), getPackageManager()));
return new PackageItemInfo(mRequest.getShortcutInfo().getPackage(),
mRequest.getShortcutInfo().getUserHandle());
}
@@ -34,7 +34,7 @@ import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.DragSource;
import com.android.launcher3.DropTarget.DragObject;
import com.android.launcher3.Launcher;
import com.android.launcher3.util.ContextTracker.SchedulerCallback;
import com.android.launcher3.util.ActivityTracker.SchedulerCallback;
import com.android.launcher3.widget.PendingItemDragHelper;
import java.util.UUID;
@@ -74,9 +74,9 @@ public abstract class BaseItemDragListener implements View.OnDragListener, DragS
}
@Override
public boolean init(Launcher launcher, boolean isHomeStarted) {
AbstractFloatingView.closeAllOpenViews(launcher, /* animate= */ isHomeStarted);
launcher.getStateManager().goToState(NORMAL, /* animated= */ isHomeStarted);
public boolean init(Launcher launcher, boolean alreadyOnHome) {
AbstractFloatingView.closeAllOpenViews(launcher, alreadyOnHome);
launcher.getStateManager().goToState(NORMAL, alreadyOnHome /* animated */);
launcher.getDragLayer().setOnDragListener(this);
launcher.getRotationHelper().setStateHandlerRequest(REQUEST_LOCK);
@@ -16,7 +16,6 @@
package com.android.launcher3.dragndrop;
import static com.android.launcher3.Flags.removeAppsRefreshOnRightClick;
import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_NOT_PINNABLE;
import android.graphics.Point;
@@ -28,7 +27,6 @@ import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.android.app.animation.Interpolators;
import com.android.launcher3.DeleteDropTarget;
@@ -79,9 +77,8 @@ public abstract class DragController<T extends ActivityContext>
*/
protected DragDriver mDragDriver = null;
@VisibleForTesting
/** Options controlling the drag behavior. */
public DragOptions mOptions;
protected DragOptions mOptions;
/** Coordinate for motion down event */
protected final Point mMotionDown = new Point();
@@ -90,8 +87,7 @@ public abstract class DragController<T extends ActivityContext>
protected final Point mTmpPoint = new Point();
@VisibleForTesting
public DropTarget.DragObject mDragObject;
protected DropTarget.DragObject mDragObject;
/** Who can receive drop events */
private final ArrayList<DropTarget> mDropTargets = new ArrayList<>();
@@ -537,21 +533,17 @@ public abstract class DragController<T extends ActivityContext>
mDragObject.dragComplete = true;
if (mIsInPreDrag) {
if (removeAppsRefreshOnRightClick()) {
mDragObject.cancelled = true;
} else {
if (dropTarget != null) {
dropTarget.onDragExit(mDragObject);
}
return;
if (dropTarget != null) {
dropTarget.onDragExit(mDragObject);
}
return;
}
// Drop onto the target.
boolean accepted = false;
if (dropTarget != null) {
dropTarget.onDragExit(mDragObject);
if (!mIsInPreDrag && dropTarget.acceptDrop(mDragObject)) {
if (dropTarget.acceptDrop(mDragObject)) {
if (flingAnimation != null) {
flingAnimation.run();
} else {
@@ -563,10 +555,9 @@ public abstract class DragController<T extends ActivityContext>
cancelDrag();
}
}
final View dropTargetAsView = dropTarget.getDropView();
dispatchDropComplete(dropTargetAsView, accepted);
}
final View dropTargetAsView = dropTarget instanceof View ? (View) dropTarget : null;
dispatchDropComplete(dropTargetAsView, accepted);
}
private boolean isNeedCancelDrag(ItemInfo item){
@@ -588,7 +579,7 @@ public abstract class DragController<T extends ActivityContext>
target.getHitRectRelativeToDragLayer(r);
if (r.contains(x, y)) {
mActivity.getDragLayer().mapCoordInSelfToDescendant(target.getDropView(),
mActivity.getDragLayer().mapCoordInSelfToDescendant((View) target,
mCoordinatesTemp);
mDragObject.x = mCoordinatesTemp[0];
mDragObject.y = mCoordinatesTemp[1];
@@ -50,7 +50,6 @@ import com.android.launcher3.DropTargetBar;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.ShortcutAndWidgetContainer;
import com.android.launcher3.ShortcutAndWidgetContainer.TranslationProvider;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.anim.PendingAnimation;
@@ -70,9 +69,7 @@ import java.util.ArrayList;
public class DragLayer extends BaseDragLayer<Launcher> implements LauncherOverlayCallbacks {
public static final int ALPHA_INDEX_OVERLAY = 0;
public static final int ALPHA_INDEX_LOADER = 1;
private static final int ALPHA_CHANNEL_COUNT = 2;
private static final int ALPHA_CHANNEL_COUNT = 1;
public static final int ANIMATION_END_DISAPPEAR = 0;
public static final int ANIMATION_END_REMAIN_VISIBLE = 2;
@@ -124,7 +121,7 @@ public class DragLayer extends BaseDragLayer<Launcher> implements LauncherOverla
@Override
public void recreateControllers() {
mControllers = mContainer.createTouchControllers();
mControllers = mActivity.createTouchControllers();
}
public ViewGroupFocusHelper getFocusIndicatorHelper() {
@@ -137,15 +134,15 @@ public class DragLayer extends BaseDragLayer<Launcher> implements LauncherOverla
}
private boolean isEventOverAccessibleDropTargetBar(MotionEvent ev) {
return isInAccessibleDrag() && isEventOverView(mContainer.getDropTargetBar(), ev);
return isInAccessibleDrag() && isEventOverView(mActivity.getDropTargetBar(), ev);
}
@Override
public boolean onInterceptHoverEvent(MotionEvent ev) {
if (mContainer == null || mContainer.getWorkspace() == null) {
if (mActivity == null || mActivity.getWorkspace() == null) {
return false;
}
AbstractFloatingView topView = AbstractFloatingView.getTopOpenView(mContainer);
AbstractFloatingView topView = AbstractFloatingView.getTopOpenView(mActivity);
if (!(topView instanceof Folder)) {
return false;
} else {
@@ -160,8 +157,7 @@ public class DragLayer extends BaseDragLayer<Launcher> implements LauncherOverla
isOverFolderOrSearchBar = isEventOverView(topView, ev) ||
isEventOverAccessibleDropTargetBar(ev);
if (!isOverFolderOrSearchBar) {
sendTapOutsideFolderAccessibilityEvent(
currentFolder.getIsEditingName());
sendTapOutsideFolderAccessibilityEvent(currentFolder.getIsEditingName());
mHoverPointClosesFolder = true;
return true;
}
@@ -171,8 +167,7 @@ public class DragLayer extends BaseDragLayer<Launcher> implements LauncherOverla
isOverFolderOrSearchBar = isEventOverView(topView, ev) ||
isEventOverAccessibleDropTargetBar(ev);
if (!isOverFolderOrSearchBar && !mHoverPointClosesFolder) {
sendTapOutsideFolderAccessibilityEvent(
currentFolder.getIsEditingName());
sendTapOutsideFolderAccessibilityEvent(currentFolder.getIsEditingName());
mHoverPointClosesFolder = true;
return true;
} else if (!isOverFolderOrSearchBar) {
@@ -200,7 +195,7 @@ public class DragLayer extends BaseDragLayer<Launcher> implements LauncherOverla
private boolean isInAccessibleDrag() {
return mContainer.getAccessibilityDelegate().isInAccessibleDrag();
return mActivity.getAccessibilityDelegate().isInAccessibleDrag();
}
@Override
@@ -213,12 +208,12 @@ public class DragLayer extends BaseDragLayer<Launcher> implements LauncherOverla
@Override
public void addChildrenForAccessibility(ArrayList<View> childrenForAccessibility) {
View topView = AbstractFloatingView.getTopOpenViewWithType(mContainer,
View topView = AbstractFloatingView.getTopOpenViewWithType(mActivity,
AbstractFloatingView.TYPE_ACCESSIBLE);
if (topView != null) {
addAccessibleChildToList(topView, childrenForAccessibility);
if (isInAccessibleDrag()) {
addAccessibleChildToList(mContainer.getDropTargetBar(), childrenForAccessibility);
addAccessibleChildToList(mActivity.getDropTargetBar(), childrenForAccessibility);
}
} else {
super.addChildrenForAccessibility(childrenForAccessibility);
@@ -249,27 +244,23 @@ public class DragLayer extends BaseDragLayer<Launcher> implements LauncherOverla
public void animateViewIntoPosition(DragView dragView, final View child, int duration,
View anchorView) {
ShortcutAndWidgetContainer childParent = (ShortcutAndWidgetContainer) child.getParent();
ShortcutAndWidgetContainer parentChildren = (ShortcutAndWidgetContainer) child.getParent();
CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
childParent.measureChild(child);
childParent.layoutChild(child);
parentChildren.measureChild(child);
parentChildren.layoutChild(child);
float coord[] = new float[2];
float childScale = child.getScaleX();
coord[0] = lp.x + (child.getMeasuredWidth() * (1 - childScale) / 2);
coord[1] = lp.y + (child.getMeasuredHeight() * (1 - childScale) / 2);
TranslationProvider translationProvider = childParent.getTranslationProvider();
if (translationProvider != null) {
coord[0] = coord[0] + translationProvider.getTranslationX(lp.getCellX());
}
// Since the child hasn't necessarily been laid out, we force the lp to be updated with
// the correct coordinates (above) and use these to determine the final location
float scale = getDescendantCoordRelativeToSelf((View) child.getParent(), coord);
// We need to account for the scale of the child itself, as the above only accounts for
// the scale in parents.
// for the scale in parents.
scale *= childScale;
int toX = Math.round(coord[0]);
int toY = Math.round(coord[1]);
@@ -427,14 +418,14 @@ public class DragLayer extends BaseDragLayer<Launcher> implements LauncherOverla
public void onViewAdded(View child) {
super.onViewAdded(child);
updateChildIndices();
mContainer.onDragLayerHierarchyChanged();
mActivity.onDragLayerHierarchyChanged();
}
@Override
public void onViewRemoved(View child) {
super.onViewRemoved(child);
updateChildIndices();
mContainer.onDragLayerHierarchyChanged();
mActivity.onDragLayerHierarchyChanged();
}
@Override
@@ -60,9 +60,8 @@ import androidx.dynamicanimation.animation.SpringForce;
import com.android.app.animation.Interpolators;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.graphics.ThemeManager;
import com.android.launcher3.icons.FastBitmapDrawable;
import com.android.launcher3.icons.IconNormalizer;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.RunnableList;
import com.android.launcher3.views.ActivityContext;
@@ -120,8 +119,8 @@ public abstract class DragView<T extends Context & ActivityContext> extends Fram
private Drawable mBadge;
public DragView(T launcher, Drawable drawable, int registrationX,
int registrationY, final float initialScale, final float scaleOnDrop,
final float finalScaleDps) {
int registrationY, final float initialScale, final float scaleOnDrop,
final float finalScaleDps) {
this(launcher, getViewFromDrawable(launcher, drawable),
drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
registrationX, registrationY, initialScale, scaleOnDrop, finalScaleDps);
@@ -143,8 +142,8 @@ public abstract class DragView<T extends Context & ActivityContext> extends Fram
* @param finalScaleDps the scale used in the zoom out animation when the drag view is shown.
*/
public DragView(T activity, View content, int width, int height, int registrationX,
int registrationY, final float initialScale, final float scaleOnDrop,
final float finalScaleDps) {
int registrationY, final float initialScale, final float scaleOnDrop,
final float finalScaleDps) {
super(activity);
mActivity = activity;
mDragLayer = activity.getDragLayer();
@@ -227,6 +226,7 @@ public abstract class DragView<T extends Context & ActivityContext> extends Fram
measure(makeMeasureSpec(width, EXACTLY), makeMeasureSpec(height, EXACTLY));
mBlurSizeOutline = getResources().getDimensionPixelSize(R.dimen.blur_size_medium_outline);
setElevation(getResources().getDimension(R.dimen.drag_elevation));
setWillNotDraw(false);
}
@@ -248,12 +248,10 @@ public abstract class DragView<T extends Context & ActivityContext> extends Fram
public void setItemInfo(final ItemInfo info) {
// Load the adaptive icon on a background thread and add the view in ui thread.
MODEL_EXECUTOR.getHandler().postAtFrontOfQueue(() -> {
ThemeManager themeManager = ThemeManager.INSTANCE.get(getContext());
int w = mWidth;
int h = mHeight;
Pair<AdaptiveIconDrawable, Drawable> fullDrawable = Utilities.getFullDrawable(
mActivity, info, w, h,
themeManager.isIconThemeEnabled());
mActivity, info, w, h, true /* shouldThemeIcon */);
if (fullDrawable != null) {
AdaptiveIconDrawable adaptiveIcon = fullDrawable.first;
int blurMargin = (int) mActivity.getResources()
@@ -265,17 +263,20 @@ public abstract class DragView<T extends Context & ActivityContext> extends Fram
// be scaled down due to icon normalization.
mBadge = fullDrawable.second;
FastBitmapDrawable.setBadgeBounds(mBadge, bounds);
Utilities.scaleRectAboutCenter(bounds, IconNormalizer.ICON_VISIBLE_AREA_FACTOR);
try (LauncherIcons li = LauncherIcons.obtain(mActivity)) {
// Since we just want the scale, avoid heavy drawing operations
Utilities.scaleRectAboutCenter(bounds, li.getNormalizer().getScale(
new CustomAdaptiveIconDrawable (new ColorDrawable(Color.BLACK), null),
null, null, null));
}
// Shrink very tiny bit so that the clip path is smaller than the original bitmap
// that has anti aliased edges and shadows.
Rect shrunkBounds = new Rect(bounds);
Utilities.scaleRectAboutCenter(shrunkBounds, 0.98f);
adaptiveIcon.setBounds(shrunkBounds);
final Path mask = (adaptiveIcon instanceof FolderAdaptiveIcon
? themeManager.getFolderShape() : themeManager.getIconShape())
.getPath(shrunkBounds);
final Path mask = adaptiveIcon.getIconMask();
mTranslateX = new SpringFloatValue(DragView.this,
w * AdaptiveIconDrawable.getExtraInsetFraction());
@@ -461,7 +462,7 @@ public abstract class DragView<T extends Context & ActivityContext> extends Fram
* Animate this DragView to the given DragLayer coordinates and then remove it.
*/
public abstract void animateTo(int toTouchX, int toTouchY, Runnable onCompleteRunnable,
int duration);
int duration);
public void animateShift(final int shiftX, final int shiftY) {
if (mShiftAnim.isStarted()) return;
@@ -565,7 +566,7 @@ public abstract class DragView<T extends Context & ActivityContext> extends Fram
return mContentViewParent;
}
/** Return true if {@link #mContent} is a {@link AppWidgetHostView}. */
/** Return true if {@link mContent} is a {@link AppWidgetHostView}. */
public boolean containsAppWidgetHostView() {
return mContent instanceof AppWidgetHostView;
}
@@ -20,13 +20,9 @@ import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.Picture;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.AdaptiveIconDrawable;
@@ -35,9 +31,11 @@ import android.os.Build;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.folder.PreviewBackground;
import com.android.launcher3.graphics.IconShape;
import com.android.launcher3.graphics.ShiftedBitmapDrawable;
import com.android.launcher3.icons.BitmapRenderer;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.views.ActivityContext;
@@ -48,7 +46,7 @@ import app.lawnchair.icons.CustomAdaptiveIconDrawable;
* {@link AdaptiveIconDrawable} representation of a {@link FolderIcon}
*/
@TargetApi(Build.VERSION_CODES.O)
public class FolderAdaptiveIcon extends AdaptiveIconDrawable {
public class FolderAdaptiveIcon extends CustomAdaptiveIconDrawable {
private static final String TAG = "FolderAdaptiveIcon";
private final Drawable mBadge;
@@ -75,97 +73,85 @@ public class FolderAdaptiveIcon extends AdaptiveIconDrawable {
}
public static @Nullable FolderAdaptiveIcon createFolderAdaptiveIcon(
ActivityContext activity, int folderId, Point size) {
ActivityContext activity, int folderId, Point dragViewSize) {
Preconditions.assertNonUiThread();
// assume square
if (size.x != size.y) {
return null;
}
int requestedSize = size.x;
// Only use the size actually needed for drawing the folder icon
int drawingSize = activity.getDeviceProfile().folderIconSizePx;
int foregroundSize = Math.max(requestedSize, drawingSize);
float shift = foregroundSize - requestedSize;
Picture background = new Picture();
Picture foreground = new Picture();
Picture badge = new Picture();
Canvas bgCanvas = background.beginRecording(requestedSize, requestedSize);
Canvas badgeCanvas = badge.beginRecording(requestedSize, requestedSize);
Canvas fgCanvas = foreground.beginRecording(foregroundSize, foregroundSize);
fgCanvas.translate(shift, shift);
// Do not clip the folder drawing since the icon previews extend outside the background.
Path mask = new Path();
mask.addRect(-shift, -shift, requestedSize + shift, requestedSize + shift,
Direction.CCW);
// Initialize the actual draw commands on the UI thread to avoid race conditions with
// Create the actual drawable on the UI thread to avoid race conditions with
// FolderIcon draw pass
try {
MAIN_EXECUTOR.submit(() -> {
return MAIN_EXECUTOR.submit(() -> {
FolderIcon icon = activity.findFolderIcon(folderId);
if (icon == null) {
throw new IllegalArgumentException("Folder not found with id: " + folderId);
}
initLayersOnUiThread(icon, requestedSize, bgCanvas, fgCanvas, badgeCanvas);
return icon == null ? null : createDrawableOnUiThread(icon, dragViewSize);
}).get();
} catch (Exception e) {
Log.e(TAG, "Unable to create folder icon", e);
return null;
} finally {
background.endRecording();
foreground.endRecording();
badge.endRecording();
}
// Only convert foreground to a bitmap as it can contain multiple draw commands. Other
// layers either draw a nothing or a single draw call.
Bitmap fgBitmap = Bitmap.createBitmap(foreground);
Paint foregroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// Do not use PictureDrawable as it moves the picture to the canvas bounds, whereas we want
// to draw it at (0,0)
return new FolderAdaptiveIcon(
new BitmapRendererDrawable(c -> c.drawPicture(background)),
new BitmapRendererDrawable(
c -> c.drawBitmap(fgBitmap, -shift, -shift, foregroundPaint)),
new BitmapRendererDrawable(c -> c.drawPicture(badge)),
mask);
}
@UiThread
private static void initLayersOnUiThread(FolderIcon icon, int size,
Canvas backgroundCanvas, Canvas foregroundCanvas, Canvas badgeCanvas) {
private static FolderAdaptiveIcon createDrawableOnUiThread(FolderIcon icon,
Point dragViewSize) {
Preconditions.assertUIThread();
icon.getPreviewBounds(sTmpRect);
PreviewBackground bg = icon.getFolderBackground();
// assume square
assert (dragViewSize.x == dragViewSize.y);
final int previewSize = sTmpRect.width();
final int margin = (size - previewSize) / 2;
final int margin = (dragViewSize.x - previewSize) / 2;
final float previewShiftX = -sTmpRect.left + margin;
final float previewShiftY = -sTmpRect.top + margin;
// Initialize badge, which consists of the outline stroke, shadow and dot; these
// must be rendered above the foreground
badgeCanvas.save();
badgeCanvas.translate(previewShiftX, previewShiftY);
icon.drawDot(badgeCanvas);
badgeCanvas.restore();
Bitmap badgeBmp = BitmapRenderer.createHardwareBitmap(dragViewSize.x, dragViewSize.y,
(canvas) -> {
canvas.save();
canvas.translate(previewShiftX, previewShiftY);
bg.drawShadow(canvas);
bg.drawBackgroundStroke(canvas);
icon.drawDot(canvas);
canvas.restore();
});
// Draw foreground
foregroundCanvas.save();
foregroundCanvas.translate(previewShiftX, previewShiftY);
icon.getPreviewItemManager().draw(foregroundCanvas);
foregroundCanvas.restore();
// Initialize mask
Path mask = new Path();
Matrix m = new Matrix();
m.setTranslate(previewShiftX, previewShiftY);
bg.getClipPath().transform(m, mask);
// Draw background
backgroundCanvas.save();
backgroundCanvas.translate(previewShiftX, previewShiftY);
icon.getFolderBackground().drawBackground(backgroundCanvas);
backgroundCanvas.restore();
Bitmap previewBitmap = BitmapRenderer.createHardwareBitmap(dragViewSize.x, dragViewSize.y,
(canvas) -> {
canvas.save();
canvas.translate(previewShiftX, previewShiftY);
icon.getPreviewItemManager().draw(canvas);
canvas.restore();
});
Bitmap bgBitmap = BitmapRenderer.createHardwareBitmap(dragViewSize.x, dragViewSize.y,
(canvas) -> {
Paint p = new Paint();
p.setColor(bg.getBgColor());
Path bgPath = new Path();
int radius = bg.getRadius();
IconShape.INSTANCE.get (icon.getContext()).getShape().addToPath(
bgPath,
dragViewSize.x / 2f - radius,
dragViewSize.y / 2f - radius,
radius);
canvas.drawPath(bgPath, p);
});
ShiftedBitmapDrawable badge = new ShiftedBitmapDrawable(badgeBmp, 0, 0);
ShiftedBitmapDrawable foreground = new ShiftedBitmapDrawable(previewBitmap, 0, 0);
ShiftedBitmapDrawable background = new ShiftedBitmapDrawable(bgBitmap, 0, 0);
return new FolderAdaptiveIcon(background, foreground, badge, mask);
}
@Override
@@ -198,52 +184,4 @@ public class FolderAdaptiveIcon extends AdaptiveIconDrawable {
& mBadge.getChangingConfigurations();
}
}
private static class BitmapRendererDrawable extends Drawable {
private final BitmapRenderer mRenderer;
BitmapRendererDrawable(BitmapRenderer renderer) {
mRenderer = renderer;
}
@Override
public void draw(Canvas canvas) {
mRenderer.draw(canvas);
}
@Override
public void setAlpha(int i) { }
@Override
public void setColorFilter(ColorFilter colorFilter) { }
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public ConstantState getConstantState() {
return new MyConstantState(mRenderer);
}
private static class MyConstantState extends ConstantState {
private final BitmapRenderer mRenderer;
MyConstantState(BitmapRenderer renderer) {
mRenderer = renderer;
}
@Override
public Drawable newDrawable() {
return new BitmapRendererDrawable(mRenderer);
}
@Override
public int getChangingConfigurations() {
return 0;
}
}
}
}
@@ -15,10 +15,7 @@
*/
package com.android.launcher3.dragndrop;
import static android.view.View.VISIBLE;
import static com.android.launcher3.AbstractFloatingView.TYPE_DISCOVERY_BOUNCE;
import static com.android.launcher3.Flags.removeAppsRefreshOnRightClick;
import static com.android.launcher3.LauncherAnimUtils.SPRING_LOADED_EXIT_DELAY;
import static com.android.launcher3.LauncherState.EDIT_MODE;
import static com.android.launcher3.LauncherState.NORMAL;
@@ -28,7 +25,6 @@ import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
@@ -37,13 +33,10 @@ import androidx.annotation.VisibleForTesting;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.DragSource;
import com.android.launcher3.DropTarget;
import com.android.launcher3.DropTarget.DragObject;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.accessibility.DragViewStateAnnouncer;
import com.android.launcher3.dragndrop.DragOptions.PreDragCondition;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.TouchUtil;
import com.android.launcher3.widget.util.WidgetDragScaleUtils;
/**
@@ -54,9 +47,6 @@ public class LauncherDragController extends DragController<Launcher> {
private static final boolean PROFILE_DRAWING_DURING_DRAG = false;
private final FlingToDeleteHelper mFlingToDeleteHelper;
/** Whether or not the drag operation is triggered by mouse right click. */
private boolean mIsInMouseRightClick = false;
public LauncherDragController(Launcher launcher) {
super(launcher);
mFlingToDeleteHelper = new FlingToDeleteHelper(launcher);
@@ -79,28 +69,6 @@ public class LauncherDragController extends DragController<Launcher> {
android.os.Debug.startMethodTracing("Launcher");
}
if (removeAppsRefreshOnRightClick() && mIsInMouseRightClick
&& options.preDragCondition == null
&& originalView instanceof View v) {
options.preDragCondition = new PreDragCondition() {
@Override
public boolean shouldStartDrag(double distanceDragged) {
return false;
}
@Override
public void onPreDragStart(DragObject dragObject) {
// Set it to visible so the text of FolderIcon would not flash (avoid it from
// being invisible and then visible)
v.setVisibility(VISIBLE);
}
@Override
public void onPreDragEnd(DragObject dragObject, boolean dragStarted) { }
};
}
mActivity.hideKeyboard();
AbstractFloatingView.closeOpenViews(mActivity, false, TYPE_DISCOVERY_BOUNCE);
@@ -151,9 +119,6 @@ public class LauncherDragController extends DragController<Launcher> {
initialDragViewScale,
dragViewScaleOnDrop,
scalePx);
// During a drag, we don't want to expose the descendendants of drag view to a11y users,
// since those decendents are not a valid position in the workspace.
dragView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
dragView.setItemInfo(dragInfo);
mDragObject.dragComplete = false;
@@ -223,7 +188,7 @@ public class LauncherDragController extends DragController<Launcher> {
@Override
protected void exitDrag() {
if (!mIsInPreDrag && !mActivity.isInState(EDIT_MODE)) {
if (!mActivity.isInState(EDIT_MODE)) {
mActivity.getStateManager().goToState(NORMAL, SPRING_LOADED_EXIT_DELAY);
}
}
@@ -250,13 +215,4 @@ public class LauncherDragController extends DragController<Launcher> {
dropCoordinates);
return mActivity.getWorkspace();
}
/**
* Intercepts touch events from a drag source view.
*/
@Override
public boolean onControllerInterceptTouchEvent(MotionEvent ev) {
mIsInMouseRightClick = TouchUtil.isMouseRightClickDownOrMove(ev);
return super.onControllerInterceptTouchEvent(ev);
}
}
@@ -30,6 +30,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.LauncherApps;
import android.content.pm.LauncherApps.PinItemRequest;
import android.content.pm.PackageManager;
import android.content.pm.ShortcutInfo;
import android.graphics.drawable.Drawable;
import android.os.Build;
@@ -39,7 +40,7 @@ import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.R;
import com.android.launcher3.icons.cache.BaseIconCache;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.PinRequestHelper;
import com.android.launcher3.pm.ShortcutConfigActivityInfo;
@@ -69,8 +70,7 @@ public class PinShortcutRequestActivityInfo extends ShortcutConfigActivityInfo {
public PinShortcutRequestActivityInfo(
ShortcutInfo si, Supplier<PinItemRequest> requestSupplier, Context context) {
super(new ComponentName(si.getPackage(), STUB_COMPONENT_CLASS),
si.getUserHandle(), context);
super(new ComponentName(si.getPackage(), STUB_COMPONENT_CLASS), si.getUserHandle());
mRequestSupplier = requestSupplier;
mInfo = si;
mContext = context;
@@ -82,12 +82,12 @@ public class PinShortcutRequestActivityInfo extends ShortcutConfigActivityInfo {
}
@Override
public CharSequence getLabel() {
public CharSequence getLabel(PackageManager pm) {
return mInfo.getShortLabel();
}
@Override
public Drawable getFullResIcon(BaseIconCache cache) {
public Drawable getFullResIcon(IconCache cache) {
Drawable d = mContext.getSystemService(LauncherApps.class)
.getShortcutIconDrawable(mInfo, LauncherAppState.getIDP(mContext).fillResIconDpi);
if (d == null) {
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2010 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.dragndrop;
import com.android.launcher3.Alarm;
import com.android.launcher3.CellLayout;
import com.android.launcher3.Launcher;
import com.android.launcher3.OnAlarmListener;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
public class SpringLoadedDragController implements OnAlarmListener {
// how long the user must hover over a mini-screen before it unshrinks
private static final long ENTER_SPRING_LOAD_HOVER_TIME = 500;
private static final long ENTER_SPRING_LOAD_HOVER_TIME_IN_TEST = 2000;
private static final long ENTER_SPRING_LOAD_CANCEL_HOVER_TIME = 950;
Alarm mAlarm;
// the screen the user is currently hovering over, if any
private CellLayout mScreen;
private Launcher mLauncher;
public SpringLoadedDragController(Launcher launcher) {
mLauncher = launcher;
mAlarm = new Alarm();
mAlarm.setOnAlarmListener(this);
}
private long getEnterSpringLoadHoverTime() {
// Some TAPL tests are flaky on Cuttlefish with a low waiting time
return Utilities.isRunningInTestHarness()
? ENTER_SPRING_LOAD_HOVER_TIME_IN_TEST
: ENTER_SPRING_LOAD_HOVER_TIME;
}
public void cancel() {
mAlarm.cancelAlarm();
}
// Set a new alarm to expire for the screen that we are hovering over now
public void setAlarm(CellLayout cl) {
mAlarm.cancelAlarm();
mAlarm.setAlarm((cl == null) ? ENTER_SPRING_LOAD_CANCEL_HOVER_TIME
: getEnterSpringLoadHoverTime());
mScreen = cl;
}
// this is called when our timer runs out
public void onAlarm(Alarm alarm) {
if (mScreen != null) {
// Snap to the screen that we are hovering over now
Workspace<?> w = mLauncher.getWorkspace();
if (!w.isVisible(mScreen)) {
w.snapToPage(w.indexOfChild(mScreen));
}
} else {
mLauncher.getDragController().cancelDrag();
}
}
}
@@ -1,7 +1,5 @@
package com.android.launcher3.folder;
import com.android.launcher3.Flags;
public class ClippedFolderIconLayoutRule {
public static final int MAX_NUM_ITEMS_IN_PREVIEW = 4;
@@ -9,12 +7,9 @@ public class ClippedFolderIconLayoutRule {
private static final float MIN_SCALE = 0.44f;
private static final float MAX_SCALE = 0.51f;
// TODO: figure out exact radius for different icons
private static final float MAX_RADIUS_DILATION_SHAPES = 0.15f;
private static final float MAX_RADIUS_DILATION = 0.25f;
// The max amount of overlap the preview items can go outside of the background bounds.
public static final float ICON_OVERLAP_FACTOR = 1 + (MAX_RADIUS_DILATION / 2f);
public static final float ICON_OVERLAP_FACTOR_SHAPES = 1f;
private static final float ITEM_RADIUS_SCALE_FACTOR = 1.15f;
public static final int EXIT_INDEX = -2;
@@ -33,7 +28,7 @@ public class ClippedFolderIconLayoutRule {
mRadius = ITEM_RADIUS_SCALE_FACTOR * availableSpace / 2f;
mIconSize = intrinsicIconSize;
mIsRtl = rtl;
mBaselineIconScale = availableSpace / intrinsicIconSize;
mBaselineIconScale = availableSpace / (intrinsicIconSize * 1f);
}
public PreviewItemDrawingParams computePreviewItemDrawingParams(int index, int curNumItems,
@@ -53,20 +48,6 @@ public class ClippedFolderIconLayoutRule {
} else if (index >= MAX_NUM_ITEMS_IN_PREVIEW) {
// Items beyond those displayed in the preview are animated to the center
mTmpPoint[0] = mTmpPoint[1] = mAvailableSpace / 2 - (mIconSize * totalScale) / 2;
} else if (Flags.enableLauncherIconShapes()) {
if (index == 0) {
// top left
getGridPosition(0, 0, mTmpPoint);
} else if (index == 1) {
// top right
getGridPosition(0, 1, mTmpPoint);
} else if (index == 2) {
// bottom left
getGridPosition(1, 0, mTmpPoint);
} else if (index == 3) {
// bottom right
getGridPosition(1, 1, mTmpPoint);
}
} else {
getPosition(index, curNumItems, mTmpPoint);
}
@@ -103,7 +84,6 @@ public class ClippedFolderIconLayoutRule {
result[1] = top + (row * dy);
}
// b/392610664 TODO: Change positioning from circular geometry to square / grid-based.
private void getPosition(int index, int curNumItems, float[] result) {
// The case of two items is homomorphic to the case of one.
curNumItems = Math.max(curNumItems, 2);
@@ -133,10 +113,8 @@ public class ClippedFolderIconLayoutRule {
}
// We bump the radius up between 0 and MAX_RADIUS_DILATION % as the number of items increase
float radiusDilation = Flags.enableLauncherIconShapes() ? MAX_RADIUS_DILATION_SHAPES
: MAX_RADIUS_DILATION;
float radius = mRadius * (1 + radiusDilation * (curNumItems - MIN_NUM_ITEMS_IN_PREVIEW)
/ (MAX_NUM_ITEMS_IN_PREVIEW - MIN_NUM_ITEMS_IN_PREVIEW));
float radius = mRadius * (1 + MAX_RADIUS_DILATION * (curNumItems -
MIN_NUM_ITEMS_IN_PREVIEW) / (MAX_NUM_ITEMS_IN_PREVIEW - MIN_NUM_ITEMS_IN_PREVIEW));
double theta = theta0 + index * (2 * Math.PI / curNumItems) * direction;
float halfIconSize = (mIconSize * scaleForItem(curNumItems)) / 2;
@@ -152,7 +130,7 @@ public class ClippedFolderIconLayoutRule {
public float scaleForItem(int numItems) {
// Scale is determined by the number of items in the preview.
final float scale;
if (numItems <= 3 && !Flags.enableLauncherIconShapes()) {
if (numItems <= 3) {
scale = MAX_SCALE;
} else {
scale = MIN_SCALE;
@@ -163,15 +141,4 @@ public class ClippedFolderIconLayoutRule {
public float getIconSize() {
return mIconSize;
}
/**
* Gets correct constant for icon overlap.
*/
public static float getIconOverlapFactor() {
if (Flags.enableLauncherIconShapes()) {
return ICON_OVERLAP_FACTOR_SHAPES;
} else {
return ICON_OVERLAP_FACTOR;
}
}
}
+163 -208
View File
@@ -12,14 +12,18 @@
* 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.
*
* Modifications copyright 2021, Lawnchair
*/
package com.android.launcher3.folder;
import static android.text.TextUtils.isEmpty;
import static com.android.launcher3.Flags.enableLauncherVisualRefresh;
import static com.android.launcher3.LauncherAnimUtils.SPRING_LOADED_EXIT_DELAY;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APP_PAIR;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT;
import static com.android.launcher3.LauncherState.EDIT_MODE;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.compat.AccessibilityManagerCompat.sendCustomAccessibilityEvent;
@@ -27,7 +31,6 @@ import static com.android.launcher3.config.FeatureFlags.ALWAYS_USE_HARDWARE_OPTI
import static com.android.launcher3.folder.FolderGridOrganizer.createFolderGridOrganizer;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_LABEL_UPDATED;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ITEM_DROP_COMPLETED;
import static com.android.launcher3.model.data.FolderInfo.willAcceptItemType;
import static com.android.launcher3.testing.shared.TestProtocol.FOLDER_OPENED_MESSAGE;
import static com.android.launcher3.util.window.RefreshRateTracker.getSingleFrameMs;
@@ -65,12 +68,11 @@ import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.view.WindowInsetsCompat;
import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.Alarm;
import com.android.launcher3.CellLayout;
@@ -96,24 +98,26 @@ import com.android.launcher3.logger.LauncherAtom.ToState;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.logging.StatsLogManager.StatsLogger;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.FolderInfo.FolderListener;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemFactory;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pageindicators.PageIndicatorDots;
import com.android.launcher3.util.Executors;
import com.android.launcher3.util.LauncherBindableItemsContainer;
import com.android.launcher3.util.LauncherBindableItemsContainer.ItemOperator;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.views.ClipPathView;
import com.android.launcher3.widget.PendingAddShortcutInfo;
import com.androidinternal.graphics.ColorUtils;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
@@ -121,7 +125,6 @@ import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import app.lawnchair.preferences2.PreferenceManager2;
import app.lawnchair.theme.color.ColorOption;
import app.lawnchair.theme.color.tokens.ColorTokens;
@@ -133,9 +136,8 @@ import app.lawnchair.util.LawnchairUtilsKt;
* Represents a set of icons chosen by the user or generated by the system.
*/
public class Folder extends AbstractFloatingView implements ClipPathView, DragSource,
View.OnLongClickListener, DropTarget, TextView.OnEditorActionListener,
View.OnFocusChangeListener, DragListener, ExtendedEditText.OnBackKeyListener,
LauncherBindableItemsContainer {
View.OnLongClickListener, DropTarget, FolderListener, TextView.OnEditorActionListener,
View.OnFocusChangeListener, DragListener, ExtendedEditText.OnBackKeyListener {
private static final String TAG = "Launcher.Folder";
private static final boolean DEBUG = false;
@@ -190,6 +192,15 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
return o instanceof ItemInfo info && willAcceptItemType(info.itemType);
}
/**
* Checks if {@code itemType} is a type that can be placed in folders.
*/
public static boolean willAcceptItemType(int itemType) {
return itemType == ITEM_TYPE_APPLICATION
|| itemType == ITEM_TYPE_DEEP_SHORTCUT
|| itemType == ITEM_TYPE_APP_PAIR;
}
private Alarm mReorderAlarm = new Alarm(Looper.getMainLooper());
private Alarm mOnExitAlarm = new Alarm(Looper.getMainLooper());
private Alarm mOnScrollHintAlarm = new Alarm(Looper.getMainLooper());
@@ -229,26 +240,23 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
private Path mClipPath;
@ViewDebug.ExportedProperty(category = "launcher",
mapping = {
@ViewDebug.IntToString(from = STATE_CLOSED, to = "STATE_CLOSED"),
@ViewDebug.IntToString(from = STATE_ANIMATING, to = "STATE_ANIMATING"),
@ViewDebug.IntToString(from = STATE_OPEN, to = "STATE_OPEN"),
})
mapping = {
@ViewDebug.IntToString(from = STATE_CLOSED, to = "STATE_CLOSED"),
@ViewDebug.IntToString(from = STATE_ANIMATING, to = "STATE_ANIMATING"),
@ViewDebug.IntToString(from = STATE_OPEN, to = "STATE_OPEN"),
})
private int mState = STATE_CLOSED;
private final List<OnFolderStateChangedListener> mOnFolderStateChangedListeners =
new ArrayList<>();
new ArrayList<>();
private OnFolderStateChangedListener mPriorityOnFolderStateChangedListener;
@ViewDebug.ExportedProperty(category = "launcher")
private boolean mRearrangeOnClose = false;
boolean mItemsInvalidated = false;
private boolean mItemsInvalidated = false;
private View mCurrentDragView;
private boolean mIsExternalDrag;
private boolean mIsDragInProgress = false;
private boolean mDeleteFolderOnDropCompleted = false;
private boolean mSuppressFolderDeletion = false;
private boolean mSuppressContentUpdate = false;
private boolean mItemAddedBackToSelfViaIcon = false;
private boolean mIsEditingName = false;
@@ -268,8 +276,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Nullable
private KeyboardInsetAnimationCallback mKeyboardInsetAnimationCallback;
private @NonNull GradientDrawable mBackground;
private GradientDrawable mBackground;
PreferenceManager2 preferenceManager2;
/**
@@ -291,11 +298,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// reliable behavior when clicking the text field (since it will always gain focus on
// click).
setFocusableInTouchMode(true);
mBackground = (GradientDrawable) Objects.requireNonNull(
ResourcesCompat.getDrawable(getResources(),
R.drawable.round_rect_folder, getContext().getTheme()));
mBackground.setCallback(this);
preferenceManager2 = PreferenceManager2.INSTANCE.get(context);
}
@@ -311,7 +313,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
final int paddingLeftRight = dp.folderContentPaddingLeftRight;
mBackground = DrawableTokens.RoundRectFolder.resolve(getContext());
// TODO-Myself: this is interesting, we can customise this.
var alpha = LawnchairUtilsKt.getFolderBackgroundAlpha(getContext());
mBackground.setAlpha(alpha);
@@ -320,13 +321,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mContent.setFolder(this);
mPageIndicator = findViewById(R.id.folder_page_indicator);
if (enableLauncherVisualRefresh()) {
MarginLayoutParams params = ((MarginLayoutParams) mPageIndicator.getLayoutParams());
int horizontalMargin = getContext().getResources()
.getDimensionPixelSize(R.dimen.folder_footer_horiz_padding);
params.setMarginStart(horizontalMargin);
params.setMarginEnd(horizontalMargin);
}
mFooter = findViewById(R.id.folder_footer);
mFooterHeight = dp.folderFooterHeightPx;
mFolderName = findViewById(R.id.folder_name);
@@ -335,10 +329,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mFolderName.setOnEditorActionListener(this);
mFolderName.setSelectAllOnFocus(true);
mFolderName.setInputType(mFolderName.getInputType()
& ~InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
| InputType.TYPE_TEXT_FLAG_CAP_WORDS);
& ~InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
| InputType.TYPE_TEXT_FLAG_CAP_WORDS);
mFolderName.forceDisableSuggestions(true);
mFolderName.setPadding(mFolderName.getPaddingLeft(),
(getFooterHeight() - mFolderName.getLineHeight()) / 2,
mFolderName.getPaddingRight(),
(getFooterHeight() - mFolderName.getLineHeight()) / 2);
@ColorInt
int accentColor = Themes.getColorAccent(mFolderName.getContext());
@@ -378,11 +376,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
return true;
}
@Override
protected boolean verifyDrawable(@NonNull Drawable who) {
return super.verifyDrawable(who) || (who == mBackground);
}
void callBeginDragShared(View v, DragOptions options) {
mLauncherDelegate.beginDragShared(v, this, options);
}
@@ -393,14 +386,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
return;
}
getDragController().addDragListener(new AccessibleDragListenerAdapter(
mContent, FolderAccessibilityHelper::new) {
mContent, FolderAccessibilityHelper::new) {
@Override
protected void enableAccessibleDrag(boolean enable,
@Nullable DragObject dragObject) {
@Nullable DragObject dragObject) {
super.enableAccessibleDrag(enable, dragObject);
mFooter.setImportantForAccessibility(enable
? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
: IMPORTANT_FOR_ACCESSIBILITY_AUTO);
? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
: IMPORTANT_FOR_ACCESSIBILITY_AUTO);
}
});
}
@@ -412,7 +405,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
if (isInAppDrawer()) {
close(true);
// LC-Note: Do not remove item
// Do not remove item
return;
}
@@ -421,8 +414,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// We do not want to get events for the item being removed, as they will get handled
// when the drop completes
executeWithContentUpdateSuppressed(() -> removeFolderContent(true, dragObject.dragInfo));
try (SuppressInfoChanges s = new SuppressInfoChanges()) {
mInfo.remove(dragObject.dragInfo, true);
}
mIsDragInProgress = true;
mItemAddedBackToSelfViaIcon = false;
}
@@ -465,8 +459,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
sendCustomAccessibilityEvent(
this, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
getContext().getString(R.string.folder_renamed, newTitle));
this, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
getContext().getString(R.string.folder_renamed, newTitle));
// This ensures that focus is gained every time the field is clicked, which selects all
// the text and brings up the soft keyboard if necessary.
@@ -480,7 +474,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (DEBUG) {
Log.d(TAG, "onEditorAction actionId=" + actionId + " key="
+ (event != null ? event.getKeyCode() : "null event"));
+ (event != null ? event.getKeyCode() : "null event"));
}
if (actionId == EditorInfo.IME_ACTION_DONE) {
mFolderName.dispatchBackKey();
@@ -505,7 +499,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
}
} catch (Throwable t) {
// LC-Catch
WindowInsetsCompat insetsCompat = WindowInsetsCompat.toWindowInsetsCompat(windowInsets);
if (insetsCompat.isVisible(WindowInsetsCompat.Type.ime())) {
androidx.core.graphics.Insets keyboardInsets = insetsCompat.getInsets(WindowInsetsCompat.Type.ime());
@@ -578,6 +571,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mInfo = info;
mFromTitle = info.title;
mFromLabelState = info.getFromLabelState();
ArrayList<ItemInfo> children = info.getContents();
Collections.sort(children, ITEM_POS_COMPARATOR);
updateItemLocationsInDatabaseBatch(true);
BaseDragLayer.LayoutParams lp = (BaseDragLayer.LayoutParams) getLayoutParams();
@@ -586,17 +581,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
lp.customPosition = true;
setLayoutParams(lp);
}
reapplyItemInfo();
// In case any children didn't come across during loading, clean up the folder accordingly
mFolderIcon.post(() -> {
if (getItemCount() <= 1) {
replaceFolderWithFinalItem();
}
});
}
public void reapplyItemInfo() {
mItemsInvalidated = true;
mInfo.addListener(this);
if (!isEmpty(mInfo.title)) {
mFolderName.setText(mInfo.title);
@@ -605,8 +591,15 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mFolderName.setText("");
mFolderName.setHint(R.string.folder_hint_text);
}
// In case any children didn't come across during loading, clean up the folder accordingly
mFolderIcon.post(() -> {
if (getItemCount() <= 1 && !isInAppDrawer()) {
replaceFolderWithFinalItem();
}
});
}
/**
* Show suggested folder title in FolderEditText if the first suggestion is non-empty, push
* rest of the suggestions to InputMethodManager.
@@ -626,12 +619,12 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
mFolderName.showKeyboard();
mFolderName.displayCompletions(
Stream.of(mInfo.suggestedFolderNames.getLabels())
.filter(Objects::nonNull)
.map(Object::toString)
.filter(s -> !s.isEmpty())
.filter(s -> !s.equalsIgnoreCase(mFolderName.getText().toString()))
.collect(Collectors.toList()));
Stream.of(mInfo.suggestedFolderNames.getLabels())
.filter(Objects::nonNull)
.map(Object::toString)
.filter(s -> !s.isEmpty())
.filter(s -> !s.equalsIgnoreCase(mFolderName.getText().toString()))
.collect(Collectors.toList()));
}
}
@@ -645,12 +638,12 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@SuppressLint("InflateParams")
static <T extends Context & ActivityContext> Folder fromXml(T activityContext) {
return (Folder) LayoutInflater.from(activityContext).cloneInContext(activityContext)
.inflate(R.layout.user_folder_icon_normalized, null);
.inflate(R.layout.user_folder_icon_normalized, null);
}
private void addAnimationStartListeners(AnimatorSet a) {
mLauncherDelegate.forEachVisibleWorkspacePage(
visiblePage -> addAnimatorListenerForPage(a, (CellLayout) visiblePage));
visiblePage -> addAnimatorListenerForPage(a, (CellLayout) visiblePage));
a.addListener(new AnimatorListenerAdapter() {
@Override
@@ -736,11 +729,11 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
if (!shouldAnimateOpen(items)) {
return;
}
Folder openFolder = getOpen(mActivityContext);
closeOpenFolder(openFolder);
mContent.bindItems(items);
mContent.setCanAnnouncePageDescriptionForFolder(true);
centerAboutIcon();
mItemsInvalidated = true;
updateTextViewFocus();
@@ -756,27 +749,19 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
} else {
if (FeatureFlags.IS_STUDIO_BUILD) {
Log.e(TAG, "Opening folder (" + this + ") which already has a parent:"
+ getParent());
+ getParent());
}
}
Log.d("b/383526431", "animateOpen: content child count before: "
+ mContent.getTotalChildCount());
mContent.completePendingPageChanges();
mContent.setCurrentPage(pageNo);
Log.d("b/383526431", "animateOpen: content child count after pending page"
+ " changes: " + mContent.getTotalChildCount());
// This is set to true in close(), but isn't reset to false until onDropCompleted(). This
// leads to an inconsistent state if you drag out of the folder and drag back in without
// dropping. One resulting issue is that replaceFolderWithFinalItem() can be called twice.
mDeleteFolderOnDropCompleted = false;
cancelRunningAnimations();
Log.d("b/383526431", "animateOpen: content child count after cancelling"
+ " animation: " + mContent.getTotalChildCount());
FolderAnimationManager fam = new FolderAnimationManager(this, true /* isOpening */);
AnimatorSet anim = fam.getAnimator();
anim.addListener(new AnimatorListenerAdapter() {
@@ -791,7 +776,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
setState(STATE_OPEN);
announceAccessibilityChanges();
AccessibilityManagerCompat.sendTestProtocolEventToTest(getContext(),
FOLDER_OPENED_MESSAGE);
FOLDER_OPENED_MESSAGE);
mContent.setFocusOnFirstChild();
}
@@ -800,7 +785,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// Footer animation
if (mContent.getPageCount() > 1 && !mInfo.hasOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION)) {
int footerWidth = mContent.getDesiredWidth()
- mFooter.getPaddingLeft() - mFooter.getPaddingRight();
- mFooter.getPaddingLeft() - mFooter.getPaddingRight();
float textWidth = mFolderName.getPaint().measureText(mFolderName.getText().toString());
float translation = (footerWidth - textWidth) / 2;
@@ -816,14 +801,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public void onAnimationEnd(Animator animation) {
mFolderName.animate().setDuration(FOLDER_NAME_ANIMATION_DURATION)
.translationX(0)
.setInterpolator(AnimationUtils.loadInterpolator(
getContext(), android.R.interpolator.fast_out_slow_in));
.translationX(0)
.setInterpolator(AnimationUtils.loadInterpolator(
getContext(), android.R.interpolator.fast_out_slow_in));
mPageIndicator.playEntryAnimation();
if (updateAnimationFlag) {
mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true,
mLauncherDelegate.getModelWriter());
mLauncherDelegate.getModelWriter());
}
}
});
@@ -882,7 +867,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
protected void handleClose(boolean animate) {
mIsOpen = false;
mContent.setCanAnnouncePageDescriptionForFolder(false);
if (!animate && mCurrentAnimator != null && mCurrentAnimator.isRunning()) {
mCurrentAnimator.cancel();
@@ -906,7 +890,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
mActivityContext.getDragLayer().sendAccessibilityEvent(
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
private void cancelRunningAnimations() {
@@ -961,7 +945,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
protected Pair<View, String> getAccessibilityTarget() {
return Pair.create(mContent, mIsOpen ? mContent.getAccessibilityDescription()
: getContext().getString(R.string.folder_closed));
: getContext().getString(R.string.folder_closed));
}
@Override
@@ -997,7 +981,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mRearrangeOnClose = false;
}
if (getItemCount() <= 1) {
if (!mIsDragInProgress && !mSuppressFolderDeletion) {
if (!mIsDragInProgress && !mSuppressFolderDeletion && !isInAppDrawer()) {
replaceFolderWithFinalItem();
} else if (mIsDragInProgress) {
mDeleteFolderOnDropCompleted = true;
@@ -1013,7 +997,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public boolean acceptDrop(DragObject d) {
return willAcceptItemType(d.dragInfo.itemType);
final ItemInfo item = d.dragInfo;
final int itemType = item.itemType;
return Folder.willAcceptItemType(itemType);
}
public void onDragEnter(DragObject d) {
@@ -1038,7 +1024,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
private int getTargetRank(DragObject d, float[] recycle) {
recycle = d.getVisualCenter(recycle);
return mContent.findNearestArea(
(int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop());
(int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop());
}
@Override
@@ -1057,7 +1043,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
if (d.stateAnnouncer != null) {
d.stateAnnouncer.announce(getContext().getString(R.string.move_to_position,
mTargetRank + 1));
mTargetRank + 1));
}
}
@@ -1065,14 +1051,14 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
int currentPage = mContent.getNextPage();
float cellOverlap = mContent.getCurrentCellLayout().getCellWidth()
* ICON_OVERSCROLL_WIDTH_FACTOR;
* ICON_OVERSCROLL_WIDTH_FACTOR;
boolean isOutsideLeftEdge = x < cellOverlap;
boolean isOutsideRightEdge = x > (getWidth() - cellOverlap);
if (currentPage > 0 && (mContent.mIsRtl ? isOutsideRightEdge : isOutsideLeftEdge)) {
showScrollHint(SCROLL_LEFT, d);
} else if (currentPage < (mContent.getPageCount() - 1)
&& (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) {
&& (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) {
showScrollHint(SCROLL_RIGHT, d);
} else {
mOnScrollHintAlarm.cancelAlarm();
@@ -1110,7 +1096,6 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
public void completeDragExit() {
if (isInAppDrawer()) {
// LC: ff8c5a827b85f47a0d8ed5e6ac449ab8042705c6
return;
}
if (mIsOpen) {
@@ -1161,29 +1146,28 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public void onDropCompleted(final View target, final DragObject d,
final boolean success) {
final boolean success) {
if (success) {
if (getItemCount() <= 1) {
mDeleteFolderOnDropCompleted = true;
}
if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon
&& target != this) {
&& target != this) {
replaceFolderWithFinalItem();
}
} else {
// The drag failed, we need to return the item to the folder
ItemInfo info = d.dragInfo;
View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info)
? mCurrentDragView : mContent.createNewView(info);
? mCurrentDragView : mContent.createNewView(info);
ArrayList<View> views = getIconsInReadingOrder();
if (!views.contains(icon)) {
info.rank = Utilities.boundToRange(info.rank, 0, views.size());
views.add(info.rank, icon);
mContent.arrangeChildren(views);
mItemsInvalidated = true;
info.rank = Utilities.boundToRange(info.rank, 0, views.size());
views.add(info.rank, icon);
mContent.arrangeChildren(views);
mItemsInvalidated = true;
executeWithContentUpdateSuppressed(
() -> mFolderIcon.onDrop(d, true /* itemReturnedOnFailedDrop */));
try (SuppressInfoChanges s = new SuppressInfoChanges()) {
mFolderIcon.onDrop(d, true /* itemReturnedOnFailedDrop */);
}
}
@@ -1211,13 +1195,13 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
if (getItemCount() <= mContent.itemsPerPage()) {
// Show the animation, next time something is added to the folder.
mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, false,
mLauncherDelegate.getModelWriter());
mLauncherDelegate.getModelWriter());
}
}
private void updateItemLocationsInDatabaseBatch(boolean isBind) {
FolderGridOrganizer verifier = createFolderGridOrganizer(
mActivityContext.getDeviceProfile()).setFolderInfo(mInfo);
mActivityContext.getDeviceProfile()).setFolderInfo(mInfo);
ArrayList<ItemInfo> items = new ArrayList<>();
int total = mInfo.getContents().size();
@@ -1286,7 +1270,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
protected int getContentAreaHeight() {
int height = Math.min(getMaxContentAreaHeight(),
mContent.getDesiredHeight());
mContent.getDesiredHeight());
return Math.max(height, MIN_CONTENT_DIMEN);
}
@@ -1294,7 +1278,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
int getMaxContentAreaHeight() {
DeviceProfile grid = mActivityContext.getDeviceProfile();
return grid.availableHeightPx - grid.getTotalWorkspacePadding().y
- getFooterHeight();
- getFooterHeight();
}
@VisibleForTesting
@@ -1333,30 +1317,13 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mContent.measure(contentAreaWidthSpec, contentAreaHeightSpec);
mFooter.measure(contentAreaWidthSpec,
MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY));
MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY));
int folderWidth = getPaddingLeft() + getPaddingRight() + contentWidth;
int folderHeight = getFolderHeight(contentHeight);
setMeasuredDimension(folderWidth, folderHeight);
}
/**
* If the Folder Title has less than 100dp of available width, we hide it. The reason we do this
* calculation in onSizeChange is because this callback is called 1x when the folder is opened.
* <p>
* The PageIndicator and the Folder Title share the same horizontal linear layout, but both
* are dynamically sized. Therefore, we are setting visibility of the folder title AFTER the
* layout is measured.
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int minTitleWidth = getResources().getDimensionPixelSize(R.dimen.folder_title_min_width);
if (enableLauncherVisualRefresh() && mFolderName.getMeasuredWidth() < minTitleWidth) {
mFolderName.setVisibility(View.GONE);
}
}
/**
* Rearranges the children based on their rank.
*/
@@ -1404,7 +1371,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
boolean isShiftPlusTab = keyCode == KeyEvent.KEYCODE_TAB &&
event.hasModifiers(KeyEvent.META_SHIFT_ON);
event.hasModifiers(KeyEvent.META_SHIFT_ON);
if (isShiftPlusTab && Folder.this.isFocused()) {
return lastChild.requestFocus();
}
@@ -1437,16 +1404,16 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
PendingAddShortcutInfo pasi = d.dragInfo instanceof PendingAddShortcutInfo
? (PendingAddShortcutInfo) d.dragInfo : null;
? (PendingAddShortcutInfo) d.dragInfo : null;
WorkspaceItemInfo pasiSi =
pasi != null ? pasi.getActivityInfo(launcher).createWorkspaceItemInfo() : null;
pasi != null ? pasi.getActivityInfo(launcher).createWorkspaceItemInfo() : null;
if (pasi != null && pasiSi == null) {
// There is no WorkspaceItemInfo, so we have to go through a configuration activity.
pasi.container = mInfo.id;
pasi.rank = mEmptyCellRank;
launcher.addPendingItem(pasi, pasi.container, pasi.screenId, null, pasi.spanX,
pasi.spanY);
pasi.spanY);
d.deferDragViewCleanupPostAnimation = false;
mRearrangeOnClose = true;
} else {
@@ -1468,7 +1435,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// Actually move the item in the database if it was an external drag. Call this
// before creating the view, so that the ItemInfo is updated appropriately.
mLauncherDelegate.getModelWriter().addOrMoveItemInDatabase(
si, mInfo.id, 0, si.cellX, si.cellY);
si, mInfo.id, 0, si.cellX, si.cellY);
mIsExternalDrag = false;
} else {
currentDragView = mCurrentDragView;
@@ -1494,7 +1461,9 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
rearrangeChildren();
// Temporarily suppress the listener, as we did all the work already here.
executeWithContentUpdateSuppressed(() -> addFolderContent(si, mEmptyCellRank, false));
try (SuppressInfoChanges s = new SuppressInfoChanges()) {
mInfo.add(si, mEmptyCellRank, false);
}
// We only need to update the locations if it doesn't get handled in
// #onDropCompleted.
@@ -1509,7 +1478,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
if (mContent.getPageCount() > 1) {
// The animation has already been shown while opening the folder.
mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true,
mLauncherDelegate.getModelWriter());
mLauncherDelegate.getModelWriter());
}
if (!launcher.isInState(EDIT_MODE)) {
@@ -1520,7 +1489,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
d.stateAnnouncer.completeAction(R.string.item_moved);
}
mStatsLogManager.logger().withItemInfo(d.dragInfo).withInstanceId(d.logInstanceId)
.log(LAUNCHER_ITEM_DROP_COMPLETED);
.log(LAUNCHER_ITEM_DROP_COMPLETED);
}
// This is used so the item doesn't immediately appear in the folder when added. In one case
@@ -1540,66 +1509,40 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
}
/** Add an app or shortcut */
public void addFolderContent(ItemInfo item) {
addFolderContent(item, mInfo.getContents().size(), true);
}
/** Add an app or shortcut for a specified rank */
public void addFolderContent(ItemInfo item, int rank, boolean animate) {
if (!willAcceptItemType(item.itemType)) {
throw new RuntimeException("tried to add an illegal type into a folder");
}
rank = Utilities.boundToRange(rank, 0, mInfo.getContents().size());
mInfo.getContents().add(rank, item);
if (!mSuppressContentUpdate) {
FolderGridOrganizer verifier = createFolderGridOrganizer(
@Override
public void onAdd(ItemInfo item, int rank) {
FolderGridOrganizer verifier = createFolderGridOrganizer(
mActivityContext.getDeviceProfile()).setFolderInfo(mInfo);
verifier.updateRankAndPos(item, rank);
mLauncherDelegate.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0,
item.cellX,
verifier.updateRankAndPos(item, rank);
mLauncherDelegate.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0, item.cellX,
item.cellY);
updateItemLocationsInDatabaseBatch(false);
updateItemLocationsInDatabaseBatch(false);
if (mContent.areViewsBound()) {
mContent.createAndAddViewForRank(item, rank);
}
mItemsInvalidated = true;
updateTextViewFocus();
if (mContent.areViewsBound()) {
mContent.createAndAddViewForRank(item, rank);
}
mLauncherDelegate.getModelWriter().notifyItemModified(mInfo);
mFolderIcon.onItemsChanged(animate);
mItemsInvalidated = true;
}
/** Remove all matching app or shortcut. Does not change the DB. */
public void removeFolderContent(boolean animate, ItemInfo... items) {
List<ItemInfo> itemArray = Arrays.asList(items);
if (mInfo.getContents().removeAll(itemArray)) {
mLauncherDelegate.getModelWriter().notifyItemModified(mInfo);
@Override
public void onRemove(List<ItemInfo> items) {
if (isInAppDrawer()) {
return;
}
if (!mSuppressContentUpdate) {
mItemsInvalidated = true;
itemArray.forEach(item -> mContent.removeItem(getViewForInfo(item)));
if (mState == STATE_ANIMATING) {
mRearrangeOnClose = true;
mItemsInvalidated = true;
items.stream().map(this::getViewForInfo).forEach(mContent::removeItem);
if (mState == STATE_ANIMATING) {
mRearrangeOnClose = true;
} else {
rearrangeChildren();
}
if (getItemCount() <= 1) {
if (mIsOpen) {
close(true);
} else {
rearrangeChildren();
replaceFolderWithFinalItem();
}
if (getItemCount() <= 1) {
if (mIsOpen) {
close(true);
} else {
replaceFolderWithFinalItem();
}
}
updateTextViewFocus();
}
mFolderIcon.onItemsChanged(animate);
}
@VisibleForTesting
@@ -1607,13 +1550,21 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
return mContent.iterateOverItems((info, view) -> info == item);
}
@Override
public void onItemsChanged(boolean animate) {
updateTextViewFocus();
}
@Override
public void onTitleChanged(CharSequence title) {
mFolderName.setText(title);
}
/**
* Utility methods to iterate over items of the view
*/
@Override
@Nullable
public View mapOverItems(@NonNull ItemOperator op) {
return mContent.iterateOverItems(op);
public void iterateOverItems(ItemOperator op) {
mContent.iterateOverItems(op);
}
/**
@@ -1634,8 +1585,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
int totalItemsInFolder = allItems.size();
int itemsPerPage = mContent.itemsPerPage();
int numItemsOnCurrentPage = page == lastPage
? totalItemsInFolder - (itemsPerPage * page)
: itemsPerPage;
? totalItemsInFolder - (itemsPerPage * page)
: itemsPerPage;
int startIndex = page * itemsPerPage;
int endIndex = Math.min(startIndex + numItemsOnCurrentPage, allItems.size());
@@ -1656,8 +1607,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
post(this::startEditingFolderName);
} else {
StatsLogger statsLogger = mStatsLogManager.logger()
.withItemInfo(mInfo)
.withFromState(mFromLabelState);
.withItemInfo(mInfo)
.withFromState(mFromLabelState);
// If the folder label is suggested, it is logged to improve prediction model.
// When both old and new labels are logged together delimiter is used.
@@ -1722,7 +1673,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
// Pause drag event until the scrolling is finished
mScrollPauseAlarm.setOnAlarmListener(new OnScrollFinishedListener(mDragObject));
int rescrollDelay = getResources().getInteger(
R.integer.config_pageSnapAnimationDuration) + RESCROLL_EXTRA_DELAY;
R.integer.config_pageSnapAnimationDuration) + RESCROLL_EXTRA_DELAY;
mScrollPauseAlarm.setAlarm(rescrollDelay);
}
}
@@ -1760,14 +1711,18 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
};
/** Executes the task while suppressing the content update for the folder */
private void executeWithContentUpdateSuppressed(Runnable task) {
if (mSuppressContentUpdate) {
task.run();
} else {
mSuppressContentUpdate = true;
task.run();
mSuppressContentUpdate = false;
/**
* Temporary resource held while we don't want to handle info changes
*/
private class SuppressInfoChanges implements AutoCloseable {
SuppressInfoChanges() {
mInfo.removeListener(Folder.this);
}
@Override
public void close() {
mInfo.addListener(Folder.this);
updateTextViewFocus();
}
}
@@ -1801,7 +1756,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
return false;
} else if (!dl.isEventOverView(this, ev)
&& mLauncherDelegate.interceptOutsideTouch(ev, dl, this)) {
&& mLauncherDelegate.interceptOutsideTouch(ev, dl, this)) {
return true;
}
}
@@ -1810,7 +1765,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
@Override
public boolean canInterceptEventsInSystemGestureRegion() {
return !mIsEditingName;
return true;
}
/**
@@ -35,7 +35,6 @@ import android.graphics.drawable.GradientDrawable;
import android.util.Property;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.CellLayout;
@@ -46,8 +45,8 @@ import com.android.launcher3.Utilities;
import com.android.launcher3.anim.PropertyResetListener;
import com.android.launcher3.apppairs.AppPairIcon;
import com.android.launcher3.celllayout.CellLayoutLayoutParams;
import com.android.launcher3.graphics.ShapeDelegate;
import com.android.launcher3.graphics.ThemeManager;
import com.android.launcher3.graphics.IconShape;
import com.android.launcher3.graphics.IconShape.ShapeDelegate;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.BaseDragLayer;
import com.androidinternal.graphics.ColorUtils;
@@ -86,10 +85,9 @@ public class FolderAnimationManager {
private final int mDuration;
private final int mDelay;
private final Interpolator mFolderOpenInterpolator;
private final Interpolator mFolderCloseInterpolator;
private final Interpolator mLargeFolderPreviewItemOpenInterpolator;
private final Interpolator mLargeFolderPreviewItemCloseInterpolator;
private final TimeInterpolator mFolderInterpolator;
private final TimeInterpolator mLargeFolderPreviewItemOpenInterpolator;
private final TimeInterpolator mLargeFolderPreviewItemCloseInterpolator;
private final PreviewItemDrawingParams mTmpParams = new PreviewItemDrawingParams(0, 0, 0);
private final FolderGridOrganizer mPreviewVerifier;
@@ -116,9 +114,7 @@ public class FolderAnimationManager {
mDuration = res.getInteger(R.integer.config_materialFolderExpandDuration);
mDelay = res.getInteger(R.integer.config_folderDelay);
mFolderOpenInterpolator = AnimationUtils.loadInterpolator(mContext,
R.interpolator.standard_interpolator);
mFolderCloseInterpolator = AnimationUtils.loadInterpolator(mContext,
mFolderInterpolator = AnimationUtils.loadInterpolator(mContext,
R.interpolator.standard_interpolator);
mLargeFolderPreviewItemOpenInterpolator = AnimationUtils.loadInterpolator(mContext,
R.interpolator.large_folder_preview_item_open_interpolator);
@@ -252,7 +248,7 @@ public class FolderAnimationManager {
}
play(a, getAnimator(mFolder.mFooter, ALPHA, 0, 1f), footerStartDelay, footerAlphaDuration);
ShapeDelegate shapeDelegate = ThemeManager.INSTANCE.get(mContext).getFolderShape();
ShapeDelegate shapeDelegate = IconShape.INSTANCE.get(mContext).getShape();
// Create reveal animator for the folder background
play(a, shapeDelegate.createRevealAnimator(
mFolder, startRect, endRect, finalRadius, !mIsOpening));
@@ -271,7 +267,6 @@ public class FolderAnimationManager {
(int) (left + (startRect.right / initialScale)) + extraRadius,
(int) (startRect.bottom / initialScale) + extraRadius);
Rect contentEnd = new Rect(left, 0, left + lp.width, lp.height);
// animated contents of folder with the folder background
play(a, shapeDelegate.createRevealAnimator(
mFolder.getContent(), contentStart, contentEnd, finalRadius, !mIsOpening));
@@ -352,11 +347,7 @@ public class FolderAnimationManager {
// We set the interpolator on all current child animators here, because the preview item
// animators may use a different interpolator.
for (Animator animator : a.getChildAnimations()) {
animator.setInterpolator(
mIsOpening
? mFolderOpenInterpolator
: mFolderCloseInterpolator
);
animator.setInterpolator(mFolderInterpolator);
}
int radiusDiff = scaledRadius - mPreviewBackground.getRadius();
@@ -491,7 +482,7 @@ public class FolderAnimationManager {
return mFolder.getItemCount() > MAX_NUM_ITEMS_IN_PREVIEW;
}
private Interpolator getPreviewItemInterpolator() {
private TimeInterpolator getPreviewItemInterpolator() {
if (isLargeFolder()) {
// With larger folders, we want the preview items to reach their final positions faster
// (when opening) and later (when closing) so that they appear aligned with the rest of
@@ -500,7 +491,7 @@ public class FolderAnimationManager {
? mLargeFolderPreviewItemOpenInterpolator
: mLargeFolderPreviewItemCloseInterpolator;
}
return mIsOpening ? mFolderOpenInterpolator : mFolderCloseInterpolator;
return mFolderInterpolator;
}
private Animator getAnimator(View view, Property property, float v1, float v2) {
@@ -19,7 +19,6 @@ package com.android.launcher3.folder;
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW;
import android.graphics.Point;
import android.util.Log;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.model.data.FolderInfo;
@@ -179,14 +178,6 @@ public class FolderGridOrganizer {
break;
}
}
if (result.isEmpty()) {
// Log specifics since we are getting empty result
Log.d("b/383526431", "previewItemsForPage: "
+ "mCountX = " + mCountX
+ ", mCountY = " + mCountY
+ ", content size = " + contents.size());
}
return result;
}
@@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications copyright 2025 Lawnchair
* Modifications copyright 2022 Lawnchair
*/
package com.android.launcher3.folder;
import static com.android.launcher3.Flags.enableCursorHoverStates;
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.ICON_OVERLAP_FACTOR;
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW;
import static com.android.launcher3.folder.FolderGridOrganizer.createFolderGridOrganizer;
import static com.android.launcher3.folder.PreviewItemManager.INITIAL_ITEM_ANIMATION_DURATION;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_AUTO_LABELED;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_AUTO_LABELING_SKIPPED_EMPTY_PRIMARY;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_AUTO_LABELING_SKIPPED_EMPTY_SUGGESTIONS;
import static com.android.launcher3.model.data.FolderInfo.willAcceptItemType;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -76,6 +76,7 @@ import com.android.launcher3.logging.InstanceId;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.model.data.AppPairInfo;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.FolderInfo.FolderListener;
import com.android.launcher3.model.data.FolderInfo.LabelState;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemFactory;
@@ -94,7 +95,7 @@ import java.util.function.Predicate;
/**
* An icon that can appear on in the workspace representing an {@link Folder}.
*/
public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion,
public class FolderIcon extends FrameLayout implements FolderListener, FloatingIconViewCompanion,
DraggableView, Reorderable {
private final MultiTranslateDelegate mTranslateDelegate = new MultiTranslateDelegate(this);
@@ -129,7 +130,7 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
private boolean mForceHideDot;
@ViewDebug.ExportedProperty(category = "launcher", deepExport = true)
private final FolderDotInfo mDotInfo = new FolderDotInfo();
private FolderDotInfo mDotInfo = new FolderDotInfo();
private DotRenderer mDotRenderer;
@ViewDebug.ExportedProperty(category = "launcher", deepExport = true)
private DotRenderer.DrawParams mDotParams;
@@ -172,24 +173,21 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
}
public static <T extends Context & ActivityContext> FolderIcon inflateFolderAndIcon(int resId,
T activityContext, ViewGroup group, FolderInfo folderInfo) {
T activityContext, ViewGroup group, FolderInfo folderInfo) {
Folder folder = Folder.fromXml(activityContext);
FolderIcon icon = inflateIcon(resId, activityContext, group, folderInfo);
folder.setFolderIcon(icon);
folder.bind(folderInfo);
icon.setFolder(folder);
return icon;
}
/**
* Builds a FolderIcon to be added to the activity.
* This method doesn't add any listeners to the FolderInfo, and hence any changes to the info
* will not be reflected in the folder.
* Builds a FolderIcon to be added to the Launcher
*/
public static FolderIcon inflateIcon(int resId, ActivityContext activity,
@Nullable ViewGroup group, FolderInfo folderInfo) {
@Nullable ViewGroup group, FolderInfo folderInfo) {
@SuppressWarnings("all") // suppress dead code warning
final boolean error = INITIAL_ITEM_ANIMATION_DURATION >= DROP_IN_ANIMATION_DURATION;
if (error) {
@@ -223,7 +221,13 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
icon.mDotRenderer = grid.mDotRendererWorkSpace;
icon.setContentDescription(icon.getAccessiblityTitle(folderInfo.title));
icon.updateDotInfo();
// Keep the notification dot up to date with the sum of all the content's dots.
FolderDotInfo folderDotInfo = new FolderDotInfo();
for (ItemInfo si : folderInfo.getContents()) {
folderDotInfo.addDotInfo(activity.getDotInfoForItem(si));
}
icon.setDotInfo(folderDotInfo);
icon.setAccessibilityDelegate(activity.getAccessibilityDelegate());
@@ -231,6 +235,8 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
icon.mPreviewVerifier.setFolderInfo(folderInfo);
icon.updatePreviewItems(false);
folderInfo.addListener(icon);
return icon;
}
@@ -247,8 +253,7 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
mPreviewItemManager.recomputePreviewDrawingParams();
mBackground.getBounds(outBounds);
// The preview items go outside of the bounds of the background.
Utilities.scaleRectAboutCenter(outBounds,
ClippedFolderIconLayoutRule.getIconOverlapFactor());
Utilities.scaleRectAboutCenter(outBounds, ICON_OVERLAP_FACTOR);
}
public float getBackgroundStrokeWidth() {
@@ -264,13 +269,22 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
}
private boolean willAcceptItem(ItemInfo item) {
return (willAcceptItemType(item.itemType) && item != mInfo && !mFolder.isOpen());
final int itemType = item.itemType;
return (Folder.willAcceptItemType(itemType) && item != mInfo && !mFolder.isOpen());
}
public boolean acceptDrop(ItemInfo dragInfo) {
return !mFolder.isDestroyed() && willAcceptItem(dragInfo);
}
public void addItem(ItemInfo item) {
mInfo.add(item, true);
}
public void removeItem(ItemInfo item, boolean animate) {
mInfo.remove(item, animate);
}
public void onDragEnter(ItemInfo dragInfo) {
if (mFolder.isDestroyed() || !willAcceptItem(dragInfo)) return;
CellLayoutLayoutParams lp = (CellLayoutLayoutParams) getLayoutParams();
@@ -297,10 +311,11 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
}
public void performCreateAnimation(final ItemInfo destInfo, final View destView,
final ItemInfo srcInfo, final DragObject d, Rect dstRect,
float scaleRelativeToDragLayer) {
final ItemInfo srcInfo, final DragObject d, Rect dstRect,
float scaleRelativeToDragLayer) {
final DragView srcView = d.dragView;
prepareCreateAnimation(destView);
getFolder().addFolderContent(destInfo);
addItem(destInfo);
// This will animate the first item from it's position as an icon into its
// position as the first item in the preview
mPreviewItemManager.createFirstItemAnimation(false /* reverse */, null)
@@ -323,7 +338,7 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
}
private void onDrop(final ItemInfo item, DragObject d, Rect finalRect,
float scaleRelativeToDragLayer, int index, boolean itemReturnedOnFailedDrop) {
float scaleRelativeToDragLayer, int index, boolean itemReturnedOnFailedDrop) {
item.cellX = -1;
item.cellY = -1;
DragView animateView = d.dragView;
@@ -354,7 +369,7 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
boolean itemAdded = false;
if (itemReturnedOnFailedDrop || index >= MAX_NUM_ITEMS_IN_PREVIEW) {
List<ItemInfo> oldPreviewItems = new ArrayList<>(mCurrentPreviewItems);
getFolder().addFolderContent(item, index, false);
mInfo.add(item, index, false);
mCurrentPreviewItems.clear();
mCurrentPreviewItems.addAll(getPreviewItemsOnPage(0));
@@ -370,12 +385,12 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
mPreviewItemManager.onDrop(oldPreviewItems, mCurrentPreviewItems, item);
itemAdded = true;
} else {
getFolder().removeFolderContent(false, item);
removeItem(item, false);
}
}
if (!itemAdded) {
getFolder().addFolderContent(item, index, true);
mInfo.add(item, index, true);
}
int[] center = new int[2];
@@ -421,7 +436,7 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
}, DROP_IN_ANIMATION_DURATION);
});
} else {
getFolder().addFolderContent(item);
addItem(item);
}
}
@@ -494,23 +509,9 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
);
}
/** Keep the notification dot up to date with the sum of all the content's dots. */
public void updateDotInfo() {
boolean hadDot = mDotInfo.hasDot();
mDotInfo.reset();
for (ItemInfo si : mInfo.getContents()) {
mDotInfo.addDotInfo(mActivity.getDotInfoForItem(si));
}
boolean isDotted = mDotInfo.hasDot();
float newDotScale = isDotted ? 1f : 0f;
// Animate when a dot is first added or when it is removed.
if ((hadDot ^ isDotted) && isShown()) {
animateDotScale(newDotScale);
} else {
cancelDotScaleAnim();
mDotScale = newDotScale;
invalidate();
}
public void setDotInfo(FolderDotInfo dotInfo) {
updateDotScale(mDotInfo.hasDot(), dotInfo.hasDot());
mDotInfo = dotInfo;
}
public ClippedFolderIconLayoutRule getLayoutRule() {
@@ -531,6 +532,22 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
}
}
/**
* Sets mDotScale to 1 or 0, animating if wasDotted or isDotted is false
* (the dot is being added or removed).
*/
private void updateDotScale(boolean wasDotted, boolean isDotted) {
float newDotScale = isDotted ? 1f : 0f;
// Animate when a dot is first added or when it is removed.
if ((wasDotted ^ isDotted) && isShown()) {
animateDotScale(newDotScale);
} else {
cancelDotScaleAnim();
mDotScale = newDotScale;
invalidate();
}
}
private void cancelDotScaleAnim() {
if (mDotScaleAnim != null) {
mDotScaleAnim.cancel();
@@ -631,7 +648,7 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
// If we are animating to the accepting state, animate the dot out.
mDotParams.scale = Math.max(0, mDotScale - mBackground.getAcceptScaleProgress());
mDotParams.dotColor = mBackground.getDotColor();
mDotRenderer.draw(canvas, mDotParams);
mDotRenderer.draw(canvas, mDotParams, mDotInfo == null ? -1 : mDotInfo.getNotificationCount());
}
}
@@ -674,6 +691,13 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
return mPreviewItemManager.verifyDrawable(who) || super.verifyDrawable(who);
}
@Override
public void onItemsChanged(boolean animate) {
updatePreviewItems(animate);
invalidate();
requestLayout();
}
private void updatePreviewItems(boolean animate) {
mPreviewItemManager.updatePreviewItems(animate);
mCurrentPreviewItems.clear();
@@ -687,15 +711,31 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
mPreviewItemManager.updatePreviewItems(itemCheck);
}
public void onItemsChanged(boolean animate) {
@Override
public void onAdd(ItemInfo item, int rank) {
updatePreviewItems(false);
updateDotInfo();
boolean wasDotted = mDotInfo.hasDot();
mDotInfo.addDotInfo(mActivity.getDotInfoForItem(item));
boolean isDotted = mDotInfo.hasDot();
updateDotScale(wasDotted, isDotted);
setContentDescription(getAccessiblityTitle(mInfo.title));
updatePreviewItems(animate);
invalidate();
requestLayout();
}
@Override
public void onRemove(List<ItemInfo> items) {
updatePreviewItems(false);
boolean wasDotted = mDotInfo.hasDot();
items.stream().map(mActivity::getDotInfoForItem).forEach(mDotInfo::subtractDotInfo);
boolean isDotted = mDotInfo.hasDot();
updateDotScale(wasDotted, isDotted);
setContentDescription(getAccessiblityTitle(mInfo.title));
invalidate();
requestLayout();
}
@Override
public void onTitleChanged(CharSequence title) {
mFolderName.setText(title);
setContentDescription(getAccessiblityTitle(title));
@@ -731,6 +771,11 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
mLongPressHelper.cancelLongPress();
}
public void removeListeners() {
mInfo.removeListener(this);
mInfo.removeListener(mFolder);
}
private boolean isInHotseat() {
return mInfo.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT;
}
@@ -784,10 +829,6 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
* Returns a formatted accessibility title for folder
*/
public String getAccessiblityTitle(CharSequence title) {
if (title == null) {
// Avoids "Talkback -> Folder: null" announcement.
title = getContext().getString(R.string.unnamed_folder);
}
int size = mInfo.getContents().size();
if (size < MAX_NUM_ITEMS_IN_PREVIEW) {
return getContext().getString(R.string.folder_name_format_exact, title, size);
@@ -819,4 +860,4 @@ public class FolderIcon extends FrameLayout implements FloatingIconViewCompanion
*/
void clearFolderLeaveBehind(FolderIcon child);
}
}
}
@@ -15,8 +15,6 @@
*/
package com.android.launcher3.folder;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_FOLDER;
import android.annotation.SuppressLint;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
@@ -39,7 +37,6 @@ import com.android.launcher3.model.ModelTaskController;
import com.android.launcher3.model.StringCache;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.CollectionInfo;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.Preconditions;
@@ -200,18 +197,9 @@ public class FolderNameProvider implements ResourceBasedOverride {
@Override
public void execute(@NonNull ModelTaskController taskController,
@NonNull BgDataModel dataModel, @NonNull AllAppsList apps) {
mCollectionInfos = getCollectionForSuggestions(dataModel);
mCollectionInfos = dataModel.collections.clone();
mAppInfos = Arrays.asList(apps.copyData());
}
}
public static IntSparseArrayMap<CollectionInfo> getCollectionForSuggestions(
BgDataModel dataModel) {
IntSparseArrayMap<CollectionInfo> result = new IntSparseArrayMap<>();
dataModel.itemsIdMap.stream()
.filter(item -> item.itemType == ITEM_TYPE_FOLDER)
.forEach(item -> result.put(item.id, (FolderInfo) item));
return result;
}
}
@@ -18,12 +18,12 @@ package com.android.launcher3.folder;
import static com.android.launcher3.AbstractFloatingView.TYPE_ALL;
import static com.android.launcher3.AbstractFloatingView.TYPE_FOLDER;
import static com.android.launcher3.folder.FolderGridOrganizer.createFolderGridOrganizer;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.util.ArrayMap;
import android.util.AttributeSet;
import android.util.Log;
@@ -37,6 +37,7 @@ import com.android.launcher3.AbstractFloatingView;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.CellLayout;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Item;
import com.android.launcher3.PagedView;
import com.android.launcher3.R;
import com.android.launcher3.ShortcutAndWidgetContainer;
@@ -48,7 +49,6 @@ import com.android.launcher3.model.data.AppPairInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pageindicators.Direction;
import com.android.launcher3.pageindicators.PageIndicatorDots;
import com.android.launcher3.util.LauncherBindableItemsContainer.ItemOperator;
import com.android.launcher3.util.Thunk;
@@ -60,7 +60,6 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.ToIntFunction;
import java.util.stream.Collectors;
@@ -102,24 +101,11 @@ public class FolderPagedView extends PagedView<PageIndicatorDots> implements Cli
// animating or is open.
private boolean mViewsBound = false;
private boolean mCanAnnouncePageDescription;
public FolderPagedView(Context context, AttributeSet attrs) {
this(
context,
attrs,
createFolderGridOrganizer(ActivityContext.lookupContext(context).getDeviceProfile())
);
}
public FolderPagedView(
Context context,
AttributeSet attrs,
FolderGridOrganizer folderGridOrganizer
) {
super(context, attrs);
ActivityContext activityContext = ActivityContext.lookupContext(context);
mOrganizer = folderGridOrganizer;
DeviceProfile profile = activityContext.getDeviceProfile();
mOrganizer = FolderGridOrganizer.createFolderGridOrganizer(profile);
mIsRtl = Utilities.isRtl(getResources());
setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
@@ -131,8 +117,6 @@ public class FolderPagedView extends PagedView<PageIndicatorDots> implements Cli
public void setFolder(Folder folder) {
mFolder = folder;
mPageIndicator = folder.findViewById(R.id.folder_page_indicator);
mPageIndicator.setArrowClickListener(direction -> snapToPageImmediately(
(Direction.END == direction) ? mCurrentPage + 1 : mCurrentPage - 1));
initParentViews(folder);
}
@@ -176,19 +160,6 @@ public class FolderPagedView extends PagedView<PageIndicatorDots> implements Cli
mViewsBound = true;
}
void setCanAnnouncePageDescriptionForFolder(boolean canAnnounce) {
mCanAnnouncePageDescription = canAnnounce;
}
private boolean canAnnouncePageDescriptionForFolder() {
return mCanAnnouncePageDescription;
}
@Override
protected boolean canAnnouncePageDescription() {
return super.canAnnouncePageDescription() && canAnnouncePageDescriptionForFolder();
}
/**
* Removes all the icons from the folder
*/
@@ -397,9 +368,8 @@ public class FolderPagedView extends PagedView<PageIndicatorDots> implements Cli
// Update footer
mPageIndicator.setVisibility(getPageCount() > 1 ? View.VISIBLE : View.GONE);
// Set the gravity as LEFT or RIGHT instead of START, as START depends on the actual text.
int horizontalGravity = getPageCount() > 1
? (mIsRtl ? Gravity.RIGHT : Gravity.LEFT) : Gravity.CENTER_HORIZONTAL;
mFolder.getFolderName().setGravity(horizontalGravity | Gravity.CENTER_VERTICAL);
mFolder.mFolderName.setGravity(getPageCount() > 1 ?
(mIsRtl ? Gravity.RIGHT : Gravity.LEFT) : Gravity.CENTER_HORIZONTAL);
}
public int getDesiredWidth() {
@@ -541,16 +511,6 @@ public class FolderPagedView extends PagedView<PageIndicatorDots> implements Cli
verifyVisibleHighResIcons(getCurrentPage() + 1);
}
int getTotalChildCount() {
AtomicInteger count = new AtomicInteger();
iterateOverItems((i, v) -> {
count.getAndIncrement();
return false;
});
return count.get();
}
/**
* Ensures that all the icons on the given page are of high-res
*/
@@ -560,10 +520,19 @@ public class FolderPagedView extends PagedView<PageIndicatorDots> implements Cli
ShortcutAndWidgetContainer parent = page.getShortcutsAndWidgets();
for (int i = parent.getChildCount() - 1; i >= 0; i--) {
View iconView = parent.getChildAt(i);
Drawable d = null;
if (iconView instanceof BubbleTextView btv) {
btv.verifyHighRes();
d = btv.getIcon();
} else if (iconView instanceof AppPairIcon api) {
api.verifyHighRes();
d = api.getIconDrawableArea().getDrawable();
}
// Set the callback back to the actual icon, in case
// it was captured by the FolderIcon
if (d != null) {
d.setCallback(iconView);
}
}
}
@@ -18,6 +18,7 @@ package com.android.launcher3.folder;
import static com.android.app.animation.Interpolators.ACCELERATE_DECELERATE;
import static com.android.app.animation.Interpolators.EMPHASIZED_DECELERATE;
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.ICON_OVERLAP_FACTOR;
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
import android.animation.Animator;
@@ -49,8 +50,8 @@ import com.android.launcher3.CellLayout;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.R;
import com.android.launcher3.celllayout.DelegatedCellDrawing;
import com.android.launcher3.graphics.ShapeDelegate;
import com.android.launcher3.graphics.ThemeManager;
import com.android.launcher3.graphics.IconShape;
import com.android.launcher3.graphics.IconShape.ShapeDelegate;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ActivityContext;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
@@ -291,7 +292,7 @@ public class PreviewBackground extends DelegatedCellDrawing {
}
private ShapeDelegate getShape() {
return ThemeManager.INSTANCE.get(mContext).getFolderShape();
return IconShape.INSTANCE.get(mContext).getShape();
}
public void drawShadow(Canvas canvas) {
@@ -403,7 +404,7 @@ public class PreviewBackground extends DelegatedCellDrawing {
public Path getClipPath() {
mPath.reset();
float radius = getScaledRadius() * ClippedFolderIconLayoutRule.getIconOverlapFactor();
float radius = getScaledRadius() * ICON_OVERLAP_FACTOR;
// Find the difference in radius so that the clip path remains centered.
float radiusDifference = radius - getRadius();
float offsetX = basePreviewOffsetX - radiusDifference;
@@ -17,14 +17,12 @@
package com.android.launcher3.folder;
import static com.android.launcher3.BubbleTextView.DISPLAY_FOLDER;
import static com.android.launcher3.LauncherSettings.Favorites.DESKTOP_ICON_FLAG;
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.ENTER_INDEX;
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.EXIT_INDEX;
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW;
import static com.android.launcher3.folder.FolderIcon.DROP_IN_ANIMATION_DURATION;
import static com.android.launcher3.graphics.PreloadIconDrawable.newPendingIcon;
import static com.android.launcher3.icons.BitmapInfo.FLAG_THEMED;
import static com.android.launcher3.model.data.ItemInfoWithIcon.FLAG_SHOW_DOWNLOAD_PROGRESS_MASK;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -44,17 +42,17 @@ import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.Flags;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.Utilities;
import com.android.launcher3.apppairs.AppPairIcon;
import com.android.launcher3.apppairs.AppPairIconDrawingParams;
import com.android.launcher3.apppairs.AppPairIconGraphic;
import com.android.launcher3.graphics.PreloadIconDrawable;
import com.android.launcher3.model.data.AppPairInfo;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ActivityContext;
import java.util.ArrayList;
@@ -456,10 +454,13 @@ public class PreviewItemManager {
@VisibleForTesting
public void setDrawable(PreviewItemDrawingParams p, ItemInfo item) {
if (item instanceof WorkspaceItemInfo wii) {
if (isActivePendingIcon(wii)) {
p.drawable = newPendingIcon(mContext, wii);
if (wii.hasPromiseIconUi() || (wii.runtimeStatusFlags
& ItemInfoWithIcon.FLAG_SHOW_DOWNLOAD_PROGRESS_MASK) != 0) {
PreloadIconDrawable drawable = newPendingIcon(mContext, wii);
p.drawable = drawable;
} else {
p.drawable = wii.newIcon(mContext, FLAG_THEMED);
p.drawable = wii.newIcon(mContext,
Themes.isThemedIconEnabled(mContext) ? FLAG_THEMED : 0);
}
p.drawable.setBounds(0, 0, mIconSize, mIconSize);
} else if (item instanceof AppPairInfo api) {
@@ -467,7 +468,7 @@ public class PreviewItemManager {
p.drawable = AppPairIconGraphic.composeDrawable(api, appPairParams);
p.drawable.setBounds(0, 0, mIconSize, mIconSize);
} else if (item instanceof ItemInfoWithIcon withIcon){
var isThemed = PreferenceManager.getInstance(mContext).getDrawerThemedIcons().get() ? 0 : FLAG_THEMED;
var isThemed = PreferenceManager.getInstance(mContext).getDrawerThemedIcons().get();
p.drawable = withIcon.newIcon(mContext, isThemed);
p.drawable.setBounds(0, 0, mIconSize, mIconSize);
}
@@ -476,27 +477,5 @@ public class PreviewItemManager {
// Set the callback to FolderIcon as it is responsible to drawing the icon. The
// callback will be released when the folder is opened.
p.drawable.setCallback(mIcon);
// Verify high res
if (item instanceof ItemInfoWithIcon info
&& info.getMatchingLookupFlag().isVisuallyLessThan(DESKTOP_ICON_FLAG)) {
LauncherAppState.getInstance(mContext).getIconCache().updateIconInBackground(
newInfo -> {
if (p.item == newInfo) {
setDrawable(p, newInfo);
mIcon.invalidate();
}
}, info);
}
}
/**
* Returns true if item is a Promise Icon or actively downloading, and the item is not an
* inactive archived app.
*/
private boolean isActivePendingIcon(WorkspaceItemInfo item) {
return (item.hasPromiseIconUi()
|| (item.runtimeStatusFlags & FLAG_SHOW_DOWNLOAD_PROGRESS_MASK) != 0)
&& !(Flags.useNewIconForArchivedApps() && item.isInactiveArchive());
}
}
@@ -21,7 +21,11 @@ import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
import android.app.Notification;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import androidx.core.graphics.ColorUtils;
import com.android.launcher3.R;
import com.android.launcher3.util.Themes;
import java.lang.IllegalArgumentException;
@@ -30,6 +34,8 @@ import java.lang.IllegalArgumentException;
* Contains colors based on the dominant color of an icon.
*/
public class IconPalette {
private static final boolean DEBUG = false;
private static final String TAG = "IconPalette";
private static final float MIN_PRELOAD_COLOR_SATURATION = 0.2f;
@@ -52,4 +58,108 @@ public class IconPalette {
}
return result;
}
/**
* Resolves a color such that it has enough contrast to be used as the
* color of an icon or text on the given background color.
*
* @return a color of the same hue with enough contrast against the background.
*
* This was copied from com.android.internal.util.NotificationColorUtil.
*/
public static int resolveContrastColor(Context context, int color, int background) {
final int resolvedColor = resolveColor(context, color);
int contrastingColor = ensureTextContrast(resolvedColor, background);
if (contrastingColor != resolvedColor) {
if (DEBUG){
Log.w(TAG, String.format(
"Enhanced contrast of notification for %s " +
"%s (over background) by changing #%s to %s",
context.getPackageName(),
contrastChange(resolvedColor, contrastingColor, background),
Integer.toHexString(resolvedColor), Integer.toHexString(contrastingColor)));
}
}
return contrastingColor;
}
/**
* Resolves {@param color} to an actual color if it is {@link Notification#COLOR_DEFAULT}
*
* This was copied from com.android.internal.util.NotificationColorUtil.
*/
private static int resolveColor(Context context, int color) {
if (color == Notification.COLOR_DEFAULT) {
return context.getColor(R.color.notification_icon_default_color);
}
return color;
}
/** For debugging. This was copied from com.android.internal.util.NotificationColorUtil. */
private static String contrastChange(int colorOld, int colorNew, int bg) {
return String.format("from %.2f:1 to %.2f:1",
ColorUtils.calculateContrast(colorOld, bg),
ColorUtils.calculateContrast(colorNew, bg));
}
/**
* Finds a text color with sufficient contrast over bg that has the same hue as the original
* color.
*
* This was copied from com.android.internal.util.NotificationColorUtil.
*/
private static int ensureTextContrast(int color, int bg) {
int res = color;
try {
res = findContrastColor(color, bg, 4.5);
} catch (IllegalArgumentException e) {
// Just returning the same color in this case
Log.e(TAG, "ensureTextContrast: Invalid fg/bg color int."
+ " fg=" + color + " bg=" + bg);
}
return res;
}
/**
* Finds a suitable color such that there's enough contrast.
*
* @param fg the color to start searching from.
* @param bg the color to ensure contrast against.
* @param minRatio the minimum contrast ratio required.
* @return a color with the same hue as {@param color}, potentially darkened to meet the
* contrast ratio.
*
* This was copied from com.android.internal.util.NotificationColorUtil.
*/
private static int findContrastColor(int fg, int bg, double minRatio) {
if (ColorUtils.calculateContrast(fg, bg) >= minRatio) {
return fg;
}
double[] lab = new double[3];
ColorUtils.colorToLAB(bg, lab);
double bgL = lab[0];
ColorUtils.colorToLAB(fg, lab);
double fgL = lab[0];
boolean isBgDark = bgL < 50;
double low = isBgDark ? fgL : 0, high = isBgDark ? 100 : fgL;
final double a = lab[1], b = lab[2];
for (int i = 0; i < 15 && high - low > 0.00001; i++) {
final double l = (low + high) / 2;
fg = ColorUtils.LABToColor(l, a, b);
if (ColorUtils.calculateContrast(fg, bg) > minRatio) {
if (isBgDark) high = l; else low = l;
} else {
if (isBgDark) low = l; else high = l;
}
}
return ColorUtils.LABToColor(low, a, b);
}
public static int getMutedColor(int color, float whiteScrimAlpha) {
int whiteScrim = setColorAlphaBound(Color.WHITE, (int) (255 * whiteScrimAlpha));
return ColorUtils.compositeColors(whiteScrim, color);
}
}
@@ -23,18 +23,9 @@ import static android.view.View.VISIBLE;
import static com.android.launcher3.BubbleTextView.DISPLAY_TASKBAR;
import static com.android.launcher3.BubbleTextView.DISPLAY_WORKSPACE;
import static com.android.launcher3.DeviceProfile.DEFAULT_SCALE;
import static com.android.launcher3.Flags.extendibleThemeManager;
import static com.android.launcher3.Hotseat.ALPHA_CHANNEL_PREVIEW_RENDERER;
import static com.android.launcher3.LauncherPrefs.GRID_NAME;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_HOTSEAT_PREDICTION;
import static com.android.launcher3.Utilities.ATLEAST_O_MR1;
import static com.android.launcher3.Utilities.ATLEAST_S;
import static com.android.launcher3.Utilities.SHOULD_SHOW_FIRST_PAGE_WIDGET;
import static com.android.launcher3.graphics.ThemeManager.PREF_ICON_SHAPE;
import static com.android.launcher3.model.ModelUtils.currentScreenContentFilter;
import static com.android.launcher3.util.ResourceBasedOverride.Overrides.getObject;
import static com.android.launcher3.widget.LauncherWidgetHolder.APPWIDGET_HOST_ID;
import static com.android.launcher3.model.ModelUtils.filterCurrentWorkspaceItems;
import static com.android.launcher3.model.ModelUtils.getMissingHotseatRanks;
import android.app.Fragment;
import android.app.WallpaperColors;
@@ -43,15 +34,14 @@ import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Size;
import android.util.SparseArray;
@@ -62,6 +52,8 @@ import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextClock;
@@ -71,50 +63,38 @@ import androidx.annotation.Nullable;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.CellLayout;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.DeviceProfile.OnDeviceProfileChangeListener;
import com.android.launcher3.Hotseat;
import com.android.launcher3.InsettableFrameLayout;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherPrefs;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.ProxyPrefs;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.WorkspaceLayoutManager;
import com.android.launcher3.apppairs.AppPairIcon;
import com.android.launcher3.celllayout.CellLayoutLayoutParams;
import com.android.launcher3.celllayout.CellPosMapper;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dagger.ApiWrapperModule;
import com.android.launcher3.dagger.AppModule;
import com.android.launcher3.dagger.LauncherAppComponent;
import com.android.launcher3.dagger.LauncherAppSingleton;
import com.android.launcher3.dagger.LauncherComponentProvider;
import com.android.launcher3.dagger.PluginManagerWrapperModule;
import com.android.launcher3.dagger.StaticObjectModule;
import com.android.launcher3.dagger.WindowManagerProxyModule;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.model.BaseLauncherBinder.BaseLauncherBinderFactory;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.model.BgDataModel;
import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.LayoutParserFactory;
import com.android.launcher3.model.LayoutParserFactory.XmlLayoutParserFactory;
import com.android.launcher3.model.LoaderTask.LoaderTaskFactory;
import com.android.launcher3.model.WidgetItem;
import com.android.launcher3.model.WidgetsModel;
import com.android.launcher3.model.data.AppPairInfo;
import com.android.launcher3.model.data.CollectionInfo;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.BaseContext;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.DaggerSingletonObject;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.MainThreadInitializedObject;
import com.android.launcher3.util.SandboxContext;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext;
import com.android.launcher3.util.WindowBounds;
import com.android.launcher3.util.window.WindowManagerProxy;
import com.android.launcher3.views.ActivityContext;
@@ -122,24 +102,15 @@ import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.widget.BaseLauncherAppWidgetHostView;
import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
import com.android.launcher3.widget.LauncherWidgetHolder;
import com.android.launcher3.widget.LauncherWidgetHolder.WidgetHolderFactory;
import com.android.launcher3.widget.LocalColorExtractor;
import com.android.launcher3.widget.util.WidgetSizes;
import com.android.systemui.shared.Flags;
import dagger.BindsInstance;
import dagger.Component;
import java.io.File;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.concurrent.ConcurrentLinkedQueue;
import app.lawnchair.DeviceProfileOverrides;
import app.lawnchair.data.iconoverride.IconOverrideRepository;
@@ -152,88 +123,64 @@ import app.lawnchair.smartspace.provider.SmartspaceProvider;
import app.lawnchair.theme.ThemeProvider;
/**
* Utility class for generating the preview of Launcher for a given InvariantDeviceProfile.
* Utility class for generating the preview of Launcher for a given
* InvariantDeviceProfile.
* Steps:
* 1) Create a dummy icon info with just white icon
* 2) Inflate a strip down layout definition for Launcher
* 3) Place appropriate elements like icons and first-page qsb
* 4) Measure and draw the view on a canvas
* 1) Create a dummy icon info with just white icon
* 2) Inflate a strip down layout definition for Launcher
* 3) Place appropriate elements like icons and first-page qsb
* 4) Measure and draw the view on a canvas
*/
// Lawnchair-TODO-Merge: Merge Lawnchair back, (reason: merge-method: theirs)
public class LauncherPreviewRenderer extends BaseContext
implements ActivityContext, WorkspaceLayoutManager, LayoutInflater.Factory2 {
public class LauncherPreviewRenderer extends ContextWrapper
implements ActivityContext, WorkspaceLayoutManager, LayoutInflater.Factory2 {
/**
* Context used just for preview. It also provides a few objects (e.g. UserCache) just for
* Context used just for preview. It also provides a few objects (e.g.
* UserCache) just for
* preview purposes.
*/
public static class PreviewContext extends SandboxContext {
private final String mPrefName;
private final InvariantDeviceProfile mIdp;
private final ConcurrentLinkedQueue<LauncherIconsForPreview> mIconPool = new ConcurrentLinkedQueue<>();
private final File mDbDir;
public PreviewContext(Context base, String gridName, String shapeKey) {
this(base, gridName, shapeKey, APPWIDGET_HOST_ID, null);
public PreviewContext(Context base, InvariantDeviceProfile idp) {
super (base);
mIdp = idp;
putBaseInstance(PreferenceManager.INSTANCE);
putBaseInstance(PreferenceManager2.INSTANCE);
putBaseInstance(FontCache.INSTANCE);
putBaseInstance(FontManager.INSTANCE);
putBaseInstance(ThemeProvider.INSTANCE);
putBaseInstance(IconPackProvider.INSTANCE);
putBaseInstance(IconOverrideRepository.INSTANCE);
putBaseInstance(SmartspaceProvider.INSTANCE);
putBaseInstance(DeviceProfileOverrides.INSTANCE);
mObjectMap.put(InvariantDeviceProfile.INSTANCE, idp);
mObjectMap.put(LauncherAppState.INSTANCE,
new LauncherAppState(this, null /* iconCacheFileName */));
}
public PreviewContext(Context base, String gridName, String shapeKey,
int widgetHostId, @Nullable String layoutXml) {
super(base);
String randomUid = UUID.randomUUID().toString();
mPrefName = "preview-" + randomUid;
LauncherPrefs prefs =
new ProxyPrefs(this, getSharedPreferences(mPrefName, MODE_PRIVATE));
prefs.put(GRID_NAME, gridName);
prefs.put(PREF_ICON_SHAPE, shapeKey);
PreviewAppComponent.Builder builder =
DaggerLauncherPreviewRenderer_PreviewAppComponent.builder().bindPrefs(prefs);
if (TextUtils.isEmpty(layoutXml) || !extendibleThemeManager()) {
mDbDir = null;
builder.bindParserFactory(new LayoutParserFactory(this))
.bindWidgetsFactory(
LauncherComponentProvider.get(base).getWidgetHolderFactory());
} else {
mDbDir = new File(base.getFilesDir(), randomUid);
emptyDbDir();
mDbDir.mkdirs();
builder.bindParserFactory(new XmlLayoutParserFactory(this, layoutXml))
.bindWidgetsFactory(c -> new LauncherWidgetHolder(c, widgetHostId));
}
initDaggerComponent(builder);
if (!TextUtils.isEmpty(layoutXml)) {
// Use null the DB file so that we use a new in-memory DB
InvariantDeviceProfile.INSTANCE.get(this).dbFile = null;
}
private void putBaseInstance(MainThreadInitializedObject mainThreadInitializedObject) {
mObjectMap.put(mainThreadInitializedObject, mainThreadInitializedObject.get(getBaseContext()));
}
private void emptyDbDir() {
if (mDbDir != null && mDbDir.exists()) {
Arrays.stream(mDbDir.listFiles()).forEach(File::delete);
}
}
private final class LauncherIconsForPreview extends LauncherIcons {
@Override
protected void cleanUpObjects() {
super.cleanUpObjects();
deleteSharedPreferences(mPrefName);
if (mDbDir != null) {
emptyDbDir();
mDbDir.delete();
private LauncherIconsForPreview(Context context , int fillResIconDpi , int iconBitmapSize , ConcurrentLinkedQueue<LauncherIcons> pool) {
super (context , fillResIconDpi , iconBitmapSize , pool);
}
}
@Override
public File getDatabasePath(String name) {
return mDbDir != null ? new File(mDbDir, name) : super.getDatabasePath(name);
@Override
public void recycle() {
// Clear any temporary state variables
clear();
mIconPool.offer(this);
}
}
}
private final List<OnDeviceProfileChangeListener> mDpChangeListeners = new ArrayList<>();
private final Handler mUiHandler;
private final Context mContext;
private final InvariantDeviceProfile mIdp;
@@ -248,130 +195,93 @@ public class LauncherPreviewRenderer extends BaseContext
private final SparseIntArray mWallpaperColorResources;
private final SparseArray<Size> mLauncherWidgetSpanInfo;
/**
* Lawnchair
* <p>
* Default search container layout.
*
* @implNote Launcher3 A16_r2 uses [R.layout.qsb_preview]
*/
private int mWorkspaceSearchContainer = R.layout.smartspace_container;
public LauncherPreviewRenderer(Context context,
InvariantDeviceProfile idp,
int widgetHostId,
WallpaperColors wallpaperColorsOverride,
@Nullable final SparseArray<Size> launcherWidgetSpanInfo) {
this(context, idp, widgetHostId, null, wallpaperColorsOverride, launcherWidgetSpanInfo);
}
InvariantDeviceProfile idp,
WallpaperColors wallpaperColorsOverride,
@Nullable final SparseArray<Size> launcherWidgetSpanInfo) {
public LauncherPreviewRenderer(Context context,
InvariantDeviceProfile idp,
int widgetHostId,
SparseIntArray previewColorOverride,
WallpaperColors wallpaperColorsOverride,
@Nullable final SparseArray<Size> launcherWidgetSpanInfo) {
super(context, Themes.getActivityThemeRes(context));
super(context);
mUiHandler = new Handler(Looper.getMainLooper());
mContext = context;
mIdp = idp;
mDp = getDeviceProfileForPreview(context).toBuilder(context).setViewScaleProvider(
this::getAppWidgetScale).build();
this::getAppWidgetScale).build();
if (context instanceof PreviewContext) {
Context tempContext = ((PreviewContext) context).getBaseContext();
mDpOrig = InvariantDeviceProfile.INSTANCE.get(tempContext)
.getDeviceProfile(tempContext)
.copy(tempContext);
mDpOrig = new InvariantDeviceProfile(tempContext, InvariantDeviceProfile
.getCurrentGridName(tempContext)).getDeviceProfile(tempContext)
.copy(tempContext);
} else {
mDpOrig = mDp;
}
mInsets = getInsets(context);
if (Utilities.ATLEAST_R) {
WindowInsets currentWindowInsets = context.getSystemService(WindowManager.class)
.getCurrentWindowMetrics().getWindowInsets();
mInsets = new Rect(
currentWindowInsets.getSystemWindowInsetLeft(),
currentWindowInsets.getSystemWindowInsetTop(),
currentWindowInsets.getSystemWindowInsetRight(),
currentWindowInsets.getSystemWindowInsetBottom());
} else {
mInsets = new Rect();
mInsets.left = mInsets.right = (mDp.widthPx - mDp.availableWidthPx) / 2;
mInsets.top = mInsets.bottom = (mDp.heightPx - mDp.availableHeightPx) / 2;
}
mDp.updateInsets(mInsets);
mHomeElementInflater = LayoutInflater.from(
new ContextThemeWrapper(this, R.style.HomeScreenElementTheme));
new ContextThemeWrapper(this, R.style.HomeScreenElementTheme));
mHomeElementInflater.setFactory2(this);
int layoutRes = mDp.isTwoPanels ? R.layout.launcher_preview_two_panel_layout
: R.layout.launcher_preview_layout;
: R.layout.launcher_preview_layout;
mRootView = (InsettableFrameLayout) mHomeElementInflater.inflate(
layoutRes, null, false);
layoutRes, null, false);
mRootView.setInsets(mInsets);
measureView(mRootView, mDp.widthPx, mDp.heightPx);
mHotseat = mRootView.findViewById(R.id.hotseat);
mHotseat.resetLayout(false);
mLauncherWidgetSpanInfo = launcherWidgetSpanInfo == null ? new SparseArray<>() :
launcherWidgetSpanInfo;
mLauncherWidgetSpanInfo = launcherWidgetSpanInfo == null ? new SparseArray<>() : launcherWidgetSpanInfo;
CellLayout firstScreen = mRootView.findViewById(R.id.workspace);
firstScreen.setPadding(
mDp.workspacePadding.left + mDp.cellLayoutPaddingPx.left,
mDp.workspacePadding.top + mDp.cellLayoutPaddingPx.top,
mDp.isTwoPanels ? (mDp.cellLayoutBorderSpacePx.x / 2)
: (mDp.workspacePadding.right + mDp.cellLayoutPaddingPx.right),
mDp.workspacePadding.bottom + mDp.cellLayoutPaddingPx.bottom
);
mDp.workspacePadding.left + mDp.cellLayoutPaddingPx.left,
mDp.workspacePadding.top + mDp.cellLayoutPaddingPx.top,
(mDp.isTwoPanels ? mDp.cellLayoutBorderSpacePx.x / 2
: mDp.workspacePadding.right) + mDp.cellLayoutPaddingPx.right,
mDp.workspacePadding.bottom + mDp.cellLayoutPaddingPx.bottom);
mWorkspaceScreens.put(FIRST_SCREEN_ID, firstScreen);
if (mDp.isTwoPanels) {
CellLayout rightPanel = mRootView.findViewById(R.id.workspace_right);
rightPanel.setPadding(
mDp.cellLayoutBorderSpacePx.x / 2,
mDp.workspacePadding.top + mDp.cellLayoutPaddingPx.top,
mDp.workspacePadding.right + mDp.cellLayoutPaddingPx.right,
mDp.workspacePadding.bottom + mDp.cellLayoutPaddingPx.bottom
);
mDp.cellLayoutBorderSpacePx.x / 2 + mDp.cellLayoutPaddingPx.left,
mDp.workspacePadding.top + mDp.cellLayoutPaddingPx.top,
mDp.workspacePadding.right + mDp.cellLayoutPaddingPx.right,
mDp.workspacePadding.bottom + mDp.cellLayoutPaddingPx.bottom);
mWorkspaceScreens.put(Workspace.SECOND_SCREEN_ID, rightPanel);
}
if (Flags.newCustomizationPickerUi()) {
if (previewColorOverride != null) {
mWallpaperColorResources = previewColorOverride;
} else if (wallpaperColorsOverride != null) {
mWallpaperColorResources = LocalColorExtractor.newInstance(
context).generateColorsOverride(wallpaperColorsOverride);
} else {
WallpaperColors wallpaperColors = null;
if (ATLEAST_O_MR1) {
wallpaperColors = WallpaperManager.getInstance(
context).getWallpaperColors(FLAG_SYSTEM);
}
mWallpaperColorResources = wallpaperColors != null
? LocalColorExtractor.newInstance(context).generateColorsOverride(
wallpaperColors)
: null;
}
} else {
WallpaperColors wallpaperColors = null;
if (ATLEAST_O_MR1) {
wallpaperColors = wallpaperColorsOverride != null
if (Utilities.ATLEAST_S) {
WallpaperColors wallpaperColors = wallpaperColorsOverride != null
? wallpaperColorsOverride
: WallpaperManager.getInstance(context).getWallpaperColors(FLAG_SYSTEM);
}
mWallpaperColorResources = wallpaperColors != null
? LocalColorExtractor.newInstance(context).generateColorsOverride(
wallpaperColors)
: null;
mWallpaperColorResources = wallpaperColors != null ? LocalColorExtractor.newInstance(
context).generateColorsOverride(wallpaperColors) : null;
} else {
mWallpaperColorResources = null;
}
mAppWidgetHost = new LauncherPreviewAppWidgetHost(context, widgetHostId);
onViewCreated();
if (widgetHostId != APPWIDGET_HOST_ID) {
mAppWidgetHost.stopListening();
}
}
@Override
public InsettableFrameLayout getRootView() {
return mRootView;
mAppWidgetHost = new LauncherPreviewAppWidgetHost(context);
}
/**
* Returns the device profile based on resource configuration for previewing various display
* Returns the device profile based on resource configuration for previewing
* various display
* sizes
*/
private DeviceProfile getDeviceProfileForPreview(Context context) {
@@ -379,10 +289,9 @@ public class LauncherPreviewRenderer extends BaseContext
Configuration config = context.getResources().getConfiguration();
return mIdp.getBestMatch(
config.screenWidthDp * density,
config.screenHeightDp * density,
WindowManagerProxy.INSTANCE.get(context).getRotation(context)
);
config.screenWidthDp * density,
config.screenHeightDp * density,
WindowManagerProxy.INSTANCE.get(context).getRotation(context));
}
/**
@@ -395,9 +304,9 @@ public class LauncherPreviewRenderer extends BaseContext
Rect insets = new Rect();
for (WindowBounds supportedBound : info.supportedBounds) {
double diff = Math.pow(display.getWidth() - supportedBound.availableSize.x, 2)
+ Math.pow(display.getHeight() - supportedBound.availableSize.y, 2);
+ Math.pow(display.getHeight() - supportedBound.availableSize.y, 2);
if (supportedBound.rotationHint == context.getDisplay().getRotation()
&& diff < maxDiff) {
&& diff < maxDiff) {
maxDiff = (float) diff;
insets = supportedBound.insets;
}
@@ -407,7 +316,7 @@ public class LauncherPreviewRenderer extends BaseContext
/** Populate preview and render it. */
public View getRenderedView(BgDataModel dataModel,
Map<ComponentKey, AppWidgetProviderInfo> widgetProviderInfoMap) {
Map<ComponentKey, AppWidgetProviderInfo> widgetProviderInfoMap) {
populate(dataModel, widgetProviderInfoMap);
return mRootView;
}
@@ -429,7 +338,7 @@ public class LauncherPreviewRenderer extends BaseContext
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PreviewFragment);
FragmentWithPreview f = (FragmentWithPreview) Fragment.instantiate(
context, ta.getString(R.styleable.PreviewFragment_android_name));
context, ta.getString(R.styleable.PreviewFragment_android_name));
f.enterPreviewMode(context);
f.onInit(null);
@@ -453,6 +362,11 @@ public class LauncherPreviewRenderer extends BaseContext
return mDp;
}
@Override
public List<OnDeviceProfileChangeListener> getOnDeviceProfileChangeListeners() {
return mDpChangeListeners;
}
@Override
public Hotseat getHotseat() {
return mHotseat;
@@ -467,12 +381,12 @@ public class LauncherPreviewRenderer extends BaseContext
mUiHandler.post(() -> {
if (mDp.isTaskbarPresent) {
// hotseat icons on bottom
mHotseat.setIconsAlpha(hide ? 0 : 1, ALPHA_CHANNEL_PREVIEW_RENDERER);
mHotseat.setIconsAlpha(hide ? 0 : 1);
if (mDp.isQsbInline) {
mHotseat.setQsbAlpha(hide ? 0 : 1, ALPHA_CHANNEL_PREVIEW_RENDERER);
mHotseat.setQsbAlpha(hide ? 0 : 1);
}
} else {
mHotseat.setQsbAlpha(hide ? 0 : 1, ALPHA_CHANNEL_PREVIEW_RENDERER);
mHotseat.setQsbAlpha(hide ? 0 : 1);
}
});
}
@@ -490,7 +404,7 @@ public class LauncherPreviewRenderer extends BaseContext
private void inflateAndAddIcon(WorkspaceItemInfo info) {
CellLayout screen = mWorkspaceScreens.get(info.screenId);
BubbleTextView icon = (BubbleTextView) mHomeElementInflater.inflate(
R.layout.app_icon, screen, false);
R.layout.app_icon, screen, false);
icon.applyFromWorkspaceItem(info);
addInScreenFromBind(icon, info);
}
@@ -498,39 +412,46 @@ public class LauncherPreviewRenderer extends BaseContext
private void inflateAndAddCollectionIcon(CollectionInfo info) {
boolean isOnDesktop = info.container == Favorites.CONTAINER_DESKTOP;
CellLayout screen = isOnDesktop
? mWorkspaceScreens.get(info.screenId)
: mHotseat;
? mWorkspaceScreens.get(info.screenId)
: mHotseat;
FrameLayout collectionIcon = info.itemType == Favorites.ITEM_TYPE_FOLDER
? FolderIcon.inflateIcon(R.layout.folder_icon, this, screen, (FolderInfo) info)
: AppPairIcon.inflateIcon(R.layout.app_pair_icon, this, screen, (AppPairInfo) info,
isOnDesktop ? DISPLAY_WORKSPACE : DISPLAY_TASKBAR);
? FolderIcon.inflateIcon(R.layout.folder_icon, this, screen, (FolderInfo) info)
: AppPairIcon.inflateIcon(R.layout.app_pair_icon, this, screen, (AppPairInfo) info,
isOnDesktop ? DISPLAY_WORKSPACE : DISPLAY_TASKBAR);
addInScreenFromBind(collectionIcon, info);
}
private void inflateAndAddWidgets(
LauncherAppWidgetInfo info,
Map<ComponentKey, AppWidgetProviderInfo> widgetProviderInfoMap) {
LauncherAppWidgetInfo info,
Map<ComponentKey, AppWidgetProviderInfo> widgetProviderInfoMap) {
if (widgetProviderInfoMap == null) {
return;
}
AppWidgetProviderInfo providerInfo = widgetProviderInfoMap.get(
new ComponentKey(info.providerName, info.user));
new ComponentKey(info.providerName, info.user));
if (providerInfo == null) {
return;
}
inflateAndAddWidgets(info, LauncherAppWidgetProviderInfo.fromProviderInfo(
getApplicationContext(), providerInfo));
getApplicationContext(), providerInfo));
}
private void inflateAndAddWidgets(LauncherAppWidgetInfo info, WidgetsModel widgetsModel) {
WidgetItem widgetItem = widgetsModel.getWidgetProviderInfoByProviderName(
info.providerName, info.user, mContext);
if (widgetItem == null) {
return;
}
inflateAndAddWidgets(info, widgetItem.widgetInfo);
}
private void inflateAndAddWidgets(
LauncherAppWidgetInfo info, LauncherAppWidgetProviderInfo providerInfo) {
LauncherAppWidgetInfo info, LauncherAppWidgetProviderInfo providerInfo) {
AppWidgetHostView view = mAppWidgetHost.createView(
mContext, info.appWidgetId, providerInfo);
mContext, info.appWidgetId, providerInfo);
if (mWallpaperColorResources != null) {
if (ATLEAST_S) {
view.setColorResources(mWallpaperColorResources);
}
view.setColorResources(mWallpaperColorResources);
}
view.setTag(info);
@@ -548,16 +469,16 @@ public class LauncherPreviewRenderer extends BaseContext
return DEFAULT_SCALE;
}
final Size origSize = WidgetSizes.getWidgetSizePx(mDpOrig,
launcherWidgetSize.getWidth(), launcherWidgetSize.getHeight());
launcherWidgetSize.getWidth(), launcherWidgetSize.getHeight());
final Size newSize = WidgetSizes.getWidgetSizePx(mDp, info.spanX, info.spanY);
return new PointF((float) newSize.getWidth() / origSize.getWidth(),
(float) newSize.getHeight() / origSize.getHeight());
(float) newSize.getHeight() / origSize.getHeight());
}
private void inflateAndAddPredictedIcon(WorkspaceItemInfo info) {
CellLayout screen = mWorkspaceScreens.get(info.screenId);
BubbleTextView icon = (BubbleTextView) mHomeElementInflater.inflate(
R.layout.predicted_app_icon, screen, false);
R.layout.predicted_app_icon, screen, false);
icon.applyFromWorkspaceItem(info);
addInScreenFromBind(icon, info);
}
@@ -581,58 +502,59 @@ public class LauncherPreviewRenderer extends BaseContext
}
private void populate(BgDataModel dataModel,
Map<ComponentKey, AppWidgetProviderInfo> widgetProviderInfoMap) {
IntSet missingHotseatRank = new IntSet();
IntStream.range(0, mDp.numShownHotseatIcons).forEach(missingHotseatRank::add);
Map<ComponentKey, AppWidgetProviderInfo> widgetProviderInfoMap) {
// Separate the items that are on the current screen, and the other remaining
// items.
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<>();
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<>();
ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<>();
ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<>();
Map<ComponentKey, AppWidgetProviderInfo>[] widgetsMap = new Map[] { widgetProviderInfoMap};
// Separate the items that are on the current screen, and the other remaining items.
dataModel.itemsIdMap.stream()
.filter(currentScreenContentFilter(IntSet.wrap(mWorkspaceScreens.keySet())))
.forEach(itemInfo -> {
switch (itemInfo.itemType) {
case Favorites.ITEM_TYPE_APPLICATION:
case Favorites.ITEM_TYPE_DEEP_SHORTCUT:
inflateAndAddIcon((WorkspaceItemInfo) itemInfo);
break;
case Favorites.ITEM_TYPE_FOLDER:
case Favorites.ITEM_TYPE_APP_PAIR:
inflateAndAddCollectionIcon((CollectionInfo) itemInfo);
break;
case Favorites.ITEM_TYPE_APPWIDGET:
case Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
if (widgetsMap[0] == null) {
widgetsMap[0] = dataModel.widgetsModel.getWidgetsByComponentKey()
.entrySet()
.stream()
.filter(entry -> entry.getValue().widgetInfo != null)
.collect(Collectors.toMap(
Entry::getKey,
entry -> entry.getValue().widgetInfo
));
}
inflateAndAddWidgets((LauncherAppWidgetInfo) itemInfo, widgetsMap[0]);
break;
default:
break;
}
if (itemInfo.container == CONTAINER_HOTSEAT) {
missingHotseatRank.remove(itemInfo.screenId);
}
});
IntArray ranks = missingHotseatRank.getArray();
FixedContainerItems hotseatPredictions =
dataModel.extraItems.get(CONTAINER_HOTSEAT_PREDICTION);
IntSet currentScreenIds = IntSet.wrap(mWorkspaceScreens.keySet());
filterCurrentWorkspaceItems(currentScreenIds, dataModel.workspaceItems,
currentWorkspaceItems, otherWorkspaceItems);
filterCurrentWorkspaceItems(currentScreenIds, dataModel.appWidgets, currentAppWidgets,
otherAppWidgets);
for (ItemInfo itemInfo : currentWorkspaceItems) {
switch (itemInfo.itemType) {
case Favorites.ITEM_TYPE_APPLICATION:
case Favorites.ITEM_TYPE_DEEP_SHORTCUT:
inflateAndAddIcon((WorkspaceItemInfo) itemInfo);
break;
case Favorites.ITEM_TYPE_FOLDER:
case Favorites.ITEM_TYPE_APP_PAIR:
inflateAndAddCollectionIcon((CollectionInfo) itemInfo);
break;
default:
break;
}
}
for (ItemInfo itemInfo : currentAppWidgets) {
switch (itemInfo.itemType) {
case Favorites.ITEM_TYPE_APPWIDGET:
case Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
if (widgetProviderInfoMap != null) {
inflateAndAddWidgets(
(LauncherAppWidgetInfo) itemInfo, widgetProviderInfoMap);
} else {
inflateAndAddWidgets((LauncherAppWidgetInfo) itemInfo,
dataModel.widgetsModel);
}
break;
default:
break;
}
}
IntArray ranks = getMissingHotseatRanks(currentWorkspaceItems,
mDp.numShownHotseatIcons);
FixedContainerItems hotseatPredictions = dataModel.extraItems.get(CONTAINER_HOTSEAT_PREDICTION);
List<ItemInfo> predictions = hotseatPredictions == null
? Collections.emptyList() : hotseatPredictions.items;
? Collections.emptyList()
: hotseatPredictions.items;
int count = Math.min(ranks.size(), predictions.size());
for (int i = 0; i < count; i++) {
int rank = ranks.get(i);
WorkspaceItemInfo itemInfo =
new WorkspaceItemInfo((WorkspaceItemInfo) predictions.get(i));
WorkspaceItemInfo itemInfo = new WorkspaceItemInfo((WorkspaceItemInfo) predictions.get(i));
itemInfo.container = CONTAINER_HOTSEAT_PREDICTION;
itemInfo.rank = rank;
itemInfo.cellX = mHotseat.getCellXFromOrder(rank);
@@ -642,13 +564,11 @@ public class LauncherPreviewRenderer extends BaseContext
}
// Add first page QSB
if (FeatureFlags.QSB_ON_FIRST_SCREEN && dataModel.isFirstPagePinnedItemEnabled
&& !SHOULD_SHOW_FIRST_PAGE_WIDGET) {
if (FeatureFlags.topQsbOnFirstScreenEnabled(mContext)) {
CellLayout firstScreen = mWorkspaceScreens.get(FIRST_SCREEN_ID);
View qsb = mHomeElementInflater.inflate(mWorkspaceSearchContainer, firstScreen, false);
// TODO: set bgHandler on qsb when it is BaseTemplateCard, which requires API changes.
CellLayoutLayoutParams lp = new CellLayoutLayoutParams(
0, 0, firstScreen.getCountX(), 1);
View qsb = mHomeElementInflater.inflate(mWorkspaceSearchContainer, firstScreen,
false);
CellLayoutLayoutParams lp = new CellLayoutLayoutParams(0, 0, mDp.inv.numColumns, 1);
lp.canReorder = false;
firstScreen.addViewToCellLayout(qsb, 0, R.id.search_container_workspace, lp, true);
}
@@ -659,14 +579,7 @@ public class LauncherPreviewRenderer extends BaseContext
// Additional measure for views which use auto text size API
measureView(mRootView, mDp.widthPx, mDp.heightPx);
}
/**
* Lawnchair
* <p>
* Set custom search container for workspace.
*
* @param resId True to hide and false to show.
*/
public void setWorkspaceSearchContainer(int resId) {
mWorkspaceSearchContainer = resId;
}
@@ -678,15 +591,15 @@ public class LauncherPreviewRenderer extends BaseContext
private class LauncherPreviewAppWidgetHost extends AppWidgetHost {
private LauncherPreviewAppWidgetHost(Context context, int hostId) {
super(context, hostId);
private LauncherPreviewAppWidgetHost(Context context) {
super(context, LauncherWidgetHolder.APPWIDGET_HOST_ID);
}
@Override
protected AppWidgetHostView onCreateView(
Context context,
int appWidgetId,
AppWidgetProviderInfo appWidget) {
Context context,
int appWidgetId,
AppWidgetProviderInfo appWidget) {
return new LauncherPreviewAppWidgetHostView(LauncherPreviewRenderer.this);
}
}
@@ -718,27 +631,4 @@ public class LauncherPreviewRenderer extends BaseContext
return true;
}
}
@LauncherAppSingleton
// Exclude widget module since we bind widget holder separately
@Component(modules = {WindowManagerProxyModule.class,
ApiWrapperModule.class,
PluginManagerWrapperModule.class,
StaticObjectModule.class,
AppModule.class})
public interface PreviewAppComponent extends LauncherAppComponent {
LoaderTaskFactory getLoaderTaskFactory();
BaseLauncherBinderFactory getBaseLauncherBinderFactory();
BgDataModel getDataModel();
/** Builder for NexusLauncherAppComponent. */
@Component.Builder
interface Builder extends LauncherAppComponent.Builder {
@BindsInstance Builder bindPrefs(LauncherPrefs prefs);
@BindsInstance Builder bindParserFactory(LayoutParserFactory parserFactory);
@BindsInstance Builder bindWidgetsFactory(WidgetHolderFactory holderFactory);
PreviewAppComponent build();
}
}
}
@@ -24,6 +24,7 @@ import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
@@ -32,15 +33,14 @@ import android.graphics.PathMeasure;
import android.graphics.Rect;
import android.util.Property;
import androidx.annotation.VisibleForTesting;
import androidx.core.graphics.ColorUtils;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimatedFloat;
import com.android.launcher3.anim.AnimatorListeners;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.FastBitmapDrawable;
import com.android.launcher3.icons.GraphicsUtils;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.util.Themes;
@@ -64,6 +64,8 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
private static final int DEFAULT_PATH_SIZE = 100;
private static final int MAX_PAINT_ALPHA = 255;
private static final int TRACK_ALPHA = (int) (0.27f * MAX_PAINT_ALPHA);
private static final int DISABLED_ICON_ALPHA = (int) (0.6f * MAX_PAINT_ALPHA);
private static final long DURATION_SCALE = 500;
private static final long SCALE_AND_ALPHA_ANIM_DURATION = 500;
@@ -119,8 +121,7 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
IconPalette.getPreloadProgressColor(context, info.bitmap.color),
getPreloadColors(context),
Utilities.isDarkTheme(context),
ThemeManager.INSTANCE.get(context).getIconShape().getPath(DEFAULT_PATH_SIZE)
);
GraphicsUtils.getShapePath(context, DEFAULT_PATH_SIZE));
}
public PreloadIconDrawable(
@@ -283,25 +284,20 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
(long) ((finalProgress - mInternalStateProgress) * DURATION_SCALE));
mCurrentAnim.setInterpolator(LINEAR);
if (isFinish) {
if (onFinishCallback != null) {
mCurrentAnim.addListener(AnimatorListeners.forEndCallback(onFinishCallback));
}
mCurrentAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mRanFinishAnimation = true;
}
});
if (onFinishCallback != null) {
mCurrentAnim.addListener(AnimatorListeners.forEndCallback(onFinishCallback));
}
}
mCurrentAnim.start();
}
}
@VisibleForTesting
public ObjectAnimator getActiveAnimation() {
return mCurrentAnim;
}
/**
* Sets the internal progress and updates the UI accordingly
* for progress <= 0:
@@ -362,7 +358,8 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
@Override
public FastBitmapConstantState newConstantState() {
return new PreloadIconConstantState(
mBitmapInfo,
mBitmap,
mIconColor,
mItem,
mIndicatorColor,
new int[] {mSystemAccentColor, mSystemBackgroundColor},
@@ -380,13 +377,14 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
private final Path mShapePath;
public PreloadIconConstantState(
BitmapInfo bitmapInfo,
Bitmap bitmap,
int iconColor,
ItemInfoWithIcon info,
int indicatorColor,
int[] preloadColors,
boolean isDarkMode,
Path shapePath) {
super(bitmapInfo);
super(bitmap, iconColor);
mInfo = info;
mIndicatorColor = indicatorColor;
mPreloadColors = preloadColors;
@@ -16,42 +16,29 @@
package com.android.launcher3.graphics;
import static android.content.res.Configuration.UI_MODE_NIGHT_NO;
import static android.content.res.Configuration.UI_MODE_NIGHT_YES;
import static android.view.Display.DEFAULT_DISPLAY;
import static com.android.launcher3.Flags.extendibleThemeManager;
import static com.android.launcher3.LauncherPrefs.GRID_NAME;
import static com.android.launcher3.WorkspaceLayoutManager.FIRST_SCREEN_ID;
import static com.android.launcher3.WorkspaceLayoutManager.SECOND_SCREEN_ID;
import static com.android.launcher3.graphics.ThemeManager.PREF_ICON_SHAPE;
import static com.android.launcher3.provider.LauncherDbUtils.selectionForWorkspaceScreen;
import static com.android.launcher3.LauncherSettings.Favorites.TABLE_NAME;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import static com.android.launcher3.widget.LauncherWidgetHolder.APPWIDGET_HOST_ID;
import android.app.WallpaperColors;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
import android.content.res.Configuration;
import android.database.Cursor;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.util.Size;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.ContextThemeWrapper;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceControlViewHost;
import android.view.SurfaceControlViewHost.SurfacePackage;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -61,102 +48,83 @@ import androidx.annotation.WorkerThread;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherPrefs;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.dagger.LauncherComponentProvider;
import com.android.launcher3.graphics.LauncherPreviewRenderer.PreviewAppComponent;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.graphics.LauncherPreviewRenderer.PreviewContext;
import com.android.launcher3.model.BaseLauncherBinder;
import com.android.launcher3.model.BgDataModel;
import com.android.launcher3.model.BgDataModel.Callbacks;
import com.android.launcher3.model.GridSizeMigrationUtil;
import com.android.launcher3.model.LoaderTask;
import com.android.launcher3.model.ModelDbController;
import com.android.launcher3.model.UserManagerState;
import com.android.launcher3.provider.LauncherDbUtils;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.RunnableList;
import com.android.launcher3.util.Themes;
import com.android.launcher3.widget.LocalColorExtractor;
import com.android.systemui.shared.Flags;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/** Render preview using surface view. */
@SuppressWarnings("NewApi")
public class PreviewSurfaceRenderer {
private static final String TAG = "PreviewSurfaceRenderer";
private static final int FADE_IN_ANIMATION_DURATION = 200;
private static final String KEY_HOST_TOKEN = "host_token";
private static final String KEY_VIEW_WIDTH = "width";
private static final String KEY_VIEW_HEIGHT = "height";
private static final String KEY_DISPLAY_ID = "display_id";
private static final String KEY_COLORS = "wallpaper_colors";
private static final String KEY_COLOR_RESOURCE_IDS = "color_resource_ids";
private static final String KEY_COLOR_VALUES = "color_values";
private static final String KEY_DARK_MODE = "use_dark_mode";
private static final String KEY_LAYOUT_XML = "layout_xml";
public static final String KEY_SKIP_ANIMATIONS = "skip_animations";
private final Context mContext;
private SparseIntArray mPreviewColorOverride;
private String mGridName;
private String mShapeKey;
private String mLayoutXml;
@Nullable private Boolean mDarkMode;
private boolean mDestroyed = false;
private boolean mHideQsb;
@Nullable private FrameLayout mViewRoot = null;
private boolean mDeletingHostOnExit = false;
private final int mCallingPid;
private Context mContext;
private final IBinder mHostToken;
private final int mWidth;
private final int mHeight;
private final boolean mSkipAnimations;
private String mGridName;
private final int mDisplayId;
private final Display mDisplay;
private final WallpaperColors mWallpaperColors;
private final RunnableList mLifeCycleTracker;
private final RunnableList mOnDestroyCallbacks = new RunnableList();
private final SurfaceControlViewHost mSurfaceControlViewHost;
public PreviewSurfaceRenderer(Context context, RunnableList lifecycleTracker, Bundle bundle,
int callingPid) throws Exception {
private boolean mDestroyed = false;
private LauncherPreviewRenderer mRenderer;
private boolean mHideQsb;
public PreviewSurfaceRenderer(Context context, Bundle bundle) throws Exception {
mContext = context;
mLifeCycleTracker = lifecycleTracker;
mCallingPid = callingPid;
mGridName = bundle.getString("name");
bundle.remove("name");
if (mGridName == null) {
mGridName = LauncherPrefs.get(context).get(GRID_NAME);
mGridName = InvariantDeviceProfile.getCurrentGridName(context);
}
mShapeKey = LauncherPrefs.get(context).get(PREF_ICON_SHAPE);
mWallpaperColors = bundle.getParcelable(KEY_COLORS);
if (Flags.newCustomizationPickerUi()) {
updateColorOverrides(bundle);
}
mHideQsb = bundle.getBoolean(GridCustomizationsProxy.KEY_HIDE_BOTTOM_ROW);
mHideQsb = bundle.getBoolean(GridCustomizationsProvider.KEY_HIDE_BOTTOM_ROW);
mHostToken = bundle.getBinder(KEY_HOST_TOKEN);
mWidth = bundle.getInt(KEY_VIEW_WIDTH);
mHeight = bundle.getInt(KEY_VIEW_HEIGHT);
mSkipAnimations = bundle.getBoolean(KEY_SKIP_ANIMATIONS, false);
mDisplayId = bundle.getInt(KEY_DISPLAY_ID);
mDisplay = context.getSystemService(DisplayManager.class)
.getDisplay(mDisplayId);
mLayoutXml = bundle.getString(KEY_LAYOUT_XML);
if (mDisplay == null) {
throw new IllegalArgumentException("Display ID does not match any displays.");
}
mSurfaceControlViewHost = MAIN_EXECUTOR.submit(() -> new MySurfaceControlViewHost(
mContext,
context.getSystemService(DisplayManager.class).getDisplay(DEFAULT_DISPLAY),
mHostToken,
mLifeCycleTracker))
.get(5, TimeUnit.SECONDS);
mLifeCycleTracker.add(this::destroy);
mSurfaceControlViewHost = MAIN_EXECUTOR.submit(() ->
new SurfaceControlViewHost(mContext, context.getSystemService(DisplayManager.class)
.getDisplay(DEFAULT_DISPLAY), mHostToken)
).get(5, TimeUnit.SECONDS);
mOnDestroyCallbacks.add(mSurfaceControlViewHost::release);
}
public int getDisplayId() {
@@ -171,25 +139,33 @@ public class PreviewSurfaceRenderer {
return mSurfaceControlViewHost.getSurfacePackage();
}
private void destroy() {
/**
* Destroys the preview and all associated data
*/
@UiThread
public void destroy() {
mDestroyed = true;
mOnDestroyCallbacks.executeAllAndDestroy();
}
/**
* A function that queries for the launcher app widget span info
*
* @return A SparseArray with the app widget id being the key and the span info being the values
* @param context The context to get the content resolver from, should be
* related to launcher
* @return A SparseArray with the app widget id being the key and the span info
* being the values
*/
@WorkerThread
@Nullable
public SparseArray<Size> getLoadedLauncherWidgetInfo() {
public SparseArray<Size> getLoadedLauncherWidgetInfo(
@NonNull final Context context) {
final SparseArray<Size> widgetInfo = new SparseArray<>();
final String query = LauncherSettings.Favorites.ITEM_TYPE + " = "
+ LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET;
ModelDbController mainController =
LauncherAppState.getInstance(mContext).getModel().getModelDbController();
try (Cursor c = mainController.query(
ModelDbController mainController = LauncherAppState.getInstance(mContext).getModel().getModelDbController();
try (Cursor c = mainController.query(TABLE_NAME,
new String[] {
LauncherSettings.Favorites.APPWIDGET_ID,
LauncherSettings.Favorites.SPANX,
@@ -221,177 +197,91 @@ public class PreviewSurfaceRenderer {
MODEL_EXECUTOR.execute(this::loadModelData);
}
/**
* Update the grid of the launcher preview
*
* @param gridName Name of the grid, e.g. normal, practical
*/
public void updateGrid(@NonNull String gridName) {
if (gridName.equals(mGridName)) {
return;
}
mGridName = gridName;
loadAsync();
}
/**
* Update the shapes of the launcher preview
*
* @param shapeKey key for the IconShape model
*/
public void updateShape(String shapeKey) {
if (shapeKey.equals(mShapeKey)) {
Log.w(TAG, "Preview shape already set, skipping. shape=" + mShapeKey);
return;
}
mShapeKey = shapeKey;
loadAsync();
}
/**
* Hides the components in the bottom row.
*
* @param hide True to hide and false to show.
*/
public void hideBottomRow(boolean hide) {
mHideQsb = hide;
loadAsync();
}
/**
* Updates the colors of the preview.
*
* @param bundle Bundle with an int array of color ids and an int array of overriding colors.
*/
public void previewColor(Bundle bundle) {
updateColorOverrides(bundle);
loadAsync();
}
private void updateColorOverrides(Bundle bundle) {
mDarkMode =
bundle.containsKey(KEY_DARK_MODE) ? bundle.getBoolean(KEY_DARK_MODE) : null;
int[] ids = bundle.getIntArray(KEY_COLOR_RESOURCE_IDS);
int[] colors = bundle.getIntArray(KEY_COLOR_VALUES);
if (ids != null && colors != null) {
mPreviewColorOverride = new SparseIntArray();
for (int i = 0; i < ids.length; i++) {
mPreviewColorOverride.put(ids[i], colors[i]);
}
} else {
mPreviewColorOverride = null;
if (mRenderer != null) {
// mRenderer.hideBottomRow(hide);
}
}
/***
* Generates a new context overriding the theme color and the display size without affecting the
* Generates a new context overriding the theme color and the display size
* without affecting the
* main application context
*/
private Context getPreviewContext() {
Context context = mContext.createDisplayContext(mDisplay);
if (mDarkMode != null) {
Configuration configuration = new Configuration(
context.getResources().getConfiguration());
if (mDarkMode) {
configuration.uiMode &= ~UI_MODE_NIGHT_NO;
configuration.uiMode |= UI_MODE_NIGHT_YES;
} else {
configuration.uiMode &= ~UI_MODE_NIGHT_YES;
configuration.uiMode |= UI_MODE_NIGHT_NO;
}
context = context.createConfigurationContext(configuration);
}
if (InvariantDeviceProfile.INSTANCE.get(context).isFixedLandscape) {
Configuration configuration = new Configuration(
context.getResources().getConfiguration()
);
int width = configuration.screenWidthDp;
int height = configuration.screenHeightDp;
if (configuration.screenHeightDp > configuration.screenWidthDp) {
configuration.screenWidthDp = height;
configuration.screenHeightDp = width;
configuration.orientation = Configuration.ORIENTATION_PORTRAIT;
}
context = context.createConfigurationContext(configuration);
}
if (Flags.newCustomizationPickerUi()) {
if (mPreviewColorOverride != null) {
LocalColorExtractor.newInstance(context)
.applyColorsOverride(context, mPreviewColorOverride);
} else if (mWallpaperColors != null) {
LocalColorExtractor.newInstance(context)
.applyColorsOverride(context, mWallpaperColors);
}
if (mWallpaperColors != null) {
return new ContextThemeWrapper(context,
Themes.getActivityThemeRes(context, mWallpaperColors.getColorHints()));
} else {
return new ContextThemeWrapper(context,
Themes.getActivityThemeRes(context));
}
} else {
if (mWallpaperColors == null) {
return new ContextThemeWrapper(context,
Themes.getActivityThemeRes(context));
}
LocalColorExtractor.newInstance(context)
.applyColorsOverride(context, mWallpaperColors);
if (mWallpaperColors == null) {
return new ContextThemeWrapper(context,
Themes.getActivityThemeRes(context, mWallpaperColors.getColorHints()));
Themes.getActivityThemeRes(context));
}
if (Utilities.ATLEAST_R) {
context = context.createWindowContext(
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, null);
}
LocalColorExtractor.newInstance(mContext)
.applyColorsOverride(context, mWallpaperColors);
return new ContextThemeWrapper(context,
Themes.getActivityThemeRes(context, mWallpaperColors.getColorHints()));
}
@WorkerThread
private void loadModelData() {
final Context inflationContext = getPreviewContext();
if (!mGridName.equals(LauncherPrefs.INSTANCE.get(mContext).get(GRID_NAME))
|| !mShapeKey.equals(LauncherPrefs.INSTANCE.get(mContext).get(PREF_ICON_SHAPE))
|| !TextUtils.isEmpty(mLayoutXml)) {
boolean isCustomLayout = extendibleThemeManager() && !TextUtils.isEmpty(mLayoutXml);
int widgetHostId = isCustomLayout ? APPWIDGET_HOST_ID + mCallingPid : APPWIDGET_HOST_ID;
final InvariantDeviceProfile idp = new InvariantDeviceProfile(inflationContext, mGridName);
if (GridSizeMigrationUtil.needsToMigrate(inflationContext, idp)) {
// Start the migration
PreviewContext previewContext = new PreviewContext(
inflationContext, mGridName, mShapeKey, widgetHostId, mLayoutXml);
PreviewAppComponent appComponent =
(PreviewAppComponent) LauncherComponentProvider.get(previewContext);
PreviewContext previewContext = new PreviewContext(inflationContext, idp);
// Copy existing data to preview DB
LauncherDbUtils.copyTable(LauncherAppState.getInstance(mContext)
.getModel().getModelDbController().getDb(),
TABLE_NAME,
LauncherAppState.getInstance(previewContext)
.getModel().getModelDbController().getDb(),
TABLE_NAME,
mContext);
LauncherAppState.getInstance(previewContext)
.getModel().getModelDbController().clearEmptyDbFlag();
if (extendibleThemeManager() && isCustomLayout && !mDeletingHostOnExit) {
mDeletingHostOnExit = true;
mLifeCycleTracker.add(() -> {
AppWidgetHost host = new AppWidgetHost(mContext, widgetHostId);
// Start listening here, so that any previous active host is disabled
host.startListening();
host.stopListening();
host.deleteHost();
});
}
BgDataModel bgModel = new BgDataModel();
new LoaderTask(
LauncherAppState.getInstance(previewContext),
/* bgAllAppsList= */ null,
bgModel,
LauncherAppState.getInstance(previewContext).getModel().getModelDelegate(),
new BaseLauncherBinder(LauncherAppState.getInstance(previewContext), bgModel,
/* bgAllAppsList= */ null, new Callbacks[0])) {
LoaderTask task = appComponent.getLoaderTaskFactory().newLoaderTask(
appComponent.getBaseLauncherBinderFactory().createBinder(new Callbacks[0]),
new UserManagerState());
@Override
public void run() {
DeviceProfile deviceProfile = idp.getDeviceProfile(previewContext);
String query = LauncherSettings.Favorites.SCREEN + " = " + Workspace.FIRST_SCREEN_ID
+ " or " + LauncherSettings.Favorites.CONTAINER + " = "
+ LauncherSettings.Favorites.CONTAINER_HOTSEAT;
if (deviceProfile.isTwoPanels) {
query += " or " + LauncherSettings.Favorites.SCREEN + " = "
+ Workspace.SECOND_SCREEN_ID;
}
loadWorkspace(new ArrayList<>(), query, null, null);
InvariantDeviceProfile idp = appComponent.getIDP();
DeviceProfile deviceProfile = idp.getDeviceProfile(previewContext);
String query = deviceProfile.isTwoPanels
? selectionForWorkspaceScreen(FIRST_SCREEN_ID, SECOND_SCREEN_ID)
: selectionForWorkspaceScreen(FIRST_SCREEN_ID);
Map<ComponentKey, AppWidgetProviderInfo> widgetProviderInfoMap = new HashMap<>();
task.loadWorkspaceForPreview(query, widgetProviderInfoMap);
final SparseArray<Size> spanInfo = getLoadedLauncherWidgetInfo();
MAIN_EXECUTOR.execute(() -> {
renderView(previewContext, appComponent.getDataModel(), widgetHostId,
widgetProviderInfoMap, spanInfo, idp);
mLifeCycleTracker.add(previewContext::onDestroy);
});
final SparseArray<Size> spanInfo = getLoadedLauncherWidgetInfo(previewContext.getBaseContext());
MAIN_EXECUTOR.execute(() -> {
renderView(previewContext, mBgDataModel, mWidgetProvidersMap, spanInfo,
idp);
mOnDestroyCallbacks.add(previewContext::onDestroy);
});
}
}.run();
} else {
LauncherAppState.getInstance(inflationContext).getModel().loadAsync(dataModel -> {
if (dataModel != null) {
MAIN_EXECUTOR.execute(() -> renderView(inflationContext, dataModel,
APPWIDGET_HOST_ID, null, null,
LauncherAppState.getIDP(inflationContext)));
MAIN_EXECUTOR.execute(() -> renderView(inflationContext, dataModel, null,
null, idp));
} else {
Log.e(TAG, "Model loading failed");
}
@@ -400,97 +290,30 @@ public class PreviewSurfaceRenderer {
}
@UiThread
private void renderView(Context inflationContext, BgDataModel dataModel, int widgetHostId,
private void renderView(Context inflationContext, BgDataModel dataModel,
Map<ComponentKey, AppWidgetProviderInfo> widgetProviderInfoMap,
@Nullable final SparseArray<Size> launcherWidgetSpanInfo, InvariantDeviceProfile idp) {
if (mDestroyed) {
return;
}
LauncherPreviewRenderer renderer;
if (Flags.newCustomizationPickerUi()) {
renderer = new LauncherPreviewRenderer(inflationContext, idp, widgetHostId,
mPreviewColorOverride, mWallpaperColors, launcherWidgetSpanInfo);
} else {
renderer = new LauncherPreviewRenderer(inflationContext, idp, widgetHostId,
mWallpaperColors, launcherWidgetSpanInfo);
}
renderer.hideBottomRow(mHideQsb);
View view = renderer.getRenderedView(dataModel, widgetProviderInfoMap);
mRenderer = new LauncherPreviewRenderer(inflationContext, idp,
mWallpaperColors, launcherWidgetSpanInfo);
// mRenderer.hideBottomRow(mHideQsb);
View view = mRenderer.getRenderedView(dataModel, widgetProviderInfoMap);
// This aspect scales the view to fit in the surface and centers it
final float scale = Math.min(mWidth / (float) view.getMeasuredWidth(),
mHeight / (float) view.getMeasuredHeight());
view.setScaleX(scale);
view.setScaleY(scale);
view.setPivotX(0);
view.setPivotY(0);
if (idp.isFixedLandscape) {
final float scale = Math.min(mHeight / (float) view.getMeasuredWidth(),
mWidth / (float) view.getMeasuredHeight());
view.setScaleX(scale);
view.setScaleY(scale);
view.setRotation(90);
view.setTranslationX((mHeight - scale * view.getWidth()) / 2 + mWidth);
view.setTranslationY((mWidth - scale * view.getHeight()) / 2);
} else {
// This aspect scales the view to fit in the surface and centers it
final float scale = Math.min(mWidth / (float) view.getMeasuredWidth(),
mHeight / (float) view.getMeasuredHeight());
view.setScaleX(scale);
view.setScaleY(scale);
view.setTranslationX((mWidth - scale * view.getWidth()) / 2);
view.setTranslationY((mHeight - scale * view.getHeight()) / 2);
}
if (!Flags.newCustomizationPickerUi()) {
view.setAlpha(mSkipAnimations ? 1 : 0);
view.animate().alpha(1)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setDuration(FADE_IN_ANIMATION_DURATION)
.start();
mSurfaceControlViewHost.setView(
view,
view.getMeasuredWidth(),
view.getMeasuredHeight()
);
return;
}
if (mViewRoot == null) {
mViewRoot = new FrameLayout(inflationContext);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT, // Width
FrameLayout.LayoutParams.WRAP_CONTENT // Height
);
mViewRoot.setLayoutParams(layoutParams);
mViewRoot.addView(view);
mViewRoot.setAlpha(mSkipAnimations ? 1 : 0);
mViewRoot.animate().alpha(1)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setDuration(FADE_IN_ANIMATION_DURATION)
.start();
mSurfaceControlViewHost.setView(
mViewRoot,
view.getMeasuredWidth(),
view.getMeasuredHeight()
);
} else {
mViewRoot.removeAllViews();
mViewRoot.addView(view);
}
}
private static class MySurfaceControlViewHost extends SurfaceControlViewHost {
private final RunnableList mLifecycleTracker;
MySurfaceControlViewHost(Context context, Display display, IBinder hostToken,
RunnableList lifeCycleTracker) {
super(context, display, hostToken);
mLifecycleTracker = lifeCycleTracker;
mLifecycleTracker.add(this::release);
}
@Override
public void release() {
super.release();
// RunnableList ensures that the callback is only called once
MAIN_EXECUTOR.execute(mLifecycleTracker::executeAllAndDestroy);
}
view.setTranslationX((mWidth - scale * view.getWidth()) / 2);
view.setTranslationY((mHeight - scale * view.getHeight()) / 2);
view.setAlpha(0);
view.animate().alpha(1)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setDuration(FADE_IN_ANIMATION_DURATION)
.start();
mSurfaceControlViewHost.setView(view, view.getMeasuredWidth(), view.getMeasuredHeight());
}
}
@@ -13,13 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications copyright 2025, Lawnchair
* Modifications copyright 2022, Lawnchair
*/
package com.android.launcher3.graphics;
import static android.graphics.Paint.DITHER_FLAG;
import static android.graphics.Paint.FILTER_BITMAP_FLAG;
import static com.android.launcher3.config.FeatureFlags.KEYGUARD_ANIMATION;
import android.animation.ObjectAnimator;
import android.graphics.Bitmap;
import android.graphics.Canvas;
@@ -34,16 +36,14 @@ import android.view.View;
import androidx.annotation.ColorInt;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.R;
import com.android.launcher3.anim.AnimatedFloat;
import com.android.launcher3.statemanager.StatefulContainer;
import com.android.launcher3.testing.shared.ResourceUtils;
import com.android.launcher3.util.ScreenOnTracker;
import com.android.launcher3.util.ScreenOnTracker.ScreenOnListener;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.ActivityContext;
import com.patrykmichalik.opto.core.PreferenceExtensionsKt;
import app.lawnchair.preferences2.PreferenceManager2;
import app.lawnchair.util.ViewExtensionsKt;
@@ -66,7 +66,8 @@ public class SysUiScrim implements View.OnAttachStateChangeListener {
@Override
public void onUserPresent() {
// ACTION_USER_PRESENT is sent after onStart/onResume. This covers the case where
// ACTION_USER_PRESENT is sent after onStart/onResume. This covers the case
// where
// the user unlocked and the Launcher is not in the foreground.
mAnimateScrimOnNextDraw = false;
}
@@ -91,7 +92,7 @@ public class SysUiScrim implements View.OnAttachStateChangeListener {
private final int mBottomMaskHeight;
private final View mRoot;
private final StatefulContainer mContainer;
private final BaseDraggingActivity mActivity;
private boolean mHideSysUiScrim;
private boolean mSkipScrimAnimationForTest = false;
@@ -101,8 +102,8 @@ public class SysUiScrim implements View.OnAttachStateChangeListener {
public SysUiScrim(View view) {
mRoot = view;
mContainer = ActivityContext.lookupContext(view.getContext());
DisplayMetrics dm = mContainer.asContext().getResources().getDisplayMetrics();
mActivity = BaseDraggingActivity.fromContext(view.getContext());
DisplayMetrics dm = mActivity.getResources().getDisplayMetrics();
mTopMaskHeight = ResourceUtils.pxFromDp(TOP_MASK_HEIGHT_DP, dm);
mBottomMaskHeight = ResourceUtils.pxFromDp(BOTTOM_MASK_HEIGHT_DP, dm);
@@ -118,7 +119,7 @@ public class SysUiScrim implements View.OnAttachStateChangeListener {
new int[] { 0x00FFFFFF, 0x2FFFFFFF },
new float[] { 0f, 1f });
if (!mHideSysUiScrim) {
if (!KEYGUARD_ANIMATION.get() && !mHideSysUiScrim) {
view.addOnAttachStateChangeListener(this);
}
@@ -151,7 +152,7 @@ public class SysUiScrim implements View.OnAttachStateChangeListener {
ObjectAnimator oa = mSysUiAnimMultiplier.animateToValue(1);
oa.setDuration(600);
oa.setStartDelay(mContainer.getWindow().getTransitionBackgroundFadeDuration());
oa.setStartDelay(mActivity.getWindow().getTransitionBackgroundFadeDuration());
oa.start();
mAnimateScrimOnNextDraw = false;
}
@@ -166,7 +167,8 @@ public class SysUiScrim implements View.OnAttachStateChangeListener {
}
/**
* Returns the sysui multiplier property for controlling fade in/out of the scrim
* Returns the sysui multiplier property for controlling fade in/out of the
* scrim
*/
public AnimatedFloat getSysUIMultiplier() {
return mSysUiAnimMultiplier;
@@ -182,24 +184,26 @@ public class SysUiScrim implements View.OnAttachStateChangeListener {
/**
* Determines whether to draw the top and/or bottom scrim based on new insets.
*
* In order for the bottom scrim to be drawn this 3 condition should be meet at the same time:
* the device is in 3 button navigation, the taskbar is not present and the Hotseat is
* In order for the bottom scrim to be drawn this 3 condition should be meet at
* the same time:
* the device is in 3 button navigation, the taskbar is not present and the
* Hotseat is
* horizontal
*/
public void onInsetsChanged(Rect insets) {
DeviceProfile dp = mContainer.getDeviceProfile();
DeviceProfile dp = mActivity.getDeviceProfile();
mDrawTopScrim = insets.top > 0;
mDrawBottomScrim = !dp.isVerticalBarLayout() && !dp.isGestureMode && !dp.isTaskbarPresent;
}
@Override
public void onViewAttachedToWindow(View view) {
ScreenOnTracker.INSTANCE.get(mContainer.asContext()).addListener(mScreenOnListener);
ScreenOnTracker.INSTANCE.get(mActivity).addListener(mScreenOnListener);
}
@Override
public void onViewDetachedFromWindow(View view) {
ScreenOnTracker.INSTANCE.get(mContainer.asContext()).removeListener(mScreenOnListener);
ScreenOnTracker.INSTANCE.get(mActivity).removeListener(mScreenOnListener);
}
/**
@@ -228,13 +232,14 @@ public class SysUiScrim implements View.OnAttachStateChangeListener {
private void reapplySysUiAlphaNoInvalidate() {
float factor = mSysUiProgress.value * mSysUiAnimMultiplier.value;
if (mSkipScrimAnimationForTest) factor = 1f;
if (mSkipScrimAnimationForTest)
factor = 1f;
mBottomMaskPaint.setAlpha(Math.round(MAX_SYSUI_SCRIM_ALPHA * factor));
mTopMaskPaint.setAlpha(Math.round(MAX_SYSUI_SCRIM_ALPHA * factor));
}
private Bitmap createDitheredAlphaMask(int height, @ColorInt int[] colors, float[] positions) {
DisplayMetrics dm = mContainer.asContext().getResources().getDisplayMetrics();
DisplayMetrics dm = mActivity.getResources().getDisplayMetrics();
int width = ResourceUtils.pxFromDp(ALPHA_MASK_BITMAP_WIDTH_DP, dm);
Bitmap dst = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
Canvas c = new Canvas(dst);
@@ -0,0 +1,75 @@
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.icons;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.UserHandle;
import androidx.annotation.NonNull;
import com.android.launcher3.icons.cache.CachingLogic;
public interface ComponentWithLabel {
ComponentName getComponent();
UserHandle getUser();
CharSequence getLabel(PackageManager pm);
class ComponentCachingLogic<T extends ComponentWithLabel> implements CachingLogic<T> {
private final PackageManager mPackageManager;
private final boolean mAddToMemCache;
public ComponentCachingLogic(Context context, boolean addToMemCache) {
mPackageManager = context.getPackageManager();
mAddToMemCache = addToMemCache;
}
@Override
@NonNull
public ComponentName getComponent(@NonNull T object) {
return object.getComponent();
}
@NonNull
@Override
public UserHandle getUser(@NonNull T object) {
return object.getUser();
}
@NonNull
@Override
public CharSequence getLabel(@NonNull T object) {
return object.getLabel(mPackageManager);
}
@NonNull
@Override
public BitmapInfo loadIcon(@NonNull Context context, @NonNull T object) {
return BitmapInfo.LOW_RES_INFO;
}
@Override
public boolean addToMemCache() {
return mAddToMemCache;
}
}
}
+244 -265
View File
@@ -17,10 +17,8 @@
package com.android.launcher3.icons;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT;
import static com.android.launcher3.icons.cache.CacheLookupFlag.DEFAULT_LOOKUP_FLAG;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import static com.android.launcher3.util.LooperExecutor.CALLER_ICON_CACHE;
import static com.android.launcher3.widget.WidgetSections.NO_CATEGORY;
import static java.util.stream.Collectors.groupingBy;
@@ -31,11 +29,16 @@ import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ShortcutInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.Drawable;
import android.os.Looper;
import android.os.Process;
import android.os.Trace;
import android.os.UserHandle;
import android.text.TextUtils;
@@ -52,13 +55,9 @@ import com.android.launcher3.Flags;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherFiles;
import com.android.launcher3.Utilities;
import com.android.launcher3.dagger.ApplicationContext;
import com.android.launcher3.dagger.LauncherAppSingleton;
import com.android.launcher3.icons.ComponentWithLabel.ComponentCachingLogic;
import com.android.launcher3.icons.cache.BaseIconCache;
import com.android.launcher3.icons.cache.CacheLookupFlag;
import com.android.launcher3.icons.cache.CachedObject;
import com.android.launcher3.icons.cache.CachedObjectCachingLogic;
import com.android.launcher3.icons.cache.LauncherActivityCachingLogic;
import com.android.launcher3.icons.cache.CachingLogic;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.IconRequestInfo;
@@ -67,9 +66,9 @@ import com.android.launcher3.model.data.PackageItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.InstallSessionHelper;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.util.FlagOp;
import com.android.launcher3.util.CancellableTask;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.DaggerSingletonTracker;
import com.android.launcher3.util.InstantAppResolver;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.widget.WidgetSections;
@@ -83,107 +82,61 @@ import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.inject.Named;
import app.lawnchair.icons.LawnchairIconProvider;
/**
* Cache of application icons. Icons can be made from any thread.
* Cache of application icons. Icons can be made from any thread.
*/
@LauncherAppSingleton
public class IconCache extends BaseIconCache {
// Shortcut extra which can point to a packageName and can be used to indicate an alternate
// Shortcut extra which can point to a packageName and can be used to indicate
// an alternate
// badge info. Launcher only reads this if the shortcut comes from a system app.
public static final String EXTRA_SHORTCUT_BADGE_OVERRIDE_PACKAGE =
"extra_shortcut_badge_override_package";
public static final String EXTRA_SHORTCUT_BADGE_OVERRIDE_PACKAGE = "extra_shortcut_badge_override_package";
private static final String TAG = "Launcher.IconCache";
private final Predicate<ItemInfoWithIcon> mIsUsingFallbackOrNonDefaultIconCheck = w ->
w.bitmap != null && (w.bitmap.isNullOrLowRes() || !isDefaultIcon(w.bitmap, w.user));
private final Predicate<ItemInfoWithIcon> mIsUsingFallbackOrNonDefaultIconCheck = w -> w.bitmap != null
&& (w.bitmap.isNullOrLowRes() || !isDefaultIcon(w.bitmap, w.user));
private final CachingLogic<ComponentWithLabel> mComponentWithLabelCachingLogic;
private final CachingLogic<LauncherActivityInfo> mLauncherActivityInfoCachingLogic;
private final CachingLogic<ShortcutInfo> mShortcutCachingLogic;
private final LauncherApps mLauncherApps;
private final UserCache mUserManager;
private final InstallSessionHelper mInstallSessionHelper;
private final InstantAppResolver mInstantAppResolver;
private final IconProvider mIconProvider;
private final CancellableTask mCancelledTask;
private final LauncherIcons.IconPool mIconPool;
private final SparseArray<BitmapInfo> mWidgetCategoryBitmapInfos;
private int mPendingIconRequestCount = 0;
// Lawnchair: Apply 3p icon pack
public IconCache(Context context, InvariantDeviceProfile idp, LauncherIcons.IconPool iconPool, DaggerSingletonTracker lifecycle) {
this(
context,
idp,
LauncherFiles.APP_ICONS_DB,
UserCache.INSTANCE.get(context),
new LawnchairIconProvider(context),
InstallSessionHelper.INSTANCE.get(context),
iconPool,
lifecycle
);
}
@Inject
public IconCache(
@ApplicationContext Context context,
InvariantDeviceProfile idp,
@Nullable @Named("ICONS_DB") String dbFileName,
UserCache userCache,
LauncherIconProvider iconProvider,
// TODO: Lawnchair stuff
// IconProvider iconProvider,
InstallSessionHelper installSessionHelper,
LauncherIcons.IconPool iconPool,
DaggerSingletonTracker lifecycle) {
super(context, dbFileName, MODEL_EXECUTOR.getLooper(),
idp.fillResIconDpi, idp.iconBitmapSize, true /* inMemoryCache */, iconProvider);
mLauncherApps = context.getSystemService(LauncherApps.class);
mUserManager = userCache;
mInstallSessionHelper = installSessionHelper;
mIconPool = iconPool;
mInstantAppResolver = InstantAppResolver.newInstance(context);
mWidgetCategoryBitmapInfos = new SparseArray<>();
mCancelledTask = new CancellableTask(() -> null, MAIN_EXECUTOR, c -> { });
mCancelledTask.cancel();
lifecycle.addCloseable(this::close);
public IconCache(Context context, InvariantDeviceProfile idp) {
this(context, idp, LauncherFiles.APP_ICONS_DB, new LawnchairIconProvider(context));
}
public IconCache(
@ApplicationContext Context context,
InvariantDeviceProfile idp,
@Nullable @Named("ICONS_DB") String dbFileName,
UserCache userCache,
IconProvider iconProvider,
InstallSessionHelper installSessionHelper,
LauncherIcons.IconPool iconPool,
DaggerSingletonTracker lifecycle) {
public IconCache(Context context, InvariantDeviceProfile idp, String dbFileName,
IconProvider iconProvider) {
super(context, dbFileName, MODEL_EXECUTOR.getLooper(),
idp.fillResIconDpi, Math.max(idp.iconBitmapSize, idp.allAppsIconBitmapSize), true /* inMemoryCache */, iconProvider);
mLauncherApps = context.getSystemService(LauncherApps.class);
mUserManager = userCache;
mInstallSessionHelper = installSessionHelper;
mIconPool = iconPool;
mInstantAppResolver = InstantAppResolver.newInstance(context);
idp.fillResIconDpi, Math.max(idp.iconBitmapSize, idp.allAppsIconBitmapSize), true /* inMemoryCache */);
mComponentWithLabelCachingLogic = new ComponentCachingLogic(context, false);
mLauncherActivityInfoCachingLogic = LauncherActivityCachingLogic.newInstance(context);
mShortcutCachingLogic = new ShortcutCachingLogic();
mLauncherApps = mContext.getSystemService(LauncherApps.class);
mUserManager = UserCache.INSTANCE.get(mContext);
mInstantAppResolver = InstantAppResolver.newInstance(mContext);
mIconProvider = iconProvider;
mWidgetCategoryBitmapInfos = new SparseArray<>();
mCancelledTask = new CancellableTask(() -> null, MAIN_EXECUTOR, c -> { });
mCancelledTask = new CancellableTask(() -> null, MAIN_EXECUTOR, c -> {
});
mCancelledTask.cancel();
lifecycle.addCloseable(this::close);
}
@Override
public long getSerialNumberForUser(@NonNull UserHandle user) {
protected long getSerialNumberForUser(@NonNull UserHandle user) {
return mUserManager.getSerialNumberForUser(user);
}
@@ -195,26 +148,25 @@ public class IconCache extends BaseIconCache {
@NonNull
@Override
public BaseIconFactory getIconFactory() {
return mIconPool.obtain();
return LauncherIcons.obtain(mContext);
}
/**
* Updates the entries related to the given package in memory and persistent DB.
*/
public synchronized void updateIconsForPkg(@NonNull final String packageName,
@NonNull final UserHandle user) {
List<LauncherActivityInfo> apps = mLauncherApps.getActivityList(packageName, user);
if (Utilities.ATLEAST_V) {
if (Flags.restoreArchivedAppIconsFromDb()
&& apps.stream().anyMatch(app -> app.getApplicationInfo().isArchived)) {
// When archiving app icon, don't delete old icon so it can be re-used.
return;
}
}
@NonNull final UserHandle user) {
removeIconsForPkg(packageName, user);
long userSerial = mUserManager.getSerialNumberForUser(user);
for (LauncherActivityInfo app : apps) {
addIconToDBAndMemCache(app, LauncherActivityCachingLogic.INSTANCE, userSerial);
try {
PackageInfo info = mPackageManager.getPackageInfo(packageName,
PackageManager.GET_UNINSTALLED_PACKAGES);
long userSerial = mUserManager.getSerialNumberForUser(user);
for (LauncherActivityInfo app : mLauncherApps.getActivityList(packageName, user)) {
addIconToDBAndMemCache(app, mLauncherActivityInfoCachingLogic, info, userSerial,
false /* replace existing */);
}
} catch (NameNotFoundException e) {
Log.d(TAG, "Package not found", e);
}
}
@@ -225,55 +177,57 @@ public class IconCache extends BaseIconCache {
// This will clear all pending updates
getUpdateHandler();
iconDb.close();
mIconDb.close();
}
/**
* Fetches high-res icon for the provided ItemInfo and updates the caller when done.
* Fetches high-res icon for the provided ItemInfo and updates the caller when
* done.
*
* @return a request ID that can be used to cancel the request.
*/
@AnyThread
public CancellableTask updateIconInBackground(final ItemInfoUpdateReceiver caller,
final ItemInfoWithIcon info) {
final ItemInfoWithIcon info) {
Supplier<ItemInfoWithIcon> task;
if (info instanceof AppInfo || info instanceof WorkspaceItemInfo) {
task = () -> {
getTitleAndIcon(info, DEFAULT_LOOKUP_FLAG);
getTitleAndIcon(info, false);
return info;
};
} else if (info instanceof PackageItemInfo pii) {
task = () -> {
getTitleAndIconForApp(pii, DEFAULT_LOOKUP_FLAG);
getTitleAndIconForApp(pii, false);
return pii;
};
} else {
Log.i(TAG, "Icon update not supported for "
+ info == null ? "null" : info.getClass().getName());
+ info == null ? "null" : info.getClass().getName());
return mCancelledTask;
}
Runnable endRunnable;
if (Looper.myLooper() == Looper.getMainLooper()) {
if (mPendingIconRequestCount <= 0) {
MODEL_EXECUTOR.elevatePriority(CALLER_ICON_CACHE);
MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
}
mPendingIconRequestCount++;
endRunnable = this::onIconRequestEnd;
} else {
endRunnable = () -> { };
endRunnable = () -> {
};
}
CancellableTask<ItemInfoWithIcon> request = new CancellableTask<>(
task, MAIN_EXECUTOR, caller::reapplyItemInfo, endRunnable);
Utilities.postAsyncCallback(workerHandler, request);
task, MAIN_EXECUTOR, caller::reapplyItemInfo, endRunnable);
Utilities.postAsyncCallback(mWorkerHandler, request);
return request;
}
private void onIconRequestEnd() {
mPendingIconRequestCount--;
if (mPendingIconRequestCount <= 0) {
MODEL_EXECUTOR.restorePriority(CALLER_ICON_CACHE);
MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
@@ -281,62 +235,67 @@ public class IconCache extends BaseIconCache {
* Updates {@param application} only if a valid entry is found.
*/
public synchronized void updateTitleAndIcon(AppInfo application) {
boolean preferPackageIcon = application.isArchived();
CacheEntry entry = cacheLocked(application.componentName,
application.user, () -> null, LauncherActivityCachingLogic.INSTANCE,
application.getMatchingLookupFlag());
if (entry.bitmap != null || !isDefaultIcon(entry.bitmap, application.user)) {
application.user, () -> null, mLauncherActivityInfoCachingLogic,
false, application.usingLowResIcon());
if (entry.bitmap == null || isDefaultIcon(entry.bitmap, application.user)) {
return;
}
if (preferPackageIcon) {
String packageName = application.getTargetPackage();
CacheEntry packageEntry = cacheLocked(new ComponentName(packageName, packageName + EMPTY_CLASS_NAME),
application.user, () -> null, mLauncherActivityInfoCachingLogic,
true, application.usingLowResIcon());
applyPackageEntry(packageEntry, application, entry);
} else {
applyCacheEntry(entry, application);
}
}
/**
* Fill in {@code info} with the icon and label for {@code activityInfo}
* Fill in {@param info} with the icon and label for {@param activityInfo}
*/
@SuppressWarnings("NewApi")
public synchronized void getTitleAndIcon(ItemInfoWithIcon info,
LauncherActivityInfo activityInfo, @NonNull CacheLookupFlag lookupFlag) {
boolean isAppArchived = Flags.enableSupportForArchiving() && activityInfo != null
&& activityInfo.getActivityInfo().isArchived;
LauncherActivityInfo activityInfo, boolean useLowResIcon) {
boolean isAppArchived;
try {
isAppArchived = Flags.enableSupportForArchiving() && activityInfo != null
&& activityInfo.getActivityInfo().isArchived;
} catch (Throwable e) {
isAppArchived = false;
}
// If we already have activity info, no need to use package icon
getTitleAndIcon(info, () -> activityInfo, lookupFlag.withUsePackageIcon(isAppArchived));
getTitleAndIcon(info, () -> activityInfo, isAppArchived, useLowResIcon,
isAppArchived);
}
/**
* Fill in {@code info} with the icon for {@code si}
* Fill in {@param info} with the icon for {@param si}
*/
public void getShortcutIcon(ItemInfoWithIcon info, ShortcutInfo si) {
getShortcutIcon(info, new CacheableShortcutInfo(si, context));
}
/**
* Fill in {@code info} with the icon for {@code si}
*/
public void getShortcutIcon(ItemInfoWithIcon info, CacheableShortcutInfo si) {
getShortcutIcon(info, si, mIsUsingFallbackOrNonDefaultIconCheck);
}
/**
* Fill in {@code info} with the icon and label for {@code si}. If the icon is not
* Fill in {@param info} with the icon and label for {@param si}. If the icon is
* not
* available, and fallback check returns true, it keeps the old icon.
* Shortcut entries are not kept in memory since they are not frequently used
*/
public <T extends ItemInfoWithIcon> void getShortcutIcon(T info, CacheableShortcutInfo si,
@NonNull Predicate<T> fallbackIconCheck) {
UserHandle user = CacheableShortcutCachingLogic.INSTANCE.getUser(si);
BitmapInfo bitmapInfo = cacheLocked(
CacheableShortcutCachingLogic.INSTANCE.getComponent(si),
user,
() -> si,
CacheableShortcutCachingLogic.INSTANCE,
DEFAULT_LOOKUP_FLAG.withSkipAddToMemCache()).bitmap;
public <T extends ItemInfoWithIcon> void getShortcutIcon(T info, ShortcutInfo si,
@NonNull Predicate<T> fallbackIconCheck) {
BitmapInfo bitmapInfo = cacheLocked(ShortcutKey.fromInfo(si).componentName,
si.getUserHandle(), () -> si, mShortcutCachingLogic, false, false).bitmap;
if (bitmapInfo.isNullOrLowRes()) {
bitmapInfo = getDefaultIcon(user);
bitmapInfo = getDefaultIcon(si.getUserHandle());
}
if (isDefaultIcon(bitmapInfo, user) && fallbackIconCheck.test(info)) {
if (isDefaultIcon(bitmapInfo, si.getUserHandle()) && fallbackIconCheck.test(info)) {
return;
}
info.bitmap = bitmapInfo.withBadgeInfo(getShortcutInfoBadge(si.getShortcutInfo()));
info.bitmap = bitmapInfo.withBadgeInfo(getShortcutInfoBadge(si));
}
/**
@@ -351,9 +310,10 @@ public class IconCache extends BaseIconCache {
// Check for badge override first.
String pkg = shortcutInfo.getPackage();
String override = shortcutInfo.getExtras() == null ? null
: shortcutInfo.getExtras().getString(EXTRA_SHORTCUT_BADGE_OVERRIDE_PACKAGE);
: shortcutInfo.getExtras().getString(EXTRA_SHORTCUT_BADGE_OVERRIDE_PACKAGE);
if (!TextUtils.isEmpty(override)
&& mInstallSessionHelper.isTrustedPackage(pkg, shortcutInfo.getUserHandle())) {
&& InstallSessionHelper.INSTANCE.get(mContext)
.isTrustedPackage(pkg, shortcutInfo.getUserHandle())) {
pkg = override;
} else {
// Try component based badge before trying the normal package badge
@@ -364,14 +324,14 @@ public class IconCache extends BaseIconCache {
appInfo.user = shortcutInfo.getUserHandle();
appInfo.componentName = cn;
appInfo.intent = new Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(cn);
getTitleAndIcon(appInfo, DEFAULT_LOOKUP_FLAG);
.addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(cn);
getTitleAndIcon(appInfo, false);
return appInfo;
}
}
PackageItemInfo pkgInfo = new PackageItemInfo(pkg, shortcutInfo.getUserHandle());
getTitleAndIconForApp(pkgInfo, DEFAULT_LOOKUP_FLAG);
getTitleAndIconForApp(pkgInfo, false);
return pkgInfo;
}
@@ -379,10 +339,9 @@ public class IconCache extends BaseIconCache {
* Fill in {@param info} with the icon and label. If the
* corresponding activity is not found, it reverts to the package icon.
*/
public synchronized void getTitleAndIcon(
@NonNull ItemInfoWithIcon info,
@NonNull CacheLookupFlag lookupFlag) {
// null info means not installed, but if we have a component from the intent then
public synchronized void getTitleAndIcon(ItemInfoWithIcon info, boolean useLowResIcon) {
// null info means not installed, but if we have a component from the intent
// then
// we should still look in the cache for restored app icons.
if (info.getTargetComponent() == null) {
info.bitmap = getDefaultIcon(info.user);
@@ -391,17 +350,14 @@ public class IconCache extends BaseIconCache {
} else {
Intent intent = info.getIntent();
getTitleAndIcon(info, () -> mLauncherApps.resolveActivity(intent, info.user),
lookupFlag.withUsePackageIcon());
true, useLowResIcon, info.isArchived());
}
}
/**
* Loads and returns the icon for the provided object without adding it to memCache
*/
public synchronized String getTitleNoCache(CachedObject info) {
public synchronized String getTitleNoCache(ComponentWithLabel info) {
CacheEntry entry = cacheLocked(info.getComponent(), info.getUser(), () -> info,
CachedObjectCachingLogic.INSTANCE,
DEFAULT_LOOKUP_FLAG.withUseLowRes().withSkipAddToMemCache());
mComponentWithLabelCachingLogic, false /* usePackageIcon */,
true /* useLowResIcon */);
return Utilities.trim(entry.title);
}
@@ -409,80 +365,108 @@ public class IconCache extends BaseIconCache {
* Fill in {@param mWorkspaceItemInfo} with the icon and label for {@param info}
*/
public synchronized void getTitleAndIcon(
@NonNull ItemInfoWithIcon infoInOut,
@NonNull Supplier<LauncherActivityInfo> activityInfoProvider,
@NonNull CacheLookupFlag lookupFlag) {
@NonNull ItemInfoWithIcon infoInOut,
@NonNull Supplier<LauncherActivityInfo> activityInfoProvider,
boolean usePkgIcon, boolean useLowResIcon) {
CacheEntry entry = cacheLocked(infoInOut.getTargetComponent(), infoInOut.user,
activityInfoProvider, LauncherActivityCachingLogic.INSTANCE, lookupFlag);
activityInfoProvider, mLauncherActivityInfoCachingLogic, usePkgIcon,
useLowResIcon);
applyCacheEntry(entry, infoInOut);
}
/**
* Creates an sql cursor for a query of a set of ItemInfoWithIcon icons and titles.
*
* @param iconRequestInfos List of IconRequestInfos representing titles and icons to query.
* @param user UserHandle all the given iconRequestInfos share
* @param lookupFlag what flags to use when loading the icon.
* Fill in {@param mWorkspaceItemInfo} with the icon and label for {@param info}
*/
private <T extends ItemInfoWithIcon> Cursor createBulkQueryCursor(
List<IconRequestInfo<T>> iconRequestInfos, UserHandle user, CacheLookupFlag lookupFlag)
throws SQLiteException {
String[] queryParams = Stream.concat(
iconRequestInfos.stream()
.map(r -> r.itemInfo.getTargetComponent())
.filter(Objects::nonNull)
.distinct()
.map(ComponentName::flattenToString),
Stream.of(Long.toString(getSerialNumberForUser(user)))).toArray(String[]::new);
String componentNameQuery = TextUtils.join(
",", Collections.nCopies(queryParams.length - 1, "?"));
return iconDb.query(
toLookupColumns(lookupFlag),
COLUMN_COMPONENT
+ " IN ( " + componentNameQuery + " )"
+ " AND " + COLUMN_USER + " = ?",
queryParams);
public synchronized void getTitleAndIcon(
@NonNull ItemInfoWithIcon infoInOut,
@NonNull Supplier<LauncherActivityInfo> activityInfoProvider,
boolean usePkgIcon, boolean useLowResIcon, boolean preferPackageEntry) {
CacheEntry entry = cacheLocked(infoInOut.getTargetComponent(), infoInOut.user,
activityInfoProvider, mLauncherActivityInfoCachingLogic, usePkgIcon,
useLowResIcon);
if (preferPackageEntry) {
String packageName = infoInOut.getTargetPackage();
CacheEntry packageEntry = cacheLocked(
new ComponentName(packageName, packageName + EMPTY_CLASS_NAME),
infoInOut.user, activityInfoProvider, mLauncherActivityInfoCachingLogic,
usePkgIcon, useLowResIcon);
applyPackageEntry(packageEntry, infoInOut, entry);
} else if (useLowResIcon || !entry.bitmap.isNullOrLowRes()
|| infoInOut.bitmap.isNullOrLowRes()) {
// Only use cache entry if it will not downgrade the current bitmap in infoInOut
applyCacheEntry(entry, infoInOut);
} else {
Log.d(TAG, "getTitleAndIcon: Cache entry bitmap was a downgrade of existing bitmap"
+ " in ItemInfo. Skipping.");
}
}
/**
* Load and fill icons requested in iconRequestInfos using a single bulk sql query.
* Creates an sql cursor for a query of a set of ItemInfoWithIcon icons and
* titles.
*
* @param iconRequestInfos List of IconRequestInfos representing titles and
* icons to query.
* @param user UserHandle all the given iconRequestInfos share
* @param useLowResIcons whether we should exclude the icon column from the
* sql results.
*/
private <T extends ItemInfoWithIcon> Cursor createBulkQueryCursor(
List<IconRequestInfo<T>> iconRequestInfos, UserHandle user, boolean useLowResIcons)
throws SQLiteException {
String[] queryParams = Stream.concat(
iconRequestInfos.stream()
.map(r -> r.itemInfo.getTargetComponent())
.filter(Objects::nonNull)
.distinct()
.map(ComponentName::flattenToString),
Stream.of(Long.toString(getSerialNumberForUser(user)))).toArray(String[]::new);
String componentNameQuery = TextUtils.join(
",", Collections.nCopies(queryParams.length - 1, "?"));
return mIconDb.query(
useLowResIcons ? IconDB.COLUMNS_LOW_RES : IconDB.COLUMNS_HIGH_RES,
IconDB.COLUMN_COMPONENT
+ " IN ( " + componentNameQuery + " )"
+ " AND " + IconDB.COLUMN_USER + " = ?",
queryParams);
}
/**
* Load and fill icons requested in iconRequestInfos using a single bulk sql
* query.
*/
public synchronized <T extends ItemInfoWithIcon> void getTitlesAndIconsInBulk(
List<IconRequestInfo<T>> iconRequestInfos) {
Map<Pair<UserHandle, Boolean>, List<IconRequestInfo<T>>> iconLoadSubsectionsMap =
iconRequestInfos.stream()
List<IconRequestInfo<T>> iconRequestInfos) {
Map<Pair<UserHandle, Boolean>, List<IconRequestInfo<T>>> iconLoadSubsectionsMap = iconRequestInfos.stream()
.filter(iconRequest -> {
if (iconRequest.itemInfo.getTargetComponent() == null) {
Log.i(TAG,
"Skipping Item info with null component name: "
+ iconRequest.itemInfo);
"Skipping Item info with null component name: "
+ iconRequest.itemInfo);
iconRequest.itemInfo.bitmap = getDefaultIcon(
iconRequest.itemInfo.user);
iconRequest.itemInfo.user);
return false;
}
return true;
})
.collect(groupingBy(iconRequest ->
Pair.create(iconRequest.itemInfo.user, iconRequest.useLowResIcon)));
.collect(groupingBy(iconRequest -> Pair.create(iconRequest.itemInfo.user, iconRequest.useLowResIcon)));
Trace.beginSection("loadIconsInBulk");
iconLoadSubsectionsMap.forEach((sectionKey, filteredList) -> {
Map<ComponentName, List<IconRequestInfo<T>>> duplicateIconRequestsMap =
filteredList.stream()
Map<ComponentName, List<IconRequestInfo<T>>> duplicateIconRequestsMap = filteredList.stream()
.filter(iconRequest -> {
// Filter out icons that should not share the same bitmap and title
if (iconRequest.itemInfo.itemType == ITEM_TYPE_DEEP_SHORTCUT) {
Log.e(TAG,
"Skipping Item info for deep shortcut: "
+ iconRequest.itemInfo,
new IllegalStateException());
"Skipping Item info for deep shortcut: "
+ iconRequest.itemInfo,
new IllegalStateException());
return false;
}
return true;
})
.collect(groupingBy(iconRequest ->
iconRequest.itemInfo.getTargetComponent()));
.collect(groupingBy(iconRequest -> iconRequest.itemInfo.getTargetComponent()));
Trace.beginSection("loadIconSubsectionInBulk");
loadIconSubsection(sectionKey, filteredList, duplicateIconRequestsMap);
@@ -492,39 +476,38 @@ public class IconCache extends BaseIconCache {
}
private <T extends ItemInfoWithIcon> void loadIconSubsection(
Pair<UserHandle, Boolean> sectionKey,
List<IconRequestInfo<T>> filteredList,
Map<ComponentName, List<IconRequestInfo<T>>> duplicateIconRequestsMap) {
Pair<UserHandle, Boolean> sectionKey,
List<IconRequestInfo<T>> filteredList,
Map<ComponentName, List<IconRequestInfo<T>>> duplicateIconRequestsMap) {
Trace.beginSection("loadIconSubsectionWithDatabase");
CacheLookupFlag lookupFlag = DEFAULT_LOOKUP_FLAG.withUseLowRes(sectionKey.second);
try (Cursor c = createBulkQueryCursor(
filteredList,
/* user = */ sectionKey.first,
lookupFlag)) {
filteredList,
/* user = */ sectionKey.first,
/* useLowResIcons = */ sectionKey.second)) {
// Database title and icon loading
int componentNameColumnIndex = c.getColumnIndexOrThrow(COLUMN_COMPONENT);
int componentNameColumnIndex = c.getColumnIndexOrThrow(IconDB.COLUMN_COMPONENT);
while (c.moveToNext()) {
ComponentName cn = ComponentName.unflattenFromString(
c.getString(componentNameColumnIndex));
List<IconRequestInfo<T>> duplicateIconRequests =
duplicateIconRequestsMap.get(cn);
c.getString(componentNameColumnIndex));
List<IconRequestInfo<T>> duplicateIconRequests = duplicateIconRequestsMap.get(cn);
if (cn != null) {
if (duplicateIconRequests != null) {
CacheEntry entry = cacheLocked(
cn,
/* user = */ sectionKey.first,
() -> duplicateIconRequests.get(0).launcherActivityInfo,
LauncherActivityCachingLogic.INSTANCE,
lookupFlag,
c);
cn,
/* user = */ sectionKey.first,
() -> duplicateIconRequests.get(0).launcherActivityInfo,
mLauncherActivityInfoCachingLogic,
c,
/* usePackageIcon= */ false,
/* useLowResIcons = */ sectionKey.second);
for (IconRequestInfo<T> iconRequest : duplicateIconRequests) {
applyCacheEntry(entry, iconRequest.itemInfo);
}
} else {
Log.e(TAG, "Found entry in icon database but no main activity "
+ "entry for cn: " + cn);
+ "entry for cn: " + cn);
}
}
}
@@ -542,13 +525,13 @@ public class IconCache extends BaseIconCache {
BitmapInfo icon = itemInfo.bitmap;
boolean loadFallbackTitle = TextUtils.isEmpty(itemInfo.title);
boolean loadFallbackIcon = icon == null
|| isDefaultIcon(icon, itemInfo.user)
|| icon == BitmapInfo.LOW_RES_INFO;
|| isDefaultIcon(icon, itemInfo.user)
|| icon == BitmapInfo.LOW_RES_INFO;
if (loadFallbackTitle || loadFallbackIcon) {
Log.i(TAG,
"Database bulk icon loading failed, using fallback bulk icon loading "
+ "for: " + cn);
"Database bulk icon loading failed, using fallback bulk icon loading "
+ "for: " + cn);
CacheEntry entry = new CacheEntry();
LauncherActivityInfo lai = iconRequestInfo.launcherActivityInfo;
@@ -562,20 +545,20 @@ public class IconCache extends BaseIconCache {
if (loadFallbackIcon) {
loadFallbackIcon(
lai,
entry,
LauncherActivityCachingLogic.INSTANCE,
/* usePackageIcon= */ false,
/* usePackageTitle= */ loadFallbackTitle,
cn,
sectionKey.first);
lai,
entry,
mLauncherActivityInfoCachingLogic,
/* usePackageIcon= */ false,
/* usePackageTitle= */ loadFallbackTitle,
cn,
sectionKey.first);
}
if (loadFallbackTitle && TextUtils.isEmpty(entry.title) && lai != null) {
loadFallbackTitle(
lai,
entry,
LauncherActivityCachingLogic.INSTANCE,
sectionKey.first);
lai,
entry,
mLauncherActivityInfoCachingLogic,
sectionKey.first);
}
for (IconRequestInfo<T> iconRequest : duplicateIconRequestsMap.get(cn)) {
@@ -590,29 +573,27 @@ public class IconCache extends BaseIconCache {
* Fill in {@param infoInOut} with the corresponding icon and label.
*/
public synchronized void getTitleAndIconForApp(
@NonNull final PackageItemInfo infoInOut,
@NonNull CacheLookupFlag lookupFlag) {
@NonNull final PackageItemInfo infoInOut, final boolean useLowResIcon) {
CacheEntry entry = getEntryForPackageLocked(
infoInOut.packageName, infoInOut.user, lookupFlag);
infoInOut.packageName, infoInOut.user, useLowResIcon);
applyCacheEntry(entry, infoInOut);
if (infoInOut.widgetCategory == NO_CATEGORY) {
return;
}
WidgetSection widgetSection = WidgetSections.getWidgetSections(context)
.get(infoInOut.widgetCategory);
infoInOut.title = context.getString(widgetSection.mSectionTitle);
infoInOut.contentDescription = getUserBadgedLabel(infoInOut.title, infoInOut.user);
WidgetSection widgetSection = WidgetSections.getWidgetSections(mContext)
.get(infoInOut.widgetCategory);
infoInOut.title = mContext.getString(widgetSection.mSectionTitle);
infoInOut.contentDescription = mPackageManager.getUserBadgedLabel(infoInOut.title, infoInOut.user);
final BitmapInfo cachedBitmap = mWidgetCategoryBitmapInfos.get(infoInOut.widgetCategory);
if (cachedBitmap != null) {
infoInOut.bitmap = getBadgedIcon(cachedBitmap, infoInOut.user);
return;
}
try (LauncherIcons li = mIconPool.obtain()) {
try (LauncherIcons li = LauncherIcons.obtain(mContext)) {
final BitmapInfo tempBitmap = li.createBadgedIconBitmap(
context.getDrawable(widgetSection.mSectionDrawable),
new BaseIconFactory.IconOptions());
mContext.getDrawable(widgetSection.mSectionDrawable));
mWidgetCategoryBitmapInfos.put(infoInOut.widgetCategory, tempBitmap);
infoInOut.bitmap = getBadgedIcon(tempBitmap, infoInOut.user);
} catch (Exception e) {
@@ -622,53 +603,51 @@ public class IconCache extends BaseIconCache {
}
private synchronized BitmapInfo getBadgedIcon(@Nullable final BitmapInfo bitmap,
@NonNull final UserHandle user) {
@NonNull final UserHandle user) {
if (bitmap == null) {
return getDefaultIcon(user);
}
return bitmap.withFlags(getUserFlagOpLocked(user));
return bitmap.withFlags(FlagOp.NO_OP);
}
protected void applyCacheEntry(@NonNull final CacheEntry entry,
@NonNull final ItemInfoWithIcon info) {
@NonNull final ItemInfoWithIcon info) {
info.title = Utilities.trim(entry.title);
info.contentDescription = entry.contentDescription;
info.bitmap = entry.bitmap;
// Clear any previously set appTitle, if the packageOverride is no longer valid
info.appTitle = null;
if (entry.bitmap == null) {
// TODO: entry.bitmap can never be null, so this should not happen at all.
Log.wtf(TAG, "Cannot find bitmap from the cache, default icon was loaded.");
info.bitmap = getDefaultIcon(info.user);
}
}
// apply package override
if (!Flags.enableSupportForArchiving() || !info.isArchived()) {
return;
}
String targetPackage = info.getTargetPackage();
if (targetPackage == null) {
return;
}
CacheEntry packageEntry = getInMemoryPackageEntryLocked(targetPackage, info.user);
if (packageEntry == null || packageEntry.bitmap.isLowRes()) {
return;
}
info.appTitle = Utilities.trim(info.title);
protected void applyPackageEntry(@NonNull final CacheEntry packageEntry,
@NonNull final ItemInfoWithIcon info, @NonNull final CacheEntry fallbackEntry) {
info.title = Utilities.trim(packageEntry.title);
info.appTitle = Utilities.trim(fallbackEntry.title);
info.contentDescription = packageEntry.contentDescription;
info.bitmap = packageEntry.bitmap;
if (packageEntry.bitmap == null) {
// TODO: entry.bitmap can never be null, so this should not happen at all.
Log.wtf(TAG, "Cannot find bitmap from the cache, default icon was loaded.");
info.bitmap = getDefaultIcon(info.user);
}
}
public Drawable getFullResIcon(LauncherActivityInfo info) {
return mIconProvider.getIcon(info, mIconDpi);
}
public void updateSessionCache(PackageUserKey key, PackageInstaller.SessionInfo info) {
cachePackageInstallInfo(key.mPackageName, key.mUser, info.getAppIcon(),
info.getAppLabel());
info.getAppLabel());
}
@VisibleForTesting
synchronized boolean isItemInDb(ComponentKey cacheKey) {
return getEntryFromDBLocked(cacheKey, new CacheEntry(), DEFAULT_LOOKUP_FLAG,
LauncherActivityCachingLogic.INSTANCE);
@Override
@NonNull
protected String getIconSystemState(String packageName) {
return mIconProvider.getSystemStateForPackage(mSystemState, packageName);
}
/**
@@ -681,7 +660,7 @@ public class IconCache extends BaseIconCache {
/** Log persistently to FileLog.d for debugging. */
@Override
protected void logPersistently(@NonNull String message, @Nullable Exception e) {
FileLog.d(BaseIconCache.TAG, message, e);
protected void logdPersistently(String tag, String message, @Nullable Exception e) {
FileLog.d(tag, message, e);
}
}
@@ -0,0 +1,172 @@
/*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.icons;
import static android.graphics.Paint.FILTER_BITMAP_FLAG;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BlendMode;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import androidx.annotation.WorkerThread;
import com.android.launcher3.icons.BaseIconFactory.ClippedMonoDrawable;
import java.nio.ByteBuffer;
/**
* Utility class to generate monochrome icons version for a given drawable.
*/
@TargetApi(Build.VERSION_CODES.TIRAMISU)
public class MonochromeIconFactory extends Drawable {
private final Bitmap mFlatBitmap;
private final Canvas mFlatCanvas;
private final Paint mCopyPaint;
private final Bitmap mAlphaBitmap;
private final Canvas mAlphaCanvas;
private final byte[] mPixels;
private final int mBitmapSize;
private final int mEdgePixelLength;
private final Paint mDrawPaint;
private final Rect mSrcRect;
MonochromeIconFactory(int iconBitmapSize) {
float extraFactor = AdaptiveIconDrawable.getExtraInsetFraction();
float viewPortScale = 1 / (1 + 2 * extraFactor);
mBitmapSize = Math.round(iconBitmapSize * 2 * viewPortScale);
mPixels = new byte[mBitmapSize * mBitmapSize];
mEdgePixelLength = mBitmapSize * (mBitmapSize - iconBitmapSize) / 2;
mFlatBitmap = Bitmap.createBitmap(mBitmapSize, mBitmapSize, Config.ARGB_8888);
mFlatCanvas = new Canvas(mFlatBitmap);
mAlphaBitmap = Bitmap.createBitmap(mBitmapSize, mBitmapSize, Config.ALPHA_8);
mAlphaCanvas = new Canvas(mAlphaBitmap);
mDrawPaint = new Paint(FILTER_BITMAP_FLAG);
mDrawPaint.setColor(Color.WHITE);
mSrcRect = new Rect(0, 0, mBitmapSize, mBitmapSize);
mCopyPaint = new Paint(FILTER_BITMAP_FLAG);
mCopyPaint.setBlendMode(BlendMode.SRC);
// Crate a color matrix which converts the icon to grayscale and then uses the average
// of RGB components as the alpha component.
ColorMatrix satMatrix = new ColorMatrix();
satMatrix.setSaturation(0);
float[] vals = satMatrix.getArray();
vals[15] = vals[16] = vals[17] = .3333f;
vals[18] = vals[19] = 0;
mCopyPaint.setColorFilter(new ColorMatrixColorFilter(vals));
}
private void drawDrawable(Drawable drawable) {
if (drawable != null) {
drawable.setBounds(0, 0, mBitmapSize, mBitmapSize);
drawable.draw(mFlatCanvas);
}
}
/**
* Creates a monochrome version of the provided drawable
*/
@WorkerThread
public Drawable wrap(AdaptiveIconDrawable icon) {
mFlatCanvas.drawColor(Color.BLACK);
drawDrawable(icon.getBackground());
drawDrawable(icon.getForeground());
generateMono();
return new ClippedMonoDrawable(this);
}
@WorkerThread
private void generateMono() {
mAlphaCanvas.drawBitmap(mFlatBitmap, 0, 0, mCopyPaint);
// Scale the end points:
ByteBuffer buffer = ByteBuffer.wrap(mPixels);
buffer.rewind();
mAlphaBitmap.copyPixelsToBuffer(buffer);
int min = 0xFF;
int max = 0;
for (byte b : mPixels) {
min = Math.min(min, b & 0xFF);
max = Math.max(max, b & 0xFF);
}
if (min < max) {
// rescale pixels to increase contrast
float range = max - min;
// In order to check if the colors should be flipped, we just take the average color
// of top and bottom edge which should correspond to be background color. If the edge
// colors have more opacity, we flip the colors;
int sum = 0;
for (int i = 0; i < mEdgePixelLength; i++) {
sum += (mPixels[i] & 0xFF);
sum += (mPixels[mPixels.length - 1 - i] & 0xFF);
}
float edgeAverage = sum / (mEdgePixelLength * 2f);
float edgeMapped = (edgeAverage - min) / range;
boolean flipColor = edgeMapped > .5f;
for (int i = 0; i < mPixels.length; i++) {
int p = mPixels[i] & 0xFF;
int p2 = Math.round((p - min) * 0xFF / range);
mPixels[i] = flipColor ? (byte) (255 - p2) : (byte) (p2);
}
buffer.rewind();
mAlphaBitmap.copyPixelsFromBuffer(buffer);
}
}
@Override
public void draw(Canvas canvas) {
canvas.drawBitmap(mAlphaBitmap, mSrcRect, getBounds(), mDrawPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int i) {
mDrawPaint.setAlpha(i);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mDrawPaint.setColorFilter(colorFilter);
}
}
@@ -199,10 +199,6 @@ public abstract class ItemFocusIndicatorHelper<T> implements AnimatorUpdateListe
}
protected void changeFocus(T item, boolean hasFocus) {
if (mLastFocusedItem != item && !hasFocus) {
return;
}
if (hasFocus) {
endCurrentAnimation();
@@ -1,6 +1,6 @@
package com.android.launcher3.logging;
import static com.android.launcher3.util.LooperExecutor.createAndStartNewLooper;
import static com.android.launcher3.util.Executors.createAndStartNewLooper;
import android.os.Handler;
import android.os.HandlerThread;
@@ -19,14 +19,11 @@ import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCH
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ALLAPPS_OPEN_UP;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_HOME_GESTURE;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_OVERVIEW_GESTURE;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.slice.SliceItem;
import com.android.launcher3.R;
import com.android.launcher3.logger.LauncherAtom;
import com.android.launcher3.logger.LauncherAtom.ContainerInfo;
@@ -46,7 +43,6 @@ import com.android.launcher3.views.ActivityContext;
* </pre>
*/
public class StatsLogManager implements ResourceBasedOverride {
public static final int LAUNCHER_STATE_UNSPECIFIED = 0;
public static final int LAUNCHER_STATE_BACKGROUND = 1;
public static final int LAUNCHER_STATE_HOME = 2;
@@ -90,13 +86,16 @@ public class StatsLogManager implements ResourceBasedOverride {
}
public interface EventEnum {
/**
* Tag used to request new UI Event IDs via presubmit analysis.
*
* <p>Use RESERVE_NEW_UI_EVENT_ID as the constructor parameter for a new {@link EventEnum}
* to signal the presubmit analyzer to reserve a new ID for the event. The new ID will be
* returned as a Gerrit presubmit finding. Do not submit {@code RESERVE_NEW_UI_EVENT_ID} as
* <p>
* Use RESERVE_NEW_UI_EVENT_ID as the constructor parameter for a new
* {@link EventEnum}
* to signal the presubmit analyzer to reserve a new ID for the event. The new
* ID will be
* returned as a Gerrit presubmit finding. Do not submit
* {@code RESERVE_NEW_UI_EVENT_ID} as
* the constructor parameter for any event.
*
* <pre>
@@ -112,16 +111,12 @@ public class StatsLogManager implements ResourceBasedOverride {
public enum LauncherEvent implements EventEnum {
/* Used to prevent double logging. */
IGNORE(-1),
@UiEvent(doc = "App launched from workspace, hotseat or folder in launcher")
LAUNCHER_APP_LAUNCH_TAP(338),
@UiEvent(doc = "Task launched from overview using TAP")
LAUNCHER_TASK_LAUNCH_TAP(339),
@UiEvent(doc = "User tapped on notification inside popup context menu.")
LAUNCHER_NOTIFICATION_LAUNCH_TAP(516),
@UiEvent(doc = "Task launched from overview using SWIPE DOWN")
LAUNCHER_TASK_LAUNCH_SWIPE_DOWN(340),
@@ -130,87 +125,57 @@ public class StatsLogManager implements ResourceBasedOverride {
@UiEvent(doc = "TASK dismissed from overview using SWIPE UP")
LAUNCHER_TASK_DISMISS_SWIPE_UP(341),
@UiEvent(doc = "User dragged a launcher item")
LAUNCHER_ITEM_DRAG_STARTED(383),
@UiEvent(doc = "A dragged launcher item is successfully dropped onto workspace, hotseat "
+ "open folder etc")
LAUNCHER_ITEM_DROP_COMPLETED(385),
@UiEvent(doc = "A dragged launcher item is successfully dropped onto a folder icon.")
LAUNCHER_ITEM_DROP_COMPLETED_ON_FOLDER_ICON(697),
@UiEvent(doc = "A dragged launcher item is successfully dropped on another item "
+ "resulting in a new folder creation")
LAUNCHER_ITEM_DROP_FOLDER_CREATED(386),
@UiEvent(doc = "Folder's label is automatically assigned.")
LAUNCHER_FOLDER_AUTO_LABELED(591),
@UiEvent(doc = "Could not auto-label a folder because primary suggestion is null or empty.")
LAUNCHER_FOLDER_AUTO_LABELING_SKIPPED_EMPTY_PRIMARY(592),
@UiEvent(doc = "Could not auto-label a folder because no suggestions exist.")
LAUNCHER_FOLDER_AUTO_LABELING_SKIPPED_EMPTY_SUGGESTIONS(593),
@UiEvent(doc = "User manually updated the folder label.")
LAUNCHER_FOLDER_LABEL_UPDATED(460),
@UiEvent(doc = "User long pressed on the workspace empty space.")
LAUNCHER_WORKSPACE_LONGPRESS(461),
@UiEvent(doc = "User tapped or long pressed on a wallpaper icon inside launcher settings.")
LAUNCHER_WALLPAPER_BUTTON_TAP_OR_LONGPRESS(462),
@UiEvent(doc = "User tapped or long pressed on settings icon inside launcher settings.")
LAUNCHER_SETTINGS_BUTTON_TAP_OR_LONGPRESS(463),
@UiEvent(doc = "User tapped or long pressed on apps icon inside launcher settings.")
LAUNCHER_ALL_APPS_TAP_OR_LONGPRESS(2204),
@UiEvent(doc = "User tapped or long pressed on widget tray icon inside launcher settings.")
LAUNCHER_WIDGETSTRAY_BUTTON_TAP_OR_LONGPRESS(464),
@UiEvent(doc = "User expanded the list of widgets for a single app in the widget picker.")
LAUNCHER_WIDGETSTRAY_APP_EXPANDED(818),
@UiEvent(doc = "User searched for a widget in the widget picker.")
LAUNCHER_WIDGETSTRAY_SEARCHED(819),
@UiEvent(doc = "User clicked on view all button to expand the displayed list in the "
+ "widget picker.")
LAUNCHER_WIDGETSTRAY_EXPAND_PRESS(1978),
@UiEvent(doc = "A dragged item is dropped on 'Remove' button in the target bar")
LAUNCHER_ITEM_DROPPED_ON_REMOVE(465),
@UiEvent(doc = "A dragged item is dropped on 'Cancel' button in the target bar")
LAUNCHER_ITEM_DROPPED_ON_CANCEL(466),
@UiEvent(doc = "A predicted item is dragged and dropped on 'Don't suggest app'"
+ " button in the target bar")
LAUNCHER_ITEM_DROPPED_ON_DONT_SUGGEST(467),
@UiEvent(doc = "A dragged item is dropped on 'Uninstall' button in target bar")
LAUNCHER_ITEM_DROPPED_ON_UNINSTALL(468),
@UiEvent(doc = "User completed uninstalling the package after dropping on "
+ "the icon onto 'Uninstall' button in the target bar")
LAUNCHER_ITEM_UNINSTALL_COMPLETED(469),
@UiEvent(doc = "User cancelled uninstalling the package after dropping on "
+ "the icon onto 'Uninstall' button in the target bar")
LAUNCHER_ITEM_UNINSTALL_CANCELLED(470),
@UiEvent(doc = "User tapped or long pressed on the task icon(aka package icon) "
+ "from overview to open task menu.")
LAUNCHER_TASK_ICON_TAP_OR_LONGPRESS(517),
@UiEvent(doc = "User opened package specific widgets list by tapping on widgets system "
+ "shortcut inside popup context menu.")
LAUNCHER_SYSTEM_SHORTCUT_WIDGETS_TAP(514),
@UiEvent(doc = "User tapped on app info system shortcut.")
LAUNCHER_SYSTEM_SHORTCUT_APP_INFO_TAP(515),
@@ -221,22 +186,14 @@ public class StatsLogManager implements ResourceBasedOverride {
@Deprecated
@UiEvent(doc = "User tapped on split screen icon on a task menu.")
LAUNCHER_SYSTEM_SHORTCUT_SPLIT_SCREEN_TAP(518),
@UiEvent(doc = "User tapped on free form icon on a task menu.")
LAUNCHER_SYSTEM_SHORTCUT_FREE_FORM_TAP(519),
@UiEvent(doc = "User tapped on desktop icon on a task menu.")
LAUNCHER_SYSTEM_SHORTCUT_DESKTOP_TAP(1706),
@UiEvent(doc = "User tapped on external display icon on a task menu,")
LAUNCHER_SYSTEM_SHORTCUT_EXTERNAL_DISPLAY_TAP(1957),
@UiEvent(doc = "User tapped on close app on a task menu,")
LAUNCHER_SYSTEM_SHORTCUT_CLOSE_APP_TAP(2081),
@UiEvent(doc = "User tapped on pause app system shortcut.")
LAUNCHER_SYSTEM_SHORTCUT_PAUSE_TAP(521),
@UiEvent(doc = "User tapped on pin system shortcut.")
LAUNCHER_SYSTEM_SHORTCUT_PIN_TAP(522),
@@ -245,74 +202,50 @@ public class StatsLogManager implements ResourceBasedOverride {
@UiEvent(doc = "User is shown All Apps education view.")
LAUNCHER_ALL_APPS_EDU_SHOWN(523),
@UiEvent(doc = "User opened a folder.")
LAUNCHER_FOLDER_OPEN(551),
@UiEvent(doc = "Hotseat education half sheet seen")
LAUNCHER_HOTSEAT_EDU_SEEN(479),
@UiEvent(doc = "Hotseat migration accepted")
LAUNCHER_HOTSEAT_EDU_ACCEPT(480),
@UiEvent(doc = "Hotseat migration denied")
LAUNCHER_HOTSEAT_EDU_DENY(481),
@UiEvent(doc = "Hotseat education tip shown")
LAUNCHER_HOTSEAT_EDU_ONLY_TIP(482),
/**
* @deprecated LauncherUiChanged.rank field is repurposed to store all apps rank, so no
* separate event is required.
* @deprecated LauncherUiChanged.rank field is repurposed to store all apps
* rank, so no
* separate event is required.
*/
@Deprecated
@UiEvent(doc = "App launch ranking logged for all apps predictions")
LAUNCHER_ALL_APPS_RANKED(552),
@UiEvent(doc = "App launch ranking logged for hotseat predictions)")
LAUNCHER_HOTSEAT_RANKED(553),
@UiEvent(doc = "Launcher is now in background. e.g., Screen off event")
LAUNCHER_ONSTOP(562),
@UiEvent(doc = "Launcher is now in foreground. e.g., Screen on event, back button")
LAUNCHER_ONRESUME(563),
@UiEvent(doc = "User swipes or fling in LEFT direction on workspace.")
LAUNCHER_SWIPELEFT(564),
@UiEvent(doc = "User swipes or fling in RIGHT direction on workspace.")
LAUNCHER_SWIPERIGHT(565),
@UiEvent(doc = "User swipes or fling in UP direction in unknown way.")
LAUNCHER_UNKNOWN_SWIPEUP(566),
@UiEvent(doc = "User swipes or fling in DOWN direction in unknown way.")
LAUNCHER_UNKNOWN_SWIPEDOWN(567),
@UiEvent(doc = "User swipes or fling in UP direction to open apps drawer.")
LAUNCHER_ALLAPPS_OPEN_UP(568),
@UiEvent(doc = "User swipes or fling in DOWN direction to close apps drawer.")
LAUNCHER_ALLAPPS_CLOSE_DOWN(569),
@UiEvent(doc = "User tap outside apps drawer sheet to close apps drawer.")
LAUNCHER_ALLAPPS_CLOSE_TAP_OUTSIDE(941),
@UiEvent(doc = "User swipes or fling in UP direction and hold from the bottom bazel area")
LAUNCHER_OVERVIEW_GESTURE(570),
@UiEvent(doc = "User swipes or fling in LEFT direction on the bottom bazel area.")
LAUNCHER_QUICKSWITCH_LEFT(571),
@UiEvent(doc = "User swipes or fling in RIGHT direction on the bottom bazel area.")
LAUNCHER_QUICKSWITCH_RIGHT(572),
@UiEvent(doc = "User swipes or fling on the bottom bazel area to enter Desktop mode.")
LAUNCHER_QUICKSWITCH_ENTER_DESKTOP_MODE(2025),
@UiEvent(doc = "User swipes or fling on the bottom bazel area to exit Desktop mode.")
LAUNCHER_QUICKSWITCH_EXIT_DESKTOP_MODE(2026),
@UiEvent(doc = "User swipes or fling in DOWN direction on the bottom bazel area.")
LAUNCHER_SWIPEDOWN_NAVBAR(573),
@@ -330,67 +263,46 @@ public class StatsLogManager implements ResourceBasedOverride {
@UiEvent(doc = "User swipes or fling in UP direction from bottom bazel area.")
LAUNCHER_HOME_GESTURE(574),
@UiEvent(doc = "User's workspace layout information is snapshot in the background.")
LAUNCHER_WORKSPACE_SNAPSHOT(579),
@UiEvent(doc = "User tapped on the screenshot button on overview)")
LAUNCHER_OVERVIEW_ACTIONS_SCREENSHOT(580),
@UiEvent(doc = "User tapped on the select button on overview)")
LAUNCHER_OVERVIEW_ACTIONS_SELECT(581),
@UiEvent(doc = "User tapped on the share button on overview")
LAUNCHER_OVERVIEW_ACTIONS_SHARE(582),
@UiEvent(doc = "User tapped on the split screen button on overview")
LAUNCHER_OVERVIEW_ACTIONS_SPLIT(895),
@UiEvent(doc = "User tapped on the close button in select mode")
LAUNCHER_SELECT_MODE_CLOSE(583),
@UiEvent(doc = "User tapped on the highlight items in select mode")
LAUNCHER_SELECT_MODE_ITEM(584),
@UiEvent(doc = "Notification dot on app icon enabled.")
LAUNCHER_NOTIFICATION_DOT_ENABLED(611),
@UiEvent(doc = "Notification dot on app icon disabled.")
LAUNCHER_NOTIFICATION_DOT_DISABLED(612),
@UiEvent(doc = "For new apps, add app icons to home screen enabled.")
LAUNCHER_ADD_NEW_APPS_TO_HOME_SCREEN_ENABLED(613),
@UiEvent(doc = "For new apps, add app icons to home screen disabled.")
LAUNCHER_ADD_NEW_APPS_TO_HOME_SCREEN_DISABLED(614),
@UiEvent(doc = "Home screen rotation is enabled when phone is rotated.")
LAUNCHER_HOME_SCREEN_ROTATION_ENABLED(615),
@UiEvent(doc = "Home screen rotation is disabled when phone is rotated.")
LAUNCHER_HOME_SCREEN_ROTATION_DISABLED(616),
@UiEvent(doc = "Suggestions in all apps list enabled.")
LAUNCHER_ALL_APPS_SUGGESTIONS_ENABLED(619),
@UiEvent(doc = "Suggestions in all apps list disabled.")
LAUNCHER_ALL_APPS_SUGGESTIONS_DISABLED(620),
@UiEvent(doc = "Suggestions on home screen is enabled.")
LAUNCHER_HOME_SCREEN_SUGGESTIONS_ENABLED(621),
@UiEvent(doc = "Suggestions on home screen is disabled.")
LAUNCHER_HOME_SCREEN_SUGGESTIONS_DISABLED(622),
@UiEvent(doc = "System navigation is 3 button mode.")
LAUNCHER_NAVIGATION_MODE_3_BUTTON(623),
@UiEvent(doc = "System navigation mode is 2 button mode.")
LAUNCHER_NAVIGATION_MODE_2_BUTTON(624),
@UiEvent(doc = "System navigation mode is 0 button mode/gesture navigation mode .")
LAUNCHER_NAVIGATION_MODE_GESTURE_BUTTON(625),
@UiEvent(doc = "User tapped on image content in Overview Select mode.")
LAUNCHER_SELECT_MODE_IMAGE(627),
@@ -402,170 +314,107 @@ public class StatsLogManager implements ResourceBasedOverride {
@UiEvent(doc = "Activity to add external item was started")
LAUNCHER_ADD_EXTERNAL_ITEM_START(641),
@UiEvent(doc = "Activity to add external item was cancelled")
LAUNCHER_ADD_EXTERNAL_ITEM_CANCELLED(642),
@UiEvent(doc = "Activity to add external item was backed out")
LAUNCHER_ADD_EXTERNAL_ITEM_BACK(643),
@UiEvent(doc = "Item was placed automatically in external item addition flow")
LAUNCHER_ADD_EXTERNAL_ITEM_PLACED_AUTOMATICALLY(644),
@UiEvent(doc = "Item was dragged in external item addition flow")
LAUNCHER_ADD_EXTERNAL_ITEM_DRAGGED(645),
@UiEvent(doc = "A folder was replaced by a single item")
LAUNCHER_FOLDER_CONVERTED_TO_ICON(646),
@UiEvent(doc = "A hotseat prediction item was pinned")
LAUNCHER_HOTSEAT_PREDICTION_PINNED(647),
@UiEvent(doc = "Undo event was tapped.")
LAUNCHER_UNDO(648),
@UiEvent(doc = "Task switcher clear all target was tapped.")
LAUNCHER_TASK_CLEAR_ALL(649),
@UiEvent(doc = "Task preview was long pressed.")
LAUNCHER_TASK_PREVIEW_LONGPRESS(650),
@UiEvent(doc = "User swiped down on workspace (triggering noti shade to open).")
LAUNCHER_SWIPE_DOWN_WORKSPACE_NOTISHADE_OPEN(651),
@UiEvent(doc = "Notification dismissed by swiping right.")
LAUNCHER_NOTIFICATION_DISMISSED(652),
@UiEvent(doc = "Current grid size is changed to 2x2")
LAUNCHER_GRID_SIZE_2_BY_2(2181),
@UiEvent(doc = "Current grid size is changed to 3x3")
LAUNCHER_GRID_SIZE_3_BY_3(2182),
@UiEvent(doc = "Current grid size is changed to 4x4")
LAUNCHER_GRID_SIZE_4_BY_4(2183),
@UiEvent(doc = "Current grid size is changed to 4x5")
LAUNCHER_GRID_SIZE_4_BY_5(2184),
@UiEvent(doc = "Current grid size is changed to 4x6")
LAUNCHER_GRID_SIZE_4_BY_6(2185),
@UiEvent(doc = "Current grid size is changed to 4x7")
LAUNCHER_GRID_SIZE_4_BY_7(2189),
@UiEvent(doc = "Current grid size is changed to 5x5")
LAUNCHER_GRID_SIZE_5_BY_5(2186),
@UiEvent(doc = "Current grid size is changed to 5x6")
LAUNCHER_GRID_SIZE_5_BY_6(2187),
@UiEvent(doc = "Current grid size is changed to 6x5")
LAUNCHER_GRID_SIZE_6_BY_5(2188),
@UiEvent(doc = "Current grid size is changed to 6.")
LAUNCHER_GRID_SIZE_6(930),
@UiEvent(doc = "Current grid size is changed to 5.")
LAUNCHER_GRID_SIZE_5(662),
@UiEvent(doc = "Current grid size is changed to 4.")
LAUNCHER_GRID_SIZE_4(663),
@UiEvent(doc = "Current grid size is changed to 3.")
LAUNCHER_GRID_SIZE_3(664),
@UiEvent(doc = "Current grid size is changed to 2.")
LAUNCHER_GRID_SIZE_2(665),
@UiEvent(doc = "Launcher entered into AllApps state.")
LAUNCHER_ALLAPPS_ENTRY(692),
@UiEvent(doc = "Launcher exited from AllApps state.")
LAUNCHER_ALLAPPS_EXIT(693),
@UiEvent(doc = "User closed the AllApps keyboard.")
LAUNCHER_ALLAPPS_KEYBOARD_CLOSED(694),
@UiEvent(doc = "User switched to AllApps Main/Personal tab by swiping left.")
LAUNCHER_ALLAPPS_SWIPE_TO_PERSONAL_TAB(695),
@UiEvent(doc = "User switched to AllApps Work tab by swiping right.")
LAUNCHER_ALLAPPS_SWIPE_TO_WORK_TAB(696),
@UiEvent(doc = "Default event when dedicated UI event is not available for the user action"
+ " on slice .")
LAUNCHER_SLICE_DEFAULT_ACTION(700),
@UiEvent(doc = "User toggled-on a Slice item.")
LAUNCHER_SLICE_TOGGLE_ON(701),
@UiEvent(doc = "User toggled-off a Slice item.")
LAUNCHER_SLICE_TOGGLE_OFF(702),
@UiEvent(doc = "User acted on a Slice item with a button.")
LAUNCHER_SLICE_BUTTON_ACTION(703),
@UiEvent(doc = "User acted on a Slice item with a slider.")
LAUNCHER_SLICE_SLIDER_ACTION(704),
@UiEvent(doc = "User tapped on the entire row of a Slice.")
LAUNCHER_SLICE_CONTENT_ACTION(705),
@UiEvent(doc = "User tapped on the see more button of a Slice.")
LAUNCHER_SLICE_SEE_MORE_ACTION(706),
@UiEvent(doc = "User selected from a selection row of Slice.")
LAUNCHER_SLICE_SELECTION_ACTION(707),
@UiEvent(doc = "IME is used for selecting the focused item on the AllApps screen.")
LAUNCHER_ALLAPPS_FOCUSED_ITEM_SELECTED_WITH_IME(718),
@UiEvent(doc = "User long-pressed on an AllApps item.")
LAUNCHER_ALLAPPS_ITEM_LONG_PRESSED(719),
@UiEvent(doc = "Launcher entered into AllApps state with device search enabled.")
LAUNCHER_ALLAPPS_ENTRY_WITH_DEVICE_SEARCH(720),
@UiEvent(doc = "User switched to AllApps Main/Personal tab by tapping on it.")
LAUNCHER_ALLAPPS_TAP_ON_PERSONAL_TAB(721),
@UiEvent(doc = "User switched to AllApps Work tab by tapping on it.")
LAUNCHER_ALLAPPS_TAP_ON_WORK_TAB(722),
@UiEvent(doc = "All apps vertical fling started.")
LAUNCHER_ALLAPPS_VERTICAL_SWIPE_BEGIN(724),
@UiEvent(doc = "All apps vertical fling ended.")
LAUNCHER_ALLAPPS_VERTICAL_SWIPE_END(725),
@UiEvent(doc = "Show URL indicator for Overview Sharing")
LAUNCHER_OVERVIEW_SHARING_SHOW_URL_INDICATOR(764),
@UiEvent(doc = "Show image indicator for Overview Sharing")
LAUNCHER_OVERVIEW_SHARING_SHOW_IMAGE_INDICATOR(765),
@UiEvent(doc = "User taps URL indicator in Overview")
LAUNCHER_OVERVIEW_SHARING_URL_INDICATOR_TAP(766),
@UiEvent(doc = "User taps image indicator in Overview")
LAUNCHER_OVERVIEW_SHARING_IMAGE_INDICATOR_TAP(767),
@UiEvent(doc = "User long presses an image in Overview")
LAUNCHER_OVERVIEW_SHARING_IMAGE_LONG_PRESS(768),
@UiEvent(doc = "User drags a URL in Overview")
LAUNCHER_OVERVIEW_SHARING_URL_DRAG(769),
@UiEvent(doc = "User drags an image in Overview")
LAUNCHER_OVERVIEW_SHARING_IMAGE_DRAG(770),
@UiEvent(doc = "User drops URL to a direct share target")
LAUNCHER_OVERVIEW_SHARING_DROP_URL_TO_TARGET(771),
@UiEvent(doc = "User drops an image to a direct share target")
LAUNCHER_OVERVIEW_SHARING_DROP_IMAGE_TO_TARGET(772),
@UiEvent(doc = "User drops URL to the More button")
LAUNCHER_OVERVIEW_SHARING_DROP_URL_TO_MORE(773),
@UiEvent(doc = "User drops an image to the More button")
LAUNCHER_OVERVIEW_SHARING_DROP_IMAGE_TO_MORE(774),
@UiEvent(doc = "User taps a share target to share URL")
LAUNCHER_OVERVIEW_SHARING_TAP_TARGET_TO_SHARE_URL(775),
@UiEvent(doc = "User taps a share target to share an image")
LAUNCHER_OVERVIEW_SHARING_TAP_TARGET_TO_SHARE_IMAGE(776),
@UiEvent(doc = "User taps the More button to share URL")
LAUNCHER_OVERVIEW_SHARING_TAP_MORE_TO_SHARE_URL(777),
@UiEvent(doc = "User taps the More button to share an image")
LAUNCHER_OVERVIEW_SHARING_TAP_MORE_TO_SHARE_IMAGE(778),
@@ -586,100 +435,69 @@ public class StatsLogManager implements ResourceBasedOverride {
@UiEvent(doc = "User started resizing a widget on their home screen.")
LAUNCHER_WIDGET_RESIZE_STARTED(820),
@UiEvent(doc = "User finished resizing a widget on their home screen.")
LAUNCHER_WIDGET_RESIZE_COMPLETED(824),
@UiEvent(doc = "User reconfigured a widget on their home screen.")
LAUNCHER_WIDGET_RECONFIGURED(821),
@UiEvent(doc = "User enabled themed icons option in wallpaper & style settings.")
LAUNCHER_THEMED_ICON_ENABLED(836),
@UiEvent(doc = "User disabled themed icons option in wallpaper & style settings.")
LAUNCHER_THEMED_ICON_DISABLED(837),
@UiEvent(doc = "User tapped on 'Turn on work apps' button in all apps window.")
LAUNCHER_TURN_ON_WORK_APPS_TAP(838),
@UiEvent(doc = "User tapped on 'Turn off work apps' button in all apps window.")
LAUNCHER_TURN_OFF_WORK_APPS_TAP(839),
@UiEvent(doc = "Launcher item drop failed since there was not enough room on the screen.")
LAUNCHER_ITEM_DROP_FAILED_INSUFFICIENT_SPACE(872),
@UiEvent(doc = "User clicks on the search icon on header to launch search in app.")
LAUNCHER_ALLAPPS_SEARCHINAPP_LAUNCH(913),
@UiEvent(doc = "User is shown the back gesture navigation tutorial step.")
LAUNCHER_GESTURE_TUTORIAL_BACK_STEP_SHOWN(959),
@UiEvent(doc = "User is shown the home gesture navigation tutorial step.")
LAUNCHER_GESTURE_TUTORIAL_HOME_STEP_SHOWN(960),
@UiEvent(doc = "User is shown the overview gesture navigation tutorial step.")
LAUNCHER_GESTURE_TUTORIAL_OVERVIEW_STEP_SHOWN(961),
@UiEvent(doc = "User completed the back gesture navigation tutorial step.")
LAUNCHER_GESTURE_TUTORIAL_BACK_STEP_COMPLETED(962),
@UiEvent(doc = "User completed the home gesture navigation tutorial step.")
LAUNCHER_GESTURE_TUTORIAL_HOME_STEP_COMPLETED(963),
@UiEvent(doc = "User completed the overview gesture navigation tutorial step.")
LAUNCHER_GESTURE_TUTORIAL_OVERVIEW_STEP_COMPLETED(964),
@UiEvent(doc = "User skips the gesture navigation tutorial.")
LAUNCHER_GESTURE_TUTORIAL_SKIPPED(965),
@UiEvent(doc = "User scrolled on one of the all apps surfaces such as A-Z list, search "
+ "result page etc.")
LAUNCHER_ALLAPPS_SCROLLED(985),
@UiEvent(doc = "User scrolled up on the all apps personal A-Z list.")
LAUNCHER_ALLAPPS_PERSONAL_SCROLLED_UP(1287),
@UiEvent(doc = "User scrolled down on the all apps personal A-Z list.")
LAUNCHER_ALLAPPS_PERSONAL_SCROLLED_DOWN(1288),
@UiEvent(doc = "User scrolled on one of the all apps surfaces such as A-Z list, search "
+ "result page etc and we don't know the direction since user came back to "
+ "original position from which they scrolled.")
LAUNCHER_ALLAPPS_SCROLLED_UNKNOWN_DIRECTION(1231),
@UiEvent(doc = "User tapped taskbar home button")
LAUNCHER_TASKBAR_HOME_BUTTON_TAP(1003),
@UiEvent(doc = "User tapped taskbar back button")
LAUNCHER_TASKBAR_BACK_BUTTON_TAP(1004),
@UiEvent(doc = "User tapped taskbar overview/recents button")
LAUNCHER_TASKBAR_OVERVIEW_BUTTON_TAP(1005),
@UiEvent(doc = "User tapped taskbar IME switcher button")
LAUNCHER_TASKBAR_IME_SWITCHER_BUTTON_TAP(1006),
@UiEvent(doc = "User tapped taskbar a11y button")
LAUNCHER_TASKBAR_A11Y_BUTTON_TAP(1007),
@UiEvent(doc = "User tapped taskbar home button")
LAUNCHER_TASKBAR_HOME_BUTTON_LONGPRESS(1008),
@UiEvent(doc = "User tapped taskbar back button")
LAUNCHER_TASKBAR_BACK_BUTTON_LONGPRESS(1009),
@UiEvent(doc = "User tapped taskbar overview/recents button")
LAUNCHER_TASKBAR_OVERVIEW_BUTTON_LONGPRESS(1010),
@UiEvent(doc = "User tapped taskbar a11y button")
LAUNCHER_TASKBAR_A11Y_BUTTON_LONGPRESS(1011),
@UiEvent(doc = "Show an 'Undo' snackbar when users dismiss a predicted hotseat item")
LAUNCHER_DISMISS_PREDICTION_UNDO(1035),
@UiEvent(doc = "User clicked on IME quicksearch button.")
LAUNCHER_ALLAPPS_QUICK_SEARCH_WITH_IME(1047),
@UiEvent(doc = "User tapped taskbar All Apps button.")
LAUNCHER_TASKBAR_ALLAPPS_BUTTON_TAP(1057),
@@ -688,54 +506,38 @@ public class StatsLogManager implements ResourceBasedOverride {
@UiEvent(doc = "User tapped on Share app system shortcut.")
LAUNCHER_SYSTEM_SHORTCUT_APP_SHARE_TAP(1075),
@UiEvent(doc = "User has invoked split to right half from an app icon menu")
LAUNCHER_APP_ICON_MENU_SPLIT_RIGHT_BOTTOM(1199),
@UiEvent(doc = "User has invoked split to left half from an app icon menu")
LAUNCHER_APP_ICON_MENU_SPLIT_LEFT_TOP(1200),
@UiEvent(doc = "Number of apps in A-Z list (personal and work profile)")
LAUNCHER_ALLAPPS_COUNT(1225),
@UiEvent(doc = "User has invoked split to right half with a keyboard shortcut.")
LAUNCHER_KEYBOARD_SHORTCUT_SPLIT_RIGHT_BOTTOM(1232),
@UiEvent(doc = "User has invoked split to left half with a keyboard shortcut.")
LAUNCHER_KEYBOARD_SHORTCUT_SPLIT_LEFT_TOP(1233),
@UiEvent(doc = "User has invoked split to right half from desktop mode.")
LAUNCHER_DESKTOP_MODE_SPLIT_RIGHT_BOTTOM(1412),
@UiEvent(doc = "User has invoked split to left half from desktop mode.")
LAUNCHER_DESKTOP_MODE_SPLIT_LEFT_TOP(1464),
@UiEvent(doc = "User has collapsed the work FAB button by scrolling down in the all apps"
+ " work A-Z list.")
LAUNCHER_WORK_FAB_BUTTON_COLLAPSE(1276),
@UiEvent(doc = "User has collapsed the work FAB button by scrolling up in the all apps"
+ " work A-Z list.")
LAUNCHER_WORK_FAB_BUTTON_EXTEND(1277),
@UiEvent(doc = "User scrolled down on the search result page.")
LAUNCHER_ALLAPPS_SEARCH_SCROLLED_DOWN(1285),
@UiEvent(doc = "User scrolled up on the search result page.")
LAUNCHER_ALLAPPS_SEARCH_SCROLLED_UP(1286),
@UiEvent(doc = "User or automatic timeout has hidden transient taskbar.")
LAUNCHER_TRANSIENT_TASKBAR_HIDE(1330),
@UiEvent(doc = "User has swiped upwards from the gesture handle to show transient taskbar.")
LAUNCHER_TRANSIENT_TASKBAR_SHOW(1331),
@UiEvent(doc = "User has clicked an app pair and launched directly into split screen.")
LAUNCHER_APP_PAIR_LAUNCH(1374),
@UiEvent(doc = "User saved an app pair.")
LAUNCHER_APP_PAIR_SAVE(1456),
@UiEvent(doc = "App launched through pending intent")
LAUNCHER_APP_LAUNCH_PENDING_INTENT(1394),
@@ -826,82 +628,6 @@ public class StatsLogManager implements ResourceBasedOverride {
@UiEvent(doc = "User launches Overview from meta+tab keyboard shortcut")
LAUNCHER_OVERVIEW_SHOW_OVERVIEW_FROM_KEYBOARD_SHORTCUT(1765),
@UiEvent(doc = "User long pressed on the taskbar IME switcher button")
LAUNCHER_TASKBAR_IME_SWITCHER_BUTTON_LONGPRESS(1798),
@UiEvent(doc = "Failed to launch assistant due to Google assistant not available")
LAUNCHER_LAUNCH_ASSISTANT_FAILED_NOT_AVAILABLE(1465),
@UiEvent(doc = "Failed to launch assistant due to service error")
LAUNCHER_LAUNCH_ASSISTANT_FAILED_SERVICE_ERROR(1466),
@UiEvent(doc = "User launched assistant by long-pressing nav handle")
LAUNCHER_LAUNCH_ASSISTANT_SUCCESSFUL_NAV_HANDLE(1467),
@UiEvent(doc = "Failed to launch due to Contextual Search not available")
LAUNCHER_LAUNCH_OMNI_FAILED_NOT_AVAILABLE(1471),
@UiEvent(doc = "Failed to launch due to Contextual Search setting disabled")
LAUNCHER_LAUNCH_OMNI_FAILED_SETTING_DISABLED(1632),
@UiEvent(doc = "User launched Contextual Search by long-pressing home in 3-button mode")
LAUNCHER_LAUNCH_OMNI_SUCCESSFUL_HOME(1481),
@UiEvent(doc = "User launched Contextual Search by using accessibility System Action")
LAUNCHER_LAUNCH_OMNI_SUCCESSFUL_SYSTEM_ACTION(1492),
@UiEvent(doc = "User launched Contextual Search by long pressing the meta key")
LAUNCHER_LAUNCH_OMNI_SUCCESSFUL_META(1606),
@UiEvent(doc = "Contextual Search invocation was attempted over the notification shade")
LAUNCHER_LAUNCH_OMNI_ATTEMPTED_OVER_NOTIFICATION_SHADE(1485),
@UiEvent(doc = "The Contextual Search all entrypoints toggle value in Settings")
LAUNCHER_SETTINGS_OMNI_ALL_ENTRYPOINTS_TOGGLE_VALUE(1633),
@UiEvent(doc = "Contextual Search invocation was attempted over the keyguard")
LAUNCHER_LAUNCH_OMNI_ATTEMPTED_OVER_KEYGUARD(1501),
@UiEvent(doc = "Contextual Search invocation was attempted while splitscreen is active")
LAUNCHER_LAUNCH_OMNI_ATTEMPTED_SPLITSCREEN(1505),
@UiEvent(doc = "User long press nav handle and a long press runnable was created.")
LAUNCHER_OMNI_GET_LONG_PRESS_RUNNABLE(1545),
@UiEvent(doc = "User tapped on \"change aspect ratio\" system shortcut.")
LAUNCHER_ASPECT_RATIO_SETTINGS_SYSTEM_SHORTCUT_TAP(2219),
// One Grid Flags
@UiEvent(doc = "User sets the device in Fixed Landscape")
FIXED_LANDSCAPE_TOGGLE_ENABLE(2014),
@UiEvent(doc = "User sets the device in Fixed Landscape")
FIXED_LANDSCAPE_TOGGLE_DISABLED(2020),
@UiEvent(doc = "Work utility view expand animation started")
LAUNCHER_WORK_UTILITY_VIEW_EXPAND_ANIMATION_BEGIN(2075),
@UiEvent(doc = "Work utility view expand animation ended")
LAUNCHER_WORK_UTILITY_VIEW_EXPAND_ANIMATION_END(2076),
@UiEvent(doc = "Work utility view shrink animation started")
LAUNCHER_WORK_UTILITY_VIEW_SHRINK_ANIMATION_BEGIN(2077),
@UiEvent(doc = "Work utility view shrink animation ended")
LAUNCHER_WORK_UTILITY_VIEW_SHRINK_ANIMATION_END(2078),
@UiEvent(doc = "Standard grid migration occurred")
LAUNCHER_STANDARD_GRID_MIGRATION(2200),
@UiEvent(doc = "Row shift grid migration occurred")
LAUNCHER_ROW_SHIFT_GRID_MIGRATION(2201),
@UiEvent(doc = "Do standard migration when upgrading to one grid")
LAUNCHER_STANDARD_ONE_GRID_MIGRATION(2205),
@UiEvent(doc = "Do row shift migration when upgrading to one grid")
LAUNCHER_ROW_SHIFT_ONE_GRID_MIGRATION(2206),
// ADD MORE
;
@@ -918,28 +644,17 @@ public class StatsLogManager implements ResourceBasedOverride {
/** Launcher's latency events. */
public enum LauncherLatencyEvent implements EventEnum {
// Details of below 6 events with prefix of "LAUNCHER_LATENCY_STARTUP_" are discussed in
// Details of below 6 events with prefix of "LAUNCHER_LATENCY_STARTUP_" are
// discussed in
// go/launcher-startup-latency
@UiEvent(doc = "The total duration of launcher startup latency.")
LAUNCHER_LATENCY_STARTUP_TOTAL_DURATION(1362),
@UiEvent(doc = "The duration of launcher activity's onCreate().")
LAUNCHER_LATENCY_STARTUP_ACTIVITY_ON_CREATE(1363),
@UiEvent(doc =
"The duration to inflate launcher root view in launcher activity's onCreate().")
@UiEvent(doc = "The duration to inflate launcher root view in launcher activity's onCreate().")
LAUNCHER_LATENCY_STARTUP_VIEW_INFLATION(1364),
@UiEvent(doc = "The duration of asynchronous loading workspace")
LAUNCHER_LATENCY_STARTUP_WORKSPACE_LOADER_ASYNC(1367),
@UiEvent(doc = "Time passed between Contextual Search runnable creation and execution. This"
+ " ensures that Recent animations have finished before Contextual Search starts.")
LAUNCHER_LATENCY_OMNI_RUNNABLE(1546),
@UiEvent(doc = "Time passed between nav handle touch down and cancellation without "
+ "triggering Contextual Search")
LAUNCHER_LATENCY_CONTEXTUAL_SEARCH_LPNH_ABANDON(2171),
;
private final int mId;
@@ -958,10 +673,9 @@ public class StatsLogManager implements ResourceBasedOverride {
* Launcher specific ranking related events.
*/
public enum LauncherRankingEvent implements EventEnum {
UNKNOWN(0);
// ADD MORE
// ADD MORE
private final int mId;
LauncherRankingEvent(int id) {
@@ -977,7 +691,6 @@ public class StatsLogManager implements ResourceBasedOverride {
* Helps to construct and log launcher event.
*/
public interface StatsLogger {
/**
* Sets log fields from provided {@link ItemInfo}.
*/
@@ -985,7 +698,6 @@ public class StatsLogManager implements ResourceBasedOverride {
return this;
}
/**
* Sets {@link InstanceId} of log message.
*/
@@ -1038,7 +750,8 @@ public class StatsLogManager implements ResourceBasedOverride {
/**
* Sets the final value for container related fields of log message.
*
* By default container related fields are derived from {@link ItemInfo}, this method would
* By default container related fields are derived from {@link ItemInfo}, this
* method would
* override those values.
*/
default StatsLogger withContainerInfo(ContainerInfo containerInfo) {
@@ -1105,7 +818,6 @@ public class StatsLogManager implements ResourceBasedOverride {
* Helps to construct and log latency event.
*/
public interface StatsLatencyLogger {
/**
* Should be in sync with:
* google3/wireless/android/sysui/aster/asterstats/launcher_event_processed.proto
@@ -1126,6 +838,7 @@ public class StatsLogManager implements ResourceBasedOverride {
// Tracking warm startup latency:
// https://developer.android.com/topic/performance/vitals/launch-time#warm
WARM(10);
private final int mId;
LatencyType(int id) {
@@ -1144,7 +857,6 @@ public class StatsLogManager implements ResourceBasedOverride {
return this;
}
/**
* Sets latency of the event.
*/
@@ -1173,7 +885,6 @@ public class StatsLogManager implements ResourceBasedOverride {
return this;
}
/** Sets cardinality of the event. */
default StatsLatencyLogger withCardinality(int cardinality) {
return this;
@@ -1197,11 +908,11 @@ public class StatsLogManager implements ResourceBasedOverride {
* Helps to construct and log impression event.
*/
public interface StatsImpressionLogger {
enum State {
UNKNOWN(0),
ALLAPPS(1),
SEARCHBOX_WIDGET(2);
private final int mLauncherState;
State(int id) {
@@ -1242,7 +953,8 @@ public class StatsLogManager implements ResourceBasedOverride {
}
/**
* Sets boolean for each of {@link com.android.app.search.ResultType} that indicates
* Sets boolean for each of {@link com.android.app.search.ResultType} that
* indicates
* if this result is above keyboard or not for the impression event.
*/
default StatsImpressionLogger withAboveKeyboard(boolean aboveKeyboard) {
@@ -1258,7 +970,8 @@ public class StatsLogManager implements ResourceBasedOverride {
}
/**
* Sets result source that indicates the origin of the result for the impression event.
* Sets result source that indicates the origin of the result for the impression
* event.
*/
default StatsImpressionLogger withResultSource(int resultSource) {
return this;
@@ -1332,7 +1045,8 @@ public class StatsLogManager implements ResourceBasedOverride {
}
/**
* Sets InstanceId to every new {@link StatsLogger} object returned by {@link #logger()} when
* Sets InstanceId to every new {@link StatsLogger} object returned by
* {@link #logger()} when
* not-null.
*/
public StatsLogManager withDefaultInstanceId(@Nullable InstanceId instanceId) {
@@ -1347,4 +1061,4 @@ public class StatsLogManager implements ResourceBasedOverride {
return Overrides.getObject(
StatsLogManager.class, context, R.string.stats_log_manager_class);
}
}
}
@@ -15,8 +15,6 @@
*/
package com.android.launcher3.model;
import static com.android.launcher3.LauncherSettings.Favorites.DESKTOP_ICON_FLAG;
import android.content.Context;
import android.content.Intent;
import android.content.pm.LauncherActivityInfo;
@@ -43,7 +41,6 @@ import com.android.launcher3.model.data.WorkspaceItemFactory;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.InstallSessionHelper;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.util.ApplicationInfoWrapper;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.PackageManagerHelper;
@@ -66,6 +63,13 @@ public class AddWorkspaceItemsTask implements ModelUpdateTask {
/**
* @param itemList items to add on the workspace
*/
public AddWorkspaceItemsTask(@NonNull final List<Pair<ItemInfo, Object>> itemList) {
this(itemList, new WorkspaceItemSpaceFinder());
}
/**
* @param itemList items to add on the workspace
* @param itemSpaceFinder inject WorkspaceItemSpaceFinder dependency for testing
*/
public AddWorkspaceItemsTask(@NonNull final List<Pair<ItemInfo, Object>> itemList,
@@ -74,7 +78,6 @@ public class AddWorkspaceItemsTask implements ModelUpdateTask {
mItemSpaceFinder = itemSpaceFinder;
}
@Override
public void execute(@NonNull ModelTaskController taskController, @NonNull BgDataModel dataModel,
@NonNull AllAppsList apps) {
@@ -84,10 +87,10 @@ public class AddWorkspaceItemsTask implements ModelUpdateTask {
final ArrayList<ItemInfo> addedItemsFinal = new ArrayList<>();
final IntArray addedWorkspaceScreensFinal = new IntArray();
final Context context = taskController.getContext();
final Context context = taskController.getApp().getContext();
synchronized (dataModel) {
IntArray workspaceScreens = dataModel.collectWorkspaceScreens(context);
IntArray workspaceScreens = dataModel.collectWorkspaceScreens();
List<ItemInfo> filteredItems = new ArrayList<>();
for (Pair<ItemInfo, Object> entry : mItemList) {
@@ -98,12 +101,6 @@ public class AddWorkspaceItemsTask implements ModelUpdateTask {
continue;
}
// b/139663018 Short-circuit this logic if the icon is a system app
if (new ApplicationInfoWrapper(context,
Objects.requireNonNull(item.getIntent())).isSystem()) {
continue;
}
if (item instanceof ItemInfoWithIcon
&& ((ItemInfoWithIcon) item).isArchived()) {
continue;
@@ -120,14 +117,13 @@ public class AddWorkspaceItemsTask implements ModelUpdateTask {
}
}
InstallSessionHelper packageInstaller =
InstallSessionHelper.INSTANCE.get(context);
InstallSessionHelper packageInstaller = InstallSessionHelper.INSTANCE.get(context);
LauncherApps launcherApps = context.getSystemService(LauncherApps.class);
for (ItemInfo item : filteredItems) {
// Find appropriate space for the item.
int[] coords = mItemSpaceFinder.findSpaceForItem(
workspaceScreens, addedWorkspaceScreensFinal, item.spanX, item.spanY, context);
int[] coords = mItemSpaceFinder.findSpaceForItem(taskController.getApp(), dataModel,
workspaceScreens, addedWorkspaceScreensFinal, item.spanX, item.spanY);
int screenId = coords[0];
ItemInfo itemInfo;
@@ -186,11 +182,12 @@ public class AddWorkspaceItemsTask implements ModelUpdateTask {
continue;
}
IconCache cache = taskController.getIconCache();
IconCache cache = taskController.getApp().getIconCache();
WorkspaceItemInfo wii = (WorkspaceItemInfo) itemInfo;
wii.title = "";
wii.bitmap = cache.getDefaultIcon(item.user);
cache.getTitleAndIcon(wii, DESKTOP_ICON_FLAG);
cache.getTitleAndIcon(wii,
((WorkspaceItemInfo) itemInfo).usingLowResIcon());
}
}
@@ -232,7 +229,8 @@ public class AddWorkspaceItemsTask implements ModelUpdateTask {
}
/**
* Returns true if the shortcuts already exists on the workspace. This must be called after
* Returns true if the shortcuts already exists on the workspace. This must be
* called after
* the workspace has been loaded. We identify a shortcut by its intent.
*/
protected boolean shortcutExists(@NonNull final BgDataModel dataModel,
@@ -18,7 +18,6 @@
package com.android.launcher3.model;
import static com.android.launcher3.icons.cache.CacheLookupFlag.DEFAULT_LOOKUP_FLAG;
import static com.android.launcher3.model.data.AppInfo.COMPONENT_KEY_COMPARATOR;
import static com.android.launcher3.model.data.AppInfo.EMPTY_ARRAY;
@@ -36,7 +35,6 @@ import androidx.annotation.Nullable;
import com.android.launcher3.AppFilter;
import com.android.launcher3.compat.AlphabeticIndexCompat;
import com.android.launcher3.dagger.LauncherAppSingleton;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.model.BgDataModel.Callbacks;
import com.android.launcher3.model.data.AppInfo;
@@ -44,7 +42,6 @@ import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.util.ApiWrapper;
import com.android.launcher3.util.ApplicationInfoWrapper;
import com.android.launcher3.util.FlagOp;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.SafeCloseable;
@@ -56,13 +53,11 @@ import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import javax.inject.Inject;
/**
* Stores the list of all applications for the all apps view.
*/
@LauncherAppSingleton
@SuppressWarnings("NewApi")
public class AllAppsList {
private static final String TAG = "AllAppsList";
@@ -75,10 +70,10 @@ public class AllAppsList {
public final ArrayList<AppInfo> data = new ArrayList<>(DEFAULT_APPLICATIONS_NUMBER);
@NonNull
private final IconCache mIconCache;
private IconCache mIconCache;
@NonNull
private final AppFilter mAppFilter;
private AppFilter mAppFilter;
private boolean mDataChanged = false;
private Consumer<AppInfo> mRemoveListener = NO_OP_CONSUMER;
@@ -97,7 +92,6 @@ public class AllAppsList {
/**
* Boring constructor.
*/
@Inject
public AllAppsList(IconCache iconCache, AppFilter appFilter) {
mIconCache = iconCache;
mAppFilter = appFilter;
@@ -158,7 +152,7 @@ public class AllAppsList {
return;
}
if (loadIcon) {
mIconCache.getTitleAndIcon(info, activityInfo, DEFAULT_LOOKUP_FLAG);
mIconCache.getTitleAndIcon(info, activityInfo, false /* useLowResIcon */);
info.sectionName = mIndex.computeSectionName(info.title);
} else {
info.title = "";
@@ -177,14 +171,14 @@ public class AllAppsList {
public AppInfo addPromiseApp(
Context context, PackageInstallInfo installInfo, boolean loadIcon) {
// only if not yet installed
if (new ApplicationInfoWrapper(context, installInfo.packageName, installInfo.user)
.isInstalled()) {
if (PackageManagerHelper.INSTANCE.get(context)
.isAppInstalled(installInfo.packageName, installInfo.user)) {
return null;
}
AppInfo promiseAppInfo = new AppInfo(installInfo);
if (loadIcon) {
mIconCache.getTitleAndIcon(promiseAppInfo, promiseAppInfo.getMatchingLookupFlag());
mIconCache.getTitleAndIcon(promiseAppInfo, promiseAppInfo.usingLowResIcon());
promiseAppInfo.sectionName = mIndex.computeSectionName(promiseAppInfo.title);
} else {
promiseAppInfo.title = "";
@@ -231,8 +225,7 @@ public class AllAppsList {
if (DEBUG) {
Log.w(TAG, "updatePromiseInstallInfo: removing app due to install"
+ " failure and appInfo not startable."
+ " package=" + appInfo.getTargetPackage()
+ ", user=" + user);
+ " package=" + appInfo.getTargetPackage());
}
removeApp(i);
}
@@ -328,8 +321,7 @@ public class AllAppsList {
if (!findActivity(matches, applicationInfo.componentName)) {
if (DEBUG) {
Log.w(TAG, "Changing shortcut target due to app component name change."
+ " component=" + applicationInfo.componentName
+ ", user=" + user);
+ " package=" + packageName);
}
removeApp(i);
}
@@ -345,7 +337,7 @@ public class AllAppsList {
} else {
Intent launchIntent = AppInfo.makeLaunchIntent(info);
mIconCache.getTitleAndIcon(applicationInfo, info, DEFAULT_LOOKUP_FLAG);
mIconCache.getTitleAndIcon(applicationInfo, info, false /* useLowResIcon */);
applicationInfo.sectionName = mIndex.computeSectionName(applicationInfo.title);
applicationInfo.intent = launchIntent;
AppInfo.updateRuntimeFlagsForActivityTarget(applicationInfo, info,
@@ -356,9 +348,8 @@ public class AllAppsList {
} else {
// Remove all data for this package.
if (DEBUG) {
Log.w(TAG, "updatePackage: no Activities matched updated package,"
+ " removing any AppInfo with package=" + packageName
+ ", user=" + user);
Log.w(TAG, "updatePromiseInstallInfo: no Activities matched updated package,"
+ " removing all apps from package=" + packageName);
}
for (int i = data.size() - 1; i >= 0; i--) {
final AppInfo applicationInfo = data.get(i);
@@ -19,14 +19,12 @@ package com.android.launcher3.model;
import static com.android.launcher3.BuildConfigs.WIDGETS_ENABLED;
import static com.android.launcher3.Flags.enableSmartspaceRemovalToggle;
import static com.android.launcher3.Flags.enableWorkspaceInflation;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_DESKTOP;
import static com.android.launcher3.model.ItemInstallQueue.FLAG_LOADER_RUNNING;
import static com.android.launcher3.model.ModelUtils.WIDGET_FILTER;
import static com.android.launcher3.model.ModelUtils.currentScreenContentFilter;
import static com.android.launcher3.model.ModelUtils.filterCurrentWorkspaceItems;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import android.content.Context;
import android.os.Process;
import android.os.Trace;
import android.util.Log;
import android.util.Pair;
@@ -35,47 +33,43 @@ import android.view.View;
import androidx.annotation.NonNull;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel.CallbackTask;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.celllayout.CellPosMapper;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dagger.ApplicationContext;
import com.android.launcher3.model.BgDataModel.Callbacks;
import com.android.launcher3.model.BgDataModel.FixedContainerItems;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.ItemInflater;
import com.android.launcher3.util.LooperExecutor;
import com.android.launcher3.util.LooperIdleLock;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.util.RunnableList;
import com.android.launcher3.widget.model.WidgetsListBaseEntriesBuilder;
import com.android.launcher3.widget.model.WidgetsListBaseEntry;
import dagger.assisted.Assisted;
import dagger.assisted.AssistedFactory;
import dagger.assisted.AssistedInject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Binds the results of {@link com.android.launcher3.model.LoaderTask} to the Callbacks objects.
* Binds the results of {@link com.android.launcher3.model.LoaderTask} to the
* Callbacks objects.
*/
public class BaseLauncherBinder {
@@ -84,9 +78,7 @@ public class BaseLauncherBinder {
protected final LooperExecutor mUiExecutor;
private final Context mContext;
private final InvariantDeviceProfile mIDP;
private final LauncherModel mModel;
protected final LauncherAppState mApp;
protected final BgDataModel mBgDataModel;
private final AllAppsList mBgAllAppsList;
@@ -94,18 +86,10 @@ public class BaseLauncherBinder {
private int mMyBindingId;
@AssistedInject
public BaseLauncherBinder(
@ApplicationContext Context context,
InvariantDeviceProfile idp,
LauncherModel model,
BgDataModel dataModel,
AllAppsList allAppsList,
@Assisted Callbacks[] callbacksList) {
public BaseLauncherBinder(LauncherAppState app, BgDataModel dataModel,
AllAppsList allAppsList, Callbacks[] callbacksList) {
mUiExecutor = MAIN_EXECUTOR;
mContext = context;
mIDP = idp;
mModel = model;
mApp = app;
mBgDataModel = dataModel;
mBgAllAppsList = allAppsList;
mCallbacksList = callbacksList;
@@ -117,32 +101,68 @@ public class BaseLauncherBinder {
public void bindWorkspace(boolean incrementBindId, boolean isBindSync) {
Trace.beginSection("BaseLauncherBinder#bindWorkspace");
try {
// Save a copy of all the bg-thread collections
IntSparseArrayMap<ItemInfo> itemsIdMap;
final IntArray orderedScreenIds = new IntArray();
ArrayList<FixedContainerItems> extraItems = new ArrayList<>();
final int workspaceItemCount;
synchronized (mBgDataModel) {
itemsIdMap = mBgDataModel.itemsIdMap.clone();
orderedScreenIds.addAll(mBgDataModel.collectWorkspaceScreens(mContext));
mBgDataModel.extraItems.forEach(extraItems::add);
if (incrementBindId) {
mBgDataModel.lastBindId++;
mBgDataModel.lastLoadId = mModel.getLastLoadId();
}
mMyBindingId = mBgDataModel.lastBindId;
workspaceItemCount = mBgDataModel.itemsIdMap.size();
}
for (Callbacks cb : mCallbacksList) {
new UnifiedWorkspaceBinder(cb, itemsIdMap, extraItems, orderedScreenIds)
.bind(isBindSync, workspaceItemCount);
if (FeatureFlags.ENABLE_WORKSPACE_LOADING_OPTIMIZATION.get()) {
DisjointWorkspaceBinder workspaceBinder = initWorkspaceBinder(incrementBindId,
mBgDataModel.collectWorkspaceScreens());
workspaceBinder.bindCurrentWorkspacePages(isBindSync);
workspaceBinder.bindOtherWorkspacePages();
} else {
bindWorkspaceAllAtOnce(incrementBindId, isBindSync);
}
} finally {
Trace.endSection();
}
}
/**
* Initializes the WorkspaceBinder for binding.
*
* @param incrementBindId this is used to stop previously started binding tasks
* that are
* obsolete but still queued.
* @param workspacePages this allows the Launcher to add the correct workspace
* screens.
*/
public DisjointWorkspaceBinder initWorkspaceBinder(boolean incrementBindId,
IntArray workspacePages) {
synchronized (mBgDataModel) {
if (incrementBindId) {
mBgDataModel.lastBindId++;
mBgDataModel.lastLoadId = mApp.getModel().getLastLoadId();
}
mMyBindingId = mBgDataModel.lastBindId;
return new DisjointWorkspaceBinder(workspacePages);
}
}
private void bindWorkspaceAllAtOnce(boolean incrementBindId, boolean isBindSync) {
// Save a copy of all the bg-thread collections
ArrayList<ItemInfo> workspaceItems = new ArrayList<>();
ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<>();
final IntArray orderedScreenIds = new IntArray();
ArrayList<FixedContainerItems> extraItems = new ArrayList<>();
final int workspaceItemCount;
synchronized (mBgDataModel) {
workspaceItems.addAll(mBgDataModel.workspaceItems);
appWidgets.addAll(mBgDataModel.appWidgets);
orderedScreenIds.addAll(mBgDataModel.collectWorkspaceScreens());
mBgDataModel.extraItems.forEach(extraItems::add);
if (incrementBindId) {
mBgDataModel.lastBindId++;
mBgDataModel.lastLoadId = mApp.getModel().getLastLoadId();
}
mMyBindingId = mBgDataModel.lastBindId;
workspaceItemCount = mBgDataModel.itemsIdMap.size();
}
for (Callbacks cb : mCallbacksList) {
new UnifiedWorkspaceBinder(cb, mUiExecutor, mApp, mBgDataModel, mMyBindingId,
workspaceItems, appWidgets, extraItems, orderedScreenIds)
.bind(isBindSync, workspaceItemCount);
}
}
/**
* BindDeepShortcuts is abstract because it is a no-op for the go launcher.
*/
@@ -167,7 +187,8 @@ public class BaseLauncherBinder {
Map<PackageUserKey, Integer> packageUserKeytoUidMap = Arrays.stream(apps).collect(
Collectors.toMap(
appInfo -> new PackageUserKey(appInfo.componentName.getPackageName(),
appInfo.user), appInfo -> appInfo.uid, (a, b) -> a));
appInfo.user),
appInfo -> appInfo.uid, (a, b) -> a));
executeCallbacksTask(c -> c.bindAllApplications(apps, flags, packageUserKeytoUidMap),
mUiExecutor);
}
@@ -179,8 +200,8 @@ public class BaseLauncherBinder {
if (!WIDGETS_ENABLED) {
return;
}
List<WidgetsListBaseEntry> widgets = new WidgetsListBaseEntriesBuilder(mContext)
.build(mBgDataModel.widgetsModel.getWidgetsByPackageItemForPicker());
final List<WidgetsListBaseEntry> widgets =
mBgDataModel.widgetsModel.getWidgetsListForPicker(mApp.getContext());
executeCallbacksTask(c -> c.bindAllWidgets(widgets), mUiExecutor);
}
@@ -195,11 +216,13 @@ public class BaseLauncherBinder {
}
/**
* Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to right)
* Sorts the set of items by hotseat, workspace (spatially from top to bottom,
* left to right)
*/
protected void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
final int screenCols = mIDP.numColumns;
final int screenCellCount = mIDP.numColumns * mIDP.numRows;
protected void sortWorkspaceItemsSpatially(InvariantDeviceProfile profile,
ArrayList<ItemInfo> workspaceItems) {
final int screenCols = profile.numColumns;
final int screenCellCount = profile.numColumns * profile.numRows;
Collections.sort(workspaceItems, (lhs, rhs) -> {
if (lhs.container == rhs.container) {
// Within containers, order by their spatial position in that container
@@ -246,7 +269,8 @@ public class BaseLauncherBinder {
*/
public LooperIdleLock newIdleLock(Object lock) {
LooperIdleLock idleLock = new LooperIdleLock(lock, mUiExecutor.getLooper());
// If we are not binding or if the main looper is already idle, there is no reason to wait
// If we are not binding or if the main looper is already idle, there is no
// reason to wait
if (mUiExecutor.getLooper().getQueue().isIdle()) {
idleLock.queueIdle();
}
@@ -255,45 +279,56 @@ public class BaseLauncherBinder {
private class UnifiedWorkspaceBinder {
private final Executor mUiExecutor;
private final Callbacks mCallbacks;
private final IntSparseArrayMap<ItemInfo> mItemIdMap;
private final LauncherAppState mApp;
private final BgDataModel mBgDataModel;
private final int mMyBindingId;
private final ArrayList<ItemInfo> mWorkspaceItems;
private final ArrayList<LauncherAppWidgetInfo> mAppWidgets;
private final IntArray mOrderedScreenIds;
private final ArrayList<FixedContainerItems> mExtraItems;
UnifiedWorkspaceBinder(
Callbacks callbacks,
IntSparseArrayMap<ItemInfo> itemIdMap,
UnifiedWorkspaceBinder(Callbacks callbacks,
Executor uiExecutor,
LauncherAppState app,
BgDataModel bgDataModel,
int myBindingId,
ArrayList<ItemInfo> workspaceItems,
ArrayList<LauncherAppWidgetInfo> appWidgets,
ArrayList<FixedContainerItems> extraItems,
IntArray orderedScreenIds) {
mCallbacks = callbacks;
mItemIdMap = itemIdMap;
mUiExecutor = uiExecutor;
mApp = app;
mBgDataModel = bgDataModel;
mMyBindingId = myBindingId;
mWorkspaceItems = workspaceItems;
mAppWidgets = appWidgets;
mExtraItems = extraItems;
mOrderedScreenIds = orderedScreenIds;
}
private void bind(boolean isBindSync, int workspaceItemCount) {
final IntSet currentScreenIds =
mCallbacks.getPagesToBindSynchronously(mOrderedScreenIds);
final IntSet currentScreenIds = mCallbacks.getPagesToBindSynchronously(mOrderedScreenIds);
Objects.requireNonNull(currentScreenIds, "Null screen ids provided by " + mCallbacks);
// Separate the items that are on the current screen, and all the other remaining items
// Separate the items that are on the current screen, and all the other
// remaining items
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<>();
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<>();
ArrayList<ItemInfo> currentAppWidgets = new ArrayList<>();
ArrayList<ItemInfo> otherAppWidgets = new ArrayList<>();
Predicate<ItemInfo> currentScreenCheck = currentScreenContentFilter(currentScreenIds);
mItemIdMap.forEach(item -> {
if (currentScreenCheck.test(item)) {
(WIDGET_FILTER.test(item) ? currentAppWidgets : currentWorkspaceItems)
.add(item);
} else if (item.container == CONTAINER_DESKTOP) {
(WIDGET_FILTER.test(item) ? otherAppWidgets : otherWorkspaceItems).add(item);
}
});
sortWorkspaceItemsSpatially(currentWorkspaceItems);
sortWorkspaceItemsSpatially(otherWorkspaceItems);
filterCurrentWorkspaceItems(currentScreenIds, mWorkspaceItems, currentWorkspaceItems,
otherWorkspaceItems);
filterCurrentWorkspaceItems(currentScreenIds, mAppWidgets, currentAppWidgets,
otherAppWidgets);
final InvariantDeviceProfile idp = mApp.getInvariantDeviceProfile();
sortWorkspaceItemsSpatially(idp, currentWorkspaceItems);
sortWorkspaceItemsSpatially(idp, otherWorkspaceItems);
// Tell the workspace that we're about to start binding items
executeCallbacksTask(c -> {
@@ -318,17 +353,16 @@ public class BaseLauncherBinder {
bindItemsInChunks(currentWorkspaceItems, ITEMS_CHUNK, mUiExecutor);
bindItemsInChunks(currentAppWidgets, 1, mUiExecutor);
}
mExtraItems.forEach(item ->
executeCallbacksTask(c -> c.bindExtraContainerItems(item), mUiExecutor));
if (!FeatureFlags.CHANGE_MODEL_DELEGATE_LOADING_ORDER.get()) {
mExtraItems.forEach(item -> executeCallbacksTask(c -> c.bindExtraContainerItems(item), mUiExecutor));
}
RunnableList pendingTasks = new RunnableList();
Executor pendingExecutor = pendingTasks::add;
RunnableList onCompleteSignal = new RunnableList();
onCompleteSignal.add(() -> Log.d(TAG, "Calling onCompleteSignal"));
if (enableWorkspaceInflation() && inflater != null) {
Log.d(TAG, "Starting async inflation");
MODEL_EXECUTOR.execute(() -> {
inflateAsyncAndBind(otherWorkspaceItems, inflater, pendingExecutor);
inflateAsyncAndBind(otherAppWidgets, inflater, pendingExecutor);
@@ -339,15 +373,20 @@ public class BaseLauncherBinder {
MAIN_EXECUTOR.execute(onCompleteSignal::executeAllAndDestroy);
});
} else {
Log.d(TAG, "Starting sync inflation");
bindItemsInChunks(otherWorkspaceItems, ITEMS_CHUNK, pendingExecutor);
bindItemsInChunks(otherAppWidgets, 1, pendingExecutor);
setupPendingBind(currentScreenIds, pendingExecutor);
onCompleteSignal.executeAllAndDestroy();
}
executeCallbacksTask(c -> c.onInitialBindComplete(currentScreenIds, pendingTasks,
onCompleteSignal, workspaceItemCount, isBindSync), mUiExecutor);
executeCallbacksTask(
c -> {
if (!enableWorkspaceInflation()) {
MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
c.onInitialBindComplete(currentScreenIds, pendingTasks, onCompleteSignal,
workspaceItemCount, isBindSync);
}, mUiExecutor);
}
private void setupPendingBind(
@@ -357,8 +396,12 @@ public class BaseLauncherBinder {
executeCallbacksTask(c -> c.bindStringCache(cacheClone), pendingExecutor);
executeCallbacksTask(c -> c.finishBindingItems(currentScreenIds), pendingExecutor);
pendingExecutor.execute(() -> ItemInstallQueue.INSTANCE.get(mContext)
.resumeModelPush(FLAG_LOADER_RUNNING));
pendingExecutor.execute(
() -> {
MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
ItemInstallQueue.INSTANCE.get(mApp.getContext())
.resumeModelPush(FLAG_LOADER_RUNNING);
});
}
/**
@@ -372,12 +415,11 @@ public class BaseLauncherBinder {
return;
}
ModelWriter writer = mModel.getWriter(
false /* verifyChanges */, CellPosMapper.DEFAULT, null);
List<Pair<ItemInfo, View>> bindItems = items.stream()
.map(i -> Pair.create(i, inflater.inflateItem(i, writer, null)))
.collect(Collectors.toList());
executeCallbacksTask(c -> c.bindInflatedItems(bindItems), executor);
ModelWriter writer = mApp.getModel()
.getWriter(false /* verifyChanges */, CellPosMapper.DEFAULT, null);
List<Pair<ItemInfo, View>> finalBindItems = items.stream().map(i ->
Pair.create(i, inflater.inflateItem(i, writer, null))).collect(Collectors.toList());
executeCallbacksTask(c -> c.bindInflatedItems(finalBindItems), executor);
}
private void bindItemsInChunks(
@@ -404,8 +446,128 @@ public class BaseLauncherBinder {
}
}
@AssistedFactory
public interface BaseLauncherBinderFactory {
BaseLauncherBinder createBinder(Callbacks[] callbacks);
private class DisjointWorkspaceBinder {
private final IntArray mOrderedScreenIds;
private final IntSet mCurrentScreenIds = new IntSet();
private final Set<Integer> mBoundItemIds = new HashSet<>();
protected DisjointWorkspaceBinder(IntArray orderedScreenIds) {
mOrderedScreenIds = orderedScreenIds;
for (Callbacks cb : mCallbacksList) {
mCurrentScreenIds.addAll(cb.getPagesToBindSynchronously(orderedScreenIds));
}
if (mCurrentScreenIds.size() == 0) {
mCurrentScreenIds.add(Workspace.FIRST_SCREEN_ID);
}
}
/**
* Binds the currently loaded items in the Data Model. Also signals to the
* Callbacks[]
* that these items have been bound and their respective screens are ready to be
* shown.
*
* If this method is called after all the items on the workspace screen have
* already been
* loaded, it will bind all workspace items immediately, and
* bindOtherWorkspacePages() will
* not bind any items.
*/
protected void bindCurrentWorkspacePages(boolean isBindSync) {
// Save a copy of all the bg-thread collections
ArrayList<ItemInfo> workspaceItems;
ArrayList<LauncherAppWidgetInfo> appWidgets;
ArrayList<FixedContainerItems> fciList = new ArrayList<>();
final int workspaceItemCount;
synchronized (mBgDataModel) {
workspaceItems = new ArrayList<>(mBgDataModel.workspaceItems);
appWidgets = new ArrayList<>(mBgDataModel.appWidgets);
if (!FeatureFlags.CHANGE_MODEL_DELEGATE_LOADING_ORDER.get()) {
mBgDataModel.extraItems.forEach(fciList::add);
}
workspaceItemCount = mBgDataModel.itemsIdMap.size();
}
workspaceItems.forEach(it -> mBoundItemIds.add(it.id));
appWidgets.forEach(it -> mBoundItemIds.add(it.id));
if (!FeatureFlags.CHANGE_MODEL_DELEGATE_LOADING_ORDER.get()) {
fciList.forEach(item -> executeCallbacksTask(c -> c.bindExtraContainerItems(item), mUiExecutor));
}
sortWorkspaceItemsSpatially(mApp.getInvariantDeviceProfile(), workspaceItems);
// Tell the workspace that we're about to start binding items
executeCallbacksTask(c -> {
c.clearPendingBinds();
c.startBinding();
}, mUiExecutor);
// Bind workspace screens
executeCallbacksTask(c -> c.bindScreens(mOrderedScreenIds), mUiExecutor);
bindWorkspaceItems(workspaceItems);
bindAppWidgets(appWidgets);
executeCallbacksTask(c -> {
MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
RunnableList onCompleteSignal = new RunnableList();
onCompleteSignal.executeAllAndDestroy();
c.onInitialBindComplete(mCurrentScreenIds, new RunnableList(), onCompleteSignal,
workspaceItemCount, isBindSync);
}, mUiExecutor);
}
protected void bindOtherWorkspacePages() {
// Save a copy of all the bg-thread collections
ArrayList<ItemInfo> workspaceItems;
ArrayList<LauncherAppWidgetInfo> appWidgets;
synchronized (mBgDataModel) {
workspaceItems = new ArrayList<>(mBgDataModel.workspaceItems);
appWidgets = new ArrayList<>(mBgDataModel.appWidgets);
}
workspaceItems.removeIf(it -> mBoundItemIds.contains(it.id));
appWidgets.removeIf(it -> mBoundItemIds.contains(it.id));
sortWorkspaceItemsSpatially(mApp.getInvariantDeviceProfile(), workspaceItems);
bindWorkspaceItems(workspaceItems);
bindAppWidgets(appWidgets);
executeCallbacksTask(c -> c.finishBindingItems(mCurrentScreenIds), mUiExecutor);
mUiExecutor.execute(() -> {
MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
ItemInstallQueue.INSTANCE.get(mApp.getContext())
.resumeModelPush(FLAG_LOADER_RUNNING);
});
StringCache cacheClone = mBgDataModel.stringCache.clone();
executeCallbacksTask(c -> c.bindStringCache(cacheClone), mUiExecutor);
}
private void bindWorkspaceItems(final ArrayList<ItemInfo> workspaceItems) {
// Bind the workspace items
int count = workspaceItems.size();
for (int i = 0; i < count; i += ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i + ITEMS_CHUNK <= count) ? ITEMS_CHUNK : (count - i);
executeCallbacksTask(
c -> c.bindItems(workspaceItems.subList(start, start + chunkSize), false),
mUiExecutor);
}
}
private void bindAppWidgets(List<LauncherAppWidgetInfo> appWidgets) {
// Bind the widgets, one at a time
int count = appWidgets.size();
for (int i = 0; i < count; i++) {
final ItemInfo widget = appWidgets.get(i);
executeCallbacksTask(
c -> c.bindItems(Collections.singletonList(widget), false),
mUiExecutor);
}
}
}
}
Loaded 100 of 1577 files, more files were not shown because too many files have changed in this diff. Show more