Merge remote-tracking branch 'aosp/android12L-release' into 12.1-dev

This commit is contained in:
Suphon Thanakornpakapong committed 2022-05-08 20:29:17 +07:00
commit 11e1a2fdc8
825 files changed
+38322 -29268

No files matched your search

@@ -65,7 +65,8 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
TYPE_OPTIONS_POPUP,
TYPE_ICON_SURFACE,
TYPE_PIN_WIDGET_FROM_EXTERNAL_POPUP,
TYPE_WIDGETS_EDUCATION_DIALOG
TYPE_WIDGETS_EDUCATION_DIALOG,
TYPE_TASKBAR_EDUCATION_DIALOG
})
@Retention(RetentionPolicy.SOURCE)
public @interface FloatingViewType {}
@@ -88,21 +89,24 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
public static final int TYPE_PIN_WIDGET_FROM_EXTERNAL_POPUP = 1 << 14;
public static final int TYPE_WIDGETS_EDUCATION_DIALOG = 1 << 15;
public static final int TYPE_TASKBAR_EDUCATION_DIALOG = 1 << 16;
// Custom compose popups
public static final int TYPE_COMPOSE_VIEW = 1 << 16;
public static final int TYPE_COMPOSE_VIEW = 1 << 20;
public static final int TYPE_ALL = TYPE_FOLDER | TYPE_ACTION_POPUP
| TYPE_WIDGETS_BOTTOM_SHEET | TYPE_WIDGET_RESIZE_FRAME | TYPE_WIDGETS_FULL_SHEET
| TYPE_ON_BOARD_POPUP | TYPE_DISCOVERY_BOUNCE | TYPE_TASK_MENU
| TYPE_OPTIONS_POPUP | TYPE_SNACKBAR | TYPE_LISTENER | TYPE_ALL_APPS_EDU
| TYPE_ICON_SURFACE | TYPE_DRAG_DROP_POPUP | TYPE_PIN_WIDGET_FROM_EXTERNAL_POPUP
| TYPE_WIDGETS_EDUCATION_DIALOG | TYPE_COMPOSE_VIEW;
| TYPE_WIDGETS_EDUCATION_DIALOG | TYPE_TASKBAR_EDUCATION_DIALOG
| 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_WIDGETS_EDUCATION_DIALOG | TYPE_COMPOSE_VIEW;
| TYPE_ALL_APPS_EDU | TYPE_ICON_SURFACE | TYPE_WIDGETS_EDUCATION_DIALOG | TYPE_COMPOSE_VIEW
| TYPE_TASKBAR_EDUCATION_DIALOG;
// Usually we show the back button when a floating view is open. Instead, hide for these types.
public static final int TYPE_HIDE_BACK_BUTTON = TYPE_ON_BOARD_POPUP | TYPE_DISCOVERY_BOUNCE
@@ -196,10 +200,24 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
}
/**
* Returns a view matching FloatingViewType
* Returns a view matching FloatingViewType and {@link #isOpen()} == true.
*/
public static <T extends AbstractFloatingView> T getOpenView(
ActivityContext activity, @FloatingViewType int type) {
return getView(activity, type, true /* mustBeOpen */);
}
/**
* Returns a view matching FloatingViewType, and {@link #isOpen()} may be false (if animating
* closed).
*/
public static <T extends AbstractFloatingView> T getAnyView(
ActivityContext activity, @FloatingViewType int type) {
return getView(activity, type, false /* mustBeOpen */);
}
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,
@@ -208,7 +226,7 @@ public abstract class AbstractFloatingView extends LinearLayout implements Touch
View child = dragLayer.getChildAt(i);
if (child instanceof AbstractFloatingView) {
AbstractFloatingView view = (AbstractFloatingView) child;
if (view.isOfType(type) && view.isOpen()) {
if (view.isOfType(type) && (!mustBeOpen || view.isOpen())) {
return (T) view;
}
}
@@ -1,6 +1,8 @@
package com.android.launcher3;
import static android.appwidget.AppWidgetHostView.getDefaultPaddingForWidget;
import static com.android.launcher3.CellLayout.SPRING_LOADED_PROGRESS;
import static com.android.launcher3.LauncherAnimUtils.LAYOUT_HEIGHT;
import static com.android.launcher3.LauncherAnimUtils.LAYOUT_WIDTH;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_WIDGET_RESIZE_COMPLETED;
@@ -8,6 +10,8 @@ import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCH
import static com.android.launcher3.views.BaseDragLayer.LAYOUT_X;
import static com.android.launcher3.views.BaseDragLayer.LAYOUT_Y;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
@@ -28,6 +32,7 @@ import androidx.annotation.Px;
import com.android.launcher3.accessibility.DragViewStateAnnouncer;
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.keyboard.ViewGroupFocusHelper;
import com.android.launcher3.logging.InstanceId;
import com.android.launcher3.logging.InstanceIdSequence;
import com.android.launcher3.model.data.ItemInfo;
@@ -51,12 +56,14 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
private static final String KEY_RECONFIGURABLE_WIDGET_EDUCATION_TIP_SEEN =
"launcher.reconfigurable_widget_education_tip_seen";
private static final Rect sTmpRect = new Rect();
private static final Rect sTmpRect2 = new Rect();
private static final int HANDLE_COUNT = 4;
private static final int INDEX_LEFT = 0;
private static final int INDEX_TOP = 1;
private static final int INDEX_RIGHT = 2;
private static final int INDEX_BOTTOM = 3;
private static final float MIN_OPACITY_FOR_CELL_LAYOUT_DURING_INVALID_RESIZE = 0.5f;
private final Launcher mLauncher;
private final DragViewStateAnnouncer mStateAnnouncer;
@@ -105,6 +112,16 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
private final InstanceId logInstanceId = new InstanceIdSequence().newInstanceId();
private final ViewGroupFocusHelper mDragLayerRelativeCoordinateHelper;
/**
* 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
* sibling {@link CellLayout} from 1f to
* {@link #MIN_OPACITY_FOR_CELL_LAYOUT_DURING_INVALID_RESIZE}.
*/
private final float mDragAcrossTwoPanelOpacityMargin;
private boolean mLeftBorderActive;
private boolean mRightBorderActive;
private boolean mTopBorderActive;
@@ -151,6 +168,10 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
for (int i = 0; i < HANDLE_COUNT; i++) {
mSystemGestureExclusionRects.add(new Rect());
}
mDragAcrossTwoPanelOpacityMargin = mLauncher.getResources().getDimensionPixelSize(
R.dimen.resize_frame_invalid_drag_across_two_panel_opacity_margin);
mDragLayerRelativeCoordinateHelper = new ViewGroupFocusHelper(mLauncher.getDragLayer());
}
@Override
@@ -203,7 +224,7 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
dl.addView(frame);
frame.mIsOpen = true;
frame.snapToWidget(false);
frame.post(() -> frame.snapToWidget(false));
}
private void setupForWidget(LauncherAppWidgetHostView widgetView, CellLayout cellLayout,
@@ -229,13 +250,15 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
// Only show resize handles for the directions in which resizing is possible.
InvariantDeviceProfile idp = LauncherAppState.getIDP(cellLayout.getContext());
mVerticalResizeActive = (info.resizeMode & AppWidgetProviderInfo.RESIZE_VERTICAL) != 0
&& mMinVSpan < idp.numRows && mMaxVSpan > 1;
&& mMinVSpan < idp.numRows && mMaxVSpan > 1
&& mMinVSpan < mMaxVSpan;
if (!mVerticalResizeActive) {
mDragHandles[INDEX_TOP].setVisibility(GONE);
mDragHandles[INDEX_BOTTOM].setVisibility(GONE);
}
mHorizontalResizeActive = (info.resizeMode & AppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0
&& mMinHSpan < idp.numColumns && mMaxHSpan > 1;
&& mMinHSpan < idp.numColumns && mMaxHSpan > 1
&& mMinHSpan < mMaxHSpan;
if (!mHorizontalResizeActive) {
mDragHandles[INDEX_LEFT].setVisibility(GONE);
mDragHandles[INDEX_RIGHT].setVisibility(GONE);
@@ -367,6 +390,37 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
lp.y = sTmpRect.top;
}
// Handle invalid resize across CellLayouts in the two panel UI.
if (mCellLayout.getParent() instanceof Workspace) {
Workspace workspace = (Workspace) mCellLayout.getParent();
CellLayout pairedCellLayout = workspace.getScreenPair(mCellLayout);
if (pairedCellLayout != null) {
Rect focusedCellLayoutBound = sTmpRect;
mDragLayerRelativeCoordinateHelper.viewToRect(mCellLayout, focusedCellLayoutBound);
Rect resizeFrameBound = sTmpRect2;
findViewById(R.id.widget_resize_frame).getGlobalVisibleRect(resizeFrameBound);
float progress = 1f;
if (workspace.indexOfChild(pairedCellLayout) < workspace.indexOfChild(mCellLayout)
&& mDeltaX < 0
&& resizeFrameBound.left < focusedCellLayoutBound.left) {
// Resize from right to left.
progress = (mDragAcrossTwoPanelOpacityMargin + mDeltaX)
/ mDragAcrossTwoPanelOpacityMargin;
} else if (workspace.indexOfChild(pairedCellLayout)
> workspace.indexOfChild(mCellLayout)
&& mDeltaX > 0
&& resizeFrameBound.right > focusedCellLayoutBound.right) {
// Resize from left to right.
progress = (mDragAcrossTwoPanelOpacityMargin - mDeltaX)
/ mDragAcrossTwoPanelOpacityMargin;
}
float alpha = Math.max(MIN_OPACITY_FOR_CELL_LAYOUT_DURING_INVALID_RESIZE, progress);
float springLoadedProgress = Math.min(1f, 1f - progress);
updateInvalidResizeEffect(mCellLayout, pairedCellLayout, alpha,
springLoadedProgress);
}
}
requestLayout();
}
@@ -379,8 +433,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
*/
private void resizeWidgetIfNeeded(boolean onDismiss) {
DeviceProfile dp = mLauncher.getDeviceProfile();
float xThreshold = mCellLayout.getCellWidth() + dp.cellLayoutBorderSpacingPx;
float yThreshold = mCellLayout.getCellHeight() + dp.cellLayoutBorderSpacingPx;
float xThreshold = mCellLayout.getCellWidth() + dp.cellLayoutBorderSpacePx.x;
float yThreshold = mCellLayout.getCellHeight() + dp.cellLayoutBorderSpacePx.y;
int hSpanInc = getSpanIncrement((mDeltaX + mDeltaXAddOn) / xThreshold - mRunningHInc);
int vSpanInc = getSpanIncrement((mDeltaY + mDeltaYAddOn) / yThreshold - mRunningVInc);
@@ -465,8 +519,8 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
private void onTouchUp() {
DeviceProfile dp = mLauncher.getDeviceProfile();
int xThreshold = mCellLayout.getCellWidth() + dp.cellLayoutBorderSpacingPx;
int yThreshold = mCellLayout.getCellHeight() + dp.cellLayoutBorderSpacingPx;
int xThreshold = mCellLayout.getCellWidth() + dp.cellLayoutBorderSpacePx.x;
int yThreshold = mCellLayout.getCellHeight() + dp.cellLayoutBorderSpacePx.y;
mDeltaXAddOn = mRunningHInc * xThreshold;
mDeltaYAddOn = mRunningVInc * yThreshold;
@@ -523,13 +577,24 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
}
final DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
final CellLayout pairedCellLayout;
if (mCellLayout.getParent() instanceof Workspace) {
Workspace workspace = (Workspace) mCellLayout.getParent();
pairedCellLayout = workspace.getScreenPair(mCellLayout);
} else {
pairedCellLayout = null;
}
if (!animate) {
lp.width = newWidth;
lp.height = newHeight;
lp.x = newX;
lp.y = newY;
for (int i = 0; i < HANDLE_COUNT; i++) {
mDragHandles[i].setAlpha(1.0f);
mDragHandles[i].setAlpha(1f);
}
if (pairedCellLayout != null) {
updateInvalidResizeEffect(mCellLayout, pairedCellLayout, /* alpha= */ 1f,
/* springLoadedProgress= */ 0f);
}
requestLayout();
} else {
@@ -546,6 +611,10 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
set.play(mFirstFrameAnimatorHelper.addTo(
ObjectAnimator.ofFloat(mDragHandles[i], ALPHA, 1f)));
}
if (pairedCellLayout != null) {
updateInvalidResizeEffect(mCellLayout, pairedCellLayout, /* alpha= */ 1f,
/* springLoadedProgress= */ 0f, /* animatorSet= */ set);
}
set.setDuration(SNAP_DURATION);
set.start();
}
@@ -632,6 +701,52 @@ public class AppWidgetResizeFrame extends AbstractFloatingView implements View.O
}
}
private void updateInvalidResizeEffect(CellLayout cellLayout, CellLayout pairedCellLayout,
float alpha, float springLoadedProgress) {
updateInvalidResizeEffect(cellLayout, pairedCellLayout, alpha,
springLoadedProgress, /* animatorSet= */ null);
}
private void updateInvalidResizeEffect(CellLayout cellLayout, CellLayout pairedCellLayout,
float alpha, float springLoadedProgress, @Nullable AnimatorSet animatorSet) {
int childCount = pairedCellLayout.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = pairedCellLayout.getChildAt(i);
if (animatorSet != null) {
animatorSet.play(
mFirstFrameAnimatorHelper.addTo(
ObjectAnimator.ofFloat(child, ALPHA, alpha)));
} else {
child.setAlpha(alpha);
}
}
if (animatorSet != null) {
animatorSet.play(mFirstFrameAnimatorHelper.addTo(
ObjectAnimator.ofFloat(cellLayout, SPRING_LOADED_PROGRESS,
springLoadedProgress)));
animatorSet.play(mFirstFrameAnimatorHelper.addTo(
ObjectAnimator.ofFloat(pairedCellLayout, SPRING_LOADED_PROGRESS,
springLoadedProgress)));
} else {
cellLayout.setSpringLoadedProgress(springLoadedProgress);
pairedCellLayout.setSpringLoadedProgress(springLoadedProgress);
}
boolean shouldShowCellLayoutBorder = springLoadedProgress > 0f;
if (animatorSet != null) {
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
cellLayout.setIsDragOverlapping(shouldShowCellLayoutBorder);
pairedCellLayout.setIsDragOverlapping(shouldShowCellLayoutBorder);
}
});
} else {
cellLayout.setIsDragOverlapping(shouldShowCellLayoutBorder);
pairedCellLayout.setIsDragOverlapping(shouldShowCellLayoutBorder);
}
}
@Override
protected boolean isOfType(int type) {
return (type & TYPE_WIDGET_RESIZE_FRAME) != 0;
@@ -145,6 +145,7 @@ public abstract class BaseActivity extends Activity implements ActivityContext {
/**
* Returns {@link StatsLogManager} for user event logging.
*/
@Override
public StatsLogManager getStatsLogManager() {
if (mStatsLogManager == null) {
mStatsLogManager = StatsLogManager.newInstance(this);
@@ -37,7 +37,6 @@ import android.util.Log;
import android.view.ActionMode;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowInsets.Type;
import android.view.WindowMetrics;
import android.widget.Toast;
@@ -51,6 +50,7 @@ import com.android.launcher3.allapps.search.DefaultSearchAdapterProvider;
import com.android.launcher3.allapps.search.SearchAdapterProvider;
import com.android.launcher3.logging.InstanceId;
import com.android.launcher3.logging.InstanceIdSequence;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.touch.ItemClickHandler;
@@ -160,12 +160,6 @@ public abstract class BaseDraggingActivity extends BaseActivity
// no-op
}
public Rect getViewBounds(View v) {
int[] pos = new int[2];
v.getLocationOnScreen(pos);
return new Rect(pos[0], pos[1], pos[0] + v.getWidth(), pos[1] + v.getHeight());
}
@NonNull
public ActivityOptionsWrapper getActivityLaunchOptions(View v, @Nullable ItemInfo item) {
int left = 0, top = 0;
@@ -200,7 +194,7 @@ public abstract class BaseDraggingActivity extends BaseActivity
// Prepare intent
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (v != null) {
intent.setSourceBounds(getViewBounds(v));
intent.setSourceBounds(Utilities.getViewBounds(v));
}
try {
boolean isShortcut = (item instanceof WorkspaceItemInfo)
@@ -219,7 +213,7 @@ public abstract class BaseDraggingActivity extends BaseActivity
}
if (item != null) {
InstanceId instanceId = new InstanceIdSequence().newInstanceId();
logAppLaunch(item, instanceId);
logAppLaunch(getStatsLogManager(), item, instanceId);
}
return true;
} catch (NullPointerException | ActivityNotFoundException | SecurityException e) {
@@ -229,8 +223,12 @@ public abstract class BaseDraggingActivity extends BaseActivity
return false;
}
protected void logAppLaunch(ItemInfo info, InstanceId instanceId) {
getStatsLogManager().logger().withItemInfo(info).withInstanceId(instanceId)
/**
* Creates and logs a new app launch event.
*/
public void logAppLaunch(StatsLogManager statsLogManager, ItemInfo info,
InstanceId instanceId) {
statsLogManager.logger().withItemInfo(info).withInstanceId(instanceId)
.log(LAUNCHER_APP_LAUNCH_TAP);
}
@@ -304,7 +302,8 @@ public abstract class BaseDraggingActivity extends BaseActivity
}
}
public OnClickListener getItemOnClickListener() {
@Override
public View.OnClickListener getItemOnClickListener() {
return ItemClickHandler.INSTANCE;
}
+188 -29
View File
@@ -18,6 +18,7 @@
package com.android.launcher3;
import static com.android.launcher3.config.FeatureFlags.ENABLE_ICON_LABEL_AUTO_SCALING;
import static com.android.launcher3.graphics.PreloadIconDrawable.newPendingIcon;
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
@@ -34,6 +35,8 @@ import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.icu.text.MessageFormat;
import android.text.TextPaint;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.util.Property;
@@ -67,9 +70,12 @@ import com.android.launcher3.model.data.SearchActionItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.util.SafeCloseable;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BubbleTextHolder;
import com.android.launcher3.views.IconLabelDotView;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Locale;
import app.lawnchair.font.FontManager;
import app.lawnchair.util.LawnchairUtilsKt;
@@ -89,12 +95,19 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
private static final int DISPLAY_SEARCH_RESULT = 6;
private static final int DISPLAY_SEARCH_RESULT_SMALL = 7;
private static final float MIN_LETTER_SPACING = -0.05f;
private static final int MAX_SEARCH_LOOP_COUNT = 20;
private static final int[] STATE_PRESSED = new int[]{android.R.attr.state_pressed};
private static final float HIGHLIGHT_SCALE = 1.16f;
private final PointF mTranslationForReorderBounce = new PointF(0, 0);
private final PointF mTranslationForReorderPreview = new PointF(0, 0);
private float mTranslationXForTaskbarAlignmentAnimation = 0f;
private final PointF mTranslationForMoveFromCenterAnimation = new PointF(0, 0);
private float mScaleForReorderBounce = 1f;
private static final Property<BubbleTextView, Float> DOT_SCALE_PROPERTY
@@ -133,6 +146,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
private final CheckLongPressHelper mLongPressHelper;
private final boolean mLayoutHorizontal;
private final boolean mIsRtl;
private final int mIconSize;
@ViewDebug.ExportedProperty(category = "launcher")
@@ -160,6 +174,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
private HandlerRunnable mIconLoadRequest;
private boolean mEnableIconUpdateAnimation = false;
private BubbleTextHolder mBubbleTextHolder;
public BubbleTextView(Context context) {
this(context, null, 0);
@@ -176,6 +191,8 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.BubbleTextView, defStyle, 0);
mLayoutHorizontal = a.getBoolean(R.styleable.BubbleTextView_layoutHorizontal, false);
mIsRtl = (getResources().getConfiguration().getLayoutDirection()
== View.LAYOUT_DIRECTION_RTL);
DeviceProfile grid = mActivity.getDeviceProfile();
mDisplay = a.getInteger(R.styleable.BubbleTextView_iconDisplay, DISPLAY_WORKSPACE);
@@ -261,9 +278,27 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
@UiThread
public void applyFromWorkspaceItem(WorkspaceItemInfo info) {
applyFromWorkspaceItem(info, /* animate = */ false, /* staggerIndex = */ 0);
}
@UiThread
public void applyFromWorkspaceItem(WorkspaceItemInfo info, boolean animate, int staggerIndex) {
applyFromWorkspaceItem(info, false);
}
/**
* Returns whether the newInfo differs from the current getTag().
*/
public boolean shouldAnimateIconChange(WorkspaceItemInfo newInfo) {
WorkspaceItemInfo oldInfo = getTag() instanceof WorkspaceItemInfo
? (WorkspaceItemInfo) getTag()
: null;
boolean changedIcons = oldInfo != null && oldInfo.getTargetComponent() != null
&& newInfo.getTargetComponent() != null
&& !oldInfo.getTargetComponent().equals(newInfo.getTargetComponent());
return changedIcons && isShown();
}
@Override
public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
if (delegate instanceof LauncherAccessibilityDelegate) {
@@ -279,7 +314,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
@UiThread
public void applyFromWorkspaceItem(WorkspaceItemInfo info, boolean promiseStateChanged) {
applyIconAndLabel(info);
setTag(info);
setItemInfo(info);
applyLoadingState(promiseStateChanged);
applyDotState(info, false /* animate */);
setDownloadStateContentDescription(info, info.getProgressLevel());
@@ -290,7 +325,8 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
applyIconAndLabel(info);
// We don't need to check the info since it's not a WorkspaceItemInfo
super.setTag(info);
setItemInfo(info);
// Verify high res immediately
verifyHighRes();
@@ -309,7 +345,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
public void applyFromItemInfoWithIcon(ItemInfoWithIcon info) {
applyIconAndLabel(info);
// We don't need to check the info since it's not a WorkspaceItemInfo
super.setTag(info);
setItemInfo(info);
// Verify high res immediately
verifyHighRes();
@@ -317,18 +353,22 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
setDownloadStateContentDescription(info, info.getProgressLevel());
}
/**
* Apply label and tag using a {@link SearchActionItemInfo}
*/
@UiThread
public void applyFromSearchActionItemInfo(SearchActionItemInfo searchActionItemInfo) {
applyIconAndLabel(searchActionItemInfo);
setTag(searchActionItemInfo);
private void setItemInfo(ItemInfoWithIcon itemInfo) {
setTag(itemInfo);
if (mBubbleTextHolder != null) {
mBubbleTextHolder.onItemInfoUpdated(itemInfo);
}
}
public void setBubbleTextHolder(
BubbleTextHolder bubbleTextHolder) {
mBubbleTextHolder = bubbleTextHolder;
}
@UiThread
protected void applyIconAndLabel(ItemInfoWithIcon info) {
boolean useTheme = mDisplay == DISPLAY_WORKSPACE || mDisplay == DISPLAY_FOLDER;
boolean useTheme = mDisplay == DISPLAY_WORKSPACE || mDisplay == DISPLAY_FOLDER
|| mDisplay == DISPLAY_TASKBAR;
FastBitmapDrawable iconDrawable = info.newIcon(getContext(), useTheme);
mDotParams.color = IconPalette.getMutedColor(iconDrawable.getIconColor(), 0.54f);
@@ -395,6 +435,10 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
* Returns true if the touch down at the provided position be ignored
*/
protected boolean shouldIgnoreTouchDown(float x, float y) {
if (mDisplay == DISPLAY_TASKBAR) {
// Allow touching within padding on taskbar, given icon sizes are smaller.
return false;
}
return y < getPaddingTop()
|| x < getPaddingLeft()
|| y > getHeight() - getPaddingBottom()
@@ -414,7 +458,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
}
}
void clearPressedBackground() {
public void clearPressedBackground() {
setPressed(false);
setStayPressed(false);
}
@@ -431,6 +475,75 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
return result;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
checkForEllipsis();
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
checkForEllipsis();
}
private void checkForEllipsis() {
if (!ENABLE_ICON_LABEL_AUTO_SCALING.get()) {
return;
}
float width = getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
if (width <= 0) {
return;
}
setLetterSpacing(0);
String text = getText().toString();
TextPaint paint = getPaint();
if (paint.measureText(text) < width) {
return;
}
float spacing = findBestSpacingValue(paint, text, width, MIN_LETTER_SPACING);
// Reset the paint value so that the call to TextView does appropriate diff.
paint.setLetterSpacing(0);
setLetterSpacing(spacing);
}
/**
* Find the appropriate text spacing to display the provided text
* @param paint the paint used by the text view
* @param text the text to display
* @param allowedWidthPx available space to render the text
* @param minSpacingEm minimum spacing allowed between characters
* @return the final textSpacing value
*
* @see #setLetterSpacing(float)
*/
private float findBestSpacingValue(TextPaint paint, String text, float allowedWidthPx,
float minSpacingEm) {
paint.setLetterSpacing(minSpacingEm);
if (paint.measureText(text) > allowedWidthPx) {
// If there is no result at high limit, we can do anything more
return minSpacingEm;
}
float lowLimit = 0;
float highLimit = minSpacingEm;
for (int i = 0; i < MAX_SEARCH_LOOP_COUNT; i++) {
float value = (lowLimit + highLimit) / 2;
paint.setLetterSpacing(value);
if (paint.measureText(text) < allowedWidthPx) {
highLimit = value;
} else {
lowLimit = value;
}
}
// At the end error on the higher side
return highLimit;
}
@SuppressWarnings("wrongcall")
protected void drawWithoutDot(Canvas canvas) {
super.onDraw(canvas);
@@ -478,19 +591,29 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
return mDotInfo != null;
}
/**
* Get the icon bounds on the view depending on the layout type.
*/
public void getIconBounds(Rect outBounds) {
getIconBounds(this, outBounds, mIconSize);
getIconBounds(mIconSize, outBounds);
}
public static void getIconBounds(View iconView, Rect outBounds, int iconSize) {
int top = iconView.getPaddingTop();
int left = (iconView.getWidth() - iconSize) / 2;
int right = left + iconSize;
int bottom = top + iconSize;
outBounds.set(left, top, right, bottom);
/**
* Get the icon bounds on the view depending on the layout type.
*/
public void getIconBounds(int iconSize, Rect outBounds) {
Utilities.setRectToViewCenter(this, iconSize, outBounds);
if (mLayoutHorizontal) {
if (mIsRtl) {
outBounds.offsetTo(getWidth() - iconSize - getPaddingRight(), outBounds.top);
} else {
outBounds.offsetTo(getPaddingLeft(), outBounds.top);
}
} else {
outBounds.offsetTo(outBounds.left, getPaddingTop());
}
}
/**
* Sets whether to vertically center the content.
*/
@@ -675,8 +798,8 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
itemInfo.contentDescription));
} else if (hasDot()) {
int count = mDotInfo.getNotificationCount();
setContentDescription(getContext().getResources().getQuantityString(
R.plurals.dotted_app_label, count, itemInfo.contentDescription, count));
setContentDescription(
getAppLabelPluralString(itemInfo.contentDescription.toString(), count));
} else {
setContentDescription(itemInfo.contentDescription);
}
@@ -776,7 +899,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
} else if (info instanceof PackageItemInfo) {
applyFromItemInfoWithIcon((PackageItemInfo) info);
} else if (info instanceof SearchActionItemInfo) {
applyFromSearchActionItemInfo((SearchActionItemInfo) info);
applyFromItemInfoWithIcon((SearchActionItemInfo) info);
}
mDisableRelayout = false;
@@ -806,8 +929,11 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
}
private void updateTranslation() {
super.setTranslationX(mTranslationForReorderBounce.x + mTranslationForReorderPreview.x);
super.setTranslationY(mTranslationForReorderBounce.y + mTranslationForReorderPreview.y);
super.setTranslationX(mTranslationForReorderBounce.x + mTranslationForReorderPreview.x
+ mTranslationForMoveFromCenterAnimation.x
+ mTranslationXForTaskbarAlignmentAnimation);
super.setTranslationY(mTranslationForReorderBounce.y + mTranslationForReorderPreview.y
+ mTranslationForMoveFromCenterAnimation.y);
}
public void setReorderBounceOffset(float x, float y) {
@@ -840,6 +966,29 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
return mScaleForReorderBounce;
}
/**
* Sets translation values for move from center animation
*/
public void setTranslationForMoveFromCenterAnimation(float x, float y) {
mTranslationForMoveFromCenterAnimation.set(x, y);
updateTranslation();
}
/**
* Sets translationX for taskbar to launcher alignment animation
*/
public void setTranslationXForTaskbarAlignmentAnimation(float translationX) {
mTranslationXForTaskbarAlignmentAnimation = translationX;
updateTranslation();
}
/**
* Returns translationX value for taskbar to launcher alignment animation
*/
public float getTranslationXForTaskbarAlignmentAnimation() {
return mTranslationXForTaskbarAlignmentAnimation;
}
public View getView() {
return this;
}
@@ -851,8 +1000,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
@Override
public void getWorkspaceVisualDragBounds(Rect bounds) {
DeviceProfile grid = mActivity.getDeviceProfile();
BubbleTextView.getIconBounds(this, bounds, grid.iconSizePx);
getIconBounds(mIconSize, bounds);
}
private int getIconSizeForDisplay(int display) {
@@ -860,15 +1008,16 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
switch (display) {
case DISPLAY_ALL_APPS:
return grid.allAppsIconSizePx;
case DISPLAY_WORKSPACE:
case DISPLAY_FOLDER:
return grid.folderChildIconSizePx;
case DISPLAY_WORKSPACE:
default:
return grid.iconSizePx;
}
}
public void getSourceVisualDragBounds(Rect bounds) {
BubbleTextView.getIconBounds(this, bounds, getIconSizeForDisplay(mDisplay));
getIconBounds(mIconSize, bounds);
}
@Override
@@ -891,4 +1040,14 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver,
setCompoundDrawables(null, newIcon, null, null);
}
}
private String getAppLabelPluralString(String appName, int notificationCount) {
MessageFormat icuCountFormat = new MessageFormat(
getResources().getString(R.string.dotted_app_label),
Locale.getDefault());
HashMap<String, Object> args = new HashMap();
args.put("app_name", appName);
args.put("count", notificationCount);
return icuCountFormat.format(args);
}
}
+24 -16
View File
@@ -72,6 +72,8 @@ public abstract class ButtonDropTarget extends TextView
private final int mDragDistanceThreshold;
/** The size of the drawable shown in the drop target. */
private final int mDrawableSize;
/** The padding, in pixels, between the text and drawable. */
private final int mDrawablePadding;
protected CharSequence mText;
protected Drawable mDrawable;
@@ -80,8 +82,6 @@ public abstract class ButtonDropTarget extends TextView
private PopupWindow mToolTip;
private int mToolTipLocation;
private int mDrawablePadding;
public ButtonDropTarget(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@@ -93,7 +93,8 @@ public abstract class ButtonDropTarget extends TextView
Resources resources = getResources();
mDragDistanceThreshold = resources.getDimensionPixelSize(R.dimen.drag_distanceThreshold);
mDrawableSize = resources.getDimensionPixelSize(R.dimen.drop_target_text_size);
mDrawablePadding = getCompoundDrawablePadding();
mDrawablePadding = resources.getDimensionPixelSize(
R.dimen.drop_target_button_drawable_padding);
}
@Override
@@ -124,8 +125,8 @@ public abstract class ButtonDropTarget extends TextView
// 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.setBounds(0, 0, mDrawableSize, mDrawableSize);
mDrawable.setTintList(getTextColors());
centerIcon();
setCompoundDrawablesRelative(mDrawable, null, null, null);
}
@@ -231,12 +232,8 @@ public abstract class ButtonDropTarget extends TextView
}
final DragLayer dragLayer = mLauncher.getDragLayer();
final DragView dragView = d.dragView;
final Rect from = new Rect();
dragLayer.getViewRectRelativeToSelf(d.dragView, from);
final Rect to = getIconRect(d);
final float scale = (float) to.width() / from.width();
dragView.disableColorExtraction();
final float scale = (float) to.width() / dragView.getMeasuredWidth();
dragView.detachContentView(/* reattachToPreviousParent= */ true);
mDropTargetBar.deferOnDragEnd();
@@ -244,14 +241,11 @@ public abstract class ButtonDropTarget extends TextView
completeDrop(d);
mDropTargetBar.onDragEnd();
mLauncher.getStateManager().goToState(NORMAL);
// Only re-enable updates once the workspace is back to normal, which will be after the
// current frame.
post(dragView::resumeColorExtraction);
};
dragLayer.animateView(d.dragView, from, to, scale, 1f, 1f, 0.1f, 0.1f,
dragLayer.animateView(d.dragView, to, scale, 0.1f, 0.1f,
DRAG_VIEW_DROP_DURATION,
Interpolators.DEACCEL_2, Interpolators.LINEAR, onAnimationEndRunnable,
Interpolators.DEACCEL_2, onAnimationEndRunnable,
DragLayer.ANIMATION_END_DISAPPEAR, null);
}
@@ -300,7 +294,7 @@ public abstract class ButtonDropTarget extends TextView
}
final int top = to.top + (getMeasuredHeight() - height) / 2;
final int bottom = top + height;
final int bottom = top + height;
to.set(left, top, right, bottom);
@@ -312,6 +306,12 @@ public abstract class ButtonDropTarget extends TextView
return to;
}
private void centerIcon() {
int x = mTextVisible ? 0
: (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 - mDrawableSize / 2;
mDrawable.setBounds(x, 0, x + mDrawableSize, mDrawableSize);
}
@Override
public void onClick(View v) {
mLauncher.getAccessibilityDelegate().handleAccessibleDrop(this, null, null);
@@ -322,11 +322,19 @@ public abstract class ButtonDropTarget extends TextView
if (mTextVisible != isVisible || !TextUtils.equals(newText, getText())) {
mTextVisible = isVisible;
setText(newText);
centerIcon();
setCompoundDrawablesRelative(mDrawable, null, null, null);
setCompoundDrawablePadding(isVisible ? mDrawablePadding : 0);
int drawablePadding = mTextVisible ? mDrawablePadding : 0;
setCompoundDrawablePadding(drawablePadding);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
centerIcon();
}
public void setToolTipLocation(int location) {
mToolTipLocation = location;
hideTooltip();
+143 -60
View File
@@ -18,8 +18,9 @@ package com.android.launcher3;
import static android.animation.ValueAnimator.areAnimatorsEnabled;
import static com.android.launcher3.Utilities.getBoundsForViewInDragLayer;
import static com.android.launcher3.anim.Interpolators.DEACCEL_1_5;
import static com.android.launcher3.dragndrop.DraggableView.DRAGGABLE_ICON;
import static com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -38,7 +39,6 @@ import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.util.ArrayMap;
@@ -62,6 +62,7 @@ import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dragndrop.DraggableView;
import com.android.launcher3.folder.PreviewBackground;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.CellAndSpan;
@@ -95,7 +96,7 @@ public class CellLayout extends ViewGroup {
private int mFixedCellWidth;
private int mFixedCellHeight;
@ViewDebug.ExportedProperty(category = "launcher")
private final int mBorderSpacing;
private final Point mBorderSpace;
@ViewDebug.ExportedProperty(category = "launcher")
private int mCountX;
@@ -240,9 +241,9 @@ public class CellLayout extends ViewGroup {
mActivity = ActivityContext.lookupContext(context);
DeviceProfile deviceProfile = mActivity.getDeviceProfile();
mBorderSpacing = mContainerType == FOLDER
? deviceProfile.folderCellLayoutBorderSpacingPx
: deviceProfile.cellLayoutBorderSpacingPx;
mBorderSpace = mContainerType == FOLDER
? new Point(deviceProfile.folderCellLayoutBorderSpacePx)
: new Point(deviceProfile.cellLayoutBorderSpacePx);
mCellWidth = mCellHeight = -1;
mFixedCellWidth = mFixedCellHeight = -1;
@@ -312,7 +313,7 @@ public class CellLayout extends ViewGroup {
mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context, mContainerType);
mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
mBorderSpacing);
mBorderSpace);
addView(mShortcutsAndWidgets);
}
@@ -372,7 +373,7 @@ public class CellLayout extends ViewGroup {
mFixedCellWidth = mCellWidth = width;
mFixedCellHeight = mCellHeight = height;
mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
mBorderSpacing);
mBorderSpace);
}
public void setGridSize(int x, int y) {
@@ -382,7 +383,7 @@ public class CellLayout extends ViewGroup {
mTmpOccupied = new GridOccupancy(mCountX, mCountY);
mTempRectStack.clear();
mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
mBorderSpacing);
mBorderSpace);
requestLayout();
}
@@ -446,18 +447,43 @@ public class CellLayout extends ViewGroup {
}
if (DEBUG_VISUALIZE_OCCUPIED) {
int[] pt = new int[2];
ColorDrawable cd = new ColorDrawable(Color.RED);
cd.setBounds(0, 0, mCellWidth, mCellHeight);
for (int i = 0; i < mCountX; i++) {
for (int j = 0; j < mCountY; j++) {
if (mOccupied.cells[i][j]) {
cellToPoint(i, j, pt);
canvas.save();
canvas.translate(pt[0], pt[1]);
cd.draw(canvas);
canvas.restore();
Rect cellBounds = new Rect();
// Will contain the bounds of the cell including spacing between cells.
Rect cellBoundsWithSpacing = new Rect();
int[] targetCell = new int[2];
int[] cellCenter = new int[2];
Paint debugPaint = new Paint();
debugPaint.setStrokeWidth(Utilities.dpToPx(1));
for (int x = 0; x < mCountX; x++) {
for (int y = 0; y < mCountY; y++) {
if (!mOccupied.cells[x][y]) {
continue;
}
targetCell[0] = x;
targetCell[1] = y;
boolean canCreateFolder = canCreateFolder(getChildAt(x, y));
cellToRect(x, y, 1, 1, cellBounds);
cellBoundsWithSpacing.set(cellBounds);
cellBoundsWithSpacing.inset(-mBorderSpace.x / 2, -mBorderSpace.y / 2);
getWorkspaceCellVisualCenter(x, y, cellCenter);
canvas.save();
canvas.clipRect(cellBoundsWithSpacing);
// Draw reorder drag target.
debugPaint.setColor(Color.RED);
canvas.drawCircle(cellCenter[0], cellCenter[1], getReorderRadius(targetCell),
debugPaint);
// Draw folder creation drag target.
if (canCreateFolder) {
debugPaint.setColor(Color.GREEN);
canvas.drawCircle(cellCenter[0], cellCenter[1],
getFolderCreationRadius(targetCell), debugPaint);
}
canvas.restore();
}
}
}
@@ -485,6 +511,14 @@ public class CellLayout extends ViewGroup {
}
}
/**
* Returns whether dropping an icon on the given View can create (or add to) a folder.
*/
private boolean canCreateFolder(View child) {
return child instanceof DraggableView
&& ((DraggableView) child).getViewType() == DRAGGABLE_ICON;
}
/**
* Indicates the progress of the Workspace entering the SpringLoaded state; allows the
* CellLayout to update various visuals for this state.
@@ -545,9 +579,9 @@ public class CellLayout extends ViewGroup {
if (mVisualizeCells) {
for (int i = 0; i < mCountX; i++) {
for (int j = 0; j < mCountY; j++) {
int transX = i * mCellWidth + (i * mBorderSpacing) + getPaddingLeft()
int transX = i * mCellWidth + (i * mBorderSpace.x) + getPaddingLeft()
+ paddingX;
int transY = j * mCellHeight + (j * mBorderSpacing) + getPaddingTop()
int transY = j * mCellHeight + (j * mBorderSpace.y) + getPaddingTop()
+ paddingY;
mVisualizeGridRect.offsetTo(transX, transY);
@@ -571,12 +605,12 @@ public class CellLayout extends ViewGroup {
// TODO b/194414754 clean this up, reconcile with cellToRect
mVisualizeGridRect.set(paddingX, paddingY,
mCellWidth * spanX + mBorderSpacing * (spanX - 1) - paddingX,
mCellHeight * spanY + mBorderSpacing * (spanY - 1) - paddingY);
mCellWidth * spanX + mBorderSpace.x * (spanX - 1) - paddingX,
mCellHeight * spanY + mBorderSpace.y * (spanY - 1) - paddingY);
int transX = x * mCellWidth + (x * mBorderSpacing)
int transX = x * mCellWidth + (x * mBorderSpace.x)
+ getPaddingLeft() + paddingX;
int transY = y * mCellHeight + (y * mBorderSpacing)
int transY = y * mCellHeight + (y * mBorderSpace.y)
+ getPaddingTop() + paddingY;
mVisualizeGridRect.offsetTo(transX, transY);
@@ -821,7 +855,7 @@ public class CellLayout extends ViewGroup {
}
/**
* Given a cell coordinate and span return the point that represents the center of the regio
* Given a cell coordinate and span return the point that represents the center of the region
*
* @param cellX X coordinate of the cell
* @param cellY Y coordinate of the cell
@@ -834,11 +868,65 @@ public class CellLayout extends ViewGroup {
result[1] = mTempRect.centerY();
}
public float getDistanceFromCell(float x, float y, int[] cell) {
cellToCenterPoint(cell[0], cell[1], mTmpPoint);
/**
* Returns the distance between the given coordinate and the visual center of the given cell.
*/
public float getDistanceFromWorkspaceCellVisualCenter(float x, float y, int[] cell) {
getWorkspaceCellVisualCenter(cell[0], cell[1], mTmpPoint);
return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
}
private void getWorkspaceCellVisualCenter(int cellX, int cellY, int[] outPoint) {
View child = getChildAt(cellX, cellY);
if (child instanceof DraggableView) {
DraggableView draggableChild = (DraggableView) child;
if (draggableChild.getViewType() == DRAGGABLE_ICON) {
cellToPoint(cellX, cellY, outPoint);
draggableChild.getWorkspaceVisualDragBounds(mTempRect);
mTempRect.offset(outPoint[0], outPoint[1]);
outPoint[0] = mTempRect.centerX();
outPoint[1] = mTempRect.centerY();
return;
}
}
cellToCenterPoint(cellX, cellY, outPoint);
}
/**
* Returns the max distance from the center of a cell that can accept a drop to create a folder.
*/
public float getFolderCreationRadius(int[] targetCell) {
DeviceProfile grid = mActivity.getDeviceProfile();
float iconVisibleRadius = ICON_VISIBLE_AREA_FACTOR * grid.iconSizePx / 2;
// Halfway between reorder radius and icon.
return (getReorderRadius(targetCell) + iconVisibleRadius) / 2;
}
/**
* Returns the max distance from the center of a cell that will start to reorder on drag over.
*/
public float getReorderRadius(int[] targetCell) {
int[] centerPoint = mTmpPoint;
getWorkspaceCellVisualCenter(targetCell[0], targetCell[1], centerPoint);
Rect cellBoundsWithSpacing = mTempRect;
cellToRect(targetCell[0], targetCell[1], 1, 1, cellBoundsWithSpacing);
cellBoundsWithSpacing.inset(-mBorderSpace.x / 2, -mBorderSpace.y / 2);
if (canCreateFolder(getChildAt(targetCell[0], targetCell[1]))) {
// Take only the circle in the smaller dimension, to ensure we don't start reordering
// too soon before accepting a folder drop.
int minRadius = centerPoint[0] - cellBoundsWithSpacing.left;
minRadius = Math.min(minRadius, centerPoint[1] - cellBoundsWithSpacing.top);
minRadius = Math.min(minRadius, cellBoundsWithSpacing.right - centerPoint[0]);
minRadius = Math.min(minRadius, cellBoundsWithSpacing.bottom - centerPoint[1]);
return minRadius;
}
// Take up the entire cell, including space between this cell and the adjacent ones.
return (float) Math.hypot(cellBoundsWithSpacing.width() / 2f,
cellBoundsWithSpacing.height() / 2f);
}
public int getCellWidth() {
return mCellWidth;
}
@@ -862,15 +950,15 @@ public class CellLayout extends ViewGroup {
int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
int cw = DeviceProfile.calculateCellWidth(childWidthSize, mBorderSpacing,
int cw = DeviceProfile.calculateCellWidth(childWidthSize, mBorderSpace.x,
mCountX);
int ch = DeviceProfile.calculateCellHeight(childHeightSize, mBorderSpacing,
int ch = DeviceProfile.calculateCellHeight(childHeightSize, mBorderSpace.y,
mCountY);
if (cw != mCellWidth || ch != mCellHeight) {
mCellWidth = cw;
mCellHeight = ch;
mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
mBorderSpacing);
mBorderSpace);
}
}
@@ -924,7 +1012,7 @@ public class CellLayout extends ViewGroup {
*/
public int getUnusedHorizontalSpace() {
return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth)
- ((mCountX - 1) * mBorderSpacing);
- ((mCountX - 1) * mBorderSpace.x);
}
@Override
@@ -1074,18 +1162,12 @@ public class CellLayout extends ViewGroup {
// Apply local extracted color if the DragView is an AppWidgetHostViewDrawable.
View view = dragObject.dragView.getContentView();
if (view instanceof LauncherAppWidgetHostView) {
Launcher launcher = Launcher.getLauncher(dragObject.dragView.getContext());
Launcher launcher = Launcher.getLauncher(getContext());
Workspace workspace = launcher.getWorkspace();
int screenId = workspace.getIdForScreen(this);
int pageId = workspace.getPageIndexForScreenId(screenId);
cellToRect(targetCell[0], targetCell[1], spanX, spanY, mTempRect);
// Now get the rect in drag layer coordinates.
getBoundsForViewInDragLayer(launcher.getDragLayer(), this, mTempRect, true,
mTmpFloatArray, mTempRectF);
Utilities.setRect(mTempRectF, mTempRect);
((LauncherAppWidgetHostView) view).handleDrag(mTempRect, pageId);
((LauncherAppWidgetHostView) view).handleDrag(mTempRect, this, screenId);
}
}
@@ -2151,7 +2233,7 @@ public class CellLayout extends ViewGroup {
mShakeAnimators.clear();
}
private void commitTempPlacement() {
private void commitTempPlacement(View dragView) {
mTmpOccupied.copyTo(mOccupied);
int screenId = Launcher.cast(mActivity).getWorkspace().getIdForScreen(this);
@@ -2169,7 +2251,7 @@ public class CellLayout extends ViewGroup {
ItemInfo info = (ItemInfo) child.getTag();
// We do a null check here because the item info can be null in the case of the
// AllApps button in the hotseat.
if (info != null) {
if (info != null && child != dragView) {
final boolean requiresDbUpdate = (info.cellX != lp.tmpCellX
|| info.cellY != lp.tmpCellY || info.spanX != lp.cellHSpan
|| info.spanY != lp.cellVSpan);
@@ -2331,7 +2413,7 @@ public class CellLayout extends ViewGroup {
animateItemsToSolution(swapSolution, dragView, commit);
if (commit) {
commitTempPlacement();
commitTempPlacement(null);
completeAndClearReorderPreviewAnimations();
setItemPlacementDirty(false);
} else {
@@ -2425,7 +2507,8 @@ public class CellLayout extends ViewGroup {
if (!DESTRUCTIVE_REORDER &&
(mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
commitTempPlacement();
// Since the temp solution didn't update dragView, don't commit it either
commitTempPlacement(dragView);
completeAndClearReorderPreviewAnimations();
setItemPlacementDirty(false);
} else {
@@ -2601,11 +2684,11 @@ public class CellLayout extends ViewGroup {
+ (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
final int vStartPadding = getPaddingTop();
int x = hStartPadding + (cellX * mBorderSpacing) + (cellX * cellWidth);
int y = vStartPadding + (cellY * mBorderSpacing) + (cellY * cellHeight);
int x = hStartPadding + (cellX * mBorderSpace.x) + (cellX * cellWidth);
int y = vStartPadding + (cellY * mBorderSpace.y) + (cellY * cellHeight);
int width = cellHSpan * cellWidth + ((cellHSpan - 1) * mBorderSpacing);
int height = cellVSpan * cellHeight + ((cellVSpan - 1) * mBorderSpacing);
int width = cellHSpan * cellWidth + ((cellHSpan - 1) * mBorderSpace.x);
int height = cellVSpan * cellHeight + ((cellVSpan - 1) * mBorderSpace.y);
resultRect.set(x, y, x + width, y + height);
}
@@ -2624,12 +2707,12 @@ public class CellLayout extends ViewGroup {
public int getDesiredWidth() {
return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth)
+ ((mCountX - 1) * mBorderSpacing);
+ ((mCountX - 1) * mBorderSpace.x);
}
public int getDesiredHeight() {
return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight)
+ ((mCountY - 1) * mBorderSpacing);
+ ((mCountY - 1) * mBorderSpace.y);
}
public boolean isOccupied(int x, int y) {
@@ -2745,20 +2828,20 @@ public class CellLayout extends ViewGroup {
}
public void setup(int cellWidth, int cellHeight, boolean invertHorizontally, int colCount,
int rowCount, int borderSpacing, @Nullable Rect inset) {
int rowCount, Point borderSpace, @Nullable Rect inset) {
setup(cellWidth, cellHeight, invertHorizontally, colCount, rowCount, 1.0f, 1.0f,
borderSpacing, inset);
borderSpace, inset);
}
/**
* Use this method, as opposed to {@link #setup(int, int, boolean, int, int, int, Rect)},
* Use this method, as opposed to {@link #setup(int, int, boolean, int, int, Point, Rect)},
* if the view needs to be scaled.
*
* ie. In multi-window mode, we setup widgets so that they are measured and laid out
* using their full/invariant device profile sizes.
*/
public void setup(int cellWidth, int cellHeight, boolean invertHorizontally, int colCount,
int rowCount, float cellScaleX, float cellScaleY, int borderSpacing,
int rowCount, float cellScaleX, float cellScaleY, Point borderSpace,
@Nullable Rect inset) {
if (isLockedToGrid) {
final int myCellHSpan = cellHSpan;
@@ -2770,16 +2853,16 @@ public class CellLayout extends ViewGroup {
myCellX = colCount - myCellX - cellHSpan;
}
int hBorderSpacing = (myCellHSpan - 1) * borderSpacing;
int vBorderSpacing = (myCellVSpan - 1) * borderSpacing;
int hBorderSpacing = (myCellHSpan - 1) * borderSpace.x;
int vBorderSpacing = (myCellVSpan - 1) * borderSpace.y;
float myCellWidth = ((myCellHSpan * cellWidth) + hBorderSpacing) / cellScaleX;
float myCellHeight = ((myCellVSpan * cellHeight) + vBorderSpacing) / cellScaleY;
width = Math.round(myCellWidth) - leftMargin - rightMargin;
height = Math.round(myCellHeight) - topMargin - bottomMargin;
x = leftMargin + (myCellX * cellWidth) + (myCellX * borderSpacing);
y = topMargin + (myCellY * cellHeight) + (myCellY * borderSpacing);
x = leftMargin + (myCellX * cellWidth) + (myCellX * borderSpace.x);
y = topMargin + (myCellY * cellHeight) + (myCellY * borderSpace.y);
if (inset != null) {
x -= inset.left;
@@ -2881,7 +2964,7 @@ public class CellLayout extends ViewGroup {
directionVector, null, false, configuration).isSolution) {
if (commitConfig) {
copySolutionToTempState(configuration, null);
commitTempPlacement();
commitTempPlacement(null);
// undo marking cells occupied since there is actually nothing being placed yet.
mOccupied.markCells(0, mCountY - 1, mCountX, 1, false);
}
@@ -25,6 +25,7 @@ import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.logging.StatsLogManager;
@@ -33,6 +34,7 @@ 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.IntSet;
import com.android.launcher3.views.Snackbar;
public class DeleteDropTarget extends ButtonDropTarget {
@@ -127,11 +129,21 @@ public class DeleteDropTarget extends ButtonDropTarget {
public void completeDrop(DragObject d) {
ItemInfo item = d.dragInfo;
if (canRemove(item)) {
int itemPage = mLauncher.getWorkspace().getCurrentPage();
ItemInfo pageItem = item;
if (item.container <= 0) {
View v = mLauncher.getWorkspace().getHomescreenIconByItemId(item.container);
if (v != null) {
pageItem = (ItemInfo) v.getTag();
}
}
IntSet pageIds = pageItem.container == Favorites.CONTAINER_DESKTOP
? IntSet.wrap(pageItem.screenId)
: mLauncher.getWorkspace().getCurrentPageScreenIds();
onAccessibilityDrop(null, item);
ModelWriter modelWriter = mLauncher.getModelWriter();
Runnable onUndoClicked = () -> {
mLauncher.setPageToBindSynchronously(itemPage);
mLauncher.setPagesToBindSynchronously(pageIds);
modelWriter.abortDelete();
mLauncher.getStatsLogManager().logger().log(LAUNCHER_UNDO);
};
@@ -36,12 +36,12 @@ import java.util.ArrayList;
* The unused or "extra" height is allocated to three different variable heights:
* - The space above the workspace
* - The space between the workspace and hotseat
* - The espace below the hotseat
* - The space below the hotseat
*/
public class DevicePaddings {
private static final String DEVICE_PADDING = "device-paddings";
private static final String DEVICE_PADDINGS = "device-padding";
private static final String DEVICE_PADDINGS = "device-paddings";
private static final String DEVICE_PADDING = "device-padding";
private static final String WORKSPACE_TOP_PADDING = "workspaceTopPadding";
private static final String WORKSPACE_BOTTOM_PADDING = "workspaceBottomPadding";
@@ -58,13 +58,13 @@ public class DevicePaddings {
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if ((type == XmlPullParser.START_TAG) && DEVICE_PADDING.equals(parser.getName())) {
if ((type == XmlPullParser.START_TAG) && DEVICE_PADDINGS.equals(parser.getName())) {
final int displayDepth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > displayDepth)
&& type != XmlPullParser.END_DOCUMENT) {
if ((type == XmlPullParser.START_TAG)
&& DEVICE_PADDINGS.equals(parser.getName())) {
&& DEVICE_PADDING.equals(parser.getName())) {
TypedArray a = context.obtainStyledAttributes(
Xml.asAttributeSet(parser), R.styleable.DevicePadding);
int maxWidthPx = a.getDimensionPixelSize(
+275 -136
View File
@@ -18,14 +18,10 @@
package com.android.launcher3;
import static android.util.DisplayMetrics.DENSITY_DEVICE_STABLE;
import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
import static com.android.launcher3.ResourceUtils.pxFromDp;
import static com.android.launcher3.Utilities.dpiFromPx;
import static com.android.launcher3.Utilities.pxFromSp;
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.ICON_OVERLAP_FACTOR;
import static com.android.launcher3.util.WindowManagerCompat.MIN_TABLET_WIDTH;
import android.annotation.SuppressLint;
import android.content.Context;
@@ -35,11 +31,8 @@ import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.WindowInsets;
import android.view.WindowManager;
import com.android.launcher3.CellLayout.ContainerType;
import com.android.launcher3.DevicePaddings.DevicePadding;
@@ -47,6 +40,7 @@ import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.icons.DotRenderer;
import com.android.launcher3.icons.GraphicsUtils;
import com.android.launcher3.icons.IconNormalizer;
import com.android.launcher3.uioverrides.ApiWrapper;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.util.DisplayController.Info;
import com.android.launcher3.util.WindowBounds;
@@ -60,6 +54,8 @@ import app.lawnchair.preferences2.PreferenceManager2;
public class DeviceProfile {
private static final int DEFAULT_DOT_SIZE = 100;
// Ratio of empty space, qsb should take up to appear visually centered.
private static final float QSB_CENTER_FACTOR = .325f;
public final InvariantDeviceProfile inv;
private final Info mInfo;
@@ -70,7 +66,6 @@ public class DeviceProfile {
public final boolean isPhone;
public final boolean transposeLayoutWithOrientation;
public final boolean isTwoPanels;
public final boolean allowRotation;
// Device properties in current orientation
public final boolean isLandscape;
@@ -86,6 +81,7 @@ public class DeviceProfile {
public final float aspectRatio;
public final boolean isScalableGrid;
private final int mTypeIndex;
/**
* The maximum amount of left/right workspace padding as a percentage of the screen width.
@@ -103,10 +99,10 @@ public class DeviceProfile {
private static final int PORTRAIT_TABLET_LEFT_RIGHT_PADDING_MULTIPLIER = 4;
// Workspace
public final int desiredWorkspaceLeftRightOriginalPx;
public int desiredWorkspaceLeftRightMarginPx;
public final int cellLayoutBorderSpacingOriginalPx;
public int cellLayoutBorderSpacingPx;
public final int desiredWorkspaceHorizontalMarginOriginalPx;
public int desiredWorkspaceHorizontalMarginPx;
public Point cellLayoutBorderSpaceOriginalPx;
public Point cellLayoutBorderSpacePx;
public final int cellLayoutPaddingLeftRightPx;
public final int cellLayoutBottomPaddingPx;
public final int edgeMarginPx;
@@ -143,7 +139,8 @@ public class DeviceProfile {
public int folderIconOffsetYPx;
// Folder content
public int folderCellLayoutBorderSpacingPx;
public Point folderCellLayoutBorderSpacePx;
public int folderCellLayoutBorderSpaceOriginalPx;
public int folderContentPaddingLeftRight;
public int folderContentPaddingTop;
@@ -168,26 +165,38 @@ public class DeviceProfile {
// Start is the side next to the nav bar, end is the side next to the workspace
public final int hotseatBarSidePaddingStartPx;
public final int hotseatBarSidePaddingEndPx;
public final int hotseatQsbHeight;
public final float qsbBottomMarginOriginalPx;
public int qsbBottomMarginPx;
// All apps
public Point allAppsCellSpacePx;
public int allAppsOpenVerticalTranslate;
public int allAppsCellHeightPx;
public int allAppsCellWidthPx;
public int allAppsIconSizePx;
public int allAppsIconDrawablePaddingPx;
public int allAppsLeftRightPadding;
public final int numShownAllAppsColumns;
public float allAppsIconTextSizePx;
private float allAppsCellHeightMultiplier;
// Overview
public final boolean overviewShowAsGrid;
public int overviewTaskMarginPx;
public int overviewTaskMarginGridPx;
public int overviewTaskIconSizePx;
public int overviewTaskIconDrawableSizePx;
public int overviewTaskIconDrawableSizeGridPx;
public int overviewTaskThumbnailTopMarginPx;
public final int overviewActionsMarginThreeButtonPx;
public final int overviewActionsMarginGesturePx;
public final int overviewActionsTopMarginGesturePx;
public final int overviewActionsBottomMarginGesturePx;
public final int overviewActionsButtonSpacing;
public int overviewPageSpacing;
public int overviewRowSpacing;
public int overviewGridSideMargin;
// Widgets
public final PointF appWidgetScale = new PointF(1.0f, 1.0f);
@@ -208,22 +217,19 @@ public class DeviceProfile {
public DotRenderer mDotRendererWorkSpace;
public DotRenderer mDotRendererAllApps;
private final Context mContext;
// Taskbar
// Taskbar
public boolean isTaskbarPresent;
// Whether Taskbar will inset the bottom of apps by taskbarSize.
public boolean isTaskbarPresentInApps;
public int taskbarSize;
// How much of the bottom inset is due to Taskbar rather than other system elements.
public int nonOverlappingTaskbarInset;
// DragController
public int flingToDeleteThresholdVelocity;
/** TODO: Once we fully migrate to staged split, remove "isMultiWindowMode" */
DeviceProfile(Context context, InvariantDeviceProfile inv, Info info, WindowBounds windowBounds,
boolean isMultiWindowMode, boolean transposeLayoutWithOrientation,
boolean useTwoPanels) {
mContext = context;
PreferenceManager2 preferenceManager2 = PreferenceManager2.INSTANCE.get(context);
allAppsCellHeightMultiplier = PreferenceExtensionsKt.firstBlocking(preferenceManager2.getDrawerCellHeightFactor());
@@ -240,15 +246,10 @@ public class DeviceProfile {
widthPx = windowBounds.bounds.width();
heightPx = windowBounds.bounds.height();
availableWidthPx = windowBounds.availableSize.x;
int nonFinalAvailableHeightPx = windowBounds.availableSize.y;
availableHeightPx = windowBounds.availableSize.y;
mInfo = info;
// If the device's pixel density was scaled (usually via settings for A11y), use the
// original dimensions to determine if rotation is allowed of not.
float originalSmallestWidth = dpiFromPx(Math.min(widthPx, heightPx), DENSITY_DEVICE_STABLE);
allowRotation = originalSmallestWidth >= MIN_TABLET_WIDTH;
// Tablet UI does not support emulated landscape.
isTablet = allowRotation && info.isTablet(windowBounds);
isTablet = info.isTablet(windowBounds);
isPhone = !isTablet;
isTwoPanels = isTablet && useTwoPanels;
@@ -262,31 +263,31 @@ public class DeviceProfile {
mMetrics = context.getResources().getDisplayMetrics();
final Resources res = context.getResources();
isTaskbarPresent = isTablet && FeatureFlags.ENABLE_TASKBAR.get();
if (isTaskbarPresent) {
// Taskbar will be added later, but provides bottom insets that we should subtract
// from availableHeightPx.
taskbarSize = res.getDimensionPixelSize(R.dimen.taskbar_size);
WindowInsets windowInsets =
context.createWindowContext(
context.getSystemService(DisplayManager.class).getDisplay(mInfo.id),
TYPE_APPLICATION, null)
.getSystemService(WindowManager.class)
.getCurrentWindowMetrics().getWindowInsets();
nonOverlappingTaskbarInset = taskbarSize - windowInsets.getSystemWindowInsetBottom();
if (nonOverlappingTaskbarInset > 0) {
nonFinalAvailableHeightPx -= nonOverlappingTaskbarInset;
if (isTwoPanels) {
if (isLandscape) {
mTypeIndex = InvariantDeviceProfile.INDEX_TWO_PANEL_LANDSCAPE;
} else {
mTypeIndex = InvariantDeviceProfile.INDEX_TWO_PANEL_PORTRAIT;
}
} else {
if (isLandscape) {
mTypeIndex = InvariantDeviceProfile.INDEX_LANDSCAPE;
} else {
mTypeIndex = InvariantDeviceProfile.INDEX_DEFAULT;
}
}
availableHeightPx = nonFinalAvailableHeightPx;
hotseatQsbHeight = res.getDimensionPixelSize(R.dimen.qsb_widget_height);
isTaskbarPresent = isTablet && ApiWrapper.TASKBAR_DRAWN_IN_PROCESS
&& FeatureFlags.ENABLE_TASKBAR.get();
if (isTaskbarPresent) {
taskbarSize = res.getDimensionPixelSize(R.dimen.taskbar_size);
}
edgeMarginPx = res.getDimensionPixelSize(R.dimen.dynamic_grid_edge_margin);
desiredWorkspaceLeftRightMarginPx = isVerticalBarLayout() ? 0 : isScalableGrid
? res.getDimensionPixelSize(R.dimen.scalable_grid_left_right_margin)
: res.getDimensionPixelSize(R.dimen.dynamic_grid_left_right_margin);
desiredWorkspaceLeftRightOriginalPx = desiredWorkspaceLeftRightMarginPx;
desiredWorkspaceHorizontalMarginPx = getHorizontalMarginPx(inv, res);
desiredWorkspaceHorizontalMarginOriginalPx = desiredWorkspaceHorizontalMarginPx;
allAppsOpenVerticalTranslate = res.getDimensionPixelSize(
R.dimen.all_apps_open_vertical_translate);
@@ -296,9 +297,14 @@ public class DeviceProfile {
res.getDimensionPixelSize(R.dimen.folder_content_padding_left_right);
folderContentPaddingTop = res.getDimensionPixelSize(R.dimen.folder_content_padding_top);
setCellLayoutBorderSpacing(pxFromDp(inv.borderSpacing, mMetrics, 1f));
cellLayoutBorderSpacingOriginalPx = cellLayoutBorderSpacingPx;
folderCellLayoutBorderSpacingPx = cellLayoutBorderSpacingPx;
cellLayoutBorderSpacePx = getCellLayoutBorderSpace(inv);
allAppsCellSpacePx = new Point(
pxFromDp(inv.borderSpaces[InvariantDeviceProfile.INDEX_ALL_APPS].x, mMetrics, 1f),
pxFromDp(inv.borderSpaces[InvariantDeviceProfile.INDEX_ALL_APPS].y, mMetrics, 1f));
cellLayoutBorderSpaceOriginalPx = new Point(cellLayoutBorderSpacePx);
folderCellLayoutBorderSpaceOriginalPx = pxFromDp(inv.folderBorderSpace, mMetrics, 1f);
folderCellLayoutBorderSpacePx = new Point(folderCellLayoutBorderSpaceOriginalPx,
folderCellLayoutBorderSpaceOriginalPx);
int cellLayoutPaddingLeftRightMultiplier = !isVerticalBarLayout() && isTablet
? PORTRAIT_TABLET_LEFT_RIGHT_PADDING_MULTIPLIER : 1;
@@ -307,8 +313,7 @@ public class DeviceProfile {
: res.getDimensionPixelSize(R.dimen.dynamic_grid_cell_layout_padding);
if (isTwoPanels) {
cellLayoutPaddingLeftRightPx =
res.getDimensionPixelSize(R.dimen.two_panel_home_side_padding);
cellLayoutPaddingLeftRightPx = 0;
cellLayoutBottomPaddingPx = 0;
} else if (isLandscape) {
cellLayoutPaddingLeftRightPx = 0;
@@ -366,23 +371,64 @@ public class DeviceProfile {
res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_side_padding);
// Add a bit of space between nav bar and hotseat in vertical bar layout.
hotseatBarSidePaddingStartPx = isVerticalBarLayout() ? workspacePageIndicatorHeight : 0;
hotseatExtraVerticalSize = res.getDimensionPixelSize(hotseatExtraVerticalSizeRes);
updateHotseatIconSize(pxFromDp(inv.iconSize, mMetrics, 1f));
hotseatExtraVerticalSize =
res.getDimensionPixelSize(hotseatExtraVerticalSizeRes);
updateHotseatIconSize(
pxFromDp(inv.iconSize[InvariantDeviceProfile.INDEX_DEFAULT], mMetrics, 1f));
qsbBottomMarginOriginalPx = isScalableGrid
? res.getDimensionPixelSize(R.dimen.scalable_grid_qsb_bottom_margin)
: 0;
overviewTaskMarginPx = res.getDimensionPixelSize(R.dimen.overview_task_margin);
overviewTaskIconSizePx =
isTablet && FeatureFlags.ENABLE_OVERVIEW_GRID.get() ? res.getDimensionPixelSize(
R.dimen.task_thumbnail_icon_size_grid) : res.getDimensionPixelSize(
R.dimen.task_thumbnail_icon_size);
overviewShowAsGrid = isTablet && FeatureFlags.ENABLE_OVERVIEW_GRID.get();
overviewTaskMarginPx = overviewShowAsGrid
? res.getDimensionPixelSize(R.dimen.overview_task_margin_focused)
: res.getDimensionPixelSize(R.dimen.overview_task_margin);
overviewTaskMarginGridPx = res.getDimensionPixelSize(R.dimen.overview_task_margin_grid);
overviewTaskIconSizePx = res.getDimensionPixelSize(R.dimen.task_thumbnail_icon_size);
overviewTaskIconDrawableSizePx =
res.getDimensionPixelSize(R.dimen.task_thumbnail_icon_drawable_size);
overviewTaskIconDrawableSizeGridPx =
res.getDimensionPixelSize(R.dimen.task_thumbnail_icon_drawable_size_grid);
overviewTaskThumbnailTopMarginPx = overviewTaskIconSizePx + overviewTaskMarginPx * 2;
overviewActionsMarginGesturePx = res.getDimensionPixelSize(
R.dimen.overview_actions_bottom_margin_gesture);
if (overviewShowAsGrid) {
if (isLandscape) {
overviewActionsTopMarginGesturePx = res.getDimensionPixelSize(
R.dimen.overview_actions_top_margin_gesture_grid_landscape);
overviewActionsBottomMarginGesturePx = res.getDimensionPixelSize(
R.dimen.overview_actions_bottom_margin_gesture_grid_landscape);
overviewPageSpacing = res.getDimensionPixelSize(
R.dimen.overview_page_spacing_grid_landscape);
} else {
overviewActionsTopMarginGesturePx = res.getDimensionPixelSize(
R.dimen.overview_actions_top_margin_gesture_grid_portrait);
overviewActionsBottomMarginGesturePx = res.getDimensionPixelSize(
R.dimen.overview_actions_bottom_margin_gesture_grid_portrait);
overviewPageSpacing = res.getDimensionPixelSize(
R.dimen.overview_page_spacing_grid_portrait);
}
overviewActionsButtonSpacing = res.getDimensionPixelSize(
R.dimen.overview_actions_button_spacing_grid);
} else {
overviewActionsTopMarginGesturePx = res.getDimensionPixelSize(
R.dimen.overview_actions_margin_gesture);
overviewActionsBottomMarginGesturePx = overviewActionsTopMarginGesturePx;
overviewActionsButtonSpacing = res.getDimensionPixelSize(
R.dimen.overview_actions_button_spacing);
overviewPageSpacing = res.getDimensionPixelSize(R.dimen.overview_page_spacing);
}
overviewActionsMarginThreeButtonPx = res.getDimensionPixelSize(
R.dimen.overview_actions_bottom_margin_three_button);
R.dimen.overview_actions_margin_three_button);
// Grid task's top margin is only overviewTaskIconSizePx + overviewTaskMarginGridPx, but
// overviewTaskThumbnailTopMarginPx is applied to all TaskThumbnailView, so exclude the
// extra margin when calculating row spacing.
int extraTopMargin = overviewTaskThumbnailTopMarginPx - overviewTaskIconSizePx
- overviewTaskMarginGridPx;
overviewRowSpacing = res.getDimensionPixelSize(R.dimen.overview_grid_row_spacing)
- extraTopMargin;
overviewGridSideMargin = isLandscape
? res.getDimensionPixelSize(R.dimen.overview_grid_side_margin_landscape)
: res.getDimensionPixelSize(R.dimen.overview_grid_side_margin_portrait);
// Calculate all of the remaining variables.
extraSpace = updateAvailableDimensions(res);
@@ -448,6 +494,16 @@ public class DeviceProfile {
new DotRenderer(allAppsIconSizePx, dotPath, DEFAULT_DOT_SIZE);
}
private int getHorizontalMarginPx(InvariantDeviceProfile idp, Resources res) {
if (isVerticalBarLayout()) {
return 0;
}
return isScalableGrid
? pxFromDp(idp.horizontalMargin[mTypeIndex], mMetrics)
: res.getDimensionPixelSize(R.dimen.dynamic_grid_left_right_margin);
}
private void updateHotseatIconSize(int hotseatIconSizePx) {
// Ensure there is enough space for folder icons, which have a slightly larger radius.
hotseatCellHeightPx = (int) Math.ceil(hotseatIconSizePx * ICON_OVERLAP_FACTOR);
@@ -461,8 +517,24 @@ public class DeviceProfile {
}
}
private void setCellLayoutBorderSpacing(int borderSpacing) {
cellLayoutBorderSpacingPx = isScalableGrid ? borderSpacing : 0;
private Point getCellLayoutBorderSpace(InvariantDeviceProfile idp) {
if (!isScalableGrid) {
return new Point(0, 0);
}
int horizontalSpacePx = pxFromDp(idp.borderSpaces[mTypeIndex].x, mMetrics);
int verticalSpacePx = pxFromDp(idp.borderSpaces[mTypeIndex].y, mMetrics);
return new Point(horizontalSpacePx, verticalSpacePx);
}
private Point getCellLayoutBorderSpaceScaled(InvariantDeviceProfile idp, float scale) {
Point original = getCellLayoutBorderSpace(idp);
return new Point((int) (original.x * scale), (int) (original.y * scale));
}
public Info getDisplayInfo() {
return mInfo;
}
/**
@@ -475,10 +547,10 @@ public class DeviceProfile {
// Check all sides to ensure that the widget won't overlap into another cell, or into
// status bar.
return workspaceTopPadding > widgetPadding.top
&& cellLayoutBorderSpacingPx > widgetPadding.left
&& cellLayoutBorderSpacingPx > widgetPadding.top
&& cellLayoutBorderSpacingPx > widgetPadding.right
&& cellLayoutBorderSpacingPx > widgetPadding.bottom;
&& cellLayoutBorderSpacePx.x > widgetPadding.left
&& cellLayoutBorderSpacePx.y > widgetPadding.top
&& cellLayoutBorderSpacePx.x > widgetPadding.right
&& cellLayoutBorderSpacePx.y > widgetPadding.bottom;
}
public Builder toBuilder(Context context) {
@@ -544,13 +616,24 @@ public class DeviceProfile {
int baseCellHeight = allAppsIconSizePx + allAppsIconDrawablePaddingPx + textHeight + (topBottomPadding * 2);
allAppsCellHeightPx = (int) (baseCellHeight * allAppsCellHeightMultiplier);
if (allAppsIconTextSizePx == 0) {
int leftRightPadding = desiredWorkspaceLeftRightMarginPx + cellLayoutPaddingLeftRightPx;
int leftRightPadding = desiredWorkspaceHorizontalMarginPx + cellLayoutPaddingLeftRightPx;
int drawerWidth = availableWidthPx - leftRightPadding * 2;
allAppsCellHeightPx = (int) (drawerWidth / inv.numAllAppsColumns * allAppsCellHeightMultiplier);
allAppsIconDrawablePaddingPx = 0;
}
}
private void updateAllAppsWidth() {
if (isTwoPanels) {
int usedWidth = (allAppsCellWidthPx * numShownAllAppsColumns)
+ (allAppsCellSpacePx.x * (numShownAllAppsColumns + 1));
allAppsLeftRightPadding = Math.max(1, (availableWidthPx - usedWidth) / 2);
} else {
allAppsLeftRightPadding =
desiredWorkspaceHorizontalMarginPx + cellLayoutPaddingLeftRightPx;
}
}
/**
* Returns the amount of extra (or unused) vertical space.
*/
@@ -571,9 +654,10 @@ public class DeviceProfile {
// We scale to fit the cellWidth and cellHeight in the available space.
// The benefit of scalable grids is that we can get consistent aspect ratios between
// devices.
float usedWidth = (cellWidthPx * inv.numColumns)
+ (cellLayoutBorderSpacingPx * (inv.numColumns - 1))
+ (desiredWorkspaceLeftRightMarginPx * 2);
int numColumns = isTwoPanels ? inv.numColumns * 2 : inv.numColumns;
float usedWidth = (cellWidthPx * numColumns)
+ (cellLayoutBorderSpacePx.x * (numColumns - 1))
+ (desiredWorkspaceHorizontalMarginPx * 2);
// We do not subtract padding here, as we also scale the workspace padding if needed.
scaleX = availableWidthPx / usedWidth;
shouldScale = true;
@@ -590,7 +674,7 @@ public class DeviceProfile {
}
private int getCellLayoutHeight() {
return (cellHeightPx * inv.numRows) + (cellLayoutBorderSpacingPx * (inv.numRows - 1));
return (cellHeightPx * inv.numRows) + (cellLayoutBorderSpacePx.y * (inv.numRows - 1));
}
/**
@@ -603,24 +687,25 @@ public class DeviceProfile {
iconScale = Math.min(1f, scale);
cellScaleToFit = scale;
// Workspace
final boolean isVerticalLayout = isVerticalBarLayout();
float invIconSizeDp = isLandscape ? inv.landscapeIconSize : inv.iconSize;
float invIconSizeDp = inv.iconSize[mTypeIndex];
float invIconTextSizeSp = inv.iconTextSize[mTypeIndex];
iconSizePx = Math.max(1, pxFromDp(invIconSizeDp, mMetrics, iconScale));
float invIconTextSizeSp = isLandscape ? inv.landscapeIconTextSize : inv.iconTextSize;
iconTextSizePx = (int) (pxFromSp(invIconTextSizeSp, mMetrics) * iconScale);
iconDrawablePaddingPx = (int) (iconDrawablePaddingOriginalPx * iconScale);
setCellLayoutBorderSpacing((int) (cellLayoutBorderSpacingOriginalPx * scale));
cellLayoutBorderSpacePx = getCellLayoutBorderSpaceScaled(inv, scale);
if (isScalableGrid) {
cellWidthPx = pxFromDp(inv.minCellWidth, mMetrics, scale);
cellHeightPx = pxFromDp(inv.minCellHeight, mMetrics, scale);
cellWidthPx = pxFromDp(inv.minCellSize[mTypeIndex].x, mMetrics, scale);
cellHeightPx = pxFromDp(inv.minCellSize[mTypeIndex].y, mMetrics, scale);
int cellContentHeight = iconSizePx + iconDrawablePaddingPx
+ Utilities.calculateTextHeight(iconTextSizePx);
cellYPaddingPx = Math.max(0, cellHeightPx - cellContentHeight) / 2;
desiredWorkspaceLeftRightMarginPx = (int) (desiredWorkspaceLeftRightOriginalPx * scale);
desiredWorkspaceHorizontalMarginPx =
(int) (desiredWorkspaceHorizontalMarginOriginalPx * scale);
} else {
cellWidthPx = iconSizePx + iconDrawablePaddingPx;
cellHeightPx = (int) Math.ceil(iconSizePx * ICON_OVERLAP_FACTOR)
@@ -638,11 +723,14 @@ public class DeviceProfile {
}
// All apps
allAppsIconSizePx = pxFromDp(inv.allAppsIconSize, mMetrics);
allAppsIconTextSizePx = pxFromSp(inv.allAppsIconTextSize, mMetrics);
allAppsIconSizePx =
pxFromDp(inv.iconSize[InvariantDeviceProfile.INDEX_ALL_APPS], mMetrics);
allAppsIconTextSizePx =
pxFromSp(inv.iconTextSize[InvariantDeviceProfile.INDEX_ALL_APPS], mMetrics);
allAppsIconDrawablePaddingPx = iconDrawablePaddingOriginalPx;
autoResizeAllAppsCells();
allAppsCellWidthPx = allAppsIconSizePx + allAppsIconDrawablePaddingPx;
updateAllAppsWidth();
if (isVerticalLayout) {
hideWorkspaceLabelsIfNotEnoughSpace();
@@ -679,14 +767,14 @@ public class DeviceProfile {
// Check if the icons fit within the available height.
float contentUsedHeight = folderCellHeightPx * inv.numFolderRows
+ ((inv.numFolderRows - 1) * folderCellLayoutBorderSpacingPx);
+ ((inv.numFolderRows - 1) * folderCellLayoutBorderSpacePx.y);
int contentMaxHeight = availableHeightPx - totalWorkspacePadding.y - folderBottomPanelSize
- folderMargin - folderContentPaddingTop;
float scaleY = contentMaxHeight / contentUsedHeight;
// Check if the icons fit within the available width.
float contentUsedWidth = folderCellWidthPx * inv.numFolderColumns
+ ((inv.numFolderColumns - 1) * folderCellLayoutBorderSpacingPx);
+ ((inv.numFolderColumns - 1) * folderCellLayoutBorderSpacePx.x);
int contentMaxWidth = availableWidthPx - totalWorkspacePadding.x - folderMargin
- folderContentPaddingLeftRight * 2;
float scaleX = contentMaxWidth / contentUsedWidth;
@@ -698,9 +786,12 @@ public class DeviceProfile {
}
private void updateFolderCellSize(float scale, Resources res) {
float invIconSizeDp = isVerticalBarLayout() ? inv.landscapeIconSize : inv.iconSize;
float invIconSizeDp = isVerticalBarLayout()
? inv.iconSize[InvariantDeviceProfile.INDEX_LANDSCAPE]
: inv.iconSize[InvariantDeviceProfile.INDEX_DEFAULT];
folderChildIconSizePx = Math.max(1, pxFromDp(invIconSizeDp, mMetrics, scale));
folderChildTextSizePx = pxFromSp(inv.iconTextSize, mMetrics, scale);
folderChildTextSizePx =
pxFromSp(inv.iconTextSize[InvariantDeviceProfile.INDEX_DEFAULT], mMetrics, scale);
folderLabelTextSizePx = (int) (folderChildTextSizePx * folderLabelTextScale);
int textHeight = Utilities.calculateTextHeight(folderChildTextSizePx);
@@ -712,10 +803,10 @@ public class DeviceProfile {
folderCellWidthPx = (int) Math.max(minWidth, cellWidthPx * scale);
folderCellHeightPx = (int) Math.max(minHeight, cellHeightPx * scale);
int borderSpacing = (int) (cellLayoutBorderSpacingOriginalPx * scale);
folderCellLayoutBorderSpacingPx = borderSpacing;
folderContentPaddingLeftRight = borderSpacing;
folderContentPaddingTop = borderSpacing;
int scaledSpace = (int) (folderCellLayoutBorderSpaceOriginalPx * scale);
folderCellLayoutBorderSpacePx = new Point(scaledSpace, scaledSpace);
folderContentPaddingLeftRight = scaledSpace;
folderContentPaddingTop = scaledSpace;
} else {
int cellPaddingX = (int) (res.getDimensionPixelSize(R.dimen.folder_cell_x_padding)
* scale);
@@ -751,16 +842,29 @@ public class DeviceProfile {
if (result == null) {
result = new Point();
}
// Since we are only concerned with the overall padding, layout direction does
// not matter.
Point padding = getTotalWorkspacePadding();
result.x = calculateCellWidth(availableWidthPx - padding.x
- cellLayoutPaddingLeftRightPx * 2, cellLayoutBorderSpacingPx, inv.numColumns);
int numColumns = isTwoPanels ? inv.numColumns * 2 : inv.numColumns;
int screenWidthPx = getWorkspaceWidth(padding);
result.x = calculateCellWidth(screenWidthPx, cellLayoutBorderSpacePx.x, numColumns);
result.y = calculateCellHeight(availableHeightPx - padding.y
- cellLayoutBottomPaddingPx, cellLayoutBorderSpacingPx, inv.numRows);
- cellLayoutBottomPaddingPx, cellLayoutBorderSpacePx.y, inv.numRows);
return result;
}
public int getWorkspaceWidth() {
return getWorkspaceWidth(getTotalWorkspacePadding());
}
public int getWorkspaceWidth(Point workspacePadding) {
int cellLayoutTotalPadding =
isTwoPanels ? 4 * cellLayoutPaddingLeftRightPx : 2 * cellLayoutPaddingLeftRightPx;
return availableWidthPx - workspacePadding.x - cellLayoutTotalPadding;
}
public Point getTotalWorkspacePadding() {
updateWorkspacePadding();
return new Point(workspacePadding.left + workspacePadding.right,
@@ -784,38 +888,22 @@ public class DeviceProfile {
padding.right = hotseatBarSizePx;
}
} else {
int hotseatTop = isTaskbarPresent ? taskbarSize : hotseatBarSizePx;
// Pad the bottom of the workspace with search/hotseat bar sizes
int hotseatTop = hotseatBarSizePx;
int paddingBottom = hotseatTop + workspacePageIndicatorHeight
+ workspaceBottomPadding - mWorkspacePageIndicatorOverlapWorkspace;
if (isTablet) {
// Pad the left and right of the workspace to ensure consistent spacing
// between all icons
// The amount of screen space available for left/right padding.
int availablePaddingX = Math.max(0, widthPx - ((inv.numColumns * cellWidthPx) +
((inv.numColumns - 1) * cellWidthPx)));
availablePaddingX = (int) Math.min(availablePaddingX,
widthPx * MAX_HORIZONTAL_PADDING_PERCENT);
int hotseatVerticalPadding = isTaskbarPresent ? 0
: hotseatBarTopPaddingPx + hotseatBarBottomPaddingPx;
int availablePaddingY = Math.max(0, heightPx - edgeMarginPx - paddingBottom
- (2 * inv.numRows * cellHeightPx) - hotseatVerticalPadding);
padding.set(availablePaddingX / 2, edgeMarginPx + availablePaddingY / 2,
availablePaddingX / 2, paddingBottom + availablePaddingY / 2);
if (isTwoPanels) {
padding.set(0, padding.top, 0, padding.bottom);
}
} else {
// Pad the top and bottom of the workspace with search/hotseat bar sizes
padding.set(desiredWorkspaceLeftRightMarginPx,
workspaceTopPadding + (isScalableGrid ? 0 : edgeMarginPx),
desiredWorkspaceLeftRightMarginPx,
paddingBottom);
}
padding.set(desiredWorkspaceHorizontalMarginPx,
workspaceTopPadding + (isScalableGrid ? 0 : edgeMarginPx),
desiredWorkspaceHorizontalMarginPx,
paddingBottom);
}
}
public Rect getHotseatLayoutPadding() {
/**
* Returns the padding for hotseat view
*/
public Rect getHotseatLayoutPadding(Context context) {
if (isVerticalBarLayout()) {
if (isSeascape()) {
mHotseatPadding.set(mInsets.left + hotseatBarSidePaddingStartPx,
@@ -824,6 +912,30 @@ public class DeviceProfile {
mHotseatPadding.set(hotseatBarSidePaddingEndPx, mInsets.top,
mInsets.right + hotseatBarSidePaddingStartPx, mInsets.bottom);
}
} else if (isTaskbarPresent) {
int hotseatHeight = workspacePadding.bottom;
int taskbarOffset = getTaskbarOffsetY();
int hotseatTopDiff = hotseatHeight - taskbarOffset;
int endOffset = ApiWrapper.getHotseatEndOffset(context);
int requiredWidth = iconSizePx * numShownHotseatIcons;
Resources res = context.getResources();
float taskbarIconSize = res.getDimension(R.dimen.taskbar_icon_size);
float taskbarIconSpacing = 2 * res.getDimension(R.dimen.taskbar_icon_spacing);
int maxSize = (int) (requiredWidth
* (taskbarIconSize + taskbarIconSpacing) / taskbarIconSize);
int hotseatSize = Math.min(maxSize, availableWidthPx - endOffset);
int sideSpacing = (availableWidthPx - hotseatSize) / 2;
mHotseatPadding.set(sideSpacing, hotseatTopDiff, sideSpacing, taskbarOffset);
if (endOffset > sideSpacing) {
int diff = Utilities.isRtl(context.getResources())
? sideSpacing - endOffset
: endOffset - sideSpacing;
mHotseatPadding.left -= diff;
mHotseatPadding.right += diff;
}
} else {
// We want the edges of the hotseat to line up with the edges of the workspace, but the
// icons in the hotseat are a different size, and so don't line up perfectly. To account
@@ -844,6 +956,30 @@ public class DeviceProfile {
return mHotseatPadding;
}
/**
* Returns the number of pixels the QSB is translated from the bottom of the screen.
*/
public int getQsbOffsetY() {
int freeSpace = isTaskbarPresent
? workspacePadding.bottom
: hotseatBarSizePx - hotseatCellHeightPx - hotseatQsbHeight;
if (isScalableGrid && qsbBottomMarginPx > mInsets.bottom) {
// Note that taskbarSize = 0 unless isTaskbarPresent.
return Math.min(qsbBottomMarginPx + taskbarSize, freeSpace);
} else {
return (int) (freeSpace * QSB_CENTER_FACTOR)
+ (isTaskbarPresent ? taskbarSize : mInsets.bottom);
}
}
/**
* Returns the number of pixels the taskbar is translated from the bottom of the screen.
*/
public int getTaskbarOffsetY() {
return (getQsbOffsetY() - taskbarSize) / 2;
}
/**
* @return the bounds for which the open folders should be contained within
*/
@@ -868,6 +1004,7 @@ public class DeviceProfile {
public static int calculateCellWidth(int width, int borderSpacing, int countX) {
return (width - ((countX - 1) * borderSpacing)) / countX;
}
public static int calculateCellHeight(int height, int borderSpacing, int countY) {
return (height - ((countY - 1) * borderSpacing)) / countY;
}
@@ -928,7 +1065,6 @@ public class DeviceProfile {
writer.println(prefix + "DeviceProfile:");
writer.println(prefix + "\t1 dp = " + mMetrics.density + " px");
writer.println(prefix + "\tallowRotation:" + allowRotation);
writer.println(prefix + "\tisTablet:" + isTablet);
writer.println(prefix + "\tisPhone:" + isPhone);
writer.println(prefix + "\ttransposeLayoutWithOrientation:"
@@ -950,11 +1086,10 @@ public class DeviceProfile {
writer.println(prefix + "\tisScalableGrid:" + isScalableGrid);
writer.println(prefix + "\tinv.minCellWidth:" + inv.minCellWidth + "dp");
writer.println(prefix + "\tinv.minCellHeight:" + inv.minCellHeight + "dp");
writer.println(prefix + "\tinv.numColumns: " + inv.numColumns);
writer.println(prefix + "\tinv.numRows: " + inv.numRows);
writer.println(prefix + "\tinv.numColumns:" + inv.numColumns);
writer.println(prefix + "\tinv.numRows:" + inv.numRows);
writer.println(prefix + "\tminCellSize: " + inv.minCellSize[mTypeIndex] + "dp");
writer.println(prefix + pxToDpStr("cellWidthPx", cellWidthPx));
writer.println(prefix + pxToDpStr("cellHeightPx", cellHeightPx));
@@ -962,7 +1097,11 @@ public class DeviceProfile {
writer.println(prefix + pxToDpStr("getCellSize().x", getCellSize().x));
writer.println(prefix + pxToDpStr("getCellSize().y", getCellSize().y));
writer.println(prefix + "\tinv.iconSize:" + inv.iconSize + "dp");
writer.println(prefix + pxToDpStr("cellLayoutBorderSpacePx Horizontal",
cellLayoutBorderSpacePx.x));
writer.println(prefix + pxToDpStr("cellLayoutBorderSpacePx Vertical",
cellLayoutBorderSpacePx.y));
writer.println(prefix + pxToDpStr("iconSizePx", iconSizePx));
writer.println(prefix + pxToDpStr("iconTextSizePx", iconTextSizePx));
writer.println(prefix + pxToDpStr("iconDrawablePaddingPx", iconDrawablePaddingPx));
@@ -973,13 +1112,12 @@ public class DeviceProfile {
writer.println(prefix + pxToDpStr("folderChildTextSizePx", folderChildTextSizePx));
writer.println(prefix + pxToDpStr("folderChildDrawablePaddingPx",
folderChildDrawablePaddingPx));
writer.println(prefix + pxToDpStr("folderCellLayoutBorderSpacingPx",
folderCellLayoutBorderSpacingPx));
writer.println(prefix + pxToDpStr("cellLayoutBorderSpacingPx",
cellLayoutBorderSpacingPx));
writer.println(prefix + pxToDpStr("desiredWorkspaceLeftRightMarginPx",
desiredWorkspaceLeftRightMarginPx));
writer.println(prefix + pxToDpStr("folderCellLayoutBorderSpaceOriginalPx",
folderCellLayoutBorderSpaceOriginalPx));
writer.println(prefix + pxToDpStr("folderCellLayoutBorderSpacePx Horizontal",
folderCellLayoutBorderSpacePx.x));
writer.println(prefix + pxToDpStr("folderCellLayoutBorderSpacePx Vertical",
folderCellLayoutBorderSpacePx.y));
writer.println(prefix + pxToDpStr("allAppsIconSizePx", allAppsIconSizePx));
writer.println(prefix + pxToDpStr("allAppsIconTextSizePx", allAppsIconTextSizePx));
@@ -999,11 +1137,11 @@ public class DeviceProfile {
writer.println(prefix + "\tnumShownHotseatIcons: " + numShownHotseatIcons);
writer.println(prefix + "\tisTaskbarPresent:" + isTaskbarPresent);
writer.println(prefix + "\tisTaskbarPresentInApps:" + isTaskbarPresentInApps);
writer.println(prefix + pxToDpStr("taskbarSize", taskbarSize));
writer.println(prefix + pxToDpStr("nonOverlappingTaskbarInset",
nonOverlappingTaskbarInset));
writer.println(prefix + pxToDpStr("desiredWorkspaceHorizontalMarginPx",
desiredWorkspaceHorizontalMarginPx));
writer.println(prefix + pxToDpStr("workspacePadding.left", workspacePadding.left));
writer.println(prefix + pxToDpStr("workspacePadding.top", workspacePadding.top));
writer.println(prefix + pxToDpStr("workspacePadding.right", workspacePadding.right));
@@ -1012,6 +1150,7 @@ public class DeviceProfile {
writer.println(prefix + pxToDpStr("iconScale", iconScale));
writer.println(prefix + pxToDpStr("cellScaleToFit ", cellScaleToFit));
writer.println(prefix + pxToDpStr("extraSpace", extraSpace));
writer.println(prefix + pxToDpStr("unscaled extraSpace", extraSpace / iconScale));
if (inv.devicePaddings != null) {
int unscaledExtraSpace = (int) (extraSpace / iconScale);
@@ -25,6 +25,7 @@ import android.animation.TimeInterpolator;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
@@ -32,10 +33,13 @@ import android.view.ViewDebug;
import android.view.ViewPropertyAnimator;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.dragndrop.DragController;
import com.android.launcher3.dragndrop.DragController.DragListener;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.testing.TestProtocol;
/*
* The top bar containing various drop targets: Delete/App Info/Uninstall.
@@ -212,6 +216,9 @@ public class DropTargetBar extends FrameLayout
}
public void animateToVisibility(boolean isVisible) {
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NO_DROP_TARGET, "8");
}
if (mVisible != isVisible) {
mVisible = isVisible;
@@ -238,6 +245,9 @@ public class DropTargetBar extends FrameLayout
*/
@Override
public void onDragStart(DropTarget.DragObject dragObject, DragOptions options) {
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NO_DROP_TARGET, "7");
}
animateToVisibility(true);
}
@@ -261,4 +271,16 @@ public class DropTargetBar extends FrameLayout
public ButtonDropTarget[] getDropTargets() {
return mDropTargets;
}
@Override
protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (TestProtocol.sDebugTracing) {
if (visibility == VISIBLE) {
Log.d(TestProtocol.NO_DROP_TARGET, "9");
} else {
Log.d(TestProtocol.NO_DROP_TARGET, "Hiding drop target", new Exception());
}
}
}
}
@@ -22,11 +22,9 @@ import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.views.ActivityContext;
import app.lawnchair.font.FontManager;
@@ -103,10 +101,6 @@ public class ExtendedEditText extends EditText {
}
}
// inherited class can override to change the appearance of the edit text.
public void show() {}
public void hide() {}
public void showKeyboard() {
mShowImeAfterFirstLayout = !showSoftInput();
}
@@ -145,15 +139,5 @@ public class ExtendedEditText extends EditText {
if (!TextUtils.isEmpty(getText())) {
setText("");
}
if (FeatureFlags.ENABLE_DEVICE_SEARCH.get()) {
return;
}
if (isFocused()) {
View nextFocus = focusSearch(View.FOCUS_DOWN);
if (nextFocus != null) {
nextFocus.requestFocus();
}
}
hideKeyboard();
}
}
+10 -39
View File
@@ -55,8 +55,6 @@ public class Hotseat extends CellLayout implements Insettable {
private final View mQsb;
private final int mQsbHeight;
private final int mTaskbarViewHeight;
public Hotseat(Context context) {
this(context, null);
}
@@ -74,8 +72,6 @@ public class Hotseat extends CellLayout implements Insettable {
mQsb = LayoutInflater.from(context).inflate(layoutId, this, false);
mQsbHeight = mQsb.getLayoutParams().height;
addView(mQsb);
mTaskbarViewHeight = context.getResources().getDimensionPixelSize(R.dimen.taskbar_size);
}
/**
@@ -123,18 +119,13 @@ public class Hotseat extends CellLayout implements Insettable {
lp.gravity = Gravity.BOTTOM;
lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
lp.height = (grid.isTaskbarPresent
? grid.workspacePadding.bottom
? grid.workspacePadding.bottom
: grid.hotseatBarSizePx)
+ (grid.isTaskbarPresent ? grid.taskbarSize : insets.bottom);
}
if (!grid.isTaskbarPresent) {
// When taskbar is present, we set the padding separately to ensure a seamless visual
// handoff between taskbar and hotseat during drag and drop.
Rect padding = grid.getHotseatLayoutPadding();
setPadding(padding.left, padding.top, padding.right, padding.bottom);
}
Rect padding = grid.getHotseatLayoutPadding(getContext());
setPadding(padding.left, padding.top, padding.right, padding.bottom);
setLayoutParams(lp);
InsettableFrameLayout.dispatchInsets(this, insets);
}
@@ -168,7 +159,8 @@ public class Hotseat extends CellLayout implements Insettable {
}
return mWorkspace.onTouchEvent(event);
}
return event.getY() > getCellHeight();
// Always let touch follow through to Workspace.
return false;
}
@Override
@@ -202,36 +194,11 @@ public class Hotseat extends CellLayout implements Insettable {
int left = (r - l - qsbWidth) / 2;
int right = left + qsbWidth;
int bottom = b - t - getQsbOffsetY();
int bottom = b - t - mActivity.getDeviceProfile().getQsbOffsetY();
int top = bottom - mQsbHeight;
mQsb.layout(left, top, right, bottom);
}
/**
* Returns the number of pixels the QSB is translated from the bottom of the screen.
*/
private int getQsbOffsetY() {
DeviceProfile dp = mActivity.getDeviceProfile();
int freeSpace = dp.isTaskbarPresent
? dp.workspacePadding.bottom
: dp.hotseatBarSizePx - dp.hotseatCellHeightPx - mQsbHeight;
if (dp.isScalableGrid && dp.qsbBottomMarginPx > dp.getInsets().bottom) {
return Math.min(dp.qsbBottomMarginPx, freeSpace);
} else {
return (int) (freeSpace * QSB_CENTER_FACTOR) + (dp.isTaskbarPresent
? dp.taskbarSize
: dp.getInsets().bottom);
}
}
/**
* Returns the number of pixels the taskbar is translated from the bottom of the screen.
*/
public int getTaskbarOffsetY() {
return (getQsbOffsetY() - mTaskbarViewHeight) / 2;
}
/**
* Sets the alpha value of just our ShortcutAndWidgetContainer.
*/
@@ -239,6 +206,10 @@ public class Hotseat extends CellLayout implements Insettable {
getShortcutsAndWidgets().setAlpha(alpha);
}
public float getIconsAlpha() {
return getShortcutsAndWidgets().getAlpha();
}
/**
* Returns the QSB inside hotseat
*/
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2015 The Android Open Source Project
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package com.android.launcher3;
import static com.android.launcher3.Utilities.dpiFromPx;
import static com.android.launcher3.Utilities.getPointString;
import static com.android.launcher3.config.FeatureFlags.ENABLE_TWO_PANEL_HOME;
import static com.android.launcher3.util.DisplayController.CHANGE_DENSITY;
import static com.android.launcher3.util.DisplayController.CHANGE_SUPPORTED_BOUNDS;
@@ -32,18 +31,23 @@ import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.util.TypedValue;
import android.util.Xml;
import android.view.Display;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.model.DeviceGridState;
import com.android.launcher3.provider.RestoreDbTask;
import com.android.launcher3.util.DisplayController;
import com.android.launcher3.util.DisplayController.Info;
import com.android.launcher3.util.IntArray;
@@ -55,7 +59,10 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
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.List;
@@ -68,11 +75,12 @@ public class InvariantDeviceProfile {
public static final MainThreadInitializedObject<InvariantDeviceProfile> INSTANCE =
new MainThreadInitializedObject<>(InvariantDeviceProfile::new);
public static final String KEY_MIGRATION_SRC_WORKSPACE_SIZE = "migration_src_workspace_size";
public static final String KEY_MIGRATION_SRC_HOTSEAT_COUNT = "migration_src_hotseat_count";
private static final int DEFAULT_TRUE = -1;
private static final int DEFAULT_SPLIT_DISPLAY = 2;
@Retention(RetentionPolicy.SOURCE)
@IntDef({TYPE_PHONE, TYPE_MULTI_DISPLAY, TYPE_TABLET})
public @interface DeviceType{}
public static final int TYPE_PHONE = 0;
public static final int TYPE_MULTI_DISPLAY = 1;
public static final int TYPE_TABLET = 2;
private static final String KEY_IDP_GRID_NAME = "idp_grid_name";
@@ -86,6 +94,15 @@ public class InvariantDeviceProfile {
// used to offset float not being able to express extremely small weights in extreme cases.
private static final float WEIGHT_EFFICIENT = 100000f;
// Used for arrays to specify different sizes (e.g. border spaces, width/height) in different
// constraints
static final int COUNT_SIZES = 5;
public static final int INDEX_DEFAULT = 0;
public static final int INDEX_LANDSCAPE = 1;
public static final int INDEX_TWO_PANEL_PORTRAIT = 2;
public static final int INDEX_TWO_PANEL_LANDSCAPE = 3;
public static final int INDEX_ALL_APPS = 4;
/**
* Original profile before preference overrides
*/
@@ -102,18 +119,18 @@ public class InvariantDeviceProfile {
*/
public int numFolderRows;
public int numFolderColumns;
public float iconSize;
public float landscapeIconSize;
public float landscapeIconTextSize;
public float[] iconSize;
public float[] iconTextSize;
public int iconBitmapSize;
public int fillResIconDpi;
public float iconTextSize;
public float allAppsIconSize;
public float allAppsIconTextSize;
public @DeviceType int deviceType;
public float minCellHeight;
public float minCellWidth;
public float borderSpacing;
public PointF[] minCellSize;
public PointF[] borderSpaces;
public float folderBorderSpace;
public float[] horizontalMargin;
private SparseArray<TypedValue> mExtraAttrs;
@@ -150,7 +167,8 @@ public class InvariantDeviceProfile {
*/
public List<DeviceProfile> supportedProfiles = Collections.EMPTY_LIST;
@Nullable public DevicePaddings devicePaddings;
@Nullable
public DevicePaddings devicePaddings;
public Point defaultWallpaperSize;
public Rect defaultWidgetPadding;
@@ -158,34 +176,7 @@ public class InvariantDeviceProfile {
private final ArrayList<OnIDPChangeListener> mChangeListeners = new ArrayList<>();
@VisibleForTesting
public InvariantDeviceProfile() {}
private InvariantDeviceProfile(InvariantDeviceProfile p) {
numRows = p.numRows;
numColumns = p.numColumns;
numFolderRows = p.numFolderRows;
numFolderColumns = p.numFolderColumns;
iconSize = p.iconSize;
landscapeIconSize = p.landscapeIconSize;
iconBitmapSize = p.iconBitmapSize;
iconTextSize = p.iconTextSize;
landscapeIconTextSize = p.landscapeIconTextSize;
numShownHotseatIcons = p.numShownHotseatIcons;
numDatabaseHotseatIcons = p.numDatabaseHotseatIcons;
numAllAppsColumns = p.numAllAppsColumns;
numDatabaseAllAppsColumns = p.numDatabaseAllAppsColumns;
isScalable = p.isScalable;
devicePaddingId = p.devicePaddingId;
minCellHeight = p.minCellHeight;
minCellWidth = p.minCellWidth;
borderSpacing = p.borderSpacing;
dbFile = p.dbFile;
allAppsIconSize = p.allAppsIconSize;
allAppsIconTextSize = p.allAppsIconTextSize;
defaultLayoutId = p.defaultLayoutId;
demoModeLayoutId = p.demoModeLayoutId;
mExtraAttrs = p.mExtraAttrs;
devicePaddings = p.devicePaddings;
public InvariantDeviceProfile() {
}
@TargetApi(23)
@@ -195,12 +186,9 @@ public class InvariantDeviceProfile {
if (!newGridName.equals(gridName)) {
Utilities.getPrefs(context).edit().putString(KEY_IDP_GRID_NAME, newGridName).apply();
}
Utilities.getPrefs(context).edit()
.putInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT, numDatabaseHotseatIcons)
.putString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, getPointString(numColumns, numRows))
.apply();
new DeviceGridState(this).writeToPrefs(context);
DisplayController.INSTANCE.get(context).addChangeListener(
DisplayController.INSTANCE.get(context).setPriorityListener(
(displayContext, info, flags) -> {
if ((flags & (CHANGE_DENSITY | CHANGE_SUPPORTED_BOUNDS)) != 0) {
onConfigChanged(displayContext);
@@ -219,25 +207,16 @@ public class InvariantDeviceProfile {
}
public InvariantDeviceProfile(Context context, DeviceProfileOverrides.Options overrideOptions) {
Info displayInfo = DisplayController.INSTANCE.get(context).getInfo();
// Determine if we have split display
boolean isTablet = false, isPhone = false;
for (WindowBounds bounds : displayInfo.supportedBounds) {
if (displayInfo.isTablet(bounds)) {
isTablet = true;
} else {
isPhone = true;
}
}
boolean isSplitDisplay = isPhone && isTablet && ENABLE_TWO_PANEL_HOME.get();
// Get the display info based on default display and interpolate it to existing display
Info defaultInfo = DisplayController.INSTANCE.get(context).getInfo();
@DeviceType int defaultDeviceType = getDeviceType(defaultInfo);
String gridName = getCurrentGridName(context);
ArrayList<DisplayOption> allOptions =
getPredefinedDeviceProfiles(context, gridName, isSplitDisplay);
getPredefinedDeviceProfiles(context, gridName, defaultDeviceType, false);
DisplayOption displayOption =
invDistWeightedInterpolate(displayInfo, allOptions, isSplitDisplay);
initGrid(context, displayInfo, displayOption, isSplitDisplay, overrideOptions);
invDistWeightedInterpolate(defaultInfo, allOptions, defaultDeviceType);
initGrid(context, defaultInfo, displayOption, defaultDeviceType, overrideOptions);
}
/**
@@ -249,28 +228,72 @@ public class InvariantDeviceProfile {
String gridName = getCurrentGridName(context);
// Get the display info based on default display and interpolate it to existing display
Info defaultInfo = DisplayController.INSTANCE.get(context).getInfo();
@DeviceType int defaultDeviceType = getDeviceType(defaultInfo);
DisplayOption defaultDisplayOption = invDistWeightedInterpolate(
DisplayController.INSTANCE.get(context).getInfo(),
getPredefinedDeviceProfiles(context, gridName, false), false);
defaultInfo,
getPredefinedDeviceProfiles(context, gridName, defaultDeviceType,
/*allowDisabledGrid=*/false),
defaultDeviceType);
Info myInfo = new Info(context, display);
@DeviceType int deviceType = getDeviceType(myInfo);
DisplayOption myDisplayOption = invDistWeightedInterpolate(
myInfo, getPredefinedDeviceProfiles(context, gridName, false), false);
myInfo,
getPredefinedDeviceProfiles(context, gridName, deviceType,
/*allowDisabledGrid=*/false),
deviceType);
DisplayOption result = new DisplayOption(defaultDisplayOption.grid)
.add(myDisplayOption);
result.iconSize = defaultDisplayOption.iconSize;
result.landscapeIconSize = defaultDisplayOption.landscapeIconSize;
if (defaultDisplayOption.allAppsIconSize < myDisplayOption.allAppsIconSize) {
result.allAppsIconSize = defaultDisplayOption.allAppsIconSize;
} else {
result.allAppsIconSize = myDisplayOption.allAppsIconSize;
result.iconSizes[INDEX_DEFAULT] =
defaultDisplayOption.iconSizes[INDEX_DEFAULT];
for (int i = 1; i < COUNT_SIZES; i++) {
result.iconSizes[i] = Math.min(
defaultDisplayOption.iconSizes[i], myDisplayOption.iconSizes[i]);
}
result.minCellHeight = defaultDisplayOption.minCellHeight;
result.minCellWidth = defaultDisplayOption.minCellWidth;
result.borderSpacing = defaultDisplayOption.borderSpacing;
initGrid(context, myInfo, result, false);
System.arraycopy(defaultDisplayOption.minCellSize, 0, result.minCellSize, 0,
COUNT_SIZES);
System.arraycopy(defaultDisplayOption.borderSpaces, 0, result.borderSpaces, 0,
COUNT_SIZES);
initGrid(context, myInfo, result, deviceType);
}
/**
* Reinitialize the current grid after a restore, where some grids might now be disabled.
*/
public void reinitializeAfterRestore(Context context) {
String currentDbFile = dbFile;
String gridName = getCurrentGridName(context);
String newGridName = initGrid(context, gridName);
if (!newGridName.equals(gridName)) {
Log.d(TAG, "Restored grid is disabled : " + gridName
+ ", migrating to: " + newGridName
+ ", removing all other grid db files");
for (String gridDbFile : LauncherFiles.GRID_DB_FILES) {
if (gridDbFile.equals(currentDbFile)) {
continue;
}
if (context.getDatabasePath(gridDbFile).delete()) {
Log.d(TAG, "Removed old grid db file: " + gridDbFile);
}
}
setCurrentGrid(context, gridName);
}
}
private static @DeviceType int getDeviceType(Info displayInfo) {
// Each screen has two profiles (portrait/landscape), so devices with four or more
// supported profiles implies two or more internal displays.
if (displayInfo.supportedBounds.size() >= 4 && ENABLE_TWO_PANEL_HOME.get()) {
return TYPE_MULTI_DISPLAY;
} else if (displayInfo.supportedBounds.stream().allMatch(displayInfo::isTablet)) {
return TYPE_TABLET;
} else {
return TYPE_PHONE;
}
}
public static String getCurrentGridName(Context context) {
@@ -280,37 +303,27 @@ public class InvariantDeviceProfile {
private String initGrid(Context context, String gridName) {
Info displayInfo = DisplayController.INSTANCE.get(context).getInfo();
// Determine if we have split display
boolean isTablet = false, isPhone = false;
for (WindowBounds bounds : displayInfo.supportedBounds) {
if (displayInfo.isTablet(bounds)) {
isTablet = true;
} else {
isPhone = true;
}
}
boolean isSplitDisplay = isPhone && isTablet && ENABLE_TWO_PANEL_HOME.get();
@DeviceType int deviceType = getDeviceType(displayInfo);
ArrayList<DisplayOption> allOptions =
getPredefinedDeviceProfiles(context, gridName, isSplitDisplay);
getPredefinedDeviceProfiles(context, gridName, deviceType,
RestoreDbTask.isPending(context));
DisplayOption displayOption =
invDistWeightedInterpolate(displayInfo, allOptions, isSplitDisplay);
initGrid(context, displayInfo, displayOption, isSplitDisplay);
invDistWeightedInterpolate(displayInfo, allOptions, deviceType);
initGrid(context, displayInfo, displayOption, deviceType);
return displayOption.grid.name;
}
private void initGrid(
Context context, Info displayInfo, DisplayOption displayOption,
boolean isSplitDisplay) {
@DeviceType int deviceType) {
DeviceProfileOverrides.Options overrideOptions = DeviceProfileOverrides.INSTANCE.get(context)
.getOverrides(displayOption.grid);
initGrid(context, displayInfo, displayOption, isSplitDisplay, overrideOptions);
initGrid(context, displayInfo, displayOption, deviceType, overrideOptions);
}
private void initGrid(
Context context, Info displayInfo, DisplayOption displayOption,
boolean isSplitDisplay, DeviceProfileOverrides.Options overrideOptions) {
private void initGrid(Context context, Info displayInfo, DisplayOption displayOption,
@DeviceType int deviceType, DeviceProfileOverrides.Options overrideOptions) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
closestProfile = displayOption.grid;
numRows = closestProfile.numRows;
@@ -322,34 +335,31 @@ public class InvariantDeviceProfile {
numFolderColumns = closestProfile.numFolderColumns;
isScalable = closestProfile.isScalable;
devicePaddingId = closestProfile.devicePaddingId;
this.deviceType = deviceType;
mExtraAttrs = closestProfile.extraAttrs;
iconSize = displayOption.iconSize;
landscapeIconSize = displayOption.landscapeIconSize;
iconBitmapSize = ResourceUtils.pxFromDp(iconSize, metrics);
iconTextSize = displayOption.iconTextSize;
landscapeIconTextSize = displayOption.landscapeIconTextSize;
fillResIconDpi = getLauncherIconDensity(iconBitmapSize);
iconSize = displayOption.iconSizes;
iconTextSize = displayOption.textSizes;
minCellHeight = displayOption.minCellHeight;
minCellWidth = displayOption.minCellWidth;
borderSpacing = displayOption.borderSpacing;
minCellSize = displayOption.minCellSize;
borderSpaces = displayOption.borderSpaces;
folderBorderSpace = displayOption.folderBorderSpace;
horizontalMargin = displayOption.horizontalMargin;
numShownHotseatIcons = closestProfile.numHotseatIcons;
numDatabaseHotseatIcons = isSplitDisplay
numDatabaseHotseatIcons = deviceType == TYPE_MULTI_DISPLAY
? closestProfile.numDatabaseHotseatIcons : closestProfile.numHotseatIcons;
numAllAppsColumns = closestProfile.numAllAppsColumns;
numDatabaseAllAppsColumns = isSplitDisplay
numDatabaseAllAppsColumns = deviceType == TYPE_MULTI_DISPLAY
? closestProfile.numDatabaseAllAppsColumns : closestProfile.numAllAppsColumns;
if (Utilities.isGridOptionsEnabled(context)) {
allAppsIconSize = displayOption.allAppsIconSize;
allAppsIconTextSize = displayOption.allAppsIconTextSize;
} else {
allAppsIconSize = iconSize;
allAppsIconTextSize = iconTextSize;
if (!Utilities.isGridOptionsEnabled(context)) {
iconSize[INDEX_ALL_APPS] = iconSize[INDEX_DEFAULT];
iconTextSize[INDEX_ALL_APPS] = iconTextSize[INDEX_DEFAULT];
}
if (devicePaddingId != 0) {
@@ -361,14 +371,18 @@ public class InvariantDeviceProfile {
applyPartnerDeviceProfileOverrides(context, metrics);
overrideOptions.apply(this);
iconBitmapSize = ResourceUtils.pxFromDp(Math.max(iconSize, allAppsIconSize), metrics);
float maxIconSize = iconSize[0];
for (int i = 1; i < iconSize.length; i++) {
maxIconSize = Math.max(maxIconSize, iconSize[i]);
}
iconBitmapSize = ResourceUtils.pxFromDp(maxIconSize, metrics);
fillResIconDpi = getLauncherIconDensity(iconBitmapSize);
final List<DeviceProfile> localSupportedProfiles = new ArrayList<>();
defaultWallpaperSize = new Point(displayInfo.currentSize);
for (WindowBounds bounds : displayInfo.supportedBounds) {
localSupportedProfiles.add(new DeviceProfile.Builder(context, this, displayInfo)
.setUseTwoPanels(isSplitDisplay)
.setUseTwoPanels(deviceType == TYPE_MULTI_DISPLAY)
.setWindowBounds(bounds).build());
// Wallpaper size should be the maximum of the all possible sizes Launcher expects
@@ -391,11 +405,6 @@ public class InvariantDeviceProfile {
defaultWidgetPadding = AppWidgetHostView.getDefaultPaddingForWidget(context, cn, null);
}
@Nullable
public TypedValue getAttrValue(int attr) {
return mExtraAttrs == null ? null : mExtraAttrs.get(attr);
}
public void addOnChangeListener(OnIDPChangeListener listener) {
mChangeListeners.add(listener);
}
@@ -411,24 +420,34 @@ public class InvariantDeviceProfile {
MAIN_EXECUTOR.execute(() -> onConfigChanged(appContext));
}
public void onPreferencesChanged(Context context) {
public void onPreferencesChanged(Context context){
Context appContext = context.getApplicationContext();
MAIN_EXECUTOR.execute(() -> onConfigChanged(appContext));
}
private Object[] toModelState() {
return new Object[]{
numColumns, numRows, numDatabaseHotseatIcons, iconBitmapSize, fillResIconDpi,
numDatabaseAllAppsColumns, dbFile};
}
private void onConfigChanged(Context context) {
Object[] oldState = toModelState();
// Re-init grid
String gridName = getCurrentGridName(context);
initGrid(context, gridName);
boolean modelPropsChanged = !Arrays.equals(oldState, toModelState());
for (OnIDPChangeListener listener : mChangeListeners) {
listener.onIdpChanged(this);
listener.onIdpChanged(modelPropsChanged);
}
}
private static ArrayList<DisplayOption> getPredefinedDeviceProfiles(
Context context, String gridName, boolean isSplitDisplay) {
private static ArrayList<DisplayOption> getPredefinedDeviceProfiles(Context context,
String gridName, @DeviceType int deviceType, boolean allowDisabledGrid) {
ArrayList<DisplayOption> profiles = new ArrayList<>();
try (XmlResourceParser parser = context.getResources().getXml(R.xml.device_profiles)) {
final int depth = parser.getDepth();
int type;
@@ -437,28 +456,31 @@ public class InvariantDeviceProfile {
if ((type == XmlPullParser.START_TAG)
&& GridOption.TAG_NAME.equals(parser.getName())) {
GridOption gridOption = new GridOption(context, Xml.asAttributeSet(parser));
final int displayDepth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > displayDepth)
&& type != XmlPullParser.END_DOCUMENT) {
if ((type == XmlPullParser.START_TAG) && "display-option".equals(
parser.getName())) {
profiles.add(new DisplayOption(gridOption, context,
Xml.asAttributeSet(parser),
isSplitDisplay ? DEFAULT_SPLIT_DISPLAY : DEFAULT_TRUE));
GridOption gridOption = new GridOption(context, Xml.asAttributeSet(parser),
deviceType);
if (gridOption.isEnabled || allowDisabledGrid) {
final int displayDepth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG
|| parser.getDepth() > displayDepth)
&& type != XmlPullParser.END_DOCUMENT) {
if ((type == XmlPullParser.START_TAG) && "display-option".equals(
parser.getName())) {
profiles.add(new DisplayOption(gridOption, context,
Xml.asAttributeSet(parser)));
}
}
}
}
}
} catch (IOException|XmlPullParserException e) {
} catch (IOException | XmlPullParserException e) {
throw new RuntimeException(e);
}
ArrayList<DisplayOption> filteredProfiles = new ArrayList<>();
if (!TextUtils.isEmpty(gridName)) {
for (DisplayOption option : profiles) {
if (gridName.equals(option.grid.name)) {
if (gridName.equals(option.grid.name)
&& (option.grid.isEnabled || allowDisabledGrid)) {
filteredProfiles.add(option);
}
}
@@ -477,9 +499,36 @@ public class InvariantDeviceProfile {
return filteredProfiles;
}
/**
* @return all the grid options that can be shown on the device
*/
public List<GridOption> parseAllGridOptions(Context context) {
List<GridOption> result = new ArrayList<>();
try (XmlResourceParser parser = context.getResources().getXml(R.xml.device_profiles)) {
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG
|| parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if ((type == XmlPullParser.START_TAG)
&& GridOption.TAG_NAME.equals(parser.getName())) {
GridOption option =
new GridOption(context, Xml.asAttributeSet(parser), deviceType);
if (option.isEnabled) {
result.add(option);
}
}
}
} catch (IOException | XmlPullParserException e) {
Log.e(TAG, "Error parsing device profile", e);
return Collections.emptyList();
}
return result;
}
private int getLauncherIconDensity(int requiredSize) {
// Densities typically defined by an app.
int[] densityBuckets = new int[] {
int[] densityBuckets = new int[]{
DisplayMetrics.DENSITY_LOW,
DisplayMetrics.DENSITY_MEDIUM,
DisplayMetrics.DENSITY_TV,
@@ -518,12 +567,12 @@ public class InvariantDeviceProfile {
}
private static DisplayOption invDistWeightedInterpolate(
Info displayInfo, ArrayList<DisplayOption> points, boolean isSplitDisplay) {
Info displayInfo, ArrayList<DisplayOption> points, @DeviceType int deviceType) {
int minWidthPx = Integer.MAX_VALUE;
int minHeightPx = Integer.MAX_VALUE;
for (WindowBounds bounds : displayInfo.supportedBounds) {
boolean isTablet = displayInfo.isTablet(bounds);
if (isTablet && isSplitDisplay) {
if (isTablet && deviceType == TYPE_MULTI_DISPLAY) {
// For split displays, take half width per page
minWidthPx = Math.min(minWidthPx, bounds.availableSize.x / 2);
minHeightPx = Math.min(minHeightPx, bounds.availableSize.y);
@@ -546,37 +595,48 @@ public class InvariantDeviceProfile {
Float.compare(dist(width, height, a.minWidthDps, a.minHeightDps),
dist(width, height, b.minWidthDps, b.minHeightDps)));
GridOption closestOption = points.get(0).grid;
DisplayOption closestPoint = points.get(0);
GridOption closestOption = closestPoint.grid;
float weights = 0;
DisplayOption p = points.get(0);
if (dist(width, height, p.minWidthDps, p.minHeightDps) == 0) {
return p;
if (dist(width, height, closestPoint.minWidthDps, closestPoint.minHeightDps) == 0) {
return closestPoint;
}
DisplayOption out = new DisplayOption(closestOption);
for (int i = 0; i < points.size() && i < KNEARESTNEIGHBOR; ++i) {
p = points.get(i);
DisplayOption p = points.get(i);
float w = weight(width, height, p.minWidthDps, p.minHeightDps, WEIGHT_POWER);
weights += w;
out.add(new DisplayOption().add(p).multiply(w));
}
return out.multiply(1.0f / weights);
out.multiply(1.0f / weights);
// Since the bitmaps are persisted, ensure that all bitmap sizes are not larger than
// predefined size to avoid cache invalidation
for (int i = INDEX_DEFAULT; i < COUNT_SIZES; i++) {
out.iconSizes[i] = Math.min(out.iconSizes[i], closestPoint.iconSizes[i]);
}
return out;
}
public DeviceProfile getDeviceProfile(Context context) {
Resources res = context.getResources();
Configuration config = context.getResources().getConfiguration();
float availableWidth = config.screenWidthDp * res.getDisplayMetrics().density;
float availableHeight = config.screenHeightDp * res.getDisplayMetrics().density;
float screenWidth = config.screenWidthDp * res.getDisplayMetrics().density;
float screenHeight = config.screenHeightDp * res.getDisplayMetrics().density;
return getBestMatch(screenWidth, screenHeight);
}
public DeviceProfile getBestMatch(float screenWidth, float screenHeight) {
DeviceProfile bestMatch = supportedProfiles.get(0);
float minDiff = Float.MAX_VALUE;
for (DeviceProfile profile : supportedProfiles) {
float diff = Math.abs(profile.availableWidthPx - availableWidth)
+ Math.abs(profile.availableHeightPx - availableHeight);
float diff = Math.abs(profile.widthPx - screenWidth)
+ Math.abs(profile.heightPx - screenHeight);
if (diff < minDiff) {
minDiff = diff;
bestMatch = profile;
@@ -605,8 +665,8 @@ public class InvariantDeviceProfile {
// We will use these two data points to extrapolate how much the wallpaper parallax effect
// to span (ie travel) at any aspect ratio:
final float ASPECT_RATIO_LANDSCAPE = 16/10f;
final float ASPECT_RATIO_PORTRAIT = 10/16f;
final float ASPECT_RATIO_LANDSCAPE = 16 / 10f;
final float ASPECT_RATIO_PORTRAIT = 10 / 16f;
final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f;
final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f;
@@ -616,7 +676,8 @@ public class InvariantDeviceProfile {
// (10/16)x + y = 1.2
// We solve for x and y and end up with a final formula:
final float x =
(WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) /
(WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE
- WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) /
(ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT);
final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT;
return x * aspectRatio + y;
@@ -627,7 +688,7 @@ public class InvariantDeviceProfile {
/**
* Called when the device provide changes
*/
void onIdpChanged(InvariantDeviceProfile profile);
void onIdpChanged(boolean modelPropertiesChanged);
}
@@ -635,9 +696,16 @@ public class InvariantDeviceProfile {
public static final String TAG_NAME = "grid-option";
private static final int DEVICE_CATEGORY_PHONE = 1 << 0;
private static final int DEVICE_CATEGORY_TABLET = 1 << 1;
private static final int DEVICE_CATEGORY_MULTI_DISPLAY = 1 << 2;
private static final int DEVICE_CATEGORY_ALL =
DEVICE_CATEGORY_PHONE | DEVICE_CATEGORY_TABLET | DEVICE_CATEGORY_MULTI_DISPLAY;
public final String name;
public final int numRows;
public final int numColumns;
public final boolean isEnabled;
public final int numFolderRows;
public final int numFolderColumns;
@@ -657,7 +725,7 @@ public class InvariantDeviceProfile {
private final SparseArray<TypedValue> extraAttrs;
public GridOption(Context context, AttributeSet attrs) {
public GridOption(Context context, AttributeSet attrs, @DeviceType int deviceType) {
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.GridDisplayOption);
name = a.getString(R.styleable.GridDisplayOption_name);
@@ -665,8 +733,10 @@ public class InvariantDeviceProfile {
numColumns = a.getInt(R.styleable.GridDisplayOption_numColumns, 0);
dbFile = a.getString(R.styleable.GridDisplayOption_dbFile);
defaultLayoutId = a.getResourceId(
R.styleable.GridDisplayOption_defaultLayoutId, 0);
defaultLayoutId = a.getResourceId(deviceType == TYPE_MULTI_DISPLAY && a.hasValue(
R.styleable.GridDisplayOption_defaultSplitDisplayLayoutId)
? R.styleable.GridDisplayOption_defaultSplitDisplayLayoutId
: R.styleable.GridDisplayOption_defaultLayoutId, 0);
demoModeLayoutId = a.getResourceId(
R.styleable.GridDisplayOption_demoModeLayoutId, defaultLayoutId);
@@ -690,6 +760,16 @@ public class InvariantDeviceProfile {
devicePaddingId = a.getResourceId(
R.styleable.GridDisplayOption_devicePaddingId, 0);
int deviceCategory = a.getInt(R.styleable.GridDisplayOption_deviceCategory,
DEVICE_CATEGORY_ALL);
isEnabled = (deviceType == TYPE_PHONE
&& ((deviceCategory & DEVICE_CATEGORY_PHONE) == DEVICE_CATEGORY_PHONE))
|| (deviceType == TYPE_TABLET
&& ((deviceCategory & DEVICE_CATEGORY_TABLET) == DEVICE_CATEGORY_TABLET))
|| (deviceType == TYPE_MULTI_DISPLAY
&& ((deviceCategory & DEVICE_CATEGORY_MULTI_DISPLAY)
== DEVICE_CATEGORY_MULTI_DISPLAY));
a.recycle();
extraAttrs = Themes.createValueMap(context, attrs,
IntArray.wrap(R.styleable.GridDisplayOption));
@@ -705,44 +785,119 @@ public class InvariantDeviceProfile {
private final float minHeightDps;
private final boolean canBeDefault;
private float minCellHeight;
private float minCellWidth;
private float borderSpacing;
private final PointF[] minCellSize = new PointF[COUNT_SIZES];
private float iconSize;
private float iconTextSize;
private float landscapeIconSize;
private float landscapeIconTextSize;
private float allAppsIconSize;
private float allAppsIconTextSize;
private float folderBorderSpace;
private final PointF[] borderSpaces = new PointF[COUNT_SIZES];
private final float[] horizontalMargin = new float[COUNT_SIZES];
DisplayOption(GridOption grid, Context context, AttributeSet attrs, int defaultFlagValue) {
private final float[] iconSizes = new float[COUNT_SIZES];
private final float[] textSizes = new float[COUNT_SIZES];
DisplayOption(GridOption grid, Context context, AttributeSet attrs) {
this.grid = grid;
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.ProfileDisplayOption);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ProfileDisplayOption);
minWidthDps = a.getFloat(R.styleable.ProfileDisplayOption_minWidthDps, 0);
minHeightDps = a.getFloat(R.styleable.ProfileDisplayOption_minHeightDps, 0);
canBeDefault = a.getInt(R.styleable.ProfileDisplayOption_canBeDefault, 0)
== defaultFlagValue;
canBeDefault = a.getBoolean(R.styleable.ProfileDisplayOption_canBeDefault, false);
minCellHeight = a.getFloat(R.styleable.ProfileDisplayOption_minCellHeightDps, 0);
minCellWidth = a.getFloat(R.styleable.ProfileDisplayOption_minCellWidthDps, 0);
borderSpacing = a.getFloat(R.styleable.ProfileDisplayOption_borderSpacingDps, 0);
float x;
float y;
iconSize = a.getFloat(R.styleable.ProfileDisplayOption_iconImageSize, 0);
landscapeIconSize = a.getFloat(R.styleable.ProfileDisplayOption_landscapeIconSize,
iconSize);
iconTextSize = a.getFloat(R.styleable.ProfileDisplayOption_iconTextSize, 0);
landscapeIconTextSize = a.getFloat(
R.styleable.ProfileDisplayOption_landscapeIconTextSize, iconTextSize);
x = a.getFloat(R.styleable.ProfileDisplayOption_minCellWidthDps, 0);
y = a.getFloat(R.styleable.ProfileDisplayOption_minCellHeightDps, 0);
minCellSize[INDEX_DEFAULT] = new PointF(x, y);
minCellSize[INDEX_LANDSCAPE] = new PointF(x, y);
minCellSize[INDEX_ALL_APPS] = new PointF(x, y);
x = a.getFloat(R.styleable.ProfileDisplayOption_twoPanelPortraitMinCellWidthDps,
minCellSize[INDEX_DEFAULT].x);
y = a.getFloat(R.styleable.ProfileDisplayOption_twoPanelPortraitMinCellHeightDps,
minCellSize[INDEX_DEFAULT].y);
minCellSize[INDEX_TWO_PANEL_PORTRAIT] = new PointF(x, y);
x = a.getFloat(R.styleable.ProfileDisplayOption_twoPanelLandscapeMinCellWidthDps,
minCellSize[INDEX_DEFAULT].x);
y = a.getFloat(R.styleable.ProfileDisplayOption_twoPanelLandscapeMinCellHeightDps,
minCellSize[INDEX_DEFAULT].y);
minCellSize[INDEX_TWO_PANEL_LANDSCAPE] = new PointF(x, y);
float borderSpace = a.getFloat(R.styleable.ProfileDisplayOption_borderSpaceDps, 0);
float twoPanelPortraitBorderSpaceDps = a.getFloat(
R.styleable.ProfileDisplayOption_twoPanelPortraitBorderSpaceDps, borderSpace);
float twoPanelLandscapeBorderSpaceDps = a.getFloat(
R.styleable.ProfileDisplayOption_twoPanelLandscapeBorderSpaceDps, borderSpace);
x = a.getFloat(R.styleable.ProfileDisplayOption_borderSpaceHorizontalDps, borderSpace);
y = a.getFloat(R.styleable.ProfileDisplayOption_borderSpaceVerticalDps, borderSpace);
borderSpaces[INDEX_DEFAULT] = new PointF(x, y);
borderSpaces[INDEX_LANDSCAPE] = new PointF(x, y);
x = a.getFloat(
R.styleable.ProfileDisplayOption_twoPanelPortraitBorderSpaceHorizontalDps,
twoPanelPortraitBorderSpaceDps);
y = a.getFloat(
R.styleable.ProfileDisplayOption_twoPanelPortraitBorderSpaceVerticalDps,
twoPanelPortraitBorderSpaceDps);
borderSpaces[INDEX_TWO_PANEL_PORTRAIT] = new PointF(x, y);
x = a.getFloat(
R.styleable.ProfileDisplayOption_twoPanelLandscapeBorderSpaceHorizontalDps,
twoPanelLandscapeBorderSpaceDps);
y = a.getFloat(
R.styleable.ProfileDisplayOption_twoPanelLandscapeBorderSpaceVerticalDps,
twoPanelLandscapeBorderSpaceDps);
borderSpaces[INDEX_TWO_PANEL_LANDSCAPE] = new PointF(x, y);
x = y = a.getFloat(R.styleable.ProfileDisplayOption_allAppsCellSpacingDps,
borderSpace);
borderSpaces[INDEX_ALL_APPS] = new PointF(x, y);
folderBorderSpace = borderSpace;
iconSizes[INDEX_DEFAULT] =
a.getFloat(R.styleable.ProfileDisplayOption_iconImageSize, 0);
iconSizes[INDEX_LANDSCAPE] =
a.getFloat(R.styleable.ProfileDisplayOption_landscapeIconSize,
iconSizes[INDEX_DEFAULT]);
iconSizes[INDEX_ALL_APPS] =
a.getFloat(R.styleable.ProfileDisplayOption_allAppsIconSize,
iconSizes[INDEX_DEFAULT]);
iconSizes[INDEX_TWO_PANEL_PORTRAIT] =
a.getFloat(R.styleable.ProfileDisplayOption_twoPanelPortraitIconSize,
iconSizes[INDEX_DEFAULT]);
iconSizes[INDEX_TWO_PANEL_LANDSCAPE] =
a.getFloat(R.styleable.ProfileDisplayOption_twoPanelLandscapeIconSize,
iconSizes[INDEX_DEFAULT]);
textSizes[INDEX_DEFAULT] =
a.getFloat(R.styleable.ProfileDisplayOption_iconTextSize, 0);
textSizes[INDEX_LANDSCAPE] =
a.getFloat(R.styleable.ProfileDisplayOption_landscapeIconTextSize,
textSizes[INDEX_DEFAULT]);
textSizes[INDEX_ALL_APPS] =
a.getFloat(R.styleable.ProfileDisplayOption_allAppsIconTextSize,
textSizes[INDEX_DEFAULT]);
textSizes[INDEX_TWO_PANEL_PORTRAIT] =
a.getFloat(R.styleable.ProfileDisplayOption_twoPanelPortraitIconTextSize,
textSizes[INDEX_DEFAULT]);
textSizes[INDEX_TWO_PANEL_LANDSCAPE] =
a.getFloat(R.styleable.ProfileDisplayOption_twoPanelLandscapeIconTextSize,
textSizes[INDEX_DEFAULT]);
horizontalMargin[INDEX_DEFAULT] = a.getFloat(
R.styleable.ProfileDisplayOption_horizontalMargin, 0);
horizontalMargin[INDEX_LANDSCAPE] = horizontalMargin[INDEX_DEFAULT];
horizontalMargin[INDEX_ALL_APPS] = horizontalMargin[INDEX_DEFAULT];
horizontalMargin[INDEX_TWO_PANEL_LANDSCAPE] = a.getFloat(
R.styleable.ProfileDisplayOption_twoPanelLandscapeHorizontalMargin,
horizontalMargin[INDEX_DEFAULT]);
horizontalMargin[INDEX_TWO_PANEL_PORTRAIT] = a.getFloat(
R.styleable.ProfileDisplayOption_twoPanelPortraitHorizontalMargin,
horizontalMargin[INDEX_DEFAULT]);
allAppsIconSize = a.getFloat(R.styleable.ProfileDisplayOption_allAppsIconSize,
iconSize);
allAppsIconTextSize = a.getFloat(R.styleable.ProfileDisplayOption_allAppsIconTextSize,
iconTextSize);
a.recycle();
}
@@ -755,34 +910,43 @@ public class InvariantDeviceProfile {
minWidthDps = 0;
minHeightDps = 0;
canBeDefault = false;
minCellHeight = 0;
minCellWidth = 0;
borderSpacing = 0;
for (int i = 0; i < COUNT_SIZES; i++) {
iconSizes[i] = 0;
textSizes[i] = 0;
borderSpaces[i] = new PointF();
minCellSize[i] = new PointF();
}
}
private DisplayOption multiply(float w) {
iconSize *= w;
landscapeIconSize *= w;
allAppsIconSize *= w;
iconTextSize *= w;
landscapeIconTextSize *= w;
allAppsIconTextSize *= w;
minCellHeight *= w;
minCellWidth *= w;
borderSpacing *= w;
for (int i = 0; i < COUNT_SIZES; i++) {
iconSizes[i] *= w;
textSizes[i] *= w;
borderSpaces[i].x *= w;
borderSpaces[i].y *= w;
minCellSize[i].x *= w;
minCellSize[i].y *= w;
horizontalMargin[i] *= w;
}
folderBorderSpace *= w;
return this;
}
private DisplayOption add(DisplayOption p) {
iconSize += p.iconSize;
landscapeIconSize += p.landscapeIconSize;
allAppsIconSize += p.allAppsIconSize;
iconTextSize += p.iconTextSize;
landscapeIconTextSize += p.landscapeIconTextSize;
allAppsIconTextSize += p.allAppsIconTextSize;
minCellHeight += p.minCellHeight;
minCellWidth += p.minCellWidth;
borderSpacing += p.borderSpacing;
for (int i = 0; i < COUNT_SIZES; i++) {
iconSizes[i] += p.iconSizes[i];
textSizes[i] += p.textSizes[i];
borderSpaces[i].x += p.borderSpaces[i].x;
borderSpaces[i].y += p.borderSpaces[i].y;
minCellSize[i].x += p.minCellSize[i].x;
minCellSize[i].y += p.minCellSize[i].y;
horizontalMargin[i] += p.horizontalMargin[i];
}
folderBorderSpace += p.folderBorderSpace;
return this;
}
}
+295 -123
View File
@@ -25,10 +25,13 @@ import static android.view.View.IMPORTANT_FOR_ACCESSIBILITY_NO;
import static android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
import static com.android.launcher3.AbstractFloatingView.TYPE_ALL;
import static com.android.launcher3.AbstractFloatingView.TYPE_FOLDER;
import static com.android.launcher3.AbstractFloatingView.TYPE_ICON_SURFACE;
import static com.android.launcher3.AbstractFloatingView.TYPE_REBIND_SAFE;
import static com.android.launcher3.AbstractFloatingView.TYPE_SNACKBAR;
import static com.android.launcher3.AbstractFloatingView.getTopOpenViewWithType;
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.LauncherState.ALL_APPS;
import static com.android.launcher3.LauncherState.FLAG_CLOSE_POPUPS;
import static com.android.launcher3.LauncherState.FLAG_MULTI_PAGE;
@@ -39,6 +42,7 @@ import static com.android.launcher3.LauncherState.NO_SCALE;
import static com.android.launcher3.LauncherState.SPRING_LOADED;
import static com.android.launcher3.Utilities.postAsyncCallback;
import static com.android.launcher3.accessibility.LauncherAccessibilityDelegate.getSupportedActions;
import static com.android.launcher3.config.FeatureFlags.ADAPTIVE_ICON_WINDOW_ANIM;
import static com.android.launcher3.dragndrop.DragLayer.ALPHA_INDEX_LAUNCHER_LOAD;
import static com.android.launcher3.logging.StatsLogManager.LAUNCHER_STATE_BACKGROUND;
import static com.android.launcher3.logging.StatsLogManager.LAUNCHER_STATE_HOME;
@@ -50,12 +54,12 @@ import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCH
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_WIDGET_RECONFIGURED;
import static com.android.launcher3.model.ItemInstallQueue.FLAG_ACTIVITY_PAUSED;
import static com.android.launcher3.model.ItemInstallQueue.FLAG_DRAG_AND_DROP;
import static com.android.launcher3.model.ItemInstallQueue.FLAG_LOADER_RUNNING;
import static com.android.launcher3.popup.SystemShortcut.APP_INFO;
import static com.android.launcher3.popup.SystemShortcut.INSTALL;
import static com.android.launcher3.popup.SystemShortcut.WIDGETS;
import static com.android.launcher3.states.RotationHelper.REQUEST_LOCK;
import static com.android.launcher3.states.RotationHelper.REQUEST_NONE;
import static com.android.launcher3.util.ItemInfoMatcher.forFolderMatch;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -82,6 +86,7 @@ import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
@@ -89,6 +94,8 @@ import android.os.Parcelable;
import android.os.Process;
import android.os.StrictMode;
import android.os.SystemClock;
import android.os.Trace;
import android.os.UserHandle;
import android.text.TextUtils;
import android.text.method.TextKeyListener;
import android.util.Log;
@@ -108,6 +115,7 @@ import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.annotation.VisibleForTesting;
@@ -119,6 +127,7 @@ import com.android.launcher3.allapps.AllAppsContainerView;
import com.android.launcher3.allapps.AllAppsStore;
import com.android.launcher3.allapps.AllAppsTransitionController;
import com.android.launcher3.allapps.DiscoveryBounce;
import com.android.launcher3.anim.AnimatorListeners;
import com.android.launcher3.anim.PropertyListBuilder;
import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.config.FeatureFlags;
@@ -151,6 +160,7 @@ import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.notification.NotificationListener;
import com.android.launcher3.pm.PinRequestHelper;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.popup.ArrowPopup;
import com.android.launcher3.popup.PopupContainerWithArrow;
import com.android.launcher3.popup.PopupDataProvider;
import com.android.launcher3.popup.SystemShortcut;
@@ -168,6 +178,7 @@ import com.android.launcher3.util.ActivityResultInfo;
import com.android.launcher3.util.ActivityTracker;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.MultiValueAlpha;
import com.android.launcher3.util.MultiValueAlpha.AlphaProperty;
@@ -175,6 +186,7 @@ import com.android.launcher3.util.OnboardingPrefs;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.util.PendingRequestArgs;
import com.android.launcher3.util.RunnableList;
import com.android.launcher3.util.SafeCloseable;
import com.android.launcher3.util.SystemUiController;
import com.android.launcher3.util.Themes;
@@ -209,6 +221,7 @@ import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -222,7 +235,8 @@ import app.lawnchair.LawnchairApp;
* Default launcher application.
*/
public class Launcher extends StatefulActivity<LauncherState> implements LauncherExterns,
Callbacks, InvariantDeviceProfile.OnIDPChangeListener, PluginListener<OverlayPlugin> {
Callbacks, InvariantDeviceProfile.OnIDPChangeListener, PluginListener<OverlayPlugin>,
LauncherOverlayCallbacks {
public static final String TAG = "Launcher";
public static final ActivityTracker<Launcher> ACTIVITY_TRACKER = new ActivityTracker<>();
@@ -250,8 +264,6 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
*/
protected static final int REQUEST_LAST = 100;
// Type: int
private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
// Type: int
private static final String RUNTIME_STATE = "launcher.state";
// Type: PendingRequestArgs
@@ -262,6 +274,8 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
private static final String RUNTIME_STATE_PENDING_ACTIVITY_RESULT = "launcher.activity_result";
// Type: SparseArray<Parcelable>
private static final String RUNTIME_STATE_WIDGET_PANEL = "launcher.widget_panel";
// Type int[]
private static final String RUNTIME_STATE_CURRENT_SCREEN_IDS = "launcher.current_screen_ids";
public static final String ON_CREATE_EVT = "Launcher.onCreate";
public static final String ON_START_EVT = "Launcher.onStart";
@@ -279,6 +293,11 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
private static final int THEME_CROSS_FADE_ANIMATION_DURATION = 375;
private static final String DISPLAY_WORKSPACE_TRACE_METHOD_NAME = "DisplayWorkspaceFirstFrame";
private static final String DISPLAY_ALL_APPS_TRACE_METHOD_NAME = "DisplayAllApps";
public static final int DISPLAY_WORKSPACE_TRACE_COOKIE = 0;
public static final int DISPLAY_ALL_APPS_TRACE_COOKIE = 1;
private Configuration mOldConfig;
@Thunk
@@ -325,8 +344,8 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
private PopupDataProvider mPopupDataProvider;
private int mSynchronouslyBoundPage = PagedView.INVALID_PAGE;
private int mPageToBindSynchronously = PagedView.INVALID_PAGE;
private IntSet mSynchronouslyBoundPages = new IntSet();
@NonNull private IntSet mPagesToBindSynchronously = new IntSet();
// We only want to get the SharedPreferences once since it does an FS stat each time we get
// it from the context.
@@ -365,7 +384,15 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
private LauncherState mPrevLauncherState;
@Override
@TargetApi(Build.VERSION_CODES.S)
protected void onCreate(Bundle savedInstanceState) {
// Only use a hard-coded cookie since we only want to trace this once.
if (Utilities.ATLEAST_S) {
Trace.beginAsyncSection(
DISPLAY_WORKSPACE_TRACE_METHOD_NAME, DISPLAY_WORKSPACE_TRACE_COOKIE);
Trace.beginAsyncSection(DISPLAY_ALL_APPS_TRACE_METHOD_NAME,
DISPLAY_ALL_APPS_TRACE_COOKIE);
}
Object traceToken = TraceHelper.INSTANCE.beginSection(ON_CREATE_EVT,
TraceHelper.FLAG_UI_EVENT);
if (DEBUG_STRICT_MODE) {
@@ -462,13 +489,12 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
restoreState(savedInstanceState);
mStateManager.reapplyState();
// We only load the page synchronously if the user rotates (or triggers a
// configuration change) while launcher is in the foreground
int currentScreen = PagedView.INVALID_PAGE;
if (savedInstanceState != null) {
currentScreen = savedInstanceState.getInt(RUNTIME_STATE_CURRENT_SCREEN, currentScreen);
int[] pageIds = savedInstanceState.getIntArray(RUNTIME_STATE_CURRENT_SCREEN_IDS);
if (pageIds != null) {
mPagesToBindSynchronously = IntSet.wrap(pageIds);
}
}
mPageToBindSynchronously = currentScreen;
if (!mModel.addCallbacksAndLoad(this)) {
if (!internalStateHandled) {
@@ -556,11 +582,19 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
AbstractFloatingView.closeOpenViews(this, false, TYPE_ICON_SURFACE);
}
@Override
public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
super.onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
// Always update device profile when multi window mode changed.
initDeviceProfile(mDeviceProfile.inv);
dispatchDeviceProfileChanged();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
int diff = newConfig.diff(mOldConfig);
if ((diff & (CONFIG_ORIENTATION | CONFIG_SCREEN_SIZE)) != 0) {
onIdpChanged(mDeviceProfile.inv);
onIdpChanged(false);
}
mOldConfig.setTo(newConfig);
@@ -568,8 +602,8 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
}
@Override
public void onIdpChanged(InvariantDeviceProfile idp) {
initDeviceProfile(idp);
public void onIdpChanged(boolean modelPropertiesChanged) {
initDeviceProfile(mDeviceProfile.inv);
dispatchDeviceProfileChanged();
reapplyUi();
mDragLayer.recreateControllers();
@@ -601,7 +635,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
}
onDeviceProfileInitiated();
mModelWriter = mModel.getWriter(getDeviceProfile().isVerticalBarLayout(), true);
mModelWriter = mModel.getWriter(getDeviceProfile().isVerticalBarLayout(), true, this);
}
public RotationHelper getRotationHelper() {
@@ -625,7 +659,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
@Override
public void setLauncherOverlay(LauncherOverlay overlay) {
if (overlay != null) {
overlay.setOverlayCallbacks(new LauncherOverlayCallbacksImpl());
overlay.setOverlayCallbacks(this);
}
mWorkspace.setLauncherOverlay(overlay);
}
@@ -873,11 +907,11 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
if (dropLayout == null) {
// it's possible that the add screen was removed because it was
// empty and a re-bind occurred
mWorkspace.addExtraEmptyScreen();
return mWorkspace.commitExtraEmptyScreen();
} else {
return screenId;
mWorkspace.addExtraEmptyScreens();
IntSet emptyPagesAdded = mWorkspace.commitExtraEmptyScreens();
return emptyPagesAdded.isEmpty() ? -1 : emptyPagesAdded.getArray().get(0);
}
return screenId;
}
@Thunk
@@ -1129,12 +1163,15 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
mAppWidgetHost.setActivityResumed(false);
}
class LauncherOverlayCallbacksImpl implements LauncherOverlayCallbacks {
public void onScrollChanged(float progress) {
if (mWorkspace != null) {
mWorkspace.onOverlayScrollChanged(progress);
}
/**
* {@code LauncherOverlayCallbacks} scroll amount.
* Indicates transition progress to -1 screen.
* @param progress From 0 to 1.
*/
@Override
public void onScrollChanged(float progress) {
if (mWorkspace != null) {
mWorkspace.onOverlayScrollChanged(progress);
}
}
@@ -1194,7 +1231,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
// Until the workspace is bound, ensure that we keep the wallpaper offset locked to the
// default state, otherwise we will update to the wrong offsets in RTL
mWorkspace.lockWallpaperToDefaultPage();
mWorkspace.bindAndInitFirstWorkspaceScreen(null /* recycled qsb */);
mWorkspace.bindAndInitFirstWorkspaceScreen();
mDragController.addDragListener(mWorkspace);
// Get the search/delete/uninstall bar
@@ -1241,7 +1278,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
*
* @param data The intent describing the shortcut.
*/
private void completeAddShortcut(Intent data, int container, int screenId, int cellX,
protected void completeAddShortcut(Intent data, int container, int screenId, int cellX,
int cellY, PendingRequestArgs args) {
if (args.getRequestCode() != REQUEST_CREATE_SHORTCUT
|| args.getPendingIntent().getComponent() == null) {
@@ -1296,7 +1333,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
}
if (!foundCellSpan) {
mWorkspace.onNoCellFound(layout);
mWorkspace.onNoCellFound(layout, info, /* logInstanceId= */ null);
return;
}
@@ -1314,7 +1351,8 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
}
}
public FolderIcon findFolderIcon(final int folderIconId) {
@Override
public @Nullable FolderIcon findFolderIcon(final int folderIconId) {
return (FolderIcon) mWorkspace.getHomescreenIconByItemId(folderIconId);
}
@@ -1365,22 +1403,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
final LauncherAppWidgetHostView launcherHostView = (LauncherAppWidgetHostView) hostView;
CellLayout cellLayout = getCellLayout(launcherInfo.container, launcherInfo.screenId);
if (mStateManager.getState() == NORMAL) {
// Show resize frame once the widget layout is drawn.
View.OnLayoutChangeListener onLayoutChangeListener =
new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View view, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight,
int oldBottom) {
AppWidgetResizeFrame.showForWidget(launcherHostView, cellLayout);
launcherHostView.removeOnLayoutChangeListener(this);
}
};
launcherHostView.addOnLayoutChangeListener(onLayoutChangeListener);
// There is a small chance that the layout was already drawn before the layout
// change listener was registered, which means that the resize frame wouldn't be
// shown. Directly call requestLayout to force a layout change.
launcherHostView.requestLayout();
AppWidgetResizeFrame.showForWidget(launcherHostView, cellLayout);
} else {
mStateManager.addStateListener(new StateManager.StateListener<LauncherState>() {
@Override
@@ -1593,18 +1616,22 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
@Override
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
mWorkspace.restoreInstanceStateForChild(mSynchronouslyBoundPage);
if (mSynchronouslyBoundPages != null) {
mSynchronouslyBoundPages.forEach(screenId -> {
int pageIndex = mWorkspace.getPageIndexForScreenId(screenId);
if (pageIndex != PagedView.INVALID_PAGE) {
mWorkspace.restoreInstanceStateForChild(pageIndex);
}
});
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mWorkspace.getChildCount() > 0) {
outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getNextPage());
}
outState.putIntArray(RUNTIME_STATE_CURRENT_SCREEN_IDS,
mWorkspace.getCurrentPageScreenIds().getArray().toArray());
outState.putInt(RUNTIME_STATE, mStateManager.getState().ordinal);
AbstractFloatingView widgets = AbstractFloatingView
.getOpenView(this, AbstractFloatingView.TYPE_WIDGETS_FULL_SHEET);
if (widgets != null) {
@@ -1620,6 +1647,8 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
AbstractFloatingView.closeOpenViews(this, false, TYPE_ALL & ~TYPE_REBIND_SAFE);
finishAutoCancelActionMode();
DragView.removeAllViews(this);
if (mPendingRequestArgs != null) {
outState.putParcelable(RUNTIME_STATE_PENDING_REQUEST_ARGS, mPendingRequestArgs);
}
@@ -1927,7 +1956,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
TestLogging.recordEvent(TestProtocol.SEQUENCE_MAIN, "Key event", event);
TestLogging.recordKeyEvent(TestProtocol.SEQUENCE_MAIN, "Key event", event);
return (event.getKeyCode() == KeyEvent.KEYCODE_HOME) || super.dispatchKeyEvent(event);
}
@@ -2083,25 +2112,58 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
}
/**
* Sets the next page to bind synchronously on next bind.
* @param page
* Sets the next pages to bind synchronously on next bind.
* @param pages should not be null.
*/
public void setPageToBindSynchronously(int page) {
mPageToBindSynchronously = page;
public void setPagesToBindSynchronously(@NonNull IntSet pages) {
mPagesToBindSynchronously = pages;
}
/**
* Implementation of the method from LauncherModel.Callbacks.
*/
@Override
public int getPageToBindSynchronously() {
if (mPageToBindSynchronously != PagedView.INVALID_PAGE) {
return mPageToBindSynchronously;
} else if (mWorkspace != null) {
return mWorkspace.getCurrentPage();
public IntSet getPagesToBindSynchronously(IntArray orderedScreenIds) {
IntSet visibleIds;
if (!mPagesToBindSynchronously.isEmpty()) {
visibleIds = mPagesToBindSynchronously;
} else if (!mWorkspaceLoading) {
visibleIds = mWorkspace.getCurrentPageScreenIds();
} else {
return 0;
// If workspace binding is still in progress, getCurrentPageScreenIds won't be accurate,
// and we should use mSynchronouslyBoundPages that's set during initial binding.
visibleIds = mSynchronouslyBoundPages;
}
IntArray actualIds = new IntArray();
IntSet result = new IntSet();
if (visibleIds.isEmpty()) {
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NULL_INT_SET, "getPagesToBindSynchronously (1): "
+ result);
}
return result;
}
for (int id : orderedScreenIds.toArray()) {
actualIds.add(id);
}
int firstId = visibleIds.getArray().get(0);
int pairId = mWorkspace.getScreenPair(firstId);
// Double check that actual screenIds contains the visibleId, as empty screens are hidden
// in single panel.
if (actualIds.contains(firstId)) {
result.add(firstId);
if (mDeviceProfile.isTwoPanels && actualIds.contains(pairId)) {
result.add(pairId);
}
} else if (LauncherAppState.getIDP(this).supportedProfiles.stream().anyMatch(
deviceProfile -> deviceProfile.isTwoPanels) && actualIds.contains(pairId)) {
// Add the right panel if left panel is hidden when switching display, due to empty
// pages being hidden in single panel.
result.add(pairId);
}
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NULL_INT_SET, "getPagesToBindSynchronously (2): "
+ result);
}
return result;
}
/**
@@ -2111,7 +2173,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
@Override
public void clearPendingBinds() {
if (mPendingExecutor != null) {
mPendingExecutor.markCompleted();
mPendingExecutor.cancel();
mPendingExecutor = null;
// We might have set this flag previously and forgot to clear it.
@@ -2149,14 +2211,14 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
@Override
public void bindScreens(IntArray orderedScreenIds) {
// Make sure the first screen is always at the start.
int firstScreenPosition = 0;
if (FeatureFlags.topQsbOnFirstScreenEnabled(this) &&
orderedScreenIds.indexOf(Workspace.FIRST_SCREEN_ID) != 0) {
orderedScreenIds.indexOf(Workspace.FIRST_SCREEN_ID) != firstScreenPosition) {
orderedScreenIds.removeValue(Workspace.FIRST_SCREEN_ID);
orderedScreenIds.add(0, Workspace.FIRST_SCREEN_ID);
orderedScreenIds.add(firstScreenPosition, Workspace.FIRST_SCREEN_ID);
} else if (!FeatureFlags.topQsbOnFirstScreenEnabled(this) && orderedScreenIds.isEmpty()) {
// If there are no screens, we need to have an empty screen
mWorkspace.addExtraEmptyScreen();
mWorkspace.addExtraEmptyScreens();
}
bindAddScreens(orderedScreenIds);
@@ -2167,13 +2229,22 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
}
private void bindAddScreens(IntArray orderedScreenIds) {
if (mDeviceProfile.isTwoPanels) {
// Some empty pages might have been removed while the phone was in a single panel
// mode, so we want to add those empty pages back.
IntSet screenIds = IntSet.wrap(orderedScreenIds);
orderedScreenIds.forEach(screenId -> screenIds.add(mWorkspace.getScreenPair(screenId)));
orderedScreenIds = screenIds.getArray();
}
int count = orderedScreenIds.size();
for (int i = 0; i < count; i++) {
int screenId = orderedScreenIds.get(i);
if (!FeatureFlags.topQsbOnFirstScreenEnabled(this) || screenId != Workspace.FIRST_SCREEN_ID) {
if (FeatureFlags.topQsbOnFirstScreenEnabled(this) && screenId == Workspace.FIRST_SCREEN_ID) {
// No need to bind the first screen, as its always bound.
mWorkspace.insertNewWorkspaceScreenBeforeEmptyScreen(screenId);
continue;
}
mWorkspace.insertNewWorkspaceScreenBeforeEmptyScreen(screenId);
}
}
@@ -2193,6 +2264,9 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
ArrayList<ItemInfo> addAnimated) {
// Add the new screens
if (newScreens != null) {
// newScreens can contain an empty right panel that is already bound, but not known
// by BgDataModel.
newScreens.removeAllValues(mWorkspace.mScreenOrder);
bindAddScreens(newScreens);
}
@@ -2234,7 +2308,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
final boolean focusFirstItemForAccessibility) {
// Get the list of added items and intersect them with the set of items here
final Collection<Animator> bounceAnims = new ArrayList<>();
final boolean animateIcons = forceAnimateIcons && canRunNewAppsAnimation();
boolean canAnimatePageChange = canAnimatePageChange();
Workspace workspace = mWorkspace;
int newItemsScreenId = -1;
int end = items.size();
@@ -2295,7 +2369,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
}
}
workspace.addInScreenFromBind(view, item);
if (animateIcons) {
if (forceAnimateIcons) {
// Animate all the applications up now
view.setAlpha(0f);
view.setScaleX(0f);
@@ -2311,7 +2385,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
View viewToFocus = newView;
// Animate to the correct pager
if (animateIcons && newItemsScreenId > -1) {
if (forceAnimateIcons && newItemsScreenId > -1) {
AnimatorSet anim = new AnimatorSet();
anim.playTogether(bounceAnims);
if (focusFirstItemForAccessibility && viewToFocus != null) {
@@ -2327,7 +2401,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
final int newScreenIndex = mWorkspace.getPageIndexForScreenId(newItemsScreenId);
final Runnable startBounceAnimRunnable = anim::start;
if (newItemsScreenId != currentScreenId) {
if (canAnimatePageChange && newItemsScreenId != currentScreenId) {
// We post the animation slightly delayed to prevent slowdowns
// when we are loading right after we return to launcher.
mWorkspace.postDelayed(new Runnable() {
@@ -2538,25 +2612,6 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
return info;
}
public void onPageBoundSynchronously(int page) {
mSynchronouslyBoundPage = page;
mWorkspace.setCurrentPage(page);
mPageToBindSynchronously = PagedView.INVALID_PAGE;
}
@Override
public void executeOnNextDraw(ViewOnDrawExecutor executor) {
clearPendingBinds();
mPendingExecutor = executor;
if (!isInState(ALL_APPS)) {
mAppsView.getAppsStore().enableDeferUpdates(AllAppsStore.DEFER_UPDATES_NEXT_DRAW);
mPendingExecutor.execute(() -> mAppsView.getAppsStore().disableDeferUpdates(
AllAppsStore.DEFER_UPDATES_NEXT_DRAW));
}
executor.attachTo(this);
}
public void clearPendingExecutor(ViewOnDrawExecutor executor) {
if (mPendingExecutor == executor) {
mPendingExecutor = null;
@@ -2564,22 +2619,33 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
}
@Override
public void finishFirstPageBind(final ViewOnDrawExecutor executor) {
@TargetApi(Build.VERSION_CODES.S)
public void onInitialBindComplete(IntSet boundPages, RunnableList pendingTasks) {
mSynchronouslyBoundPages = boundPages;
mPagesToBindSynchronously = new IntSet();
clearPendingBinds();
ViewOnDrawExecutor executor = new ViewOnDrawExecutor(pendingTasks);
mPendingExecutor = executor;
if (!isInState(ALL_APPS)) {
mAppsView.getAppsStore().enableDeferUpdates(AllAppsStore.DEFER_UPDATES_NEXT_DRAW);
pendingTasks.add(() -> mAppsView.getAppsStore().disableDeferUpdates(
AllAppsStore.DEFER_UPDATES_NEXT_DRAW));
}
AlphaProperty property = mDragLayer.getAlphaProperty(ALPHA_INDEX_LAUNCHER_LOAD);
if (property.getValue() < 1) {
ObjectAnimator anim = ObjectAnimator.ofFloat(property, MultiValueAlpha.VALUE, 1);
if (executor != null) {
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
executor.onLoadAnimationCompleted();
}
});
}
anim.addListener(AnimatorListeners.forEndCallback(executor::onLoadAnimationCompleted));
anim.start();
} else if (executor != null) {
} else {
executor.onLoadAnimationCompleted();
}
executor.attachTo(this);
if (Utilities.ATLEAST_S) {
Trace.endAsyncSection(DISPLAY_WORKSPACE_TRACE_METHOD_NAME,
DISPLAY_WORKSPACE_TRACE_COOKIE);
}
}
/**
@@ -2587,7 +2653,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void finishBindingItems(int pageBoundFirst) {
public void finishBindingItems(IntSet pagesBoundFirst) {
Object traceToken = TraceHelper.INSTANCE.beginSection("finishBindingItems");
mWorkspace.restoreInstanceStateForRemainingPages();
@@ -2599,14 +2665,14 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
mPendingActivityResult = null;
}
ItemInstallQueue.INSTANCE.get(this)
.resumeModelPush(FLAG_LOADER_RUNNING);
int currentPage = pagesBoundFirst != null && !pagesBoundFirst.isEmpty()
? mWorkspace.getPageIndexForScreenId(pagesBoundFirst.getArray().get(0))
: PagedView.INVALID_PAGE;
// When undoing the removal of the last item on a page, return to that page.
// Since we are just resetting the current page without user interaction,
// override the previous page so we don't log the page switch.
mWorkspace.setCurrentPage(pageBoundFirst, pageBoundFirst /* overridePrevPage */);
mPageToBindSynchronously = PagedView.INVALID_PAGE;
mWorkspace.setCurrentPage(currentPage, currentPage /* overridePrevPage */);
mPagesToBindSynchronously = new IntSet();
// Cache one page worth of icons
getViewCache().setCacheSize(R.layout.folder_application,
@@ -2616,7 +2682,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
TraceHelper.INSTANCE.endSection(traceToken);
}
private boolean canRunNewAppsAnimation() {
private boolean canAnimatePageChange() {
if (mDragController.isDragging()) {
return false;
} else {
@@ -2625,6 +2691,79 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
}
}
/**
* Similar to {@link #getFirstMatch} but optimized to finding a suitable view for the app close
* animation.
*
* @param preferredItemId The id of the preferred item to match to if it exists.
* @param packageName The package name of the app to match.
* @param user The user of the app to match.
*/
public View getFirstMatchForAppClose(int preferredItemId, String packageName, UserHandle user) {
final ItemInfoMatcher preferredItem = (info, cn) ->
info != null && info.id == preferredItemId;
final ItemInfoMatcher packageAndUserAndApp = (info, cn) ->
info != null
&& info.itemType == ITEM_TYPE_APPLICATION
&& info.user.equals(user)
&& info.getTargetComponent() != null
&& TextUtils.equals(info.getTargetComponent().getPackageName(),
packageName);
if (isInState(LauncherState.ALL_APPS)) {
return getFirstMatch(Collections.singletonList(mAppsView.getActiveRecyclerView()),
preferredItem, packageAndUserAndApp);
} else {
List<ViewGroup> containers = new ArrayList<>(mWorkspace.getPanelCount() + 1);
containers.add(mWorkspace.getHotseat().getShortcutsAndWidgets());
mWorkspace.forEachVisiblePage(page
-> containers.add(((CellLayout) page).getShortcutsAndWidgets()));
// Order: Preferred item by itself or in folder, then by matching package/user
if (ADAPTIVE_ICON_WINDOW_ANIM.get()) {
return getFirstMatch(containers, preferredItem, forFolderMatch(preferredItem),
packageAndUserAndApp, forFolderMatch(packageAndUserAndApp));
} else {
// Do not use Folder as a criteria, since it'll cause a crash when trying to draw
// FolderAdaptiveIcon as the background.
return getFirstMatch(containers, preferredItem, packageAndUserAndApp);
}
}
}
/**
* Finds the first view matching the ordered operators across the given viewgroups in order.
* @param containers List of ViewGroups to scan, in order of preference.
* @param operators List of operators, in order starting from best matching operator.
*/
private static View getFirstMatch(Iterable<ViewGroup> containers,
final ItemInfoMatcher... operators) {
for (ItemInfoMatcher operator : operators) {
for (ViewGroup container : containers) {
View match = mapOverViewGroup(container, operator);
if (match != null) {
return match;
}
}
}
return null;
}
/**
* Returns the first view matching the operator in the given ViewGroups, or null if none.
* Forward iteration matters.
*/
private static View mapOverViewGroup(ViewGroup container, ItemInfoMatcher op) {
final int itemCount = container.getChildCount();
for (int itemIdx = 0; itemIdx < itemCount; itemIdx++) {
View item = container.getChildAt(itemIdx);
if (op.matchesInfo((ItemInfo) item.getTag())) {
return item;
}
}
return null;
}
private ValueAnimator createNewAppBounceAnimation(View v, int i) {
ValueAnimator bounceAnim = new PropertyListBuilder().alpha(1).scale(1).build(v)
.setDuration(ItemInstallQueue.NEW_SHORTCUT_BOUNCE_DURATION);
@@ -2643,9 +2782,14 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
* Implementation of the method from LauncherModel.Callbacks.
*/
@Override
@TargetApi(Build.VERSION_CODES.S)
public void bindAllApplications(AppInfo[] apps, int flags) {
mAppsView.getAppsStore().setApps(apps, flags);
PopupContainerWithArrow.dismissInvalidPopup(this);
if (Utilities.ATLEAST_S) {
Trace.endAsyncSection(DISPLAY_ALL_APPS_TRACE_METHOD_NAME,
DISPLAY_ALL_APPS_TRACE_COOKIE);
}
}
/**
@@ -2676,7 +2820,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
@Override
public void bindWorkspaceItemsChanged(List<WorkspaceItemInfo> updated) {
if (!updated.isEmpty()) {
mWorkspace.updateShortcuts(updated);
mWorkspace.updateWorkspaceItems(updated, this);
PopupContainerWithArrow.dismissInvalidPopup(this);
}
}
@@ -2688,7 +2832,7 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
*/
@Override
public void bindRestoreItemsChange(HashSet<ItemInfo> updates) {
mWorkspace.updateRestoreItems(updates);
mWorkspace.updateRestoreItems(updates, this);
}
/**
@@ -2840,13 +2984,39 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
if (Utilities.IS_RUNNING_IN_TEST_HARNESS) {
Log.d(TestProtocol.PERMANENT_DIAG_TAG, "Opening options popup on key up");
}
OptionsPopupView.showDefaultOptions(this, -1, -1);
showDefaultOptions(-1, -1);
}
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* Shows the default options popup
*/
public void showDefaultOptions(float x, float y) {
OptionsPopupView.show(this, getPopupTarget(x, y), OptionsPopupView.getOptions(this),
false);
}
/**
* Returns target rectangle for anchoring a popup menu.
*/
protected RectF getPopupTarget(float x, float y) {
float halfSize = getResources().getDimension(R.dimen.options_menu_thumb_size) / 2;
if (x < 0 || y < 0) {
x = mDragLayer.getWidth() / 2;
y = mDragLayer.getHeight() / 2;
}
return new RectF(x - halfSize, y - halfSize, x + halfSize, y + halfSize);
}
@Override
public boolean shouldUseColorExtractionForPopup() {
return getTopOpenViewWithType(this, TYPE_FOLDER) == null
&& getStateManager().getState() != LauncherState.ALL_APPS;
}
@Override
protected void collectStateHandlers(List<StateHandler> out) {
out.add(getAllAppsController());
@@ -2890,13 +3060,6 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
return new float[] {NO_SCALE, NO_OFFSET};
}
/**
* @see LauncherState#getTaskbarScale(Launcher)
*/
public float getNormalTaskbarScale() {
return 1f;
}
public static Launcher getLauncher(Context context) {
return fromContext(context);
}
@@ -2960,4 +3123,13 @@ public class Launcher extends StatefulActivity<LauncherState> implements Launche
public StatsLogManager getStatsLogManager() {
return super.getStatsLogManager().withDefaultInstanceId(mAllAppsSessionLogId);
}
/**
* Returns the current popup for testing, if any.
*/
@VisibleForTesting
@Nullable
public ArrowPopup<?> getOptionsPopup() {
return findViewById(R.id.popup_container);
}
}
+10 -12
View File
@@ -50,13 +50,12 @@ import com.android.launcher3.util.SafeCloseable;
import com.android.launcher3.util.SettingsCache;
import com.android.launcher3.util.SimpleBroadcastReceiver;
import com.android.launcher3.util.Themes;
import com.android.launcher3.widget.DatabaseWidgetPreviewLoader;
import com.android.launcher3.widget.custom.CustomWidgetManager;
import app.lawnchair.LawnchairAppKt;
import app.lawnchair.icons.LawnchairIconProvider;
public class LauncherAppState {
public class LauncherAppState implements SafeCloseable {
public static final String ACTION_FORCE_ROLOAD = "force-reload-launcher";
private static final String KEY_ICON_STATE = "pref_icon_shape_path";
@@ -76,7 +75,6 @@ public class LauncherAppState {
private final LauncherModel mModel;
private final IconProvider mIconProvider;
private final IconCache mIconCache;
private final DatabaseWidgetPreviewLoader mWidgetCache;
private final InvariantDeviceProfile mInvariantDeviceProfile;
private final RunnableList mOnTerminateCallback = new RunnableList();
@@ -97,7 +95,11 @@ public class LauncherAppState {
Log.v(Launcher.TAG, "LauncherAppState initiated");
Preconditions.assertUIThread();
mInvariantDeviceProfile.addOnChangeListener(idp -> refreshAndReloadLauncher());
mInvariantDeviceProfile.addOnChangeListener(modelPropertiesChanged -> {
if (modelPropertiesChanged) {
refreshAndReloadLauncher();
}
});
mContext.getSystemService(LauncherApps.class).registerCallback(mModel);
@@ -151,8 +153,8 @@ public class LauncherAppState {
mIconProvider = new LawnchairIconProvider(context, Themes.isThemedIconEnabled(context));
mIconCache = new IconCache(mContext, mInvariantDeviceProfile,
iconCacheFileName, mIconProvider);
mWidgetCache = new DatabaseWidgetPreviewLoader(mContext, mIconCache);
mModel = new LauncherModel(context, this, mIconCache, new AppFilter(mContext));
mModel = new LauncherModel(context, this, mIconCache, new AppFilter(mContext),
iconCacheFileName != null);
mOnTerminateCallback.add(mIconCache::close);
}
@@ -167,14 +169,14 @@ public class LauncherAppState {
LauncherIcons.clearPool();
mIconCache.updateIconParams(
mInvariantDeviceProfile.fillResIconDpi, mInvariantDeviceProfile.iconBitmapSize);
mWidgetCache.refresh();
mModel.forceReload();
}
/**
* Call from Application.onTerminate(), which is not guaranteed to ever be called.
*/
public void onTerminate() {
@Override
public void close() {
mModel.destroy();
mContext.getSystemService(LauncherApps.class).unregisterCallback(mModel);
CustomWidgetManager.INSTANCE.get(mContext).setWidgetRefreshCallback(null);
@@ -201,10 +203,6 @@ public class LauncherAppState {
return mModel;
}
public DatabaseWidgetPreviewLoader getWidgetCache() {
return mWidgetCache;
}
public InvariantDeviceProfile getInvariantDeviceProfile() {
return mInvariantDeviceProfile;
}
@@ -31,6 +31,6 @@ public class LauncherBackupAgent extends BackupAgent {
@Override
public void onRestoreFinished() {
RestoreDbTask.setPending(this, true);
RestoreDbTask.setPending(this);
}
}
+13 -2
View File
@@ -1,5 +1,6 @@
package com.android.launcher3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -15,6 +16,7 @@ public class LauncherFiles {
private static final String XML = ".xml";
public static final String LAUNCHER_DB = "launcher.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_4_DB = "launcher_4_by_4.db";
public static final String LAUNCHER_3_BY_3_DB = "launcher_3_by_3.db";
@@ -29,16 +31,25 @@ public class LauncherFiles {
public static final String WIDGET_PREVIEWS_DB = "widgetpreviews.db";
public static final String APP_ICONS_DB = "app_icons.db";
public static final List<String> ALL_FILES = Collections.unmodifiableList(Arrays.asList(
public static final List<String> GRID_DB_FILES = Collections.unmodifiableList(Arrays.asList(
LAUNCHER_DB,
LAUNCHER_6_BY_5_DB,
LAUNCHER_4_BY_5_DB,
LAUNCHER_4_BY_4_DB,
LAUNCHER_3_BY_3_DB,
LAUNCHER_2_BY_2_DB,
LAUNCHER_2_BY_2_DB));
public static final List<String> OTHER_FILES = Collections.unmodifiableList(Arrays.asList(
BACKUP_DB,
SHARED_PREFERENCES_KEY + XML,
WIDGET_PREVIEWS_DB,
MANAGED_USER_PREFERENCES_KEY + XML,
DEVICE_PREFERENCES_KEY + XML,
APP_ICONS_DB));
public static final List<String> ALL_FILES = Collections.unmodifiableList(
new ArrayList<String>() {{
addAll(GRID_DB_FILES);
addAll(OTHER_FILES);
}});
}
+50 -30
View File
@@ -62,6 +62,7 @@ import com.android.launcher3.pm.InstallSessionTracker;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.PackageUserKey;
@@ -74,6 +75,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
@@ -97,9 +99,10 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
// our monitoring of the package manager provides all updates and we never
// need to do a requery. This is only ever touched from the loader thread.
private boolean mModelLoaded;
private boolean mModelDestroyed = false;
public boolean isModelLoaded() {
synchronized (mLock) {
return mModelLoaded && mLoaderTask == null;
return mModelLoaded && mLoaderTask == null && !mModelDestroyed;
}
}
@@ -126,10 +129,12 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
}
};
LauncherModel(Context context, LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
LauncherModel(Context context, LauncherAppState app, IconCache iconCache, AppFilter appFilter,
boolean isPrimaryInstance) {
mApp = app;
mBgAllAppsList = new AllAppsList(iconCache, appFilter);
mModelDelegate = ModelDelegate.newInstance(context, app, mBgAllAppsList, mBgDataModel);
mModelDelegate = ModelDelegate.newInstance(context, app, mBgAllAppsList, mBgDataModel,
isPrimaryInstance);
}
public ModelDelegate getModelDelegate() {
@@ -146,9 +151,10 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
enqueueModelUpdateTask(new AddWorkspaceItemsTask(itemList));
}
public ModelWriter getWriter(boolean hasVerticalHotseat, boolean verifyChanges) {
public ModelWriter getWriter(boolean hasVerticalHotseat, boolean verifyChanges,
@Nullable Callbacks owner) {
return new ModelWriter(mApp.getContext(), this, mBgDataModel,
hasVerticalHotseat, verifyChanges);
hasVerticalHotseat, verifyChanges, owner);
}
@Override
@@ -245,6 +251,7 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
* Called when the model is destroyed
*/
public void destroy() {
mModelDestroyed = true;
MODEL_EXECUTOR.execute(mModelDelegate::destroy);
}
@@ -331,7 +338,7 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
public boolean addCallbacksAndLoad(Callbacks callbacks) {
synchronized (mLock) {
addCallbacks(callbacks);
return startLoader();
return startLoader(new Callbacks[] { callbacks });
}
}
@@ -342,6 +349,12 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
public void addCallbacks(Callbacks callbacks) {
Preconditions.assertUIThread();
synchronized (mCallbacksList) {
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NULL_INT_SET, "addCallbacks pointer: "
+ callbacks
+ ", name: "
+ callbacks.getClass().getName(), new Exception());
}
mCallbacksList.add(callbacks);
}
}
@@ -351,26 +364,32 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
* @return true if the page could be bound synchronously.
*/
public boolean startLoader() {
return startLoader(new Callbacks[0]);
}
private boolean startLoader(Callbacks[] newCallbacks) {
// Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems
ItemInstallQueue.INSTANCE.get(mApp.getContext())
.pauseModelPush(ItemInstallQueue.FLAG_LOADER_RUNNING);
synchronized (mLock) {
// Don't bother to start the thread if we know it's not going to do anything
final Callbacks[] callbacksList = getCallbacks();
// If there is already one running, tell it to stop.
boolean wasRunning = stopLoader();
boolean bindDirectly = mModelLoaded && !mIsLoaderTaskRunning;
boolean bindAllCallbacks = wasRunning || !bindDirectly || newCallbacks.length == 0;
final Callbacks[] callbacksList = bindAllCallbacks ? getCallbacks() : newCallbacks;
if (callbacksList.length > 0) {
// Clear any pending bind-runnables from the synchronized load process.
for (Callbacks cb : callbacksList) {
MAIN_EXECUTOR.execute(cb::clearPendingBinds);
}
// If there is already one running, tell it to stop.
stopLoader();
LoaderResults loaderResults = new LoaderResults(
mApp, mBgDataModel, mBgAllAppsList, callbacksList);
if (mModelLoaded && !mIsLoaderTaskRunning) {
if (bindDirectly) {
// Divide the set of loaded items into those that we are binding synchronously,
// and everything else that is to be bound normally (asynchronously).
loaderResults.bindWorkspace();
loaderResults.bindWorkspace(bindAllCallbacks);
// For now, continue posting the binding of AllApps as there are other
// issues that arise from that.
loaderResults.bindAllApps();
@@ -378,7 +397,13 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
loaderResults.bindWidgets();
return true;
} else {
startLoaderForResults(loaderResults);
stopLoader();
mLoaderTask = new LoaderTask(
mApp, mBgAllAppsList, mBgDataModel, mModelDelegate, loaderResults);
// Always post the loader task, instead of running directly
// (even on same thread) so that we exit any nested synchronized blocks
MODEL_EXECUTOR.post(mLoaderTask);
}
}
}
@@ -389,7 +414,7 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
* If there is already a loader task running, tell it to stop.
* @return true if an existing loader was stopped.
*/
public boolean stopLoader() {
private boolean stopLoader() {
synchronized (mLock) {
LoaderTask oldTask = mLoaderTask;
mLoaderTask = null;
@@ -401,25 +426,17 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
}
}
public void startLoaderForResults(LoaderResults results) {
/**
* Loads the model if not loaded
* @param callback called with the data model upon successful load or null on model thread.
*/
public void loadAsync(Consumer<BgDataModel> callback) {
synchronized (mLock) {
stopLoader();
mLoaderTask = new LoaderTask(
mApp, mBgAllAppsList, mBgDataModel, mModelDelegate, results);
// Always post the loader task, instead of running directly (even on same thread) so
// that we exit any nested synchronized blocks
MODEL_EXECUTOR.post(mLoaderTask);
}
}
public void startLoaderForResultsIfNotLoaded(LoaderResults results) {
synchronized (mLock) {
if (!isModelLoaded()) {
Log.d(TAG, "Workspace not loaded, loading now");
startLoaderForResults(results);
if (!mModelLoaded && !mIsLoaderTaskRunning) {
startLoader();
}
}
MODEL_EXECUTOR.post(() -> callback.accept(isModelLoaded() ? mBgDataModel : null));
}
@Override
@@ -553,6 +570,9 @@ public class LauncherModel extends LauncherApps.Callback implements InstallSessi
}
public void enqueueModelUpdateTask(ModelUpdateTask task) {
if (mModelDestroyed) {
return;
}
task.init(mApp, this, mBgDataModel, mBgAllAppsList, MAIN_EXECUTOR);
MODEL_EXECUTOR.execute(task);
}
+38 -81
View File
@@ -16,7 +16,6 @@
package com.android.launcher3;
import static com.android.launcher3.config.FeatureFlags.MULTI_DB_GRID_MIRATION_ALGO;
import static com.android.launcher3.provider.LauncherDbUtils.copyTable;
import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
import static com.android.launcher3.provider.LauncherDbUtils.tableExists;
@@ -61,7 +60,6 @@ import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.model.DbDowngradeHelper;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.provider.LauncherDbUtils;
import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
@@ -101,7 +99,7 @@ public class LauncherProvider extends ContentProvider {
* Represents the schema of the database. Changes in scheme need not be backwards compatible.
* When increasing the scheme version, ensure that downgrade_schema.json is updated
*/
public static final int SCHEMA_VERSION = 29;
public static final int SCHEMA_VERSION = 30;
public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".settings";
public static final String KEY_LAYOUT_PROVIDER_AUTHORITY = "KEY_LAYOUT_PROVIDER_AUTHORITY";
@@ -155,15 +153,7 @@ public class LauncherProvider extends ContentProvider {
mOpenHelper = DatabaseHelper.createDatabaseHelper(
getContext(), false /* forMigration */);
if (RestoreDbTask.isPending(getContext())) {
if (!RestoreDbTask.performRestore(getContext(), mOpenHelper,
new BackupManager(getContext()))) {
mOpenHelper.createEmptyDB(mOpenHelper.getWritableDatabase());
}
// Set is pending to false irrespective of the result, so that it doesn't get
// executed again.
RestoreDbTask.setPending(getContext(), false);
}
RestoreDbTask.restoreIfNeeded(getContext(), mOpenHelper);
}
}
@@ -398,7 +388,7 @@ public class LauncherProvider extends ContentProvider {
case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
Bundle result = new Bundle();
result.putInt(LauncherSettings.Settings.EXTRA_VALUE,
mOpenHelper.generateNewScreenId());
mOpenHelper.getNewScreenId());
return result;
}
case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
@@ -439,36 +429,30 @@ public class LauncherProvider extends ContentProvider {
return null;
}
case LauncherSettings.Settings.METHOD_UPDATE_CURRENT_OPEN_HELPER: {
if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
Bundle result = new Bundle();
result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
prepForMigration(
InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
Favorites.TMP_TABLE,
() -> mOpenHelper,
() -> DatabaseHelper.createDatabaseHelper(
getContext(), true /* forMigration */)));
return result;
}
return null;
Bundle result = new Bundle();
result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
prepForMigration(
InvariantDeviceProfile.INSTANCE.get(getContext()).dbFile,
Favorites.TMP_TABLE,
() -> mOpenHelper,
() -> DatabaseHelper.createDatabaseHelper(
getContext(), true /* forMigration */)));
return result;
}
case LauncherSettings.Settings.METHOD_RE_INITIALIZE_IDS: {
mOpenHelper.reInitIds();
return null;
}
case LauncherSettings.Settings.METHOD_PREP_FOR_PREVIEW: {
if (MULTI_DB_GRID_MIRATION_ALGO.get()) {
Bundle result = new Bundle();
result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
prepForMigration(
arg /* dbFile */,
Favorites.PREVIEW_TABLE_NAME,
() -> DatabaseHelper.createDatabaseHelper(
getContext(), arg, true /* forMigration */),
() -> mOpenHelper));
return result;
}
return null;
Bundle result = new Bundle();
result.putBoolean(LauncherSettings.Settings.EXTRA_VALUE,
prepForMigration(
arg /* dbFile */,
Favorites.PREVIEW_TABLE_NAME,
() -> DatabaseHelper.createDatabaseHelper(
getContext(), arg, true /* forMigration */),
() -> mOpenHelper));
return result;
}
case LauncherSettings.Settings.METHOD_SWITCH_DATABASE: {
if (TextUtils.equals(arg, mOpenHelper.getDatabaseName())) return null;
@@ -508,7 +492,7 @@ public class LauncherProvider extends ContentProvider {
LauncherSettings.Favorites.CONTAINER + " FROM "
+ Favorites.TABLE_NAME + ")";
IntArray folderIds = LauncherDbUtils.queryIntArray(db, Favorites.TABLE_NAME,
IntArray folderIds = LauncherDbUtils.queryIntArray(false, db, Favorites.TABLE_NAME,
Favorites._ID, selection, null, null);
if (!folderIds.isEmpty()) {
db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
@@ -653,7 +637,6 @@ public class LauncherProvider extends ContentProvider {
private final Context mContext;
private final boolean mForMigration;
private int mMaxItemId = -1;
private int mMaxScreenId = -1;
private boolean mBackupTableExists;
private boolean mHotseatRestoreTableExists;
@@ -664,8 +647,7 @@ public class LauncherProvider extends ContentProvider {
static DatabaseHelper createDatabaseHelper(Context context, String dbName,
boolean forMigration) {
if (dbName == null) {
dbName = MULTI_DB_GRID_MIRATION_ALGO.get() ? InvariantDeviceProfile.INSTANCE.get(
context).dbFile : LauncherFiles.LAUNCHER_DB;
dbName = InvariantDeviceProfile.INSTANCE.get(context).dbFile;
LawnchairAppKt.getLawnchairApp(context).migrateDbName(dbName);
}
DatabaseHelper databaseHelper = new DatabaseHelper(context, dbName, forMigration);
@@ -677,10 +659,6 @@ public class LauncherProvider extends ContentProvider {
// This operation is a no-op if the table already exists.
databaseHelper.addFavoritesTable(databaseHelper.getWritableDatabase(), true);
}
if (!MULTI_DB_GRID_MIRATION_ALGO.get()) {
databaseHelper.mBackupTableExists = tableExists(
databaseHelper.getReadableDatabase(), Favorites.BACKUP_TABLE_NAME);
}
databaseHelper.mHotseatRestoreTableExists = tableExists(
databaseHelper.getReadableDatabase(), Favorites.HYBRID_HOTSEAT_BACKUP_TABLE);
@@ -703,9 +681,6 @@ public class LauncherProvider extends ContentProvider {
if (mMaxItemId == -1) {
mMaxItemId = initializeMaxItemId(getWritableDatabase());
}
if (mMaxScreenId == -1) {
mMaxScreenId = initializeMaxScreenId(getWritableDatabase());
}
}
protected void reInitIds() {
@@ -718,7 +693,6 @@ public class LauncherProvider extends ContentProvider {
if (LOGD) Log.d(TAG, "creating new launcher database");
mMaxItemId = 1;
mMaxScreenId = 0;
addFavoritesTable(db, false);
@@ -867,16 +841,12 @@ public class LauncherProvider extends ContentProvider {
case 25:
convertShortcutsToLauncherActivities(db);
case 26:
// QSB was moved to the grid. Clear the first row on screen 0.
if (FeatureFlags.topQsbOnFirstScreenEnabled(mContext) &&
!LauncherDbUtils.prepareScreenZeroToHostQsb(mContext, db)) {
break;
}
// QSB was moved to the grid. Ignore overlapping items
case 27: {
// Update the favorites table so that the screen ids are ordered based on
// workspace page rank.
IntArray finalScreens = LauncherDbUtils.queryIntArray(db, "workspaceScreens",
BaseColumns._ID, null, null, "screenRank");
IntArray finalScreens = LauncherDbUtils.queryIntArray(false, db,
"workspaceScreens", BaseColumns._ID, null, null, "screenRank");
int[] original = finalScreens.toArray();
Arrays.sort(original);
String updatemap = "";
@@ -904,6 +874,11 @@ public class LauncherProvider extends ContentProvider {
}
}
case 29: {
// Remove widget panel related leftover workspace items
db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
Favorites.SCREEN, IntArray.wrap(-777, -778)), null);
}
case 30: {
// DB Upgraded successfully
return;
}
@@ -954,7 +929,7 @@ public class LauncherProvider extends ContentProvider {
Log.e(TAG, "getAppWidgetIds not supported", e);
return;
}
final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(db,
final IntSet validWidgets = IntSet.wrap(LauncherDbUtils.queryIntArray(false, db,
Favorites.TABLE_NAME, Favorites.APPWIDGET_ID,
"itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null));
for (int widgetId : allWidgets) {
@@ -1078,36 +1053,19 @@ public class LauncherProvider extends ContentProvider {
public void checkId(ContentValues values) {
int id = values.getAsInteger(Favorites._ID);
mMaxItemId = Math.max(id, mMaxItemId);
Integer screen = values.getAsInteger(Favorites.SCREEN);
Integer container = values.getAsInteger(Favorites.CONTAINER);
if (screen != null && container != null
&& container.intValue() == Favorites.CONTAINER_DESKTOP) {
mMaxScreenId = Math.max(screen, mMaxScreenId);
}
}
private int initializeMaxItemId(SQLiteDatabase db) {
return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s", Favorites._ID, Favorites.TABLE_NAME);
}
// Generates a new ID to use for an workspace screen in your database. This method
// should be only called from the main UI thread. As an exception, we do call it when we
// call the constructor from the worker thread; however, this doesn't extend until after the
// constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
// after that point
public int generateNewScreenId() {
if (mMaxScreenId < 0) {
throw new RuntimeException("Error: max screen id was not initialized");
}
mMaxScreenId += 1;
return mMaxScreenId;
}
private int initializeMaxScreenId(SQLiteDatabase db) {
return getMaxId(db, "SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d",
// Returns a new ID to use for an workspace screen in your database that is greater than all
// existing screen IDs.
private int getNewScreenId() {
return getMaxId(getWritableDatabase(),
"SELECT MAX(%1$s) FROM %2$s WHERE %3$s = %4$d AND %1$s >= 0",
Favorites.SCREEN, Favorites.TABLE_NAME, Favorites.CONTAINER,
Favorites.CONTAINER_DESKTOP);
Favorites.CONTAINER_DESKTOP) + 1;
}
@Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
@@ -1116,7 +1074,6 @@ public class LauncherProvider extends ContentProvider {
// Ensure that the max ids are initialized
mMaxItemId = initializeMaxItemId(db);
mMaxScreenId = initializeMaxScreenId(db);
return count;
}
}
+70 -10
View File
@@ -1,18 +1,24 @@
package com.android.launcher3;
import static com.android.launcher3.ResourceUtils.INVALID_RESOURCE_HANDLE;
import static com.android.launcher3.config.FeatureFlags.SEPARATE_RECENTS_ACTIVITY;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Insets;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.ViewDebug;
import android.view.WindowInsets;
import androidx.annotation.RequiresApi;
import com.android.launcher3.graphics.SysUiScrim;
import com.android.launcher3.statemanager.StatefulActivity;
import com.android.launcher3.uioverrides.ApiWrapper;
import java.util.Collections;
import java.util.List;
@@ -42,15 +48,8 @@ public class LauncherRootView extends InsettableFrameLayout {
}
private void handleSystemWindowInsets(Rect insets) {
DeviceProfile dp = mActivity.getDeviceProfile();
// Taskbar provides insets, but we don't want that for most Launcher elements so remove it.
mTempRect.set(insets);
insets = mTempRect;
insets.bottom = Math.max(0, insets.bottom - dp.nonOverlappingTaskbarInset);
// Update device profile before notifying the children.
dp.updateInsets(insets);
mActivity.getDeviceProfile().updateInsets(insets);
boolean resetState = !insets.equals(mInsets);
setInsets(insets);
@@ -61,12 +60,73 @@ public class LauncherRootView extends InsettableFrameLayout {
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
mTempRect.set(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(),
insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
if (Utilities.ATLEAST_R) {
insets = updateInsetsDueToTaskbar(insets);
Insets systemWindowInsets = insets.getInsetsIgnoringVisibility(
WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout());
mTempRect.set(systemWindowInsets.left, systemWindowInsets.top, systemWindowInsets.right,
systemWindowInsets.bottom);
} else {
mTempRect.set(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(),
insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
}
handleSystemWindowInsets(mTempRect);
return insets;
}
/**
* Taskbar provides nav bar and tappable insets. However, taskbar is not attached immediately,
* and can be destroyed and recreated. Thus, instead of relying on taskbar being present to
* get its insets, we calculate them ourselves so they are stable regardless of whether taskbar
* is currently attached.
*
* @param oldInsets The system-provided insets, which we are modifying.
* @return The updated insets.
*/
@RequiresApi(api = Build.VERSION_CODES.R)
private WindowInsets updateInsetsDueToTaskbar(WindowInsets oldInsets) {
if (!ApiWrapper.TASKBAR_DRAWN_IN_PROCESS) {
// 3P launchers based on Launcher3 should still be inset like normal.
return oldInsets;
}
WindowInsets.Builder updatedInsetsBuilder = new WindowInsets.Builder(oldInsets);
DeviceProfile dp = mActivity.getDeviceProfile();
Resources resources = getResources();
Insets oldNavInsets = oldInsets.getInsets(WindowInsets.Type.navigationBars());
Rect newNavInsets = new Rect(oldNavInsets.left, oldNavInsets.top, oldNavInsets.right,
oldNavInsets.bottom);
if (dp.isLandscape) {
boolean isGesturalMode = ResourceUtils.getIntegerByName(
"config_navBarInteractionMode",
resources,
INVALID_RESOURCE_HANDLE) == 2;
if (dp.isTablet || isGesturalMode) {
newNavInsets.bottom = ResourceUtils.getNavbarSize(
"navigation_bar_height_landscape", resources);
} else {
int navWidth = ResourceUtils.getNavbarSize("navigation_bar_width", resources);
if (dp.isSeascape()) {
newNavInsets.left = navWidth;
} else {
newNavInsets.right = navWidth;
}
}
} else {
newNavInsets.bottom = ResourceUtils.getNavbarSize("navigation_bar_height", resources);
}
updatedInsetsBuilder.setInsets(WindowInsets.Type.navigationBars(), Insets.of(newNavInsets));
updatedInsetsBuilder.setInsetsIgnoringVisibility(WindowInsets.Type.navigationBars(),
Insets.of(newNavInsets));
mActivity.updateWindowInsets(updatedInsetsBuilder, oldInsets);
return updatedInsetsBuilder.build();
}
@Override
public void setInsets(Rect insets) {
// If the insets haven't changed, this is a no-op. Avoid unnecessary layout caused by
@@ -94,6 +94,12 @@ public class LauncherSettings {
*/
public static final int ITEM_TYPE_DEEP_SHORTCUT = 6;
/**
* The favroite is a search action
*/
public static final int ITEM_TYPE_SEARCH_ACTION = 7;
/**
* Type of the item is recents task.
* TODO(hyunyoungs): move constants not related to Favorites DB to a better location.
@@ -199,6 +205,7 @@ public class LauncherSettings {
public static final int CONTAINER_WIDGETS_TRAY = -105;
public static final int CONTAINER_BOTTOM_WIDGETS_TRAY = -112;
public static final int CONTAINER_PIN_WIDGETS = -113;
public static final int CONTAINER_WALLPAPERS = -114;
// Represents search results view.
public static final int CONTAINER_SEARCH_RESULTS = -106;
public static final int CONTAINER_SHORTCUTS = -107;
+14 -13
View File
@@ -57,10 +57,9 @@ public abstract class LauncherState implements BaseState<LauncherState> {
public static final int ALL_APPS_CONTENT = 1 << 1;
public static final int VERTICAL_SWIPE_INDICATOR = 1 << 2;
public static final int OVERVIEW_ACTIONS = 1 << 3;
public static final int TASKBAR = 1 << 4;
public static final int CLEAR_ALL_BUTTON = 1 << 5;
public static final int WORKSPACE_PAGE_INDICATOR = 1 << 6;
public static final int SPLIT_PLACHOLDER_VIEW = 1 << 7;
public static final int CLEAR_ALL_BUTTON = 1 << 4;
public static final int WORKSPACE_PAGE_INDICATOR = 1 << 5;
public static final int SPLIT_PLACHOLDER_VIEW = 1 << 6;
// Flag indicating workspace has multiple pages visible.
public static final int FLAG_MULTI_PAGE = BaseState.getFlag(0);
@@ -181,20 +180,12 @@ public abstract class LauncherState implements BaseState<LauncherState> {
return launcher.getNormalOverviewScaleAndOffset();
}
public float getTaskbarScale(Launcher launcher) {
return launcher.getNormalTaskbarScale();
}
public float getTaskbarTranslationY(Launcher launcher) {
return -launcher.getHotseat().getTaskbarOffsetY();
}
public float getOverviewFullscreenProgress() {
return 0;
}
public int getVisibleElements(Launcher launcher) {
return HOTSEAT_ICONS | WORKSPACE_PAGE_INDICATOR | VERTICAL_SWIPE_INDICATOR | TASKBAR;
return HOTSEAT_ICONS | WORKSPACE_PAGE_INDICATOR | VERTICAL_SWIPE_INDICATOR;
}
/**
@@ -205,6 +196,16 @@ public abstract class LauncherState implements BaseState<LauncherState> {
return (getVisibleElements(launcher) & elements) == elements;
}
/** Returns whether taskbar is stashed and thus should replace hotseat with a handle */
public boolean isTaskbarStashed(Launcher launcher) {
return false;
}
/** Returns whether taskbar is aligned with the hotseat vs position inside apps */
public boolean isTaskbarAlignedWithHotseat(Launcher launcher) {
return !isTaskbarStashed(launcher);
}
/**
* Fraction shift in the vertical translation UI and related properties
*
+207 -96
View File
@@ -16,6 +16,8 @@
package com.android.launcher3;
import static androidx.annotation.VisibleForTesting.PACKAGE_PRIVATE;
import static com.android.launcher3.anim.Interpolators.SCROLL;
import static com.android.launcher3.compat.AccessibilityManagerCompat.isAccessibilityEnabled;
import static com.android.launcher3.compat.AccessibilityManagerCompat.isObservedEventType;
@@ -48,6 +50,7 @@ import android.widget.OverScroller;
import android.widget.ScrollView;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.config.FeatureFlags;
@@ -55,6 +58,7 @@ import com.android.launcher3.pageindicators.PageIndicator;
import com.android.launcher3.touch.PagedOrientationHandler;
import com.android.launcher3.touch.PagedOrientationHandler.ChildBounds;
import com.android.launcher3.util.EdgeEffectCompat;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.ActivityContext;
@@ -102,6 +106,12 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
@ViewDebug.ExportedProperty(category = "launcher")
protected int mCurrentPage;
// Difference between current scroll position and mCurrentPage's page scroll. Used to maintain
// relative scroll position unchanged in updateCurrentPageScroll. Cleared when snapping to a
// page.
protected int mCurrentPageScrollDiff;
// The current page the PagedView is scrolling over on it's way to the destination page.
protected int mCurrentScrollOverPage;
@ViewDebug.ExportedProperty(category = "launcher")
protected int mNextPage = INVALID_PAGE;
@@ -174,6 +184,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
mScroller = new OverScroller(context, SCROLL);
mCurrentPage = 0;
mCurrentScrollOverPage = 0;
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = configuration.getScaledTouchSlop();
@@ -199,7 +210,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
public void initParentViews(View parent) {
if (mPageIndicatorViewId > -1) {
mPageIndicator = parent.findViewById(mPageIndicatorViewId);
mPageIndicator.setMarkersCount(getChildCount());
mPageIndicator.setMarkersCount(getChildCount() / getPanelCount());
}
}
@@ -232,10 +243,6 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
return getChildAt(index);
}
protected int indexToPage(int index) {
return index;
}
/**
* Updates the scroll of the current page immediately to its final scroll position. We use this
* in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
@@ -245,11 +252,11 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
// If the current page is invalid, just reset the scroll position to zero
int newPosition = 0;
if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
newPosition = getScrollForPage(mCurrentPage);
newPosition = getScrollForPage(mCurrentPage) + mCurrentPageScrollDiff;
}
mOrientationHandler.set(this, VIEW_SCROLL_TO, newPosition);
mOrientationHandler.setPrimary(this, VIEW_SCROLL_TO, newPosition);
mScroller.startScroll(mScroller.getCurrX(), 0, newPosition - mScroller.getCurrX(), 0);
forceFinishScroller(true);
forceFinishScroller();
}
/**
@@ -271,14 +278,16 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
}
}
private void forceFinishScroller(boolean resetNextPage) {
/**
* Immediately finishes any in-progress scroll, maintaining the current position. Also sets
* mNextPage = INVALID_PAGE and calls pageEndTransition().
*/
public void forceFinishScroller() {
mScroller.forceFinished(true);
// We need to clean up the next page here to avoid computeScrollHelper from
// updating current page on the pass.
if (resetNextPage) {
mNextPage = INVALID_PAGE;
pageEndTransition();
}
mNextPage = INVALID_PAGE;
pageEndTransition();
}
private int validateNewPage(int newPage) {
@@ -287,15 +296,21 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
newPage = Utilities.boundToRange(newPage, 0, getPageCount() - 1);
if (getPanelCount() > 1) {
// Always return left panel as new page
// Always return left most panel as new page
newPage = getLeftmostVisiblePageForIndex(newPage);
}
return newPage;
}
private int getLeftmostVisiblePageForIndex(int pageIndex) {
/**
* In most cases where panelCount is 1, this method will just return the page index that was
* passed in.
* But for example when two panel home is enabled we might need the leftmost visible page index
* because that page is the current page.
*/
public int getLeftmostVisiblePageForIndex(int pageIndex) {
int panelCount = getPanelCount();
return (pageIndex / panelCount) * panelCount;
return pageIndex - pageIndex % panelCount;
}
/**
@@ -305,24 +320,82 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
return 1;
}
/**
* Returns an IntSet with the indices of the currently visible pages
*/
@VisibleForTesting(otherwise = PACKAGE_PRIVATE)
public IntSet getVisiblePageIndices() {
return getPageIndices(mCurrentPage);
}
/**
* In case the panelCount is 1 this just returns the same page index in an IntSet.
* But in cases where the panelCount > 1 this will return all the page indices that belong
* together, i.e. on the Workspace they are next to each other and shown at the same time.
*/
private IntSet getPageIndices(int pageIndex) {
// we want to make sure the pageIndex is the leftmost page
pageIndex = getLeftmostVisiblePageForIndex(pageIndex);
IntSet pageIndices = new IntSet();
int panelCount = getPanelCount();
int pageCount = getPageCount();
for (int page = pageIndex; page < pageIndex + panelCount && page < pageCount; page++) {
pageIndices.add(page);
}
return pageIndices;
}
/**
* Returns an IntSet with the indices of the neighbour pages that are in the focus direction.
*/
private IntSet getNeighbourPageIndices(int focus) {
int panelCount = getPanelCount();
// getNextPage is more reliable than getCurrentPage
int currentPage = getNextPage();
int nextPage;
if (focus == View.FOCUS_LEFT) {
nextPage = currentPage - panelCount;
} else if (focus == View.FOCUS_RIGHT) {
nextPage = currentPage + panelCount;
} else {
// no neighbours to other directions
return new IntSet();
}
nextPage = validateNewPage(nextPage);
if (nextPage == currentPage) {
// We reached the end of the pages
return new IntSet();
}
return getPageIndices(nextPage);
}
/**
* Executes the callback against each visible page
*/
public void forEachVisiblePage(Consumer<View> callback) {
int panelCount = getPanelCount();
for (int i = mCurrentPage; i < mCurrentPage + panelCount; i++) {
View page = getPageAt(i);
getVisiblePageIndices().forEach(pageIndex -> {
View page = getPageAt(pageIndex);
if (page != null) {
callback.accept(page);
}
}
});
}
/**
* Returns true if the view is on one of the current pages, false otherwise.
*/
public boolean isVisible(View child) {
return getLeftmostVisiblePageForIndex(indexOfChild(child)) == mCurrentPage;
return isVisible(indexOfChild(child));
}
/**
* Returns true if the page with the given index is currently visible, false otherwise.
*/
private boolean isVisible(int pageIndex) {
return getLeftmostVisiblePageForIndex(pageIndex) == mCurrentPage;
}
/**
@@ -371,6 +444,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
}
int prevPage = overridePrevPage != INVALID_PAGE ? overridePrevPage : mCurrentPage;
mCurrentPage = validateNewPage(currentPage);
mCurrentScrollOverPage = mCurrentPage;
updateCurrentPageScroll();
notifyPageSwitchListener(prevPage);
invalidate();
@@ -426,6 +500,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
* to provide custom behavior during animation.
*/
protected void onPageEndTransition() {
mCurrentPageScrollDiff = 0;
AccessibilityManagerCompat.sendScrollFinishedEventToTest(getContext());
AccessibilityManagerCompat.sendCustomAccessibilityEvent(getPageAt(mCurrentPage),
AccessibilityEvent.TYPE_VIEW_FOCUSED, null);
@@ -483,16 +558,18 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
int oldPos = mOrientationHandler.getPrimaryScroll(this);
int newPos = mScroller.getCurrX();
if (oldPos != newPos) {
mOrientationHandler.set(this, VIEW_SCROLL_TO, mScroller.getCurrX());
mOrientationHandler.setPrimary(this, VIEW_SCROLL_TO, mScroller.getCurrX());
}
if (mAllowOverScroll) {
if (newPos < mMinScroll && oldPos >= mMinScroll) {
mEdgeGlowLeft.onAbsorb((int) mScroller.getCurrVelocity());
mScroller.abortAnimation();
onEdgeAbsorbingScroll();
} else if (newPos > mMaxScroll && oldPos <= mMaxScroll) {
mEdgeGlowRight.onAbsorb((int) mScroller.getCurrVelocity());
mScroller.abortAnimation();
onEdgeAbsorbingScroll();
}
}
@@ -510,6 +587,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
sendScrollAccessibilityEvent();
int prevPage = mCurrentPage;
mCurrentPage = validateNewPage(mNextPage);
mCurrentScrollOverPage = mCurrentPage;
mNextPage = INVALID_PAGE;
notifyPageSwitchListener(prevPage);
@@ -562,7 +640,10 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
}
private int getPageWidthSize(int widthSize) {
return (widthSize - mInsets.left - mInsets.right) / getPanelCount();
// It's necessary to add the padding back because it is remove when measuring children,
// like when MeasureSpec.getSize in CellLayout.
return (widthSize - mInsets.left - mInsets.right - getPaddingLeft() - getPaddingRight())
/ getPanelCount() + getPaddingLeft() + getPaddingRight();
}
@Override
@@ -678,6 +759,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
final int scrollOffsetStart = mOrientationHandler.getScrollOffsetStart(this, mInsets);
final int scrollOffsetEnd = mOrientationHandler.getScrollOffsetEnd(this, mInsets);
boolean pageScrollChanged = false;
int panelCount = getPanelCount();
for (int i = startIndex, childStart = scrollOffsetStart; i != endIndex; i += delta) {
final View child = getPageAt(i);
@@ -695,14 +777,19 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
pageScrollChanged = true;
outPageScrolls[i] = pageScroll;
}
childStart += primaryDimension + mPageSpacing + getChildGap();
childStart += primaryDimension + getChildGap();
// This makes sure that the space is added after the page, not after each panel
int lastPanel = mIsRtl ? 0 : panelCount - 1;
if (i % panelCount == lastPanel) {
childStart += mPageSpacing;
}
}
}
int panelCount = getPanelCount();
if (panelCount > 1) {
for (int i = 0; i < childCount; i++) {
// In case we have multiple panels, always use left panel's page scroll for all
// In case we have multiple panels, always use left most panel's page scroll for all
// panels on the screen.
int adjustedScroll = outPageScrolls[getLeftmostVisiblePageForIndex(i)];
if (outPageScrolls[i] != adjustedScroll) {
@@ -748,7 +835,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
private void dispatchPageCountChanged() {
if (mPageIndicator != null) {
mPageIndicator.setMarkersCount(getChildCount());
mPageIndicator.setMarkersCount(getChildCount() / getPanelCount());
}
// This ensures that when children are added, they get the correct transforms / alphas
// in accordance with any scroll effects.
@@ -765,6 +852,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
public void onViewRemoved(View child) {
super.onViewRemoved(child);
mCurrentPage = validateNewPage(mCurrentPage);
mCurrentScrollOverPage = mCurrentPage;
dispatchPageCountChanged();
}
@@ -781,8 +869,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
int page = indexToPage(indexOfChild(child));
if (page != mCurrentPage || !mScroller.isFinished()) {
int page = indexOfChild(child);
if (!isVisible(page) || !mScroller.isFinished()) {
if (immediate) {
setCurrentPage(page);
} else {
@@ -821,21 +909,25 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
direction = View.FOCUS_LEFT;
}
}
if (direction == View.FOCUS_LEFT) {
if (getCurrentPage() > 0) {
int nextPage = validateNewPage(getCurrentPage() - 1);
snapToPage(nextPage);
getChildAt(nextPage).requestFocus(direction);
return true;
}
} else if (direction == View.FOCUS_RIGHT) {
if (getCurrentPage() < getPageCount() - 1) {
int nextPage = validateNewPage(getCurrentPage() + 1);
snapToPage(nextPage);
getChildAt(nextPage).requestFocus(direction);
return true;
int currentPage = getNextPage();
int closestNeighbourIndex = -1;
int closestNeighbourDistance = Integer.MAX_VALUE;
// Find the closest neighbour page
for (int neighbourPageIndex : getNeighbourPageIndices(direction)) {
int distance = Math.abs(neighbourPageIndex - currentPage);
if (closestNeighbourDistance > distance) {
closestNeighbourDistance = distance;
closestNeighbourIndex = neighbourPageIndex;
}
}
if (closestNeighbourIndex != -1) {
View page = getPageAt(closestNeighbourIndex);
snapToPage(closestNeighbourIndex);
page.requestFocus(direction);
return true;
}
return false;
}
@@ -845,28 +937,12 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
return;
}
// Add the current page's views as focusable and the next possible page's too. If the
// last focus change action was left then the left neighbour's views will be added, and
// if it was right then the right neighbour's views will be added.
// Unfortunately mCurrentPage can be outdated if there were multiple control actions in a
// short period of time, but mNextPage is up to date because it is always updated by
// method snapToPage.
int nextPage = getNextPage();
// XXX-RTL: This will be fixed in a future CL
if (nextPage >= 0 && nextPage < getPageCount()) {
getPageAt(nextPage).addFocusables(views, direction, focusableMode);
}
if (direction == View.FOCUS_LEFT) {
if (nextPage > 0) {
nextPage = validateNewPage(nextPage - 1);
getPageAt(nextPage).addFocusables(views, direction, focusableMode);
}
} else if (direction == View.FOCUS_RIGHT) {
if (nextPage < getPageCount() - 1) {
nextPage = validateNewPage(nextPage + 1);
getPageAt(nextPage).addFocusables(views, direction, focusableMode);
}
}
// nextPage is more reliable when multiple control movements have been done in a short
// period of time
getPageIndices(getNextPage())
.addAll(getNeighbourPageIndices(direction))
.forEach(pageIndex ->
getPageAt(pageIndex).addFocusables(views, direction, focusableMode));
}
/**
@@ -986,7 +1062,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
/**
* If being flinged and user touches the screen, initiate drag; otherwise don't.
*/
private void updateIsBeingDraggedOnTouchDown(MotionEvent ev) {
protected void updateIsBeingDraggedOnTouchDown(MotionEvent ev) {
// mScroller.isFinished should be false when being flinged.
final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
final boolean finishedScrolling = (mScroller.isFinished() || xDist < mPageSlop / 3);
@@ -1056,26 +1132,25 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
protected float getScrollProgress(int screenCenter, View v, int page) {
final int halfScreenSize = getMeasuredWidth() / 2;
int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
int count = getChildCount();
int panelCount = getPanelCount();
int pageCount = getChildCount();
final int totalDistance;
int adjacentPage = page + 1;
int adjacentPage = page + panelCount;
if ((delta < 0 && !mIsRtl) || (delta > 0 && mIsRtl)) {
adjacentPage = page - 1;
adjacentPage = page - panelCount;
}
if (adjacentPage < 0 || adjacentPage > count - 1) {
totalDistance = v.getMeasuredWidth() + mPageSpacing;
final int totalDistance;
if (adjacentPage < 0 || adjacentPage > pageCount - 1) {
totalDistance = (v.getMeasuredWidth() + mPageSpacing) * panelCount;
} else {
totalDistance = Math.abs(getScrollForPage(adjacentPage) - getScrollForPage(page));
}
float scrollProgress = delta / (totalDistance * 1.0f);
scrollProgress = Math.min(scrollProgress, MAX_SCROLL_PROGRESS);
scrollProgress = Math.max(scrollProgress, - MAX_SCROLL_PROGRESS);
scrollProgress = Math.max(scrollProgress, -MAX_SCROLL_PROGRESS);
return scrollProgress;
}
@@ -1122,6 +1197,10 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
mAllowOverScroll = enable;
}
protected float getSignificantMoveThreshold() {
return SIGNIFICANT_MOVE_THRESHOLD;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// Skip touch handling if there are no pages to swipe
@@ -1193,6 +1272,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
}
delta -= consumed;
}
delta /= mOrientationHandler.getPrimaryScale(this);
// Only scroll and update mLastMotionX if we have moved some discrete amount. We
// keep the remainder because we are actually testing if we've moved from the last
@@ -1202,7 +1282,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
mLastMotionRemainder = delta - movedDelta;
if (delta != 0) {
mOrientationHandler.set(this, VIEW_SCROLL_BY, movedDelta);
mOrientationHandler.setPrimary(this, VIEW_SCROLL_BY, movedDelta);
if (mAllowOverScroll) {
final float pulledToX = oldScroll + delta;
@@ -1245,11 +1325,12 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
int velocity = (int) mOrientationHandler.getPrimaryVelocity(velocityTracker,
mActivePointerId);
int delta = (int) (primaryDirection - mDownMotionPrimary);
float delta = primaryDirection - mDownMotionPrimary;
delta /= mOrientationHandler.getPrimaryScale(this);
int pageOrientedSize = mOrientationHandler.getMeasuredSize(getPageAt(mCurrentPage));
boolean isSignificantMove = Math.abs(delta) > pageOrientedSize *
SIGNIFICANT_MOVE_THRESHOLD;
boolean isSignificantMove = Math.abs(delta)
> pageOrientedSize * getSignificantMoveThreshold();
mTotalMotion += Math.abs(mLastMotion + mLastMotionRemainder - primaryDirection);
boolean passedSlop = mAllowEasyFling || mTotalMotion > mPageSlop;
@@ -1343,6 +1424,20 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
protected void onNotSnappingToPageInFreeScroll() { }
/**
* Called when the view edges absorb part of the scroll. Subclasses can override this
* to provide custom behavior during animation.
*/
protected void onEdgeAbsorbingScroll() {
}
/**
* Called when the current page closest to the center of the screen changes as part of the
* scroll. Subclasses can override this to provide custom behavior during scroll.
*/
protected void onScrollOverPageChanged() {
}
protected boolean shouldFlingForVelocity(int velocity) {
float threshold = mAllowEasyFling ? mEasyFlingThresholdVelocity : mFlingThresholdVelocity;
return Math.abs(velocity) > threshold;
@@ -1441,8 +1536,8 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
setCurrentPage(nextPage);
}
int page = indexToPage(indexOfChild(child));
if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
int page = indexOfChild(child);
if (page >= 0 && !isVisible(page) && !isInTouchMode()) {
snapToPage(page);
}
}
@@ -1488,7 +1583,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
return getDisplacementFromScreenCenter(childIndex, screenCenter);
}
private int getScreenCenter(int primaryScroll) {
protected int getScreenCenter(int primaryScroll) {
float primaryScale = mOrientationHandler.getPrimaryScale(this);
float primaryPivot = mOrientationHandler.getPrimaryValue(getPivotX(), getPivotY());
int pageOrientationSize = mOrientationHandler.getMeasuredSize(this);
@@ -1573,7 +1668,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
return false;
}
if (FeatureFlags.IS_STUDIO_BUILD) {
if (FeatureFlags.IS_STUDIO_BUILD && !Utilities.IS_RUNNING_IN_TEST_HARNESS) {
duration *= Settings.Global.getFloat(getContext().getContentResolver(),
Settings.Global.WINDOW_ANIMATION_SCALE, 1);
}
@@ -1612,7 +1707,7 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
public boolean scrollLeft() {
if (getNextPage() > 0) {
snapToPage(getNextPage() - 1);
snapToPage(getNextPage() - getPanelCount());
return true;
}
return mAllowOverScroll;
@@ -1620,12 +1715,25 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
public boolean scrollRight() {
if (getNextPage() < getChildCount() - 1) {
snapToPage(getNextPage() + 1);
snapToPage(getNextPage() + getPanelCount());
return true;
}
return mAllowOverScroll;
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
if (mScroller.isFinished()) {
// This was not caused by the scroller, skip it.
return;
}
int newDestinationPage = getDestinationPage();
if (newDestinationPage >= 0 && newDestinationPage != mCurrentScrollOverPage) {
mCurrentScrollOverPage = newDestinationPage;
onScrollOverPageChanged();
}
}
@Override
public CharSequence getAccessibilityClassName() {
// Some accessibility services have special logic for ScrollView. Since we provide same
@@ -1643,22 +1751,25 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
final boolean pagesFlipped = isPageOrderFlipped();
int offset = (mAllowOverScroll ? 0 : 1);
info.setScrollable(getPageCount() > offset);
if (getCurrentPage() < getPageCount() - offset) {
info.setScrollable(getPageCount() > 0);
int primaryScroll = mOrientationHandler.getPrimaryScroll(this);
if (getCurrentPage() < getPageCount() - getPanelCount()
|| (getCurrentPage() == getPageCount() - getPanelCount()
&& primaryScroll != getScrollForPage(getPageCount() - getPanelCount()))) {
info.addAction(pagesFlipped ?
AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD
: AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD);
AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD
: AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD);
if (Utilities.ATLEAST_Q) {
info.addAction(mIsRtl ?
AccessibilityNodeInfo.AccessibilityAction.ACTION_PAGE_LEFT
: AccessibilityNodeInfo.AccessibilityAction.ACTION_PAGE_RIGHT);
}
}
if (getCurrentPage() >= offset) {
if (getCurrentPage() > 0
|| (getCurrentPage() == 0 && primaryScroll != getScrollForPage(0))) {
info.addAction(pagesFlipped ?
AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD
: AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD);
AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_FORWARD
: AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_BACKWARD);
if (Utilities.ATLEAST_Q) {
info.addAction(mIsRtl ?
AccessibilityNodeInfo.AccessibilityAction.ACTION_PAGE_RIGHT
@@ -1705,16 +1816,16 @@ public abstract class PagedView<T extends View & PageIndicator> extends ViewGrou
} break;
case android.R.id.accessibilityActionPageRight: {
if (!mIsRtl) {
return scrollRight();
return scrollRight();
} else {
return scrollLeft();
return scrollLeft();
}
}
case android.R.id.accessibilityActionPageLeft: {
if (!mIsRtl) {
return scrollLeft();
return scrollLeft();
} else {
return scrollRight();
return scrollRight();
}
}
}
+1 -1
View File
@@ -142,7 +142,7 @@ public class Partner {
}
if (iconSize > 0) {
inv.iconSize = iconSize;
inv.iconSize[InvariantDeviceProfile.INDEX_DEFAULT] = iconSize;
}
}
}
@@ -23,6 +23,7 @@ import static com.android.launcher3.CellLayout.WORKSPACE;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
@@ -31,7 +32,7 @@ import android.view.ViewGroup;
import com.android.launcher3.CellLayout.ContainerType;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.widget.LauncherAppWidgetHostView;
import com.android.launcher3.widget.NavigableAppWidgetHostView;
public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.FolderIconParent {
static final String TAG = "ShortcutAndWidgetContainer";
@@ -48,7 +49,7 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
private int mCellWidth;
private int mCellHeight;
private int mBorderSpacing;
private Point mBorderSpace;
private int mCountX;
private int mCountY;
@@ -64,12 +65,12 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
}
public void setCellDimensions(int cellWidth, int cellHeight, int countX, int countY,
int borderSpacing) {
Point borderSpace) {
mCellWidth = cellWidth;
mCellHeight = cellHeight;
mCountX = countX;
mCountY = countY;
mBorderSpacing = borderSpacing;
mBorderSpace = borderSpace;
}
public View getChildAt(int cellX, int cellY) {
@@ -104,14 +105,14 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
public void setupLp(View child) {
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (child instanceof LauncherAppWidgetHostView) {
if (child instanceof NavigableAppWidgetHostView) {
DeviceProfile profile = mActivity.getDeviceProfile();
((LauncherAppWidgetHostView) child).getWidgetInset(profile, mTempRect);
((NavigableAppWidgetHostView) child).getWidgetInset(profile, mTempRect);
lp.setup(mCellWidth, mCellHeight, invertLayoutHorizontally(), mCountX, mCountY,
profile.appWidgetScale.x, profile.appWidgetScale.y, mBorderSpacing, mTempRect);
profile.appWidgetScale.x, profile.appWidgetScale.y, mBorderSpace, mTempRect);
} else {
lp.setup(mCellWidth, mCellHeight, invertLayoutHorizontally(), mCountX, mCountY,
mBorderSpacing, null);
mBorderSpace, null);
}
}
@@ -129,13 +130,13 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
final DeviceProfile dp = mActivity.getDeviceProfile();
if (child instanceof LauncherAppWidgetHostView) {
((LauncherAppWidgetHostView) child).getWidgetInset(dp, mTempRect);
if (child instanceof NavigableAppWidgetHostView) {
((NavigableAppWidgetHostView) child).getWidgetInset(dp, mTempRect);
lp.setup(mCellWidth, mCellHeight, invertLayoutHorizontally(), mCountX, mCountY,
dp.appWidgetScale.x, dp.appWidgetScale.y, mBorderSpacing, mTempRect);
dp.appWidgetScale.x, dp.appWidgetScale.y, mBorderSpace, mTempRect);
} else {
lp.setup(mCellWidth, mCellHeight, invertLayoutHorizontally(), mCountX, mCountY,
mBorderSpacing, null);
mBorderSpace, null);
// Center the icon/folder
int cHeight = getCellContentHeight();
int cellPaddingY = dp.isScalableGrid && mContainerType == WORKSPACE
@@ -143,8 +144,9 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
: (int) Math.max(0, ((lp.height - cHeight) / 2f));
// No need to add padding when cell layout border spacing is present.
boolean noPaddingX = (dp.cellLayoutBorderSpacingPx > 0 && mContainerType == WORKSPACE)
|| (dp.folderCellLayoutBorderSpacingPx > 0 && mContainerType == FOLDER);
boolean noPaddingX =
(dp.cellLayoutBorderSpacePx.x > 0 && mContainerType == WORKSPACE)
|| (dp.folderCellLayoutBorderSpacePx.x > 0 && mContainerType == FOLDER);
int cellPaddingX = noPaddingX
? 0
: mContainerType == WORKSPACE
@@ -178,16 +180,16 @@ public class ShortcutAndWidgetContainer extends ViewGroup implements FolderIcon.
*/
public void layoutChild(View child) {
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (child instanceof LauncherAppWidgetHostView) {
LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) child;
if (child instanceof NavigableAppWidgetHostView) {
NavigableAppWidgetHostView nahv = (NavigableAppWidgetHostView) child;
// Scale and center the widget to fit within its cells.
DeviceProfile profile = mActivity.getDeviceProfile();
float scaleX = profile.appWidgetScale.x;
float scaleY = profile.appWidgetScale.y;
lahv.setScaleToFit(Math.min(scaleX, scaleY));
lahv.setTranslationForCentering(-(lp.width - (lp.width * scaleX)) / 2.0f,
nahv.setScaleToFit(Math.min(scaleX, scaleY));
nahv.setTranslationForCentering(-(lp.width - (lp.width * scaleX)) / 2.0f,
-(lp.height - (lp.height * scaleY)) / 2.0f);
}
+56 -29
View File
@@ -45,6 +45,7 @@ import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.InsetDrawable;
@@ -68,6 +69,7 @@ import android.view.ViewConfiguration;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.core.graphics.ColorUtils;
import androidx.core.os.BuildCompat;
@@ -80,11 +82,13 @@ import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.icons.ShortcutCachingLogic;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.model.data.SearchActionItemInfo;
import com.android.launcher3.pm.ShortcutConfigActivityInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.widget.PendingAddShortcutInfo;
@@ -395,6 +399,21 @@ public final class Utilities {
return scale;
}
/**
* 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) {
float px = r.centerX();
float py = r.centerY();
r.offset(-px, -py);
r.left = r.left * scaleX;
r.top = r.top * scaleY;
r.right = r.right * scaleX;
r.bottom = r.bottom * scaleY;
r.offset(px, py);
}
/**
* Maps t from one range to another range.
* @param t The value to map.
@@ -523,6 +542,18 @@ public final class Utilities {
return defaultValue;
}
/**
* Using the view's bounds and icon size, calculate where the icon bounds will
* be if it was positioned at the center of the view.
*/
public static void setRectToViewCenter(View iconView, int iconSize, Rect outBounds) {
int top = (iconView.getHeight() - iconSize) / 2;
int left = (iconView.getWidth() - iconSize) / 2;
int right = left + iconSize;
int bottom = top + iconSize;
outBounds.set(left, top, right, bottom);
}
/**
* Ensures that a value is within given bounds. Specifically:
* If value is less than lowerBound, return lowerBound; else if value is greater than upperBound,
@@ -648,21 +679,6 @@ public final class Utilities {
handler.sendMessage(msg);
}
/**
* Parses a string encoded using {@link #getPointString(int, int)}
*/
public static Point parsePoint(String point) {
String[] split = point.split(",");
return new Point(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
}
/**
* Encodes a point to string to that it can be persisted atomically.
*/
public static String getPointString(int x, int y) {
return String.format(Locale.ENGLISH, "%d,%d", x, y);
}
public static void unregisterReceiverSafely(Context context, BroadcastReceiver receiver) {
try {
context.unregisterReceiver(receiver);
@@ -675,25 +691,26 @@ public final class Utilities {
* @param outObj this is set to the internal data associated with {@param info},
* eg {@link LauncherActivityInfo} or {@link ShortcutInfo}.
*/
public static Drawable getFullDrawable(Launcher launcher, ItemInfo info, int width, int height,
public static Drawable getFullDrawable(Context context, ItemInfo info, int width, int height,
Object[] outObj) {
Drawable icon = loadFullDrawableWithoutTheme(launcher, info, width, height, outObj);
Drawable icon = loadFullDrawableWithoutTheme(context, info, width, height, outObj);
if (icon instanceof BitmapInfo.Extender) {
icon = ((BitmapInfo.Extender) icon).getThemedDrawable(launcher);
icon = ((BitmapInfo.Extender) icon).getThemedDrawable(context);
}
return icon;
}
public static Drawable loadFullDrawableWithoutTheme(Launcher launcher, ItemInfo info,
public static Drawable loadFullDrawableWithoutTheme(Context context, ItemInfo info,
int width, int height, Object[] outObj) {
LauncherAppState appState = LauncherAppState.getInstance(launcher);
ActivityContext activity = ActivityContext.lookupContext(context);
LauncherAppState appState = LauncherAppState.getInstance(context);
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
LauncherActivityInfo activityInfo = launcher.getSystemService(LauncherApps.class)
LauncherActivityInfo activityInfo = context.getSystemService(LauncherApps.class)
.resolveActivity(info.getIntent(), info.user);
outObj[0] = activityInfo;
return activityInfo == null ? null : LauncherAppState.getInstance(launcher)
return activityInfo == null ? null : LauncherAppState.getInstance(context)
.getIconProvider().getIcon(
activityInfo, launcher.getDeviceProfile().inv.fillResIconDpi);
activityInfo, activity.getDeviceProfile().inv.fillResIconDpi);
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
if (info instanceof PendingAddShortcutInfo) {
ShortcutConfigActivityInfo activityInfo =
@@ -702,23 +719,27 @@ public final class Utilities {
return activityInfo.getFullResIcon(appState.getIconCache());
}
List<ShortcutInfo> si = ShortcutKey.fromItemInfo(info)
.buildRequest(launcher)
.buildRequest(context)
.query(ShortcutRequest.ALL);
if (si.isEmpty()) {
return null;
} else {
outObj[0] = si.get(0);
return ShortcutCachingLogic.getIcon(launcher, si.get(0),
return ShortcutCachingLogic.getIcon(context, si.get(0),
appState.getInvariantDeviceProfile().fillResIconDpi);
}
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
FolderAdaptiveIcon icon = FolderAdaptiveIcon.createFolderAdaptiveIcon(
launcher, info.id, new Point(width, height));
activity, info.id, new Point(width, height));
if (icon == null) {
return null;
}
outObj[0] = icon;
return icon;
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_SEARCH_ACTION
&& info instanceof SearchActionItemInfo) {
return new AdaptiveIconDrawable(
new FastBitmapDrawable(((SearchActionItemInfo) info).bitmap), null);
} else {
return null;
}
@@ -731,8 +752,8 @@ public final class Utilities {
* badge. When dragged from workspace or folder, it may contain app AND/OR work profile badge
**/
@TargetApi(Build.VERSION_CODES.O)
public static Drawable getBadge(Launcher launcher, ItemInfo info, Object obj) {
LauncherAppState appState = LauncherAppState.getInstance(launcher);
public static Drawable getBadge(Context context, ItemInfo info, Object obj) {
LauncherAppState appState = LauncherAppState.getInstance(context);
int iconSize = appState.getInvariantDeviceProfile().iconBitmapSize;
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
boolean iconBadged = (info instanceof ItemInfoWithIcon)
@@ -752,7 +773,7 @@ public final class Utilities {
} else if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
return ((FolderAdaptiveIcon) obj).getBadge();
} else {
return launcher.getPackageManager()
return context.getPackageManager()
.getUserBadgedIcon(new FixedSizeEmptyDrawable(iconSize), info.user);
}
}
@@ -854,6 +875,12 @@ public final class Utilities {
view.setLayoutParams(lp);
}
public static Rect getViewBounds(@NonNull View v) {
int[] pos = new int[2];
v.getLocationOnScreen(pos);
return new Rect(pos[0], pos[1], pos[0] + v.getWidth(), pos[1] + v.getHeight());
}
private static class FixedSizeEmptyDrawable extends ColorDrawable {
private final int mSize;
File diff suppressed because it is too large. Load diff
@@ -23,6 +23,7 @@ import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.touch.ItemLongClickListener;
import com.android.launcher3.util.IntSet;
public interface WorkspaceLayoutManager {
@@ -30,8 +31,16 @@ public interface WorkspaceLayoutManager {
// The screen id used for the empty screen always present at the end.
int EXTRA_EMPTY_SCREEN_ID = -201;
// The screen id used for the second empty screen always present at the end for two panel home.
int EXTRA_EMPTY_SCREEN_SECOND_ID = -200;
// The screen ids used for the empty screens at the end of the workspaces.
IntSet EXTRA_EMPTY_SCREEN_IDS =
IntSet.wrap(EXTRA_EMPTY_SCREEN_ID, EXTRA_EMPTY_SCREEN_SECOND_ID);
// The is the first screen. It is always present, even if its empty.
int FIRST_SCREEN_ID = 0;
// This is the second page. On two panel home it is always present, even if its empty.
int SECOND_SCREEN_ID = 1;
/**
* At bind time, we use the rank (screenId) to compute x and y for hotseat items.
@@ -79,9 +88,9 @@ public interface WorkspaceLayoutManager {
return;
}
}
if (screenId == EXTRA_EMPTY_SCREEN_ID) {
if (EXTRA_EMPTY_SCREEN_IDS.contains(screenId)) {
// This should never happen
throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID");
throw new RuntimeException("Screen id should not be extra empty screen: " + screenId);
}
final CellLayout layout;
@@ -45,6 +45,7 @@ import com.android.launcher3.popup.ArrowPopup;
import com.android.launcher3.popup.PopupContainerWithArrow;
import com.android.launcher3.touch.ItemLongClickListener;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.ShortcutUtil;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.OptionsPopupView;
@@ -161,7 +162,8 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
}
}
if ((item instanceof AppInfo) || (item instanceof PendingAddItemInfo)) {
if ((item instanceof AppInfo) || (item instanceof WorkspaceItemInfo)
|| (item instanceof PendingAddItemInfo)) {
out.add(mActions.get(ADD_TO_WORKSPACE));
}
}
@@ -221,6 +223,9 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
} else if (action == ADD_TO_WORKSPACE) {
final int[] coordinates = new int[2];
final int screenId = findSpaceOnWorkspace(item, coordinates);
if (screenId == -1) {
return false;
}
mLauncher.getStateManager().goToState(NORMAL, true, forSuccessCallback(() -> {
if (item instanceof AppInfo) {
WorkspaceItemInfo info = ((AppInfo) item).makeWorkspaceItem();
@@ -240,6 +245,13 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
mLauncher.addPendingItem(info, Favorites.CONTAINER_DESKTOP,
screenId, coordinates, info.spanX, info.spanY);
}
else if (item instanceof WorkspaceItemInfo) {
WorkspaceItemInfo info = ((WorkspaceItemInfo) item).clone();
mLauncher.getModelWriter().addItemToDatabase(info,
Favorites.CONTAINER_DESKTOP,
screenId, coordinates[0], coordinates[1]);
mLauncher.bindItems(Collections.singletonList(info), true, true);
}
}));
return true;
} else if (action == MOVE_TO_WORKSPACE) {
@@ -250,6 +262,9 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
final int[] coordinates = new int[2];
final int screenId = findSpaceOnWorkspace(item, coordinates);
if (screenId == -1) {
return false;
}
mLauncher.getModelWriter().moveItemInDatabase(info,
Favorites.CONTAINER_DESKTOP,
screenId, coordinates[0], coordinates[1]);
@@ -489,8 +504,14 @@ public class LauncherAccessibilityDelegate extends AccessibilityDelegate impleme
return screenId;
}
workspace.addExtraEmptyScreen();
screenId = workspace.commitExtraEmptyScreen();
workspace.addExtraEmptyScreens();
IntSet emptyScreenIds = workspace.commitExtraEmptyScreens();
if (emptyScreenIds.isEmpty()) {
// Couldn't create extra empty screens for some reason (e.g. Workspace is loading)
return -1;
}
screenId = emptyScreenIds.getArray().get(0);
layout = workspace.getScreenWithId(screenId);
found = layout.findCellForSpan(outCoordinates, info.spanX, info.spanY);
@@ -68,6 +68,9 @@ public class ShortcutMenuAccessibilityDelegate extends LauncherAccessibilityDele
final WorkspaceItemInfo info = ((DeepShortcutView) host.getParent()).getFinalInfo();
final int[] coordinates = new int[2];
final int screenId = findSpaceOnWorkspace(item, coordinates);
if (screenId == -1) {
return false;
}
mLauncher.getStateManager().goToState(NORMAL, true, forSuccessCallback(() -> {
mLauncher.getModelWriter().addItemToDatabase(info,
LauncherSettings.Favorites.CONTAINER_DESKTOP,
@@ -19,15 +19,11 @@ package com.android.launcher3.allapps;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ALLAPPS_TAP_ON_PERSONAL_TAB;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ALLAPPS_TAP_ON_WORK_TAB;
import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_HAS_SHORTCUT_PERMISSION;
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 android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
@@ -36,7 +32,7 @@ import android.graphics.Rect;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.Process;
import android.text.Selection;
import android.os.UserManager;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.util.Log;
@@ -70,7 +66,6 @@ import com.android.launcher3.allapps.search.SearchAdapterProvider;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.keyboard.FocusedItemDecorator;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.Themes;
import com.android.launcher3.views.RecyclerViewFastScroller;
@@ -94,11 +89,12 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
public static final float FLING_VELOCITY_MULTIPLIER = 1200f;
private final Paint mHeaderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Rect mInsets = new Rect();
protected final BaseDraggingActivity mLauncher;
protected final AdapterHolder[] mAH;
private final ItemInfoMatcher mPersonalMatcher = ItemInfoMatcher.ofUser(Process.myUserHandle());
private final ItemInfoMatcher mWorkMatcher = mPersonalMatcher.negate();
protected final ItemInfoMatcher mPersonalMatcher = ItemInfoMatcher.ofUser(
Process.myUserHandle());
private final AllAppsStore mAllAppsStore = new AllAppsStore();
private final RecyclerView.OnScrollListener mScrollListener =
@@ -108,6 +104,8 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
updateHeaderScroll(((AllAppsRecyclerView) recyclerView).getCurrentScrollY());
}
};
private final WorkProfileManager mWorkManager;
private final Paint mNavBarScrimPaint;
private int mNavBarScrimHeight = 0;
@@ -117,27 +115,24 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
private AllAppsPagedView mViewPager;
protected FloatingHeaderView mHeader;
private float mHeaderTop;
private WorkModeSwitch mWorkModeSwitch;
private SpannableStringBuilder mSearchQueryBuilder = null;
protected boolean mUsingTabs;
private boolean mSearchModeWhileUsingTabs = false;
private boolean mIsSearching;
private boolean mHasWorkApps;
protected RecyclerViewFastScroller mTouchHandler;
protected final Point mFastScrollerOffset = new Point();
private Rect mInsets = new Rect();
private SearchAdapterProvider mSearchAdapterProvider;
private WorkAdapterProvider mWorkAdapterProvider;
private final int mScrimColor;
private final int mHeaderProtectionColor;
private final float mHeaderThreshold;
private ScrimView mScrimView;
private int mHeaderColor;
private int mTabsProtectionAlpha;
public AllAppsContainerView(Context context) {
this(context, null);
@@ -160,15 +155,11 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
mLauncher.addOnDeviceProfileChangeListener(this);
mSearchAdapterProvider = mLauncher.createSearchAdapterProvider(this);
mSearchQueryBuilder = new SpannableStringBuilder();
Selection.setSelection(mSearchQueryBuilder, 0);
mAH = new AdapterHolder[2];
mWorkAdapterProvider = new WorkAdapterProvider(mLauncher, () -> {
if (mAH[AdapterHolder.WORK] != null) {
mAH[AdapterHolder.WORK].appsList.updateAdapterItems();
}
});
mWorkManager = new WorkProfileManager(mLauncher.getSystemService(UserManager.class), this,
Utilities.getPrefs(mLauncher));
mAH[AdapterHolder.MAIN] = new AdapterHolder(false /* isWork */);
mAH[AdapterHolder.WORK] = new AdapterHolder(true /* isWork */);
@@ -195,7 +186,7 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
int currentPage = state.getInt(BUNDLE_KEY_CURRENT_PAGE, 0);
if (currentPage != 0 && mViewPager != null) {
mViewPager.setCurrentPage(currentPage);
rebindAdapters(true);
rebindAdapters();
} else {
reset(true);
}
@@ -224,8 +215,8 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
return mAllAppsStore;
}
public WorkModeSwitch getWorkModeSwitch() {
return mWorkModeSwitch;
public WorkProfileManager getWorkManager() {
return mWorkManager;
}
@Override
@@ -244,27 +235,20 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
private void onAppsUpdated() {
boolean hasWorkApps = false;
for (AppInfo app : mAllAppsStore.getApps()) {
if (mWorkMatcher.matches(app, null)) {
if (mWorkManager.getMatcher().matches(app, null)) {
hasWorkApps = true;
break;
}
}
mHasWorkApps = hasWorkApps;
if (!mAH[AdapterHolder.MAIN].appsList.hasFilter()) {
rebindAdapters(hasWorkApps);
rebindAdapters();
if (hasWorkApps) {
resetWorkProfile();
mWorkManager.reset();
}
}
}
private void resetWorkProfile() {
boolean isEnabled = !mAllAppsStore.hasModelFlag(FLAG_QUIET_MODE_ENABLED);
if (mWorkModeSwitch != null) {
mWorkModeSwitch.updateCurrentState(isEnabled);
}
mWorkAdapterProvider.updateCurrentState(isEnabled);
}
/**
* Returns whether the view itself will handle the touch event or not.
*/
@@ -328,6 +312,8 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
mViewPager.getNextPage() == 0
? R.string.all_apps_button_personal_label
: R.string.all_apps_button_work_label;
} else if (mIsSearching) {
descriptionRes = R.string.all_apps_search_results;
} else {
descriptionRes = R.string.all_apps_button_label;
}
@@ -376,7 +362,7 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
});
mHeader = findViewById(R.id.all_apps_header);
rebindAdapters(mUsingTabs, true /* force */);
rebindAdapters(true /* force */);
mSearchContainer = findViewById(R.id.search_container_all_apps);
mSearchUiManager = (SearchUiManager) mSearchContainer;
@@ -401,12 +387,10 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
public void setInsets(Rect insets) {
mInsets.set(insets);
DeviceProfile grid = mLauncher.getDeviceProfile();
int leftRightPadding = grid.desiredWorkspaceLeftRightMarginPx
+ grid.cellLayoutPaddingLeftRightPx;
for (int i = 0; i < mAH.length; i++) {
mAH[i].padding.bottom = insets.bottom;
mAH[i].padding.left = mAH[i].padding.right = leftRightPadding;
mAH[i].padding.left = mAH[i].padding.right = grid.allAppsLeftRightPadding;
mAH[i].applyPadding();
}
@@ -427,8 +411,7 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
@Override
public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
if (Utilities.ATLEAST_Q) {
mNavBarScrimHeight = insets.getTappableElementInsets().bottom
- mLauncher.getDeviceProfile().nonOverlappingTaskbarInset;
mNavBarScrimHeight = insets.getTappableElementInsets().bottom;
} else {
mNavBarScrimHeight = insets.getStableInsetBottom();
}
@@ -445,11 +428,12 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
}
}
private void rebindAdapters(boolean showTabs) {
rebindAdapters(showTabs, false /* force */);
private void rebindAdapters() {
rebindAdapters(false /* force */);
}
protected void rebindAdapters(boolean showTabs, boolean force) {
protected void rebindAdapters(boolean force) {
boolean showTabs = mHasWorkApps && !mIsSearching;
if (showTabs == mUsingTabs && !force) {
return;
}
@@ -460,9 +444,8 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
mAllAppsStore.unregisterIconContainer(mAH[AdapterHolder.WORK].recyclerView);
if (mUsingTabs) {
setupWorkToggle();
mAH[AdapterHolder.MAIN].setup(mViewPager.getChildAt(0), mPersonalMatcher);
mAH[AdapterHolder.WORK].setup(mViewPager.getChildAt(1), mWorkMatcher);
mAH[AdapterHolder.WORK].setup(mViewPager.getChildAt(1), mWorkManager.getMatcher());
mAH[AdapterHolder.WORK].recyclerView.setId(R.id.apps_list_view_work);
mViewPager.getPageIndicator().setActiveMarker(AdapterHolder.MAIN);
findViewById(R.id.tab_personal)
@@ -494,23 +477,12 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
mAllAppsStore.registerIconContainer(mAH[AdapterHolder.WORK].recyclerView);
}
private void setupWorkToggle() {
if (Utilities.ATLEAST_P) {
mWorkModeSwitch = (WorkModeSwitch) mLauncher.getLayoutInflater().inflate(
R.layout.work_mode_fab, this, false);
this.addView(mWorkModeSwitch);
mWorkModeSwitch.setInsets(mInsets);
mWorkModeSwitch.post(() -> {
mAH[AdapterHolder.WORK].applyPadding();
resetWorkProfile();
});
}
}
private void replaceRVContainer(boolean showTabs) {
for (int i = 0; i < mAH.length; i++) {
if (mAH[i].recyclerView != null) {
mAH[i].recyclerView.setLayoutManager(null);
for (AdapterHolder adapterHolder : mAH) {
if (adapterHolder.recyclerView != null) {
adapterHolder.recyclerView.setLayoutManager(null);
adapterHolder.recyclerView.setAdapter(null);
}
}
View oldView = getRecyclerViewContainer();
@@ -519,15 +491,15 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
int layout = showTabs ? R.layout.all_apps_tabs : R.layout.all_apps_rv_layout;
View newView = getLayoutInflater().inflate(layout, this, false);
addView(newView, index);
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.WORK_PROFILE_REMOVED, "should show tabs:" + showTabs,
new Exception());
}
if (showTabs) {
mViewPager = (AllAppsPagedView) newView;
mViewPager.initParentViews(this);
mViewPager.getPageIndicator().setOnActivePageChangedListener(this);
if (mWorkManager.attachWorkModeSwitch()) {
mWorkManager.getWorkModeSwitch().post(() -> mAH[AdapterHolder.WORK].applyPadding());
}
} else {
mWorkManager.detachWorkModeSwitch();
mViewPager = null;
}
}
@@ -543,19 +515,8 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
mAH[currentActivePage].recyclerView.bindFastScrollbar();
}
reset(true /* animate */);
if (mWorkModeSwitch != null) {
mWorkModeSwitch.setWorkTabVisible(currentActivePage == AdapterHolder.WORK
&& mAllAppsStore.hasModelFlag(
FLAG_HAS_SHORTCUT_PERMISSION | FLAG_QUIET_MODE_CHANGE_PERMISSION));
if (currentActivePage == AdapterHolder.WORK) {
if (mWorkModeSwitch.getParent() == null) {
addView(mWorkModeSwitch);
}
} else {
removeView(mWorkModeSwitch);
}
}
mWorkManager.onActivePageChanged(currentActivePage);
}
// Used by tests only
@@ -623,26 +584,26 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
for (int i = 0; i < mAH.length; i++) {
mAH[i].padding.top = padding;
mAH[i].applyPadding();
if (mAH[i].recyclerView != null) {
mAH[i].recyclerView.scrollToTop();
}
}
mHeaderTop = mHeader.getTop();
}
public void setLastSearchQuery(String query) {
for (int i = 0; i < mAH.length; i++) {
mAH[i].adapter.setLastSearchQuery(query);
}
if (mUsingTabs) {
mSearchModeWhileUsingTabs = true;
rebindAdapters(false); // hide tabs
}
mIsSearching = true;
rebindAdapters();
mHeader.setCollapsed(true);
}
public void onClearSearchResult() {
if (mSearchModeWhileUsingTabs) {
rebindAdapters(true); // show tabs
mSearchModeWhileUsingTabs = false;
}
mIsSearching = false;
mHeader.setCollapsed(false);
rebindAdapters();
mHeader.reset(false);
}
public void onSearchResultsChanged() {
@@ -713,16 +674,16 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
@Override
public void drawOnScrim(Canvas canvas) {
if (!mHeader.isHeaderProtectionSupported()) return;
mHeaderPaint.setColor(mHeaderColor);
mHeaderPaint.setAlpha((int) (getAlpha() * Color.alpha(mHeaderColor)));
if (Color.alpha(mHeaderPaint.getColor()) != 0 && mHeaderPaint.getColor() != 0) {
int bottom = mUsingTabs && mHeader.mHeaderCollapsed ? mHeader.getVisibleBottomBound()
: mSearchContainer.getBottom();
canvas.drawRect(0, 0, canvas.getWidth(), bottom + getTranslationY(),
mHeaderPaint);
if (FeatureFlags.ENABLE_DEVICE_SEARCH.get() && getTranslationY() == 0) {
mSearchUiManager.getEditText().setBackground(null);
if (mHeaderPaint.getColor() != mScrimColor && mHeaderPaint.getColor() != 0) {
int bottom = (int) (mSearchContainer.getBottom() + getTranslationY());
canvas.drawRect(0, 0, canvas.getWidth(), bottom, mHeaderPaint);
int tabsHeight = getFloatingHeaderView().getPeripheralProtectionHeight();
if (mTabsProtectionAlpha > 0 && tabsHeight != 0) {
mHeaderPaint.setAlpha((int) (getAlpha() * mTabsProtectionAlpha));
canvas.drawRect(0, bottom, canvas.getWidth(), bottom + tabsHeight, mHeaderPaint);
}
}
}
@@ -731,7 +692,6 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
public static final int MAIN = 0;
public static final int WORK = 1;
private ItemInfoMatcher mInfoMatcher;
private final boolean mIsWork;
public final AllAppsGridAdapter adapter;
final LinearLayoutManager layoutManager;
@@ -739,17 +699,16 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
final Rect padding = new Rect();
AllAppsRecyclerView recyclerView;
boolean verticalFadingEdge;
private View mOverlay;
boolean mWorkDisabled;
AdapterHolder(boolean isWork) {
mIsWork = isWork;
appsList = new LawnchairAlphabeticalAppsList(mLauncher, mAllAppsStore,
isWork ? mWorkAdapterProvider : null);
isWork ? mWorkManager.getAdapterProvider() : null);
BaseAdapterProvider[] adapterProviders =
isWork ? new BaseAdapterProvider[]{mSearchAdapterProvider, mWorkAdapterProvider}
isWork ? new BaseAdapterProvider[]{mSearchAdapterProvider,
mWorkManager.getAdapterProvider()}
: new BaseAdapterProvider[]{mSearchAdapterProvider};
adapter = new AllAppsGridAdapter(mLauncher, getLayoutInflater(), appsList,
@@ -759,7 +718,6 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
}
void setup(@NonNull View rv, @Nullable ItemInfoMatcher matcher) {
mInfoMatcher = matcher;
appsList.updateItemFilter(matcher);
recyclerView = (AllAppsRecyclerView) rv;
recyclerView.setEdgeEffectFactory(createEdgeEffectFactory());
@@ -782,12 +740,10 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
void applyPadding() {
if (recyclerView != null) {
Resources res = getResources();
int switchH = res.getDimensionPixelSize(R.dimen.work_profile_footer_padding) * 2
+ mInsets.bottom + Utilities.calculateTextHeight(
res.getDimension(R.dimen.work_profile_footer_text_size));
int bottomOffset = mWorkModeSwitch != null && mIsWork ? switchH : 0;
int bottomOffset = 0;
if (mIsWork && mWorkManager.getWorkModeSwitch() != null) {
bottomOffset = mInsets.bottom + mWorkManager.getWorkModeSwitch().getHeight();
}
recyclerView.setPadding(padding.left, padding.top, padding.right,
padding.bottom + bottomOffset);
}
@@ -802,25 +758,27 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
protected void updateHeaderScroll(int scrolledOffset) {
float prog = Math.max(0, Math.min(1, (float) scrolledOffset / mHeaderThreshold));
int transparentScrim = ColorUtils.setAlphaComponent(mScrimColor, 0);
int viewBG = ColorUtils.blendARGB(transparentScrim, mHeaderProtectionColor, prog);
int searchAlpha = (int) (getSearchView().getAlpha() * prog * 255);
int headerColor = ColorUtils.setAlphaComponent(viewBG, searchAlpha);
if (headerColor != mHeaderColor) {
float prog = Utilities.boundToRange((float) scrolledOffset / mHeaderThreshold, 0f, 1f);
int viewBG = ColorUtils.blendARGB(mScrimColor, mHeaderProtectionColor, prog);
int headerColor = ColorUtils.setAlphaComponent(viewBG,
(int) (getSearchView().getAlpha() * 255));
int tabsAlpha = mHeader.getPeripheralProtectionHeight() == 0 ? 0
: (int) (Utilities.boundToRange(
(scrolledOffset + mHeader.mSnappedScrolledY) / mHeaderThreshold, 0f, 1f)
* 255);
if (headerColor != mHeaderColor || mTabsProtectionAlpha != tabsAlpha) {
mHeaderColor = headerColor;
getSearchView().setBackgroundColor(searchAlpha == 255 ? viewBG : 0);
getFloatingHeaderView().setHeaderColor(viewBG);
mTabsProtectionAlpha = tabsAlpha;
invalidateHeader();
ExtendedEditText editText = mSearchUiManager.getEditText();
if (editText != null) {
if (searchAlpha == 0) {
editText.show();
} else {
editText.hide();
}
}
if (mSearchUiManager.getEditText() != null) {
boolean bgVisible = mSearchUiManager.getBackgroundVisibility();
if (scrolledOffset == 0 && !mIsSearching) {
bgVisible = true;
} else if (scrolledOffset > mHeaderThreshold) {
bgVisible = false;
}
mSearchUiManager.setBackgroundVisibility(bgVisible, 1 - prog);
}
}
@@ -828,7 +786,7 @@ public class AllAppsContainerView extends StretchRecyclerViewContainer implement
* redraws header protection
*/
public void invalidateHeader() {
if (mScrimView != null && FeatureFlags.ENABLE_DEVICE_SEARCH.get()) {
if (mScrimView != null && mHeader.isHeaderProtectionSupported()) {
mScrimView.invalidate();
}
}
@@ -43,7 +43,9 @@ import androidx.recyclerview.widget.RecyclerView;
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.R;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.Themes;
@@ -98,16 +100,15 @@ public class AllAppsGridAdapter extends
// The type of this item
public int viewType;
/** App-only properties */
// The section name of this app. Note that there can be multiple items with different
// The section name of this item. Note that there can be multiple items with different
// sectionNames in the same section
public String sectionName = null;
// The row that this item shows up on
public int rowIndex;
// The index of this app in the row
public int rowAppIndex;
// The associated AppInfo for the app
public AppInfo appInfo = null;
// The associated ItemInfoWithIcon for the item
public ItemInfoWithIcon itemInfo = null;
// The index of this app not including sections
public int appIndex = -1;
// Search section associated to result
@@ -122,7 +123,7 @@ public class AllAppsGridAdapter extends
item.viewType = VIEW_TYPE_ICON;
item.position = pos;
item.sectionName = sectionName;
item.appInfo = appInfo;
item.itemInfo = appInfo;
item.appIndex = appIndex;
return item;
}
@@ -276,6 +277,8 @@ public class AllAppsGridAdapter extends
// The intent to send off to the market app, updated each time the search query changes.
private Intent mMarketSearchIntent;
private final int mExtraHeight;
public AllAppsGridAdapter(BaseDraggingActivity launcher, LayoutInflater inflater,
AlphabeticalAppsList apps, BaseAdapterProvider[] adapterProviders) {
Resources res = launcher.getResources();
@@ -291,6 +294,7 @@ public class AllAppsGridAdapter extends
mAdapterProviders = adapterProviders;
setAppsPerRow(mLauncher.getDeviceProfile().numShownAllAppsColumns);
mExtraHeight = launcher.getResources().getDimensionPixelSize(R.dimen.all_apps_height_extra);
}
public void setAppsPerRow(int appsPerRow) {
@@ -350,14 +354,19 @@ public class AllAppsGridAdapter extends
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case VIEW_TYPE_ICON:
int layout = !FeatureFlags.ENABLE_TWOLINE_ALLAPPS.get() ? R.layout.all_apps_icon
: R.layout.all_apps_icon_twoline;
BubbleTextView icon = (BubbleTextView) mLayoutInflater.inflate(
R.layout.all_apps_icon, parent, false);
layout, parent, false);
icon.setLongPressTimeoutFactor(1f);
icon.setOnFocusChangeListener(mIconFocusListener);
icon.setOnClickListener(mOnIconClickListener);
icon.setOnLongClickListener(mOnIconLongClickListener);
// Ensure the all apps icon height matches the workspace icons in portrait mode.
icon.getLayoutParams().height = mLauncher.getDeviceProfile().allAppsCellHeightPx;
if (FeatureFlags.ENABLE_TWOLINE_ALLAPPS.get()) {
icon.getLayoutParams().height += mExtraHeight;
}
return new ViewHolder(icon);
case VIEW_TYPE_EMPTY_SEARCH:
return new ViewHolder(mLayoutInflater.inflate(R.layout.all_apps_empty_search,
@@ -378,7 +387,7 @@ public class AllAppsGridAdapter extends
if (adapterProvider != null) {
return adapterProvider.onCreateViewHolder(mLayoutInflater, parent, viewType);
}
throw new RuntimeException("Unexpected view type");
throw new RuntimeException("Unexpected view type" + viewType);
}
}
@@ -387,10 +396,13 @@ public class AllAppsGridAdapter extends
switch (holder.getItemViewType()) {
case VIEW_TYPE_ICON:
AdapterItem adapterItem = mApps.getAdapterItems().get(position);
AppInfo info = adapterItem.appInfo;
BubbleTextView icon = (BubbleTextView) holder.itemView;
icon.reset();
icon.applyFromApplicationInfo(info);
if (adapterItem.itemInfo instanceof AppInfo) {
icon.applyFromApplicationInfo((AppInfo) adapterItem.itemInfo);
} else {
icon.applyFromItemInfoWithIcon(adapterItem.itemInfo);
}
break;
case VIEW_TYPE_EMPTY_SEARCH:
TextView emptyViewText = (TextView) holder.itemView;
@@ -21,6 +21,7 @@ import static android.view.View.MeasureSpec.makeMeasureSpec;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ALLAPPS_VERTICAL_SWIPE_BEGIN;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ALLAPPS_VERTICAL_SWIPE_END;
import static com.android.launcher3.util.LogConfig.SEARCH_LOGGING;
import static com.android.launcher3.util.UiThreadHelper.hideKeyboardAsync;
import android.content.Context;
@@ -40,6 +41,7 @@ import com.android.launcher3.BaseRecyclerView;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.logging.StatsLogManager;
import com.android.launcher3.views.ActivityContext;
@@ -54,6 +56,7 @@ import java.util.List;
public class AllAppsRecyclerView extends BaseRecyclerView {
private static final String TAG = "AllAppsContainerView";
private static final boolean DEBUG = false;
private static final boolean DEBUG_LATENCY = Utilities.isPropertyEnabled(SEARCH_LOGGING);
private AlphabeticalAppsList mApps;
private final int mNumAppsPerRow;
@@ -63,6 +66,13 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
private final SparseIntArray mCachedScrollPositions = new SparseIntArray();
private final AllAppsFastScrollHelper mFastScrollHelper;
private final AdapterDataObserver mObserver = new RecyclerView.AdapterDataObserver() {
public void onChanged() {
mCachedScrollPositions.clear();
}
};
// The empty-search result background
private AllAppsBackgroundDrawable mEmptySearchBackground;
private int mEmptySearchBackgroundTopOffset;
@@ -126,6 +136,10 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
if (DEBUG) {
Log.d(TAG, "onDraw at = " + System.currentTimeMillis());
}
if (DEBUG_LATENCY) {
Log.d(SEARCH_LOGGING,
"-- Recycle view onDraw, time stamp = " + System.currentTimeMillis());
}
super.onDraw(c);
}
@@ -247,12 +261,13 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
@Override
public void setAdapter(Adapter adapter) {
if (getAdapter() != null) {
getAdapter().unregisterAdapterDataObserver(mObserver);
}
super.setAdapter(adapter);
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
public void onChanged() {
mCachedScrollPositions.clear();
}
});
if (adapter != null) {
adapter.registerAdapterDataObserver(mObserver);
}
}
@Override
@@ -17,6 +17,7 @@ package com.android.launcher3.allapps;
import static com.android.launcher3.LauncherState.ALL_APPS;
import static com.android.launcher3.LauncherState.ALL_APPS_CONTENT;
import static com.android.launcher3.LauncherState.NORMAL;
import static com.android.launcher3.anim.Interpolators.DEACCEL_1_7;
import static com.android.launcher3.anim.Interpolators.LINEAR;
import static com.android.launcher3.anim.PropertySetter.NO_ANIM_PROPERTY_SETTER;
@@ -28,6 +29,7 @@ import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.util.FloatProperty;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.view.animation.Interpolator;
@@ -37,7 +39,6 @@ import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.AnimatorListeners;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.anim.PropertySetter;
import com.android.launcher3.config.FeatureFlags;
@@ -59,7 +60,6 @@ public class AllAppsTransitionController
implements StateHandler<LauncherState>, OnDeviceProfileChangeListener {
// This constant should match the second derivative of the animator interpolator.
public static final float INTERP_COEFF = 1.7f;
private static final float CONTENT_VISIBLE_MAX_THRESHOLD = 0.5f;
public static final FloatProperty<AllAppsTransitionController> ALL_APPS_PROGRESS =
new FloatProperty<AllAppsTransitionController>("allAppsProgress") {
@@ -168,6 +168,11 @@ public class AllAppsTransitionController
builder.add(anim);
setAlphas(toState, config, builder);
if (ALL_APPS.equals(toState) && mLauncher.isInState(NORMAL)) {
mLauncher.getAppsView().performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
}
}
public Animator createSpringAnimation(float... progressValues) {
@@ -181,8 +186,7 @@ public class AllAppsTransitionController
int visibleElements = state.getVisibleElements(mLauncher);
boolean hasAllAppsContent = (visibleElements & ALL_APPS_CONTENT) != 0;
Interpolator allAppsFade = config.getInterpolator(ANIM_ALL_APPS_FADE,
Interpolators.clampToProgress(LINEAR, 0, CONTENT_VISIBLE_MAX_THRESHOLD));
Interpolator allAppsFade = config.getInterpolator(ANIM_ALL_APPS_FADE, LINEAR);
setter.setViewAlpha(mAppsView, hasAllAppsContent ? 1 : 0, allAppsFade);
boolean shouldProtectHeader =
@@ -47,6 +47,8 @@ public interface FloatingHeaderRow {
/**
* Scrolls the content vertically.
* @param scroll scrolled distance in pixels for active recyclerview.
* @param isScrolledOut bool to determine if row is scrolled out of view
*/
void setVerticalScroll(int scroll, boolean isScrolledOut);
@@ -17,9 +17,6 @@ package com.android.launcher3.allapps;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.ArrayMap;
@@ -50,11 +47,10 @@ public class FloatingHeaderView extends LinearLayout implements
ValueAnimator.AnimatorUpdateListener, PluginListener<AllAppsRow>, Insettable,
OnHeightUpdatedListener {
private final Rect mClip = new Rect(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE);
private final Rect mRVClip = new Rect(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE);
private final Rect mHeaderClip = new Rect(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE);
private final ValueAnimator mAnimator = ValueAnimator.ofInt(0, 0);
private final ValueAnimator mHeaderAnimator = ValueAnimator.ofInt(0, 1).setDuration(100);
private final Point mTempOffset = new Point();
private final Paint mBGPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final RecyclerView.OnScrollListener mOnScrollListener =
new RecyclerView.OnScrollListener() {
@Override
@@ -82,19 +78,19 @@ public class FloatingHeaderView extends LinearLayout implements
}
};
private final int mHeaderTopPadding;
protected final Map<AllAppsRow, PluginHeaderRow> mPluginRows = new ArrayMap<>();
private final int mHeaderTopPadding;
private final boolean mHeaderProtectionSupported;
protected ViewGroup mTabLayout;
private AllAppsRecyclerView mMainRV;
private AllAppsRecyclerView mWorkRV;
private AllAppsRecyclerView mCurrentRV;
private ViewGroup mParent;
public boolean mHeaderCollapsed;
private int mSnappedScrolledY;
protected int mSnappedScrolledY;
private int mTranslationY;
private int mHeaderColor;
private boolean mForwardToRecyclerView;
@@ -112,6 +108,7 @@ public class FloatingHeaderView extends LinearLayout implements
// enabled or disabled, and represent the current set of all rows.
private FloatingHeaderRow[] mAllRows = FloatingHeaderRow.NO_ROWS;
public FloatingHeaderView(@NonNull Context context) {
this(context, null);
}
@@ -120,6 +117,8 @@ public class FloatingHeaderView extends LinearLayout implements
super(context, attrs);
mHeaderTopPadding = context.getResources()
.getDimensionPixelSize(R.dimen.all_apps_header_top_padding);
mHeaderProtectionSupported = context.getResources().getBoolean(
R.bool.config_header_protection_supported);
}
@Override
@@ -138,7 +137,6 @@ public class FloatingHeaderView extends LinearLayout implements
}
mFixedRows = rows.toArray(new FloatingHeaderRow[rows.size()]);
mAllRows = mFixedRows;
mHeaderAnimator.addUpdateListener(valueAnimator -> invalidate());
}
@Override
@@ -285,7 +283,7 @@ public class FloatingHeaderView extends LinearLayout implements
mHeaderCollapsed = false;
}
mTranslationY = currentScrollY;
} else if (!mHeaderCollapsed) {
} else {
mTranslationY = currentScrollY - mSnappedScrolledY - mMaxTranslation;
// update state vars
@@ -295,31 +293,10 @@ public class FloatingHeaderView extends LinearLayout implements
} else if (mTranslationY <= -mMaxTranslation) { // hide or stay hidden
mHeaderCollapsed = true;
mSnappedScrolledY = -mMaxTranslation;
mHeaderAnimator.setCurrentFraction(0);
mHeaderAnimator.start();
}
}
}
/**
* Set current header protection background color
*/
public void setHeaderColor(int color) {
mHeaderColor = color;
invalidate();
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (mHeaderCollapsed && !mCollapsed && mTabLayout.getVisibility() == VISIBLE
&& mHeaderColor != Color.TRANSPARENT && FeatureFlags.ENABLE_DEVICE_SEARCH.get()) {
mBGPaint.setColor(mHeaderColor);
mBGPaint.setAlpha((int) (255 * mHeaderAnimator.getAnimatedFraction()));
canvas.drawRect(0, 0, getWidth(), getHeight() + mTranslationY, mBGPaint);
}
super.dispatchDraw(canvas);
}
protected void applyVerticalMove() {
int uncappedTranslationY = mTranslationY;
mTranslationY = Math.max(mTranslationY, -mMaxTranslation);
@@ -336,11 +313,15 @@ public class FloatingHeaderView extends LinearLayout implements
}
mTabLayout.setTranslationY(mTranslationY);
mClip.top = mMaxTranslation + mTranslationY;
int clipHeight = mHeaderTopPadding - getPaddingBottom();
mRVClip.top = mTabsHidden ? clipHeight : 0;
mHeaderClip.top = clipHeight;
// clipping on a draw might cause additional redraw
mMainRV.setClipBounds(mClip);
setClipBounds(mHeaderClip);
mMainRV.setClipBounds(mRVClip);
if (mWorkRV != null) {
mWorkRV.setClipBounds(mClip);
mWorkRV.setClipBounds(mRVClip);
}
}
@@ -421,6 +402,10 @@ public class FloatingHeaderView extends LinearLayout implements
return false;
}
public boolean isHeaderProtectionSupported() {
return mHeaderProtectionSupported;
}
@Override
public boolean hasOverlappingRendering() {
return false;
@@ -444,10 +429,19 @@ public class FloatingHeaderView extends LinearLayout implements
}
/**
* Returns visible height of FloatingHeaderView contents
* Returns visible height of FloatingHeaderView contents requiring header protection
*/
public int getVisibleBottomBound() {
return getBottom() + mTranslationY;
public int getPeripheralProtectionHeight() {
if (!mHeaderProtectionSupported) {
return 0;
}
// we only want to show protection when work tab is available and header is either
// collapsed or animating to/from collapsed state
if (mTabsHidden || !mHeaderCollapsed) {
return 0;
}
return Math.max(getHeight() - getPaddingTop() + mTranslationY, 0);
}
}
@@ -22,7 +22,6 @@ import android.view.MotionEvent;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
import com.android.launcher3.statemanager.StateManager.StateListener;
/**
* AllAppsContainerView with launcher specific callbacks
@@ -31,8 +30,6 @@ public class LauncherAllAppsContainerView extends AllAppsContainerView {
private final Launcher mLauncher;
private StateListener<LauncherState> mWorkTabListener;
public LauncherAllAppsContainerView(Context context) {
this(context, null);
}
@@ -74,14 +71,6 @@ public class LauncherAllAppsContainerView extends AllAppsContainerView {
mLauncher.getAllAppsController().setScrollRangeDelta(allAppsStartingPositionY);
}
@Override
public void setupHeader() {
super.setupHeader();
if (mWorkTabListener != null && !mUsingTabs) {
mLauncher.getStateManager().removeStateListener(mWorkTabListener);
}
}
@Override
public void onActivePageChanged(int currentActivePage) {
super.onActivePageChanged(currentActivePage);
@@ -48,6 +48,19 @@ public interface SearchUiManager {
@Nullable
ExtendedEditText getEditText();
/**
* Sets whether EditText background should be visible
* @param maxAlpha defines the maximum alpha the background should animates to
*/
default void setBackgroundVisibility(boolean visible, float maxAlpha) {}
/**
* Returns whether a visible background is set on EditText
*/
default boolean getBackgroundVisibility() {
return false;
}
/**
* sets highlight result's title
*/
@@ -15,12 +15,11 @@
*/
package com.android.launcher3.allapps;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import java.util.ArrayList;
@@ -33,13 +32,13 @@ public class WorkAdapterProvider extends BaseAdapterProvider {
private static final int VIEW_TYPE_WORK_EDU_CARD = 1 << 20;
private static final int VIEW_TYPE_WORK_DISABLED_CARD = 1 << 21;
private final Runnable mRefreshCB;
private final BaseDraggingActivity mLauncher;
private boolean mEnabled;
WorkAdapterProvider(BaseDraggingActivity launcher, Runnable refreshCallback) {
mLauncher = launcher;
mRefreshCB = refreshCallback;
@WorkProfileManager.WorkProfileState
private int mState;
private SharedPreferences mPreferences;
WorkAdapterProvider(SharedPreferences prefs) {
mPreferences = prefs;
}
@Override
@@ -61,19 +60,19 @@ public class WorkAdapterProvider extends BaseAdapterProvider {
* returns whether or not work apps should be visible in work tab.
*/
public boolean shouldShowWorkApps() {
return mEnabled;
return mState != WorkProfileManager.STATE_DISABLED;
}
/**
* Adds work profile specific adapter items to adapterItems and returns number of items added
*/
public int addWorkItems(ArrayList<AllAppsGridAdapter.AdapterItem> adapterItems) {
if (!mEnabled) {
if (mState == WorkProfileManager.STATE_DISABLED) {
//add disabled card here.
AllAppsGridAdapter.AdapterItem disabledCard = new AllAppsGridAdapter.AdapterItem();
disabledCard.viewType = VIEW_TYPE_WORK_DISABLED_CARD;
adapterItems.add(disabledCard);
} else if (!isEduSeen()) {
} else if (mState == WorkProfileManager.STATE_ENABLED && !isEduSeen()) {
AllAppsGridAdapter.AdapterItem eduCard = new AllAppsGridAdapter.AdapterItem();
eduCard.viewType = VIEW_TYPE_WORK_EDU_CARD;
adapterItems.add(eduCard);
@@ -85,9 +84,8 @@ public class WorkAdapterProvider extends BaseAdapterProvider {
/**
* Sets the current state of work profile
*/
public void updateCurrentState(boolean isEnabled) {
mEnabled = isEnabled;
mRefreshCB.run();
public void updateCurrentState(@WorkProfileManager.WorkProfileState int state) {
mState = state;
}
@Override
@@ -101,6 +99,6 @@ public class WorkAdapterProvider extends BaseAdapterProvider {
}
private boolean isEduSeen() {
return Utilities.getPrefs(mLauncher).getInt(KEY_WORK_EDU_STEP, 0) != 0;
return mPreferences.getInt(KEY_WORK_EDU_STEP, 0) != 0;
}
}
@@ -16,30 +16,24 @@
package com.android.launcher3.allapps;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_TURN_OFF_WORK_APPS_TAP;
import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Insets;
import android.graphics.Rect;
import android.os.Build;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.widget.Button;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.Insettable;
import com.android.launcher3.Launcher;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.KeyboardInsetAnimationCallback;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.workprofile.PersonalWorkSlidingTabStrip;
import app.lawnchair.font.FontManager;
import app.lawnchair.theme.color.ColorStateListTokens;
@@ -48,15 +42,20 @@ import app.lawnchair.theme.drawable.DrawableTokens;
/**
* Work profile toggle switch shown at the bottom of AllApps work tab
*/
public class WorkModeSwitch extends Button implements Insettable, View.OnClickListener {
public class WorkModeSwitch extends Button implements Insettable, View.OnClickListener,
KeyboardInsetAnimationCallback.KeyboardInsetListener,
PersonalWorkSlidingTabStrip.OnActivePageChangedListener {
private Rect mInsets = new Rect();
private static final int FLAG_FADE_ONGOING = 1 << 1;
private static final int FLAG_TRANSLATION_ONGOING = 1 << 2;
private static final int FLAG_PROFILE_TOGGLE_ONGOING = 1 << 3;
private final Rect mInsets = new Rect();
private int mFlags;
private boolean mWorkEnabled;
private boolean mOnWorkTab;
@Nullable
private KeyboardInsetAnimationCallback mKeyboardInsetAnimationCallback;
public WorkModeSwitch(Context context) {
this(context, null, 0);
}
@@ -77,14 +76,17 @@ public class WorkModeSwitch extends Button implements Insettable, View.OnClickLi
setSelected(true);
setOnClickListener(this);
if (Utilities.ATLEAST_R) {
mKeyboardInsetAnimationCallback = new KeyboardInsetAnimationCallback(this);
setWindowInsetsAnimationCallback(mKeyboardInsetAnimationCallback);
KeyboardInsetAnimationCallback keyboardInsetAnimationCallback =
new KeyboardInsetAnimationCallback(this);
setWindowInsetsAnimationCallback(keyboardInsetAnimationCallback);
}
setBackground(DrawableTokens.WorkAppsToggleBackground.resolve(getContext()));
ColorStateList textColor = ColorStateListTokens.AllAppsTabText.resolve(getContext());
setTextColor(textColor);
setCompoundDrawableTintList(textColor);
DeviceProfile grid = BaseDraggingActivity.fromContext(getContext()).getDeviceProfile();
setInsets(grid.getInsets());
}
@Override
@@ -98,58 +100,58 @@ public class WorkModeSwitch extends Button implements Insettable, View.OnClickLi
}
}
/**
* Animates in/out work profile toggle panel based on the tab user is on
*/
public void setWorkTabVisible(boolean workTabVisible) {
clearAnimation();
if (workTabVisible) {
setEnabled(true);
if (mWorkEnabled) {
setVisibility(VISIBLE);
}
setAlpha(0);
animate().alpha(1).start();
} else {
animate().alpha(0).withEndAction(() -> this.setVisibility(GONE)).start();
}
@Override
public void onActivePageChanged(int page) {
mOnWorkTab = page == AllAppsContainerView.AdapterHolder.WORK;
updateVisibility();
}
@Override
public void onClick(View view) {
if (Utilities.ATLEAST_P) {
setEnabled(false);
Launcher.fromContext(getContext()).getStatsLogManager().logger().log(
LAUNCHER_TURN_OFF_WORK_APPS_TAP);
UI_HELPER_EXECUTOR.post(() -> setWorkProfileEnabled(getContext(), false));
if (Utilities.ATLEAST_P && isEnabled()) {
setFlag(FLAG_PROFILE_TOGGLE_ONGOING);
Launcher launcher = Launcher.getLauncher(getContext());
launcher.getStatsLogManager().logger().log(LAUNCHER_TURN_OFF_WORK_APPS_TAP);
launcher.getAppsView().getWorkManager().setWorkProfileEnabled(false);
}
}
@Override
public boolean isEnabled() {
return super.isEnabled() && getVisibility() == VISIBLE && mFlags == 0;
}
/**
* Sets the enabled or disabled state of the button
*/
public void updateCurrentState(boolean active) {
mWorkEnabled = active;
setEnabled(true);
setVisibility(active ? VISIBLE : GONE);
public void updateCurrentState(boolean isEnabled) {
removeFlag(FLAG_PROFILE_TOGGLE_ONGOING);
if (mWorkEnabled != isEnabled) {
mWorkEnabled = isEnabled;
updateVisibility();
}
}
@RequiresApi(Build.VERSION_CODES.P)
public static Boolean setWorkProfileEnabled(Context context, boolean enabled) {
UserManager userManager = context.getSystemService(UserManager.class);
boolean showConfirm = false;
for (UserHandle userProfile : UserCache.INSTANCE.get(context).getUserProfiles()) {
if (Process.myUserHandle().equals(userProfile)) {
continue;
}
showConfirm |= !userManager.requestQuietModeEnabled(!enabled, userProfile);
private void updateVisibility() {
clearAnimation();
if (mWorkEnabled && mOnWorkTab) {
setFlag(FLAG_FADE_ONGOING);
setVisibility(VISIBLE);
animate().alpha(1).withEndAction(() -> removeFlag(FLAG_FADE_ONGOING)).start();
} else if (getVisibility() != GONE) {
setFlag(FLAG_FADE_ONGOING);
animate().alpha(0).withEndAction(() -> {
removeFlag(FLAG_FADE_ONGOING);
this.setVisibility(GONE);
}).start();
}
return showConfirm;
}
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (Utilities.ATLEAST_R) {
if (Utilities.ATLEAST_R && isEnabled()) {
setTranslationY(0);
if (insets.isVisible(WindowInsets.Type.ime())) {
Insets keyboardInsets = insets.getInsets(WindowInsets.Type.ime());
@@ -158,4 +160,22 @@ public class WorkModeSwitch extends Button implements Insettable, View.OnClickLi
}
return insets;
}
@Override
public void onTranslationStart() {
setFlag(FLAG_TRANSLATION_ONGOING);
}
@Override
public void onTranslationEnd() {
removeFlag(FLAG_TRANSLATION_ONGOING);
}
private void setFlag(int flag) {
mFlags |= flag;
}
private void removeFlag(int flag) {
mFlags &= ~flag;
}
}
@@ -16,7 +16,6 @@
package com.android.launcher3.allapps;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_TURN_ON_WORK_APPS_TAP;
import static com.android.launcher3.util.Executors.UI_HELPER_EXECUTOR;
import android.content.Context;
import android.content.res.Configuration;
@@ -70,8 +69,8 @@ public class WorkPausedCard extends LinearLayout implements View.OnClickListener
public void onClick(View view) {
if (Utilities.ATLEAST_P) {
setEnabled(false);
mLauncher.getAppsView().getWorkManager().setWorkProfileEnabled(true);
mLauncher.getStatsLogManager().logger().log(LAUNCHER_TURN_ON_WORK_APPS_TAP);
UI_HELPER_EXECUTOR.post(() -> WorkModeSwitch.setWorkProfileEnabled(getContext(), true));
}
}
@@ -0,0 +1,182 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.allapps;
import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_HAS_SHORTCUT_PERMISSION;
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.util.Executors.UI_HELPER_EXECUTOR;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.Log;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.android.launcher3.R;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.workprofile.PersonalWorkSlidingTabStrip;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Companion class for {@link AllAppsContainerView} to manage work tab and personal tab related
* logic based on {@link WorkProfileState}?
*/
public class WorkProfileManager implements PersonalWorkSlidingTabStrip.OnActivePageChangedListener {
private static final String TAG = "WorkProfileManager";
public static final int STATE_ENABLED = 1;
public static final int STATE_DISABLED = 2;
public static final int STATE_TRANSITION = 3;
private final UserManager mUserManager;
/**
* Work profile manager states
*/
@IntDef(value = {
STATE_ENABLED,
STATE_DISABLED,
STATE_TRANSITION
})
@Retention(RetentionPolicy.SOURCE)
public @interface WorkProfileState {
}
private final AllAppsContainerView mAllApps;
private final WorkAdapterProvider mAdapterProvider;
private final ItemInfoMatcher mMatcher;
private WorkModeSwitch mWorkModeSwitch;
@WorkProfileState
private int mCurrentState;
public WorkProfileManager(UserManager userManager, AllAppsContainerView allApps,
SharedPreferences preferences) {
mUserManager = userManager;
mAllApps = allApps;
mAdapterProvider = new WorkAdapterProvider(preferences);
mMatcher = mAllApps.mPersonalMatcher.negate();
}
/**
* Posts quite mode enable/disable call for work profile user
*/
@RequiresApi(Build.VERSION_CODES.P)
public void setWorkProfileEnabled(boolean enabled) {
updateCurrentState(STATE_TRANSITION);
UI_HELPER_EXECUTOR.post(() -> {
for (UserHandle userProfile : mUserManager.getUserProfiles()) {
if (Process.myUserHandle().equals(userProfile)) {
continue;
}
mUserManager.requestQuietModeEnabled(!enabled, userProfile);
}
});
}
@Override
public void onActivePageChanged(int page) {
if (mWorkModeSwitch != null) {
mWorkModeSwitch.onActivePageChanged(page);
}
}
/**
* Requests work profile state from {@link AllAppsStore} and updates work profile related views
*/
public void reset() {
boolean isEnabled = !mAllApps.getAppsStore().hasModelFlag(FLAG_QUIET_MODE_ENABLED);
updateCurrentState(isEnabled ? STATE_ENABLED : STATE_DISABLED);
}
private void updateCurrentState(@WorkProfileState int currentState) {
mCurrentState = currentState;
mAdapterProvider.updateCurrentState(currentState);
if (getAH() != null) {
getAH().appsList.updateAdapterItems();
}
if (mWorkModeSwitch != null) {
mWorkModeSwitch.updateCurrentState(currentState == STATE_ENABLED);
}
}
/**
* Creates and attaches for profile toggle button to {@link AllAppsContainerView}
*/
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 (mWorkModeSwitch == null) {
mWorkModeSwitch = (WorkModeSwitch) mAllApps.getLayoutInflater().inflate(
R.layout.work_mode_fab, mAllApps, false);
}
if (mWorkModeSwitch.getParent() != mAllApps) {
mAllApps.addView(mWorkModeSwitch);
}
if (getAH() != null) {
getAH().applyPadding();
}
mWorkModeSwitch.updateCurrentState(mCurrentState == STATE_ENABLED);
return true;
}
/**
* Removes work profile toggle button from {@link AllAppsContainerView}
*/
public void detachWorkModeSwitch() {
if (mWorkModeSwitch != null && mWorkModeSwitch.getParent() == mAllApps) {
mAllApps.removeView(mWorkModeSwitch);
}
mWorkModeSwitch = null;
}
public WorkAdapterProvider getAdapterProvider() {
return mAdapterProvider;
}
public ItemInfoMatcher getMatcher() {
return mMatcher;
}
@Nullable
public WorkModeSwitch getWorkModeSwitch() {
return mWorkModeSwitch;
}
private AllAppsContainerView.AdapterHolder getAH() {
return mAllApps.mAH[AllAppsContainerView.AdapterHolder.WORK];
}
public int getCurrentState() {
return mCurrentState;
}
}
@@ -18,8 +18,10 @@ package com.android.launcher3.allapps.search;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_ALLAPPS_FOCUSED_ITEM_SELECTED_WITH_IME;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.SuggestionSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
@@ -47,6 +49,7 @@ public class AllAppsSearchBarController
protected SearchCallback<AdapterItem> mCallback;
protected ExtendedEditText mInput;
protected String mQuery;
private String[] mTextConversions;
protected SearchAlgorithm<AdapterItem> mSearchAlgorithm;
@@ -78,7 +81,20 @@ public class AllAppsSearchBarController
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Do nothing
mTextConversions = extractTextConversions(s);
}
private static String[] extractTextConversions(CharSequence text) {
if (text instanceof SpannableStringBuilder) {
SpannableStringBuilder spanned = (SpannableStringBuilder) text;
SuggestionSpan[] suggestionSpans =
spanned.getSpans(0, text.length(), SuggestionSpan.class);
if (suggestionSpans != null && suggestionSpans.length > 0) {
spanned.removeSpan(suggestionSpans[0]);
return suggestionSpans[0].getSuggestions();
}
}
return null;
}
@Override
@@ -89,7 +105,7 @@ public class AllAppsSearchBarController
mCallback.clearSearchResult();
} else {
mSearchAlgorithm.cancel(false);
mSearchAlgorithm.doSearch(mQuery, mCallback);
mSearchAlgorithm.doSearch(mQuery, mTextConversions, mCallback);
}
}
@@ -154,4 +170,4 @@ public class AllAppsSearchBarController
public boolean isSearchFieldFocused() {
return mInput.isFocused();
}
}
}
@@ -105,8 +105,8 @@ public class AppsSearchContainerLayout extends ExtendedEditText
int rowWidth = myRequestedWidth - mAppsView.getActiveRecyclerView().getPaddingLeft()
- mAppsView.getActiveRecyclerView().getPaddingRight();
int cellWidth = DeviceProfile.calculateCellWidth(rowWidth, dp.cellLayoutBorderSpacingPx,
dp.numShownHotseatIcons);
int cellWidth = DeviceProfile.calculateCellWidth(rowWidth,
dp.cellLayoutBorderSpacePx.x, dp.numShownHotseatIcons);
int iconVisibleSize = Math.round(ICON_VISIBLE_AREA_FACTOR * dp.iconSizePx);
int iconPadding = cellWidth - iconVisibleSize;
@@ -40,8 +40,8 @@ public class FlingSpringAnim {
private float mTargetPosition;
public <K> FlingSpringAnim(K object, Context context, FloatPropertyCompat<K> property,
float startPosition, float targetPosition, float startVelocity, float minVisChange,
float minValue, float maxValue, float springVelocityFactor,
float startPosition, float targetPosition, float startVelocityPxPerS,
float minVisChange, float minValue, float maxValue,
OnAnimationEndListener onEndListener) {
ResourceProvider rp = DynamicResource.provider(context);
float damping = rp.getFloat(R.dimen.swipe_up_rect_xy_damping_ratio);
@@ -53,19 +53,19 @@ public class FlingSpringAnim {
// Have the spring pull towards the target if we've slowed down too much before
// reaching it.
.setMinimumVisibleChange(minVisChange)
.setStartVelocity(startVelocity)
.setStartVelocity(startVelocityPxPerS)
.setMinValue(minValue)
.setMaxValue(maxValue);
mTargetPosition = targetPosition;
// We are already past the fling target, so skip it to avoid losing a frame of the spring.
mSkipFlingAnim = startPosition <= minValue && startVelocity < 0
|| startPosition >= maxValue && startVelocity > 0;
mSkipFlingAnim = startPosition <= minValue && startVelocityPxPerS < 0
|| startPosition >= maxValue && startVelocityPxPerS > 0;
mFlingAnim.addEndListener(((animation, canceled, value, velocity) -> {
mSpringAnim = new SpringAnimation(object, property)
.setStartValue(value)
.setStartVelocity(velocity * springVelocityFactor)
.setStartVelocity(velocity)
.setSpring(new SpringForce(mTargetPosition)
.setStiffness(stiffness)
.setDampingRatio(damping));
@@ -65,7 +65,32 @@ public class KeyboardInsetAnimationCallback extends WindowInsetsAnimation.Callba
public WindowInsetsAnimation.Bounds onStart(WindowInsetsAnimation animation,
WindowInsetsAnimation.Bounds bounds) {
mTerminalTranslation = mView.getTranslationY();
mView.setTranslationY(mInitialTranslation);
if (mView instanceof KeyboardInsetListener) {
((KeyboardInsetListener) mView).onTranslationStart();
}
return super.onStart(animation, bounds);
}
@Override
public void onEnd(WindowInsetsAnimation animation) {
if (mView instanceof KeyboardInsetListener) {
((KeyboardInsetListener) mView).onTranslationEnd();
}
super.onEnd(animation);
}
/**
* Interface Allowing views to listen for keyboard translation events
*/
public interface KeyboardInsetListener {
/**
* Called from {@link KeyboardInsetAnimationCallback#onStart}
*/
void onTranslationStart();
/**
* Called from {@link KeyboardInsetAnimationCallback#onEnd}
*/
void onTranslationEnd();
}
}
@@ -56,6 +56,10 @@ public class PendingAnimation implements PropertySetter {
mAnim = new AnimatorSet();
}
public long getDuration() {
return mDuration;
}
/**
* Utility method to sent an interpolator on an animation and add it to the list
*/
@@ -16,6 +16,7 @@
package com.android.launcher3.anim;
import android.animation.Animator;
import android.animation.TimeInterpolator;
import android.util.FloatProperty;
import android.util.IntProperty;
@@ -64,4 +65,9 @@ public interface PropertySetter {
TimeInterpolator interpolator) {
property.setValue(target, value);
}
default void add(Animator animatorSet) {
animatorSet.setDuration(0);
animatorSet.start();
}
}
@@ -26,9 +26,27 @@ public abstract class RevealOutlineAnimation extends ViewOutlineProvider {
/** Sets the progress, from 0 to 1, of the reveal animation. */
abstract void setProgress(float progress);
/**
* @see #createRevealAnimator(View, boolean, float) where startProgress is set to 0.
*/
public ValueAnimator createRevealAnimator(final View revealView, boolean isReversed) {
ValueAnimator va =
isReversed ? ValueAnimator.ofFloat(1f, 0f) : ValueAnimator.ofFloat(0f, 1f);
return createRevealAnimator(revealView, isReversed, 0f /* startProgress */);
}
/**
* Animates the given View's ViewOutline according to {@link #setProgress(float)}.
* @param revealView The View whose outline we are animating.
* @param isReversed Whether we are hiding rather than revealing the View.
* @param startProgress The progress at which to start the newly created animation. Useful if
* the previous reveal animation was cancelled and we want to create a new animation where it
* left off. Note that if isReversed=true, we start at 1 - startProgress (and go to 0).
* @return The Animator, which the caller must start.
*/
public ValueAnimator createRevealAnimator(final View revealView, boolean isReversed,
float startProgress) {
ValueAnimator va = isReversed
? ValueAnimator.ofFloat(1f - startProgress, 0f)
: ValueAnimator.ofFloat(startProgress, 1f);
final float elevation = revealView.getElevation();
va.addListener(new AnimatorListenerAdapter() {
@@ -41,11 +41,10 @@ public class AccessibilityManagerCompat {
}
/**
*
* @param target The view the accessibility event is initialized on.
* If null, this method has no effect.
* @param type See TYPE_ constants defined in {@link AccessibilityEvent}.
* @param text Optional text to add to the event, which will be announced to the user.
* @param type See TYPE_ constants defined in {@link AccessibilityEvent}.
* @param text Optional text to add to the event, which will be announced to the user.
*/
public static void sendCustomAccessibilityEvent(@Nullable View target, int type,
@Nullable String text) {
@@ -89,6 +88,24 @@ public class AccessibilityManagerCompat {
sendEventToTest(accessibilityManager, context, TestProtocol.PAUSE_DETECTED_MESSAGE, null);
}
public static void sendDismissAnimationEndsEventToTest(Context context) {
final AccessibilityManager accessibilityManager = getAccessibilityManagerForTest(context);
if (accessibilityManager == null) return;
sendEventToTest(accessibilityManager, context, TestProtocol.DISMISS_ANIMATION_ENDS_MESSAGE,
null);
}
/**
* Notify running tests of a folder opened.
*/
public static void sendFolderOpenedEventToTest(Context context) {
final AccessibilityManager accessibilityManager = getAccessibilityManagerForTest(context);
if (accessibilityManager == null) return;
sendEventToTest(accessibilityManager, context, TestProtocol.FOLDER_OPENED_MESSAGE, null);
}
private static void sendEventToTest(
AccessibilityManager accessibilityManager,
Context context, String eventTag, Bundle data) {
@@ -79,12 +79,7 @@ public final class FeatureFlags {
"PROMISE_APPS_NEW_INSTALLS", true,
"Adds a promise icon to the home screen for new install sessions.");
public static final BooleanFlag QUICKSTEP_SPRINGS = getDebugFlag(
"QUICKSTEP_SPRINGS", true, "Enable springs for quickstep animations");
public static final BooleanFlag UNSTABLE_SPRINGS = getDebugFlag(
"UNSTABLE_SPRINGS", false, "Enable unstable springs for quickstep animations");
// TODO: b/206508141: Long pressing on some icons on home screen cause launcher to crash.
public static final BooleanFlag ENABLE_LOCAL_COLOR_POPUPS = getDebugFlag(
"ENABLE_LOCAL_COLOR_POPUPS", false, "Enable local color extraction for popups.");
@@ -101,14 +96,12 @@ public final class FeatureFlags {
"ENABLE_QUICKSTEP_WIDGET_APP_START", Utilities.ATLEAST_S,
"Enable Quickstep animation when launching activities from an app widget");
// Keep as DeviceFlag to allow remote disable in emergency.
public static final BooleanFlag ENABLE_SUGGESTED_ACTIONS_OVERVIEW = new DeviceFlag(
"ENABLE_SUGGESTED_ACTIONS_OVERVIEW", false, "Show chip hints on the overview screen");
public static final BooleanFlag ENABLE_DEVICE_SEARCH = new DeviceFlag(
"ENABLE_DEVICE_SEARCH", true, "Allows on device search in all apps");
public static final BooleanFlag ENABLE_TWOLINE_ALLAPPS = getDebugFlag(
"ENABLE_TWOLINE_ALLAPPS", false, "Enables two line label inside all apps.");
public static final BooleanFlag ENABLE_DEVICE_SEARCH_PERFORMANCE_LOGGING = new DeviceFlag(
"ENABLE_DEVICE_SEARCH_PERFORMANCE_LOGGING", true,
"Allows on device search in all apps logging");
@@ -131,16 +124,6 @@ public final class FeatureFlags {
public static final BooleanFlag ENABLE_PREDICTION_DISMISS = getDebugFlag(
"ENABLE_PREDICTION_DISMISS", true, "Allow option to dimiss apps from predicted list");
public static final BooleanFlag ENABLE_QUICK_CAPTURE_GESTURE = getDebugFlag(
"ENABLE_QUICK_CAPTURE_GESTURE", true, "Swipe from right to left to quick capture");
public static final BooleanFlag ENABLE_QUICK_CAPTURE_WINDOW = getDebugFlag(
"ENABLE_QUICK_CAPTURE_WINDOW", false, "Use window to host quick capture");
public static final BooleanFlag FORCE_LOCAL_OVERSCROLL_PLUGIN = getDebugFlag(
"FORCE_LOCAL_OVERSCROLL_PLUGIN", false,
"Use a launcher-provided OverscrollPlugin if available");
public static final BooleanFlag ASSISTANT_GIVES_LAUNCHER_FOCUS = getDebugFlag(
"ASSISTANT_GIVES_LAUNCHER_FOCUS", false,
"Allow Launcher to handle nav bar gestures while Assistant is running over it");
@@ -151,46 +134,34 @@ public final class FeatureFlags {
public static final BooleanFlag ENABLE_DEEP_SHORTCUT_ICON_CACHE = getDebugFlag(
"ENABLE_DEEP_SHORTCUT_ICON_CACHE", true, "R/W deep shortcut in IconCache");
public static final BooleanFlag MULTI_DB_GRID_MIRATION_ALGO = getDebugFlag(
"MULTI_DB_GRID_MIRATION_ALGO", true, "Use the multi-db grid migration algorithm");
public static final BooleanFlag ENABLE_THEMED_ICONS = getDebugFlag(
"ENABLE_THEMED_ICONS", true, "Enable themed icons on workspace");
public static final BooleanFlag ENABLE_BULK_WORKSPACE_ICON_LOADING = getDebugFlag(
"ENABLE_BULK_WORKSPACE_ICON_LOADING",
false,
"Enable loading workspace icons in bulk.");
public static final BooleanFlag ENABLE_BULK_ALL_APPS_ICON_LOADING = getDebugFlag(
"ENABLE_BULK_ALL_APPS_ICON_LOADING",
false,
"Enable loading all apps icons in bulk.");
// Keep as DeviceFlag for remote disable in emergency.
public static final BooleanFlag ENABLE_OVERVIEW_SELECTIONS = new DeviceFlag(
"ENABLE_OVERVIEW_SELECTIONS", true, "Show Select Mode button in Overview Actions");
public static final BooleanFlag ENABLE_WIDGETS_PICKER_AIAI_SEARCH = new DeviceFlag(
"ENABLE_WIDGETS_PICKER_AIAI_SEARCH", false, "Enable AiAi search in the widgets picker");
public static final BooleanFlag ENABLE_OVERVIEW_SHARE = getDebugFlag(
"ENABLE_OVERVIEW_SHARE", false, "Show Share button in Overview Actions");
"ENABLE_WIDGETS_PICKER_AIAI_SEARCH", true, "Enable AiAi search in the widgets picker");
public static final BooleanFlag ENABLE_OVERVIEW_SHARING_TO_PEOPLE = getDebugFlag(
"ENABLE_OVERVIEW_SHARING_TO_PEOPLE", true,
"Show indicators for content on Overview to share with top people. ");
public static final BooleanFlag ENABLE_OVERVIEW_CONTENT_PUSH = getDebugFlag(
"ENABLE_OVERVIEW_CONTENT_PUSH", false, "Show Content Push button in Overview Actions");
public static final BooleanFlag ENABLE_DATABASE_RESTORE = getDebugFlag(
"ENABLE_DATABASE_RESTORE", false,
"Enable database restore when new restore session is created");
public static final BooleanFlag ENABLE_SMARTSPACE_UNIVERSAL = getDebugFlag(
"ENABLE_SMARTSPACE_UNIVERSAL", false,
"Replace Smartspace with a version rendered by System UI.");
public static final BooleanFlag ENABLE_SMARTSPACE_ENHANCED = getDebugFlag(
"ENABLE_SMARTSPACE_ENHANCED", true,
"Replace Smartspace with the enhanced version. "
+ "Ignored if ENABLE_SMARTSPACE_UNIVERSAL is enabled.");
public static final BooleanFlag ENABLE_SMARTSPACE_FEEDBACK = getDebugFlag(
"ENABLE_SMARTSPACE_FEEDBACK", true,
"Adds a menu option to send feedback for Enhanced Smartspace.");
public static final BooleanFlag ENABLE_SMARTSPACE_DISMISS = getDebugFlag(
"ENABLE_SMARTSPACE_DISMISS", true,
"Adds a menu option to dismiss the current Enhanced Smartspace card.");
@@ -227,14 +198,21 @@ public final class FeatureFlags {
+ "predictions to be updated while they are visible to the user.");
public static final BooleanFlag ENABLE_TASKBAR = getDebugFlag(
"ENABLE_TASKBAR", false, "Allows a system Taskbar to be shown on larger devices.");
"ENABLE_TASKBAR", true, "Allows a system Taskbar to be shown on larger devices.");
public static final BooleanFlag ENABLE_TASKBAR_EDU = getDebugFlag("ENABLE_TASKBAR_EDU", true,
"Enables showing taskbar education the first time an app is opened.");
public static final BooleanFlag ENABLE_TASKBAR_POPUP_MENU = getDebugFlag(
"ENABLE_TASKBAR_POPUP_MENU", false, "Enables long pressing taskbar icons to show the"
+ " popup menu.");
public static final BooleanFlag ENABLE_OVERVIEW_GRID = getDebugFlag(
"ENABLE_OVERVIEW_GRID", false, "Uses grid overview layout. "
"ENABLE_OVERVIEW_GRID", true, "Uses grid overview layout. "
+ "Only applicable on large screen devices.");
public static final BooleanFlag ENABLE_TWO_PANEL_HOME = getDebugFlag(
"ENABLE_TWO_PANEL_HOME", false,
"ENABLE_TWO_PANEL_HOME", true,
"Uses two panel on home screen. Only applicable on large screen devices.");
public static final BooleanFlag ENABLE_SCRIM_FOR_APP_LAUNCH = getDebugFlag(
@@ -242,7 +220,7 @@ public final class FeatureFlags {
"Enables scrim during app launch animation.");
public static final BooleanFlag ENABLE_SPLIT_SELECT = getDebugFlag(
"ENABLE_SPLIT_SELECT", false, "Uses new split screen selection overview UI");
"ENABLE_SPLIT_SELECT", true, "Uses new split screen selection overview UI");
public static final BooleanFlag ENABLE_ENFORCED_ROUNDED_CORNERS = new DeviceFlag(
"ENABLE_ENFORCED_ROUNDED_CORNERS", true, "Enforce rounded corners on all App Widgets");
@@ -254,13 +232,26 @@ public final class FeatureFlags {
public static final BooleanFlag NOTIFY_CRASHES = getDebugFlag("NOTIFY_CRASHES", false,
"Sends a notification whenever launcher encounters an uncaught exception.");
public static final BooleanFlag PROTOTYPE_APP_CLOSE = getDebugFlag(
"PROTOTYPE_APP_CLOSE", false, "Enables new app close");
public static final BooleanFlag ENABLE_WALLPAPER_SCRIM = getDebugFlag(
"ENABLE_WALLPAPER_SCRIM", false,
"Enables scrim over wallpaper for text protection.");
public static final BooleanFlag WIDGETS_IN_LAUNCHER_PREVIEW = getDebugFlag(
"WIDGETS_IN_LAUNCHER_PREVIEW", true,
"Enables widgets in Launcher preview for the Wallpaper app.");
public static final BooleanFlag QUICK_WALLPAPER_PICKER = getDebugFlag(
"QUICK_WALLPAPER_PICKER", true,
"Shows quick wallpaper picker in long-press menu");
public static final BooleanFlag ENABLE_BACK_SWIPE_HOME_ANIMATION = getDebugFlag(
"ENABLE_BACK_SWIPE_HOME_ANIMATION", true,
"Enables home animation to icon when user swipes back.");
public static final BooleanFlag ENABLE_ICON_LABEL_AUTO_SCALING = getDebugFlag(
"ENABLE_ICON_LABEL_AUTO_SCALING", true,
"Enables scaling/spacing for icon labels to make more characters visible");
public static void initialize(Context context) {
synchronized (sDebugFlags) {
for (DebugFlag flag : sDebugFlags) {
@@ -298,7 +289,7 @@ public final class FeatureFlags {
public static class BooleanFlag {
public final String key;
public boolean defaultValue;
public final boolean defaultValue;
public BooleanFlag(String key, boolean defaultValue) {
this.key = key;
@@ -317,16 +308,12 @@ public final class FeatureFlags {
protected StringBuilder appendProps(StringBuilder src) {
return src.append(key).append(", defaultValue=").append(defaultValue);
}
public void addChangeListener(Context context, Runnable r) { }
public void removeChangeListener(Runnable r) {}
}
public static class DebugFlag extends BooleanFlag {
public final String description;
private boolean mCurrentValue;
protected boolean mCurrentValue;
public DebugFlag(String key, boolean defaultValue, String description) {
super(key, defaultValue);
@@ -189,10 +189,18 @@ public class AddItemActivity extends BaseActivity
if (appWidgetHostView != null) {
bounds = new Rect();
appWidgetHostView.getSourceVisualDragBounds(bounds);
bounds.offset(appWidgetHostView.getLeft() - (int) mLastTouchPos.x,
appWidgetHostView.getTop() - (int) mLastTouchPos.y);
listener = new PinItemDragListener(mRequest, bounds,
appWidgetHostView.getMeasuredWidth(), appWidgetHostView.getMeasuredWidth());
float appWidgetHostViewScale = mWidgetCell.getAppWidgetHostViewScale();
int xOffset =
appWidgetHostView.getLeft() - (int) (mLastTouchPos.x * appWidgetHostViewScale);
int yOffset =
appWidgetHostView.getTop() - (int) (mLastTouchPos.y * appWidgetHostViewScale);
bounds.offset(xOffset, yOffset);
listener = new PinItemDragListener(
mRequest,
bounds,
appWidgetHostView.getMeasuredWidth(),
appWidgetHostView.getMeasuredWidth(),
appWidgetHostViewScale);
} else {
bounds = img.getBitmapBounds();
bounds.offset(img.getLeft() - (int) mLastTouchPos.x,
@@ -278,9 +286,7 @@ public class AddItemActivity extends BaseActivity
@Override
protected void onPostExecute(WidgetItem item) {
mWidgetCell.setPreviewSize(item);
mWidgetCell.applyFromCellItem(item, mApp.getWidgetCache());
mWidgetCell.ensurePreview();
mWidgetCell.applyFromCellItem(item);
}
}.executeOnExecutor(MODEL_EXECUTOR);
// TODO: Create a worker looper executor and reuse that everywhere.
@@ -22,6 +22,7 @@ import android.content.ComponentName;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.DragEvent;
import android.view.KeyEvent;
import android.view.MotionEvent;
@@ -34,6 +35,7 @@ import com.android.launcher3.DropTarget;
import com.android.launcher3.logging.InstanceId;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.TouchController;
import com.android.launcher3.views.ActivityContext;
@@ -74,7 +76,7 @@ public abstract class DragController<T extends ActivityContext>
/** Coordinate for last touch event **/
protected final Point mLastTouch = new Point();
private final Point mTmpPoint = new Point();
protected final Point mTmpPoint = new Point();
protected DropTarget.DragObject mDragObject;
@@ -146,6 +148,9 @@ public abstract class DragController<T extends ActivityContext>
float initialDragViewScale,
float dragViewScaleOnDrop,
DragOptions options) {
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NO_DROP_TARGET, "4");
}
return startDrag(drawable, /* view= */ null, originalView, dragLayerX, dragLayerY,
source, dragInfo, dragOffset, dragRegion, initialDragViewScale, dragViewScaleOnDrop,
options);
@@ -203,6 +208,9 @@ public abstract class DragController<T extends ActivityContext>
DragOptions options);
protected void callOnDragStart() {
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NO_DROP_TARGET, "6");
}
if (mOptions.preDragCondition != null) {
mOptions.preDragCondition.onPreDragEnd(mDragObject, true /* dragStarted*/);
}
@@ -317,7 +325,7 @@ public abstract class DragController<T extends ActivityContext>
mDragObject.dragView.animateTo(mMotionDown.x, mMotionDown.y, onCompleteRunnable, duration);
}
private void callOnDragEnd() {
protected void callOnDragEnd() {
if (mIsInPreDrag && mOptions.preDragCondition != null) {
mOptions.preDragCondition.onPreDragEnd(mDragObject, false /* dragStarted*/);
}
@@ -343,7 +351,7 @@ public abstract class DragController<T extends ActivityContext>
/**
* Clamps the position to the drag layer bounds.
*/
private Point getClampedDragLayerPos(float x, float y) {
protected Point getClampedDragLayerPos(float x, float y) {
mActivity.getDragLayer().getLocalVisibleRect(mRectTemp);
mTmpPoint.x = (int) Math.max(mRectTemp.left, Math.min(x, mRectTemp.right - 1));
mTmpPoint.y = (int) Math.max(mRectTemp.top, Math.min(y, mRectTemp.bottom - 1));
@@ -390,7 +398,7 @@ public abstract class DragController<T extends ActivityContext>
return false;
}
Point dragLayerPos = getClampedDragLayerPos(ev.getX(), ev.getY());
Point dragLayerPos = getClampedDragLayerPos(getX(ev), getY(ev));
mLastTouch.set(dragLayerPos.x, dragLayerPos.y);
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// Remember location of down touch
@@ -403,6 +411,14 @@ public abstract class DragController<T extends ActivityContext>
return mDragDriver != null && mDragDriver.onInterceptTouchEvent(ev);
}
protected float getX(MotionEvent ev) {
return ev.getX();
}
protected float getY(MotionEvent ev) {
return ev.getY();
}
/**
* Call this from a drag source view.
*/
@@ -165,8 +165,11 @@ public abstract class DragDriver {
* Class for driving an internal (i.e. not using framework) drag/drop operation.
*/
static class InternalDragDriver extends DragDriver {
private final DragController mDragController;
InternalDragDriver(DragController dragController, Consumer<MotionEvent> sec) {
super(dragController, sec);
mDragController = dragController;
}
@Override
@@ -176,11 +179,14 @@ public abstract class DragDriver {
switch (action) {
case MotionEvent.ACTION_MOVE:
mEventListener.onDriverDragMove(ev.getX(), ev.getY());
mEventListener.onDriverDragMove(mDragController.getX(ev),
mDragController.getY(ev));
break;
case MotionEvent.ACTION_UP:
mEventListener.onDriverDragMove(ev.getX(), ev.getY());
mEventListener.onDriverDragEnd(ev.getX(), ev.getY());
mEventListener.onDriverDragMove(mDragController.getX(ev),
mDragController.getY(ev));
mEventListener.onDriverDragEnd(mDragController.getX(ev),
mDragController.getY(ev));
break;
case MotionEvent.ACTION_CANCEL:
mEventListener.onDriverDragCancel();
@@ -197,7 +203,8 @@ public abstract class DragDriver {
switch (action) {
case MotionEvent.ACTION_UP:
mEventListener.onDriverDragEnd(ev.getX(), ev.getY());
mEventListener.onDriverDragEnd(mDragController.getX(ev),
mDragController.getY(ev));
break;
case MotionEvent.ACTION_CANCEL:
mEventListener.onDriverDragCancel();
@@ -17,14 +17,19 @@
package com.android.launcher3.dragndrop;
import static android.animation.ObjectAnimator.ofFloat;
import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_X;
import static com.android.launcher3.LauncherAnimUtils.VIEW_TRANSLATE_Y;
import static com.android.launcher3.Utilities.mapRange;
import static com.android.launcher3.anim.AnimatorListeners.forEndCallback;
import static com.android.launcher3.anim.Interpolators.DEACCEL_1_5;
import static com.android.launcher3.compat.AccessibilityManagerCompat.sendCustomAccessibilityEvent;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.animation.TypeEvaluator;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
@@ -44,10 +49,11 @@ import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.ShortcutAndWidgetContainer;
import com.android.launcher3.Workspace;
import com.android.launcher3.anim.PendingAnimation;
import com.android.launcher3.anim.SpringProperty;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.graphics.Scrim;
import com.android.launcher3.keyboard.ViewGroupFocusHelper;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.util.TouchController;
import com.android.launcher3.views.BaseDragLayer;
@@ -69,11 +75,9 @@ public class DragLayer extends BaseDragLayer<Launcher> {
private DragController mDragController;
// Variables relating to animation of views after drop
private ValueAnimator mDropAnim = null;
private Animator mDropAnim = null;
@Thunk DragView mDropView = null;
@Thunk int mAnchorViewInitialScrollX = 0;
@Thunk View mAnchorView = null;
private DragView mDropView = null;
private boolean mHoverPointClosesFolder = false;
@@ -220,12 +224,7 @@ public class DragLayer extends BaseDragLayer<Launcher> {
public void animateViewIntoPosition(DragView dragView, final int[] pos, float alpha,
float scaleX, float scaleY, int animationEndStyle, Runnable onFinishRunnable,
int duration) {
Rect r = new Rect();
getViewRectRelativeToSelf(dragView, r);
final int fromX = r.left;
final int fromY = r.top;
animateViewIntoPosition(dragView, fromX, fromY, pos[0], pos[1], alpha, 1, 1, scaleX, scaleY,
animateViewIntoPosition(dragView, pos[0], pos[1], alpha, scaleX, scaleY,
onFinishRunnable, animationEndStyle, duration, null);
}
@@ -241,11 +240,6 @@ public class DragLayer extends BaseDragLayer<Launcher> {
parentChildren.measureChild(child);
parentChildren.layoutChild(child);
Rect dragViewBounds = new Rect();
getViewRectRelativeToSelf(dragView, dragViewBounds);
final int fromX = dragViewBounds.left;
final int fromY = dragViewBounds.top;
float coord[] = new float[2];
float childScale = child.getScaleX();
@@ -288,51 +282,50 @@ public class DragLayer extends BaseDragLayer<Launcher> {
child.setVisibility(INVISIBLE);
Runnable onCompleteRunnable = () -> child.setVisibility(VISIBLE);
animateViewIntoPosition(dragView, fromX, fromY, toX, toY, 1, 1, 1, toScale, toScale,
animateViewIntoPosition(dragView, toX, toY, 1, toScale, toScale,
onCompleteRunnable, ANIMATION_END_DISAPPEAR, duration, anchorView);
}
public void animateViewIntoPosition(final DragView view, final int fromX, final int fromY,
final int toX, final int toY, float finalAlpha, float initScaleX, float initScaleY,
float finalScaleX, float finalScaleY, Runnable onCompleteRunnable,
int animationEndStyle, int duration, View anchorView) {
Rect from = new Rect(fromX, fromY, fromX +
view.getMeasuredWidth(), fromY + view.getMeasuredHeight());
Rect to = new Rect(toX, toY, toX + view.getMeasuredWidth(), toY + view.getMeasuredHeight());
animateView(view, from, to, finalAlpha, initScaleX, initScaleY, finalScaleX, finalScaleY, duration,
null, null, onCompleteRunnable, animationEndStyle, anchorView);
}
/**
* This method animates a view at the end of a drag and drop animation.
*
*/
public void animateViewIntoPosition(final DragView view,
final int toX, final int toY, float finalAlpha,
float finalScaleX, float finalScaleY, Runnable onCompleteRunnable,
int animationEndStyle, int duration, View anchorView) {
Rect to = new Rect(toX, toY, toX + view.getMeasuredWidth(), toY + view.getMeasuredHeight());
animateView(view, to, finalAlpha, finalScaleX, finalScaleY, duration,
null, onCompleteRunnable, animationEndStyle, anchorView);
}
/**
* This method animates a view at the end of a drag and drop animation.
* @param view The view to be animated. This view is drawn directly into DragLayer, and so
* doesn't need to be a child of DragLayer.
* @param from The initial location of the view. Only the left and top parameters are used.
* @param to The final location of the view. Only the left and top parameters are used. This
* location doesn't account for scaling, and so should be centered about the desired
* final location (including scaling).
* location doesn't account for scaling, and so should be centered about the desired
* final location (including scaling).
* @param finalAlpha The final alpha of the view, in case we want it to fade as it animates.
* @param finalScaleX The final scale of the view. The view is scaled about its center.
* @param finalScaleY The final scale of the view. The view is scaled about its center.
* @param duration The duration of the animation.
* @param motionInterpolator The interpolator to use for the location of the view.
* @param alphaInterpolator The interpolator to use for the alpha of the view.
* @param onCompleteRunnable Optional runnable to run on animation completion.
* @param animationEndStyle Whether or not to fade out the view once the animation completes.
* {@link #ANIMATION_END_DISAPPEAR} or {@link #ANIMATION_END_REMAIN_VISIBLE}.
* {@link #ANIMATION_END_DISAPPEAR} or {@link #ANIMATION_END_REMAIN_VISIBLE}.
* @param anchorView If not null, this represents the view which the animated view stays
* anchored to in case scrolling is currently taking place. Note: currently this is
* only used for the X dimension for the case of the workspace.
*/
public void animateView(final DragView view, final Rect from, final Rect to,
final float finalAlpha, final float initScaleX, final float initScaleY,
final float finalScaleX, final float finalScaleY, int duration,
final Interpolator motionInterpolator, final Interpolator alphaInterpolator,
final Runnable onCompleteRunnable, final int animationEndStyle, View anchorView) {
public void animateView(final DragView view, final Rect to,
final float finalAlpha, final float finalScaleX, final float finalScaleY, int duration,
final Interpolator motionInterpolator, final Runnable onCompleteRunnable,
final int animationEndStyle, View anchorView) {
view.cancelAnimation();
view.requestLayout();
final int[] from = getViewLocationRelativeToSelf(view);
// Calculate the duration of the animation based on the object's distance
final float dist = (float) Math.hypot(to.left - from.left, to.top - from.top);
final float dist = (float) Math.hypot(to.left - from[0], to.top - from[1]);
final Resources res = getResources();
final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
@@ -346,93 +339,45 @@ public class DragLayer extends BaseDragLayer<Launcher> {
}
// Fall back to cubic ease out interpolator for the animation if none is specified
TimeInterpolator interpolator = null;
if (alphaInterpolator == null || motionInterpolator == null) {
interpolator = DEACCEL_1_5;
}
TimeInterpolator interpolator =
motionInterpolator == null ? DEACCEL_1_5 : motionInterpolator;
// Animate the view
final float initAlpha = view.getAlpha();
final float dropViewScale = view.getScaleX();
AnimatorUpdateListener updateCb = new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
final float percent = (Float) animation.getAnimatedValue();
final int width = view.getMeasuredWidth();
final int height = view.getMeasuredHeight();
PendingAnimation anim = new PendingAnimation(duration);
anim.add(ofFloat(view, View.SCALE_X, finalScaleX), interpolator, SpringProperty.DEFAULT);
anim.add(ofFloat(view, View.SCALE_Y, finalScaleY), interpolator, SpringProperty.DEFAULT);
anim.setViewAlpha(view, finalAlpha, interpolator);
anim.setFloat(view, VIEW_TRANSLATE_Y, to.top, interpolator);
float alphaPercent = alphaInterpolator == null ? percent :
alphaInterpolator.getInterpolation(percent);
float motionPercent = motionInterpolator == null ? percent :
motionInterpolator.getInterpolation(percent);
float initialScaleX = initScaleX * dropViewScale;
float initialScaleY = initScaleY * dropViewScale;
float scaleX = finalScaleX * percent + initialScaleX * (1 - percent);
float scaleY = finalScaleY * percent + initialScaleY * (1 - percent);
float alpha = finalAlpha * alphaPercent + initAlpha * (1 - alphaPercent);
float fromLeft = from.left + (initialScaleX - 1f) * width / 2;
float fromTop = from.top + (initialScaleY - 1f) * height / 2;
int x = (int) (fromLeft + Math.round(((to.left - fromLeft) * motionPercent)));
int y = (int) (fromTop + Math.round(((to.top - fromTop) * motionPercent)));
int anchorAdjust = mAnchorView == null ? 0 : (int) (mAnchorView.getScaleX() *
(mAnchorViewInitialScrollX - mAnchorView.getScrollX()));
int xPos = x - mDropView.getScrollX() + anchorAdjust;
int yPos = y - mDropView.getScrollY();
mDropView.setTranslationX(xPos);
mDropView.setTranslationY(yPos);
mDropView.setScaleX(scaleX);
mDropView.setScaleY(scaleY);
mDropView.setAlpha(alpha);
}
};
animateView(view, updateCb, duration, interpolator, onCompleteRunnable, animationEndStyle,
anchorView);
ObjectAnimator xMotion = ofFloat(view, VIEW_TRANSLATE_X, to.left);
if (anchorView != null) {
final int startScroll = anchorView.getScrollX();
TypeEvaluator<Float> evaluator = (f, s, e) -> mapRange(f, s, e)
+ (anchorView.getScaleX() * (startScroll - anchorView.getScrollX()));
xMotion.setEvaluator(evaluator);
}
anim.add(xMotion, interpolator, SpringProperty.DEFAULT);
if (onCompleteRunnable != null) {
anim.addListener(forEndCallback(onCompleteRunnable));
}
playDropAnimation(view, anim.buildAnim(), animationEndStyle);
}
public void animateView(final DragView view, AnimatorUpdateListener updateCb, int duration,
TimeInterpolator interpolator, final Runnable onCompleteRunnable,
final int animationEndStyle, View anchorView) {
/**
* Runs a previously constructed drop animation
*/
public void playDropAnimation(final DragView view, Animator animator, int animationEndStyle) {
// Clean up the previous animations
if (mDropAnim != null) mDropAnim.cancel();
// Show the drop view if it was previously hidden
mDropView = view;
mDropView.cancelAnimation();
mDropView.requestLayout();
// Set the anchor view if the page is scrolling
if (anchorView != null) {
mAnchorViewInitialScrollX = anchorView.getScrollX();
}
mAnchorView = anchorView;
// Create and start the animation
mDropAnim = new ValueAnimator();
mDropAnim.setInterpolator(interpolator);
mDropAnim.setDuration(duration);
mDropAnim.setFloatValues(0f, 1f);
mDropAnim.addUpdateListener(updateCb);
mDropAnim.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
if (onCompleteRunnable != null) {
onCompleteRunnable.run();
}
switch (animationEndStyle) {
case ANIMATION_END_DISAPPEAR:
clearAnimatedView();
break;
case ANIMATION_END_REMAIN_VISIBLE:
break;
}
mDropAnim = null;
}
});
mDropAnim = animator;
mDropAnim.addListener(forEndCallback(() -> mDropAnim = null));
if (animationEndStyle == ANIMATION_END_DISAPPEAR) {
mDropAnim.addListener(forEndCallback(this::clearAnimatedView));
}
mDropAnim.start();
}
@@ -23,6 +23,8 @@ import static com.android.launcher3.LauncherAnimUtils.VIEW_ALPHA;
import static com.android.launcher3.Utilities.getBadge;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
@@ -53,25 +55,21 @@ import androidx.dynamicanimation.animation.FloatPropertyCompat;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherState;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.anim.Interpolators;
import com.android.launcher3.icons.FastBitmapDrawable;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.statemanager.StateManager.StateListener;
import com.android.launcher3.util.RunnableList;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.widget.LauncherAppWidgetHostView;
import app.lawnchair.icons.CustomAdaptiveIconDrawable;
/** A custom view for rendering an icon, folder, shortcut or widget during drag-n-drop. */
public class DragView extends FrameLayout implements StateListener<LauncherState> {
public abstract class DragView<T extends Context & ActivityContext> extends FrameLayout {
public static final int VIEW_ZOOM_DURATION = 150;
@@ -84,22 +82,23 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
private final int mHeight;
private final int mBlurSizeOutline;
private final int mRegistrationX;
private final int mRegistrationY;
protected final int mRegistrationX;
protected final int mRegistrationY;
private final float mInitialScale;
private final float mScaleOnDrop;
private final int[] mTempLoc = new int[2];
protected final float mScaleOnDrop;
protected final int[] mTempLoc = new int[2];
private final RunnableList mOnDragStartCallback = new RunnableList();
private Point mDragVisualizeOffset = null;
private Rect mDragRegion = null;
private final Launcher mLauncher;
private final DragLayer mDragLayer;
@Thunk final DragController mDragController;
protected final T mActivity;
private final BaseDragLayer<T> mDragLayer;
private boolean mHasDrawn = false;
final ValueAnimator mAnim;
// Whether mAnim has started. Unlike mAnim.isStarted(), this is true even after mAnim ends.
private boolean mAnimStarted;
private int mLastTouchX;
private int mLastTouchY;
@@ -112,7 +111,7 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
private Path mScaledMaskPath;
private Drawable mBadge;
public DragView(Launcher launcher, Drawable drawable, int registrationX,
public DragView(T launcher, Drawable drawable, int registrationX,
int registrationY, final float initialScale, final float scaleOnDrop,
final float finalScaleDps) {
this(launcher, getViewFromDrawable(launcher, drawable),
@@ -125,7 +124,7 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
* <p>
* The registration point is the point inside our view that the touch events should
* be centered upon.
* @param launcher The Launcher instance
* @param activity The Launcher instance/ActivityContext this DragView is in.
* @param content the view content that is attached to the drag view.
* @param width the width of the dragView
* @param height the height of the dragView
@@ -135,13 +134,12 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
* @param scaleOnDrop the scale used in the drop animation.
* @param finalScaleDps the scale used in the zoom out animation when the drag view is shown.
*/
public DragView(Launcher launcher, View content, int width, int height, int registrationX,
public DragView(T activity, View content, int width, int height, int registrationX,
int registrationY, final float initialScale, final float scaleOnDrop,
final float finalScaleDps) {
super(launcher);
mLauncher = launcher;
mDragLayer = launcher.getDragLayer();
mDragController = launcher.getDragController();
super(activity);
mActivity = activity;
mDragLayer = activity.getDragLayer();
mContent = content;
mWidth = width;
@@ -155,6 +153,12 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
addView(content, new LayoutParams(width, height));
// If there is already a scale set on the content, we don't want to clip the children.
if (content.getScaleX() != 1 || content.getScaleY() != 1) {
setClipChildren(false);
setClipToPadding(false);
}
final float scale = (width + finalScaleDps) / width;
// Set the initial scale to avoid any jumps
@@ -172,6 +176,12 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
animation.cancel();
}
});
mAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
mAnimStarted = true;
}
});
setDragRegion(new Rect(0, 0, width, height));
@@ -190,24 +200,6 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
setWillNotDraw(false);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mLauncher.getStateManager().addStateListener(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mLauncher.getStateManager().removeStateListener(this);
}
@Override
public void onStateTransitionComplete(LauncherState finalState) {
setVisibility((finalState == LauncherState.NORMAL
|| finalState == LauncherState.SPRING_LOADED) ? VISIBLE : INVISIBLE);
}
/**
* Initialize {@code #mIconDrawable} if the item can be represented using
* an {@link AdaptiveIconDrawable} or {@link FolderAdaptiveIcon}.
@@ -215,6 +207,7 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
@TargetApi(Build.VERSION_CODES.O)
public void setItemInfo(final ItemInfo info) {
if (info.itemType != LauncherSettings.Favorites.ITEM_TYPE_APPLICATION
&& info.itemType != LauncherSettings.Favorites.ITEM_TYPE_SEARCH_ACTION
&& info.itemType != LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT
&& info.itemType != LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
return;
@@ -224,10 +217,10 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
Object[] outObj = new Object[1];
int w = mWidth;
int h = mHeight;
Drawable dr = Utilities.getFullDrawable(mLauncher, info, w, h, outObj);
Drawable dr = Utilities.getFullDrawable(mActivity, info, w, h, outObj);
if (dr instanceof AdaptiveIconDrawable) {
int blurMargin = (int) mLauncher.getResources()
int blurMargin = (int) mActivity.getResources()
.getDimension(R.dimen.blur_size_medium_outline) / 2;
Rect bounds = new Rect(0, 0, w, h);
@@ -235,13 +228,13 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
// Badge is applied after icon normalization so the bounds for badge should not
// be scaled down due to icon normalization.
Rect badgeBounds = new Rect(bounds);
mBadge = getBadge(mLauncher, info, outObj[0]);
mBadge = getBadge(mActivity, info, outObj[0]);
mBadge.setBounds(badgeBounds);
// Do not draw the background in case of folder as its translucent
final boolean shouldDrawBackground = !(dr instanceof FolderAdaptiveIcon);
try (LauncherIcons li = LauncherIcons.obtain(mLauncher)) {
try (LauncherIcons li = LauncherIcons.obtain(mActivity)) {
Drawable nDr; // drawable to be normalized
if (shouldDrawBackground) {
nDr = dr;
@@ -308,16 +301,6 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
mOnDragStartCallback.executeAllAndDestroy();
}
// TODO(b/183609936): This is only for LauncherAppWidgetHostView that is rendered in a drawable.
// Once LauncherAppWidgetHostView is directly rendered in this view, removes this method.
@Override
public void invalidate() {
super.invalidate();
if (mContent instanceof ImageView) {
mContent.invalidate();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(makeMeasureSpec(mWidth, EXACTLY), makeMeasureSpec(mHeight, EXACTLY));
@@ -415,6 +398,10 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
}
}
public boolean isAnimationFinished() {
return mAnimStarted && !mAnim.isRunning();
}
/**
* Move the window containing this view.
*
@@ -432,12 +419,11 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
applyTranslation();
}
public void animateTo(int toTouchX, int toTouchY, Runnable onCompleteRunnable, int duration) {
mTempLoc[0] = toTouchX - mRegistrationX;
mTempLoc[1] = toTouchY - mRegistrationY;
mDragLayer.animateViewIntoPosition(this, mTempLoc, 1f, mScaleOnDrop, mScaleOnDrop,
DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
}
/**
* Animate this DragView to the given DragLayer coordinates and then remove it.
*/
public abstract void animateTo(int toTouchX, int toTouchY, Runnable onCompleteRunnable,
int duration);
public void animateShift(final int shiftX, final int shiftY) {
if (mAnim.isStarted()) {
@@ -473,7 +459,7 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
Picture picture = new Picture();
mContent.draw(picture.beginRecording(mWidth, mHeight));
picture.endRecording();
View view = new View(mLauncher);
View view = new View(mActivity);
view.setBackground(new PictureDrawable(picture));
view.measure(makeMeasureSpec(mWidth, EXACTLY), makeMeasureSpec(mHeight, EXACTLY));
view.layout(mContent.getLeft(), mContent.getTop(),
@@ -493,24 +479,6 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
}
}
/**
* If the drag view uses color extraction, block it.
*/
public void disableColorExtraction() {
if (mContent instanceof LauncherAppWidgetHostView) {
((LauncherAppWidgetHostView) mContent).disableColorExtraction();
}
}
/**
* If the drag view uses color extraction, restores it.
*/
public void resumeColorExtraction() {
if (mContent instanceof LauncherAppWidgetHostView) {
((LauncherAppWidgetHostView) mContent).enableColorExtraction(/* updateColors= */ false);
}
}
/**
* Removes this view from the {@link DragLayer}.
*
@@ -599,4 +567,19 @@ public class DragView extends FrameLayout implements StateListener<LauncherState
iv.setImageDrawable(drawable);
return iv;
}
/**
* Removes any stray DragView from the DragLayer.
*/
public static void removeAllViews(ActivityContext activity) {
BaseDragLayer dragLayer = activity.getDragLayer();
// Iterate in reverse order. DragView 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);
if (child instanceof DragView) {
dragLayer.removeView(child);
}
}
}
}
@@ -32,12 +32,12 @@ import android.util.Log;
import androidx.annotation.Nullable;
import com.android.launcher3.Launcher;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.folder.PreviewBackground;
import com.android.launcher3.graphics.ShiftedBitmapDrawable;
import com.android.launcher3.icons.BitmapRenderer;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.views.ActivityContext;
import app.lawnchair.icons.CustomAdaptiveIconDrawable;
@@ -72,14 +72,14 @@ public class FolderAdaptiveIcon extends CustomAdaptiveIconDrawable {
}
public static @Nullable FolderAdaptiveIcon createFolderAdaptiveIcon(
Launcher launcher, int folderId, Point dragViewSize) {
ActivityContext activity, int folderId, Point dragViewSize) {
Preconditions.assertNonUiThread();
// Create the actual drawable on the UI thread to avoid race conditions with
// FolderIcon draw pass
try {
return MAIN_EXECUTOR.submit(() -> {
FolderIcon icon = launcher.findFolderIcon(folderId);
FolderIcon icon = activity.findFolderIcon(folderId);
return icon == null ? null : createDrawableOnUiThread(icon, dragViewSize);
}).get();
@@ -24,6 +24,7 @@ import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.View;
@@ -36,6 +37,7 @@ import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.accessibility.DragViewStateAnnouncer;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.testing.TestProtocol;
/**
* Drag controller for Launcher activity
@@ -65,6 +67,9 @@ public class LauncherDragController extends DragController<Launcher> {
float initialDragViewScale,
float dragViewScaleOnDrop,
DragOptions options) {
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NO_DROP_TARGET, "5");
}
if (PROFILE_DRAWING_DURING_DRAG) {
android.os.Debug.startMethodTracing("Launcher");
}
@@ -96,7 +101,7 @@ public class LauncherDragController extends DragController<Launcher> {
final float scaleDps = mIsInPreDrag
? res.getDimensionPixelSize(R.dimen.pre_drag_view_scale) : 0f;
final DragView dragView = mDragObject.dragView = drawable != null
? new DragView(
? new LauncherDragView(
mActivity,
drawable,
registrationX,
@@ -104,7 +109,7 @@ public class LauncherDragController extends DragController<Launcher> {
initialDragViewScale,
dragViewScaleOnDrop,
scaleDps)
: new DragView(
: new LauncherDragView(
mActivity,
view,
view.getMeasuredWidth(),
@@ -0,0 +1,70 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.dragndrop;
import android.graphics.drawable.Drawable;
import android.view.View;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherState;
import com.android.launcher3.statemanager.StateManager;
/**
* A DragView drawn/used by the Launcher activity.
*/
public class LauncherDragView extends DragView<Launcher>
implements StateManager.StateListener<LauncherState> {
public LauncherDragView(Launcher launcher, Drawable drawable, int registrationX,
int registrationY, float initialScale, float scaleOnDrop, float finalScaleDps) {
super(launcher, drawable, registrationX, registrationY, initialScale, scaleOnDrop,
finalScaleDps);
}
public LauncherDragView(Launcher launcher, View content, int width, int height,
int registrationX, int registrationY, float initialScale, float scaleOnDrop,
float finalScaleDps) {
super(launcher, content, width, height, registrationX, registrationY, initialScale,
scaleOnDrop, finalScaleDps);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mActivity.getStateManager().addStateListener(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mActivity.getStateManager().removeStateListener(this);
}
@Override
public void onStateTransitionComplete(LauncherState finalState) {
setVisibility((finalState == LauncherState.NORMAL
|| finalState == LauncherState.SPRING_LOADED) ? VISIBLE : INVISIBLE);
}
@Override
public void animateTo(int toTouchX, int toTouchY, Runnable onCompleteRunnable, int duration) {
mTempLoc[0] = toTouchX - mRegistrationX;
mTempLoc[1] = toTouchY - mRegistrationY;
mActivity.getDragLayer().animateViewIntoPosition(this, mTempLoc, 1f, mScaleOnDrop,
mScaleOnDrop, DragLayer.ANIMATION_END_DISAPPEAR, onCompleteRunnable, duration);
}
}
@@ -48,12 +48,19 @@ public class PinItemDragListener extends BaseItemDragListener {
private final PinItemRequest mRequest;
private final CancellationSignal mCancelSignal;
private final float mPreviewScale;
public PinItemDragListener(PinItemRequest request, Rect previewRect,
int previewBitmapWidth, int previewViewWidth) {
this(request, previewRect, previewBitmapWidth, previewViewWidth, /* previewScale= */ 1f);
}
public PinItemDragListener(PinItemRequest request, Rect previewRect,
int previewBitmapWidth, int previewViewWidth, float previewScale) {
super(previewRect, previewBitmapWidth, previewViewWidth);
mRequest = request;
mCancelSignal = new CancellationSignal();
mPreviewScale = previewScale;
}
@Override
@@ -98,7 +105,7 @@ public class PinItemDragListener extends BaseItemDragListener {
PendingItemDragHelper dragHelper = new PendingItemDragHelper(view);
if (mRequest.getRequestType() == PinItemRequest.REQUEST_TYPE_APPWIDGET) {
dragHelper.setRemoteViewsPreview(getPreview(mRequest));
dragHelper.setRemoteViewsPreview(getPreview(mRequest), mPreviewScale);
}
return dragHelper;
}
+19 -13
View File
@@ -78,10 +78,10 @@ import com.android.launcher3.PagedView;
import com.android.launcher3.R;
import com.android.launcher3.ShortcutAndWidgetContainer;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace.ItemOperator;
import com.android.launcher3.accessibility.AccessibleDragListenerAdapter;
import com.android.launcher3.accessibility.FolderAccessibilityHelper;
import com.android.launcher3.anim.KeyboardInsetAnimationCallback;
import com.android.launcher3.compat.AccessibilityManagerCompat;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dragndrop.DragController;
import com.android.launcher3.dragndrop.DragController.DragListener;
@@ -98,6 +98,7 @@ import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pageindicators.PageIndicatorDots;
import com.android.launcher3.util.Executors;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.LauncherBindableItemsContainer.ItemOperator;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
@@ -282,15 +283,19 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
mPageIndicator = findViewById(R.id.folder_page_indicator);
mFolderName = findViewById(R.id.folder_name);
mFolderName.setTextSize(TypedValue.COMPLEX_UNIT_PX, dp.folderLabelTextSizePx);
mFolderName.setOnBackKeyListener(this);
mFolderName.setOnFocusChangeListener(this);
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);
mFolderName.forceDisableSuggestions(true);
if (mActivityContext.supportsIme()) {
mFolderName.setOnBackKeyListener(this);
mFolderName.setOnFocusChangeListener(this);
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);
mFolderName.forceDisableSuggestions(true);
} else {
mFolderName.setEnabled(false);
}
@ColorInt int accentColor = Themes.getColorAccent(mFolderName.getContext());
EditTextExtensions.setCursorColor(mFolderName, accentColor);
@@ -697,6 +702,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
public void onAnimationEnd(Animator animation) {
mState = STATE_OPEN;
announceAccessibilityChanges();
AccessibilityManagerCompat.sendFolderOpenedEventToTest(getContext());
mContent.setFocusOnFirstChild();
}
@@ -1210,8 +1216,7 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
}
void replaceFolderWithFinalItem() {
mLauncherDelegate.replaceFolderWithFinalItem(this);
mDestroyed = true;
mDestroyed = mLauncherDelegate.replaceFolderWithFinalItem(this);
}
public boolean isDestroyed() {
@@ -1276,7 +1281,8 @@ public class Folder extends AbstractFloatingView implements ClipPathView, DragSo
PendingAddShortcutInfo pasi = d.dragInfo instanceof PendingAddShortcutInfo
? (PendingAddShortcutInfo) d.dragInfo : null;
WorkspaceItemInfo pasiSi = pasi != null ? pasi.activityInfo.createWorkspaceItemInfo() : null;
WorkspaceItemInfo pasiSi =
pasi != null ? pasi.activityInfo.createWorkspaceItemInfo() : null;
if (pasi != null && pasiSi == null) {
// There is no WorkspaceItemInfo, so we have to go through a configuration activity.
pasi.container = mInfo.id;
@@ -24,7 +24,6 @@ import static com.android.launcher3.BubbleTextView.TEXT_ALPHA_PROPERTY;
import static com.android.launcher3.LauncherAnimUtils.SCALE_PROPERTY;
import static com.android.launcher3.folder.ClippedFolderIconLayoutRule.MAX_NUM_ITEMS_IN_PREVIEW;
import static com.android.launcher3.graphics.IconShape.getShape;
import static com.android.launcher3.icons.GraphicsUtils.setColorAlphaBound;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -179,15 +178,10 @@ public class FolderAnimationManager {
final float yDistance = initialY - lp.y;
// Set up the Folder background.
final int finalColor;
int folderFillColor = ColorTokens.FolderFillColor.resolveColor(mContext);
if (mIsOpening) {
finalColor = folderFillColor;
} else {
finalColor = mFolderBackground.getColor().getDefaultColor();
}
final int initialColor = setColorAlphaBound(
folderFillColor, mPreviewBackground.getBackgroundAlpha());
// TODO: apply colortokens
final int initialColor = Themes.getAttrColor(mContext, R.attr.folderPreviewColor);
final int finalColor = Themes.getAttrColor(mContext, R.attr.folderBackgroundColor);
mFolderBackground.mutate();
mFolderBackground.setColor(mIsOpening ? initialColor : finalColor);
@@ -243,9 +237,9 @@ public class FolderAnimationManager {
mFolder, startRect, endRect, finalRadius, !mIsOpening));
// Create reveal animator for the folder content (capture the top 4 icons 2x2)
int width = mDeviceProfile.folderCellLayoutBorderSpacingPx
int width = mDeviceProfile.folderCellLayoutBorderSpacePx.x
+ mDeviceProfile.folderCellWidthPx * 2;
int height = mDeviceProfile.folderCellLayoutBorderSpacingPx
int height = mDeviceProfile.folderCellLayoutBorderSpacePx.y
+ mDeviceProfile.folderCellHeightPx * 2;
int page = mIsOpening ? mContent.getCurrentPage() : mContent.getDestinationPage();
int left = mContent.getPaddingLeft() + page * lp.width;
@@ -137,6 +137,9 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel
private Rect mTouchArea = new Rect();
private final PointF mTranslationForMoveFromCenterAnimation = new PointF(0, 0);
private float mTranslationXForTaskbarAlignmentAnimation = 0f;
private final PointF mTranslationForReorderBounce = new PointF(0, 0);
private final PointF mTranslationForReorderPreview = new PointF(0, 0);
private float mScaleForReorderBounce = 1f;
@@ -342,8 +345,6 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel
if (animateView != null && mActivity instanceof Launcher) {
final Launcher launcher = (Launcher) mActivity;
DragLayer dragLayer = launcher.getDragLayer();
Rect from = new Rect();
dragLayer.getViewRectRelativeToSelf(animateView, from);
Rect to = finalRect;
if (to == null) {
to = new Rect();
@@ -409,13 +410,14 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel
}
final int finalIndex = index;
dragLayer.animateView(animateView, from, to, finalAlpha,
1, 1, finalScale, finalScale, DROP_IN_ANIMATION_DURATION,
Interpolators.DEACCEL_2, Interpolators.ACCEL_2,
dragLayer.animateView(animateView, to, finalAlpha,
finalScale, finalScale, DROP_IN_ANIMATION_DURATION,
Interpolators.DEACCEL_2,
() -> {
mPreviewItemManager.hidePreviewItem(finalIndex, false);
mFolder.showItem(item);
}, DragLayer.ANIMATION_END_DISAPPEAR, null);
},
DragLayer.ANIMATION_END_DISAPPEAR, null);
mFolder.hideItem(item);
@@ -633,7 +635,10 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel
public void drawDot(Canvas canvas) {
if (!mForceHideDot && ((mDotInfo != null && mDotInfo.hasDot()) || mDotScale > 0)) {
Rect iconBounds = mDotParams.iconBounds;
BubbleTextView.getIconBounds(this, iconBounds, mActivity.getDeviceProfile().iconSizePx);
Utilities.setRectToViewCenter(this, mActivity.getDeviceProfile().iconSizePx,
iconBounds);
iconBounds.offsetTo(iconBounds.left, getPaddingTop());
float iconScale = (float) mBackground.previewSize / iconBounds.width();
Utilities.scaleRectAboutCenter(iconBounds, iconScale);
@@ -690,6 +695,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel
@Override
public void onAdd(WorkspaceItemInfo item, int rank) {
updatePreviewItems(false);
boolean wasDotted = mDotInfo.hasDot();
mDotInfo.addDotInfo(mActivity.getDotInfoForItem(item));
boolean isDotted = mDotInfo.hasDot();
@@ -701,6 +707,7 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel
@Override
public void onRemove(List<WorkspaceItemInfo> items) {
updatePreviewItems(false);
boolean wasDotted = mDotInfo.hasDot();
items.stream().map(mActivity::getDotInfoForItem).forEach(mDotInfo::subtractDotInfo);
boolean isDotted = mDotInfo.hasDot();
@@ -771,8 +778,11 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel
}
private void updateTranslation() {
super.setTranslationX(mTranslationForReorderBounce.x + mTranslationForReorderPreview.x);
super.setTranslationY(mTranslationForReorderBounce.y + mTranslationForReorderPreview.y);
super.setTranslationX(mTranslationForReorderBounce.x + mTranslationForReorderPreview.x
+ mTranslationForMoveFromCenterAnimation.x
+ mTranslationXForTaskbarAlignmentAnimation);
super.setTranslationY(mTranslationForReorderBounce.y + mTranslationForReorderPreview.y
+ mTranslationForMoveFromCenterAnimation.y);
}
public void setReorderBounceOffset(float x, float y) {
@@ -784,6 +794,29 @@ public class FolderIcon extends FrameLayout implements FolderListener, IconLabel
offset.set(mTranslationForReorderBounce);
}
/**
* Sets translationX value for taskbar to launcher alignment animation
*/
public void setTranslationForTaskbarAlignmentAnimation(float translationX) {
mTranslationXForTaskbarAlignmentAnimation = translationX;
updateTranslation();
}
/**
* Returns translation values for taskbar to launcher alignment animation
*/
public float getTranslationXForTaskbarAlignmentAnimation() {
return mTranslationXForTaskbarAlignmentAnimation;
}
/**
* Sets translation values for move from center animation
*/
public void setTranslationForMoveFromCenterAnimation(float x, float y) {
mTranslationForMoveFromCenterAnimation.set(x, y);
updateTranslation();
}
@Override
public void setReorderPreviewOffset(float x, float y) {
mTranslationForReorderPreview.set(x, y);
@@ -18,6 +18,7 @@ package com.android.launcher3.folder;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
@@ -117,4 +118,16 @@ public class FolderNameEditText extends ExtendedEditText {
return super.setComposingText(cs, newCursorPos);
}
}
@Override
public void reset() {
super.reset();
if (isFocused()) {
View nextFocus = focusSearch(View.FOCUS_DOWN);
if (nextFocus != null) {
nextFocus.requestFocus();
}
}
hideKeyboard();
}
}
@@ -41,12 +41,12 @@ import com.android.launcher3.PagedView;
import com.android.launcher3.R;
import com.android.launcher3.ShortcutAndWidgetContainer;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace.ItemOperator;
import com.android.launcher3.keyboard.ViewGroupFocusHelper;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pageindicators.PageIndicatorDots;
import com.android.launcher3.touch.ItemClickHandler;
import com.android.launcher3.util.LauncherBindableItemsContainer.ItemOperator;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.util.ViewCache;
import com.android.launcher3.views.ActivityContext;
@@ -18,8 +18,6 @@ package com.android.launcher3.folder;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_FOLDER_CONVERTED_TO_ICON;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.View;
@@ -38,10 +36,7 @@ import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.views.BaseDragLayer.LayoutParams;
import com.android.launcher3.widget.LocalColorExtractor;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Consumer;
@@ -51,8 +46,6 @@ import java.util.function.Consumer;
public class LauncherDelegate {
private final Launcher mLauncher;
private final Rect mTempRect = new Rect();
private final RectF mTempRectF = new RectF();
private LauncherDelegate(Launcher launcher) {
mLauncher = launcher;
@@ -84,16 +77,7 @@ public class LauncherDelegate {
return mLauncher;
}
void addRectForColorExtraction(BaseDragLayer.LayoutParams lp, LocalColorExtractor target) {
mTempRect.set(lp.x, lp.y, lp.x + lp.width, lp.y + lp.height);
target.getExtractedRectForViewRect(mLauncher,
mLauncher.getWorkspace().getCurrentPage(), mTempRect, mTempRectF);
if (!mTempRectF.isEmpty()) {
target.addLocation(Arrays.asList(mTempRectF));
}
}
void replaceFolderWithFinalItem(Folder folder) {
boolean replaceFolderWithFinalItem(Folder folder) {
// Add the last remaining child to the workspace in place of the folder
Runnable onCompleteRunnable = new Runnable() {
@Override
@@ -147,6 +131,7 @@ public class LauncherDelegate {
} else {
onCompleteRunnable.run();
}
return true;
}
@@ -191,7 +176,7 @@ public class LauncherDelegate {
ModelWriter getModelWriter() {
if (mWriter == null) {
mWriter = LauncherAppState.getInstance((Context) mContext).getModel()
.getWriter(false, false);
.getWriter(false, false, null);
}
return mWriter;
}
@@ -205,16 +190,15 @@ public class LauncherDelegate {
}
@Override
void replaceFolderWithFinalItem(Folder folder) { }
boolean replaceFolderWithFinalItem(Folder folder) {
return false;
}
@Override
boolean interceptOutsideTouch(MotionEvent ev, BaseDragLayer dl, Folder folder) {
folder.close(true);
return true;
}
@Override
void addRectForColorExtraction(LayoutParams lp, LocalColorExtractor target) { }
}
static LauncherDelegate from(ActivityContext context) {
@@ -68,7 +68,6 @@ public class PreviewBackground extends CellLayout.DelegatedCellDrawing {
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
float mScale = 1f;
private float mColorMultiplier = 1f;
private int mBgColor;
private int mStrokeColor;
private int mDotColor;
@@ -76,7 +75,6 @@ public class PreviewBackground extends CellLayout.DelegatedCellDrawing {
private int mStrokeAlpha = MAX_BG_OPACITY;
private int mShadowAlpha = 255;
private View mInvalidateDelegate;
private int bgOpacity = 255;
int previewSize;
int basePreviewOffsetX;
@@ -90,9 +88,9 @@ public class PreviewBackground extends CellLayout.DelegatedCellDrawing {
// Drawing / animation configurations
private static final float ACCEPT_SCALE_FACTOR = 1.20f;
private static final float ACCEPT_COLOR_MULTIPLIER = 1.5f;
// Expressed on a scale from 0 to 255.
private static final int BG_OPACITY = 255;
private static final int MAX_BG_OPACITY = 255;
private static final int SHADOW_OPACITY = 40;
@@ -229,12 +227,7 @@ public class PreviewBackground extends CellLayout.DelegatedCellDrawing {
}
public int getBgColor() {
int alpha = (int) Math.min(MAX_BG_OPACITY, bgOpacity * mColorMultiplier);
return setColorAlphaBound(mBgColor, alpha);
}
public void setBgOpacity(int opacity) {
bgOpacity = opacity;
return mBgColor;
}
public int getDotColor() {
@@ -390,14 +383,10 @@ public class PreviewBackground extends CellLayout.DelegatedCellDrawing {
return mDrawingDelegate != null;
}
private void animateScale(float finalScale, float finalMultiplier,
final Runnable onStart, final Runnable onEnd) {
private void animateScale(float finalScale, final Runnable onStart, final Runnable onEnd) {
final float scale0 = mScale;
final float scale1 = finalScale;
final float bgMultiplier0 = mColorMultiplier;
final float bgMultiplier1 = finalMultiplier;
if (mScaleAnimator != null) {
mScaleAnimator.cancel();
}
@@ -409,7 +398,6 @@ public class PreviewBackground extends CellLayout.DelegatedCellDrawing {
public void onAnimationUpdate(ValueAnimator animation) {
float prog = animation.getAnimatedFraction();
mScale = prog * scale1 + (1 - prog) * scale0;
mColorMultiplier = prog * bgMultiplier1 + (1 - prog) * bgMultiplier0;
invalidate();
}
});
@@ -435,8 +423,7 @@ public class PreviewBackground extends CellLayout.DelegatedCellDrawing {
}
public void animateToAccept(CellLayout cl, int cellX, int cellY) {
animateScale(ACCEPT_SCALE_FACTOR, ACCEPT_COLOR_MULTIPLIER,
() -> delegateDrawing(cl, cellX, cellY), null);
animateScale(ACCEPT_SCALE_FACTOR, () -> delegateDrawing(cl, cellX, cellY), null);
}
public void animateToRest() {
@@ -446,14 +433,10 @@ public class PreviewBackground extends CellLayout.DelegatedCellDrawing {
CellLayout cl = mDrawingDelegate;
int cellX = mDelegateCellX;
int cellY = mDelegateCellY;
animateScale(1f, 1f, () -> delegateDrawing(cl, cellX, cellY), this::clearDrawingDelegate);
}
public int getBackgroundAlpha() {
return (int) Math.min(MAX_BG_OPACITY, bgOpacity * mColorMultiplier);
animateScale(1f, () -> delegateDrawing(cl, cellX, cellY), this::clearDrawingDelegate);
}
public float getStrokeWidth() {
return mStrokeWidth;
}
}
}
@@ -32,13 +32,13 @@ import android.view.View;
import androidx.annotation.Nullable;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dragndrop.DraggableView;
import com.android.launcher3.icons.BitmapRenderer;
import com.android.launcher3.icons.FastBitmapDrawable;
import com.android.launcher3.util.SafeCloseable;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.widget.LauncherAppWidgetHostView;
import java.nio.ByteBuffer;
@@ -150,7 +150,7 @@ public class DragPreviewProvider {
}
public float getScaleAndPosition(Drawable preview, int[] outPos) {
float scale = Launcher.getLauncher(mView.getContext())
float scale = ActivityContext.lookupContext(mView.getContext())
.getDragLayer().getLocationInDragLayer(mView, outPos);
if (mView instanceof LauncherAppWidgetHostView) {
// App widgets are technically scaled, but are drawn at their expected size -- so the
@@ -167,7 +167,7 @@ public class DragPreviewProvider {
/** Returns the scale and position of a given view for drag-n-drop. */
public float getScaleAndPosition(View view, int[] outPos) {
float scale = Launcher.getLauncher(mView.getContext())
float scale = ActivityContext.lookupContext(mView.getContext())
.getDragLayer().getLocationInDragLayer(mView, outPos);
if (mView instanceof LauncherAppWidgetHostView) {
// App widgets are technically scaled, but are drawn at their expected size -- so the
@@ -201,7 +201,7 @@ public class DragPreviewProvider {
public void run() {
Bitmap preview = convertPreviewToAlphaBitmap(mPreviewSnapshot);
if (mIsIcon) {
int size = Launcher.getLauncher(mContext).getDeviceProfile().iconSizePx;
int size = ActivityContext.lookupContext(mContext).getDeviceProfile().iconSizePx;
preview = Bitmap.createScaledBitmap(preview, size, size, false);
}
//else case covers AppWidgetHost (doesn't drag/drop across different device profiles)
@@ -9,7 +9,6 @@ import android.annotation.TargetApi;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
@@ -23,23 +22,13 @@ import android.os.Message;
import android.os.Messenger;
import android.util.ArrayMap;
import android.util.Log;
import android.util.Xml;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.InvariantDeviceProfile.GridOption;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.util.Executors;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Exposes various launcher grid options and allows the caller to change them.
* APIs:
@@ -94,7 +83,7 @@ public class GridCustomizationsProvider extends ContentProvider {
MatrixCursor cursor = new MatrixCursor(new String[] {
KEY_NAME, KEY_ROWS, KEY_COLS, KEY_PREVIEW_COUNT, KEY_IS_DEFAULT});
InvariantDeviceProfile idp = InvariantDeviceProfile.INSTANCE.get(getContext());
for (GridOption gridOption : parseAllGridOptions()) {
for (GridOption gridOption : idp.parseAllGridOptions(getContext())) {
cursor.newRow()
.add(KEY_NAME, gridOption.name)
.add(KEY_ROWS, gridOption.numRows)
@@ -116,25 +105,6 @@ public class GridCustomizationsProvider extends ContentProvider {
}
}
private List<GridOption> parseAllGridOptions() {
List<GridOption> result = new ArrayList<>();
try (XmlResourceParser parser = getContext().getResources().getXml(R.xml.device_profiles)) {
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if ((type == XmlPullParser.START_TAG)
&& GridOption.TAG_NAME.equals(parser.getName())) {
result.add(new GridOption(getContext(), Xml.asAttributeSet(parser)));
}
}
} catch (IOException | XmlPullParserException e) {
Log.e(TAG, "Error parsing device profile", e);
return Collections.emptyList();
}
return result;
}
@Override
public String getType(Uri uri) {
return "vnd.android.cursor.dir/launcher_grid";
@@ -155,9 +125,10 @@ public class GridCustomizationsProvider extends ContentProvider {
switch (uri.getPath()) {
case KEY_DEFAULT_GRID: {
String gridName = values.getAsString(KEY_NAME);
InvariantDeviceProfile idp = InvariantDeviceProfile.INSTANCE.get(getContext());
// Verify that this is a valid grid option
GridOption match = null;
for (GridOption option : parseAllGridOptions()) {
for (GridOption option : idp.parseAllGridOptions(getContext())) {
if (option.name.equals(gridName)) {
match = option;
break;
@@ -167,8 +138,7 @@ public class GridCustomizationsProvider extends ContentProvider {
return 0;
}
InvariantDeviceProfile.INSTANCE.get(getContext())
.setCurrentGrid(getContext(), gridName);
idp.setCurrentGrid(getContext(), gridName);
return 1;
}
case ICON_THEMED:
@@ -31,6 +31,7 @@ import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.WallpaperColors;
import android.app.WallpaperManager;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
@@ -66,6 +67,7 @@ import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.WorkspaceLayoutManager;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.folder.FolderIcon;
@@ -86,21 +88,22 @@ import com.android.launcher3.uioverrides.PredictedAppIconInflater;
import com.android.launcher3.uioverrides.plugins.PluginManagerWrapper;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.MainThreadInitializedObject;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.MainThreadInitializedObject.SandboxContext;
import com.android.launcher3.views.ActivityContext;
import com.android.launcher3.views.BaseDragLayer;
import com.android.launcher3.widget.BaseLauncherAppWidgetHostView;
import com.android.launcher3.widget.LauncherAppWidgetHost;
import com.android.launcher3.widget.LauncherAppWidgetProviderInfo;
import com.android.launcher3.widget.LocalColorExtractor;
import com.android.launcher3.widget.NavigableAppWidgetHostView;
import com.android.launcher3.widget.custom.CustomWidgetManager;
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.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import app.lawnchair.font.FontCache;
@@ -125,22 +128,16 @@ public class LauncherPreviewRenderer extends ContextWrapper
* Context used just for preview. It also provides a few objects (e.g. UserCache) just for
* preview purposes.
*/
public static class PreviewContext extends ContextWrapper {
private final Set<MainThreadInitializedObject> mAllowedObjects = new HashSet<>(
Arrays.asList(UserCache.INSTANCE, InstallSessionHelper.INSTANCE,
LauncherAppState.INSTANCE, InvariantDeviceProfile.INSTANCE,
CustomWidgetManager.INSTANCE, PluginManagerWrapper.INSTANCE));
public static class PreviewContext extends SandboxContext {
private final InvariantDeviceProfile mIdp;
private final Map<MainThreadInitializedObject, Object> mObjectMap = new HashMap<>();
private final ConcurrentLinkedQueue<LauncherIconsForPreview> mIconPool =
new ConcurrentLinkedQueue<>();
private boolean mDestroyed = false;
public PreviewContext(Context base, InvariantDeviceProfile idp) {
super(base);
super(base, UserCache.INSTANCE, InstallSessionHelper.INSTANCE,
LauncherAppState.INSTANCE, InvariantDeviceProfile.INSTANCE,
CustomWidgetManager.INSTANCE, PluginManagerWrapper.INSTANCE);
mIdp = idp;
putBaseInstance(PreferenceManager.INSTANCE);
putBaseInstance(FontCache.INSTANCE);
@@ -156,37 +153,6 @@ public class LauncherPreviewRenderer extends ContextWrapper
mObjectMap.put(mainThreadInitializedObject, mainThreadInitializedObject.get(getBaseContext()));
}
@Override
public Context getApplicationContext() {
return this;
}
public void onDestroy() {
CustomWidgetManager.INSTANCE.get(this).onDestroy();
LauncherAppState.INSTANCE.get(this).onTerminate();
mDestroyed = true;
}
/**
* Find a cached object from mObjectMap if we have already created one. If not, generate
* an object using the provider.
*/
public <T> T getObject(MainThreadInitializedObject<T> mainThreadInitializedObject,
MainThreadInitializedObject.ObjectProvider<T> provider) {
if (FeatureFlags.IS_STUDIO_BUILD && mDestroyed) {
throw new RuntimeException("Context already destroyed");
}
if (!mAllowedObjects.contains(mainThreadInitializedObject)) {
throw new IllegalStateException("Leaking unknown objects");
}
if (mObjectMap.containsKey(mainThreadInitializedObject)) {
return (T) mObjectMap.get(mainThreadInitializedObject);
}
T t = provider.get(this);
mObjectMap.put(mainThreadInitializedObject, t);
return t;
}
public LauncherIcons newLauncherIcons(Context context, boolean shapeDetection) {
LauncherIconsForPreview launcherIconsForPreview = mIconPool.poll();
if (launcherIconsForPreview != null) {
@@ -221,7 +187,8 @@ public class LauncherPreviewRenderer extends ContextWrapper
private final LayoutInflater mHomeElementInflater;
private final InsettableFrameLayout mRootView;
private final Hotseat mHotseat;
private final CellLayout mWorkspace;
private final Map<Integer, CellLayout> mWorkspaceScreens = new HashMap<>();
private final AppWidgetHost mAppWidgetHost;
private final SparseIntArray mWallpaperColorResources;
public LauncherPreviewRenderer(Context context,
@@ -266,19 +233,35 @@ public class LauncherPreviewRenderer extends ContextWrapper
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;
mRootView = (InsettableFrameLayout) mHomeElementInflater.inflate(
R.layout.launcher_preview_layout, null, false);
layoutRes, null, false);
mRootView.setInsets(mInsets);
measureView(mRootView, mDp.widthPx, mDp.heightPx);
mHotseat = mRootView.findViewById(R.id.hotseat);
mHotseat.resetLayout(false);
mWorkspace = mRootView.findViewById(R.id.workspace);
mWorkspace.setPadding(mDp.workspacePadding.left + mDp.cellLayoutPaddingLeftRightPx,
CellLayout firstScreen = mRootView.findViewById(R.id.workspace);
firstScreen.setPadding(mDp.workspacePadding.left + mDp.cellLayoutPaddingLeftRightPx,
mDp.workspacePadding.top,
mDp.workspacePadding.right + mDp.cellLayoutPaddingLeftRightPx,
mDp.workspacePadding.bottom);
(mDp.isTwoPanels ? mDp.cellLayoutBorderSpacePx.x / 2
: mDp.workspacePadding.right) + mDp.cellLayoutPaddingLeftRightPx,
mDp.workspacePadding.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.cellLayoutPaddingLeftRightPx,
mDp.workspacePadding.top,
mDp.workspacePadding.right + mDp.cellLayoutPaddingLeftRightPx,
mDp.workspacePadding.bottom
);
mWorkspaceScreens.put(Workspace.SECOND_SCREEN_ID, rightPanel);
}
if (Utilities.ATLEAST_S) {
WallpaperColors wallpaperColors = wallpaperColorsOverride != null
@@ -289,6 +272,9 @@ public class LauncherPreviewRenderer extends ContextWrapper
} else {
mWallpaperColorResources = null;
}
mAppWidgetHost = FeatureFlags.WIDGETS_IN_LAUNCHER_PREVIEW.get()
? new LauncherPreviewAppWidgetHost(context)
: null;
}
/** Populate preview and render it. */
@@ -346,18 +332,22 @@ public class LauncherPreviewRenderer extends ContextWrapper
@Override
public CellLayout getScreenWithId(int screenId) {
return mWorkspace;
return mWorkspaceScreens.get(screenId);
}
private void inflateAndAddIcon(WorkspaceItemInfo info) {
CellLayout screen = mWorkspaceScreens.get(info.screenId);
BubbleTextView icon = (BubbleTextView) mHomeElementInflater.inflate(
R.layout.app_icon, mWorkspace, false);
R.layout.app_icon, screen, false);
icon.applyFromWorkspaceItem(info);
addInScreenFromBind(icon, info);
}
private void inflateAndAddFolder(FolderInfo info) {
FolderIcon folderIcon = FolderIcon.inflateIcon(R.layout.folder_icon, this, mWorkspace,
CellLayout screen = info.container == Favorites.CONTAINER_DESKTOP
? mWorkspaceScreens.get(info.screenId)
: mHotseat;
FolderIcon folderIcon = FolderIcon.inflateIcon(R.layout.folder_icon, this, screen,
info);
addInScreenFromBind(folderIcon, info);
}
@@ -379,7 +369,7 @@ public class LauncherPreviewRenderer extends ContextWrapper
private void inflateAndAddWidgets(LauncherAppWidgetInfo info, WidgetsModel widgetsModel) {
WidgetItem widgetItem = widgetsModel.getWidgetProviderInfoByProviderName(
info.providerName);
info.providerName, info.user);
if (widgetItem == null) {
return;
}
@@ -388,20 +378,31 @@ public class LauncherPreviewRenderer extends ContextWrapper
private void inflateAndAddWidgets(
LauncherAppWidgetInfo info, LauncherAppWidgetProviderInfo providerInfo) {
AppWidgetHostView view = new AppWidgetHostView(mContext);
view.setAppWidget(-1, providerInfo);
view.updateAppWidget(null);
view.setTag(info);
AppWidgetHostView view;
if (FeatureFlags.WIDGETS_IN_LAUNCHER_PREVIEW.get()) {
view = mAppWidgetHost.createView(mContext, info.appWidgetId, providerInfo);
} else {
view = new NavigableAppWidgetHostView(this) {
@Override
protected boolean shouldAllowDirectClick() {
return false;
}
};
view.setAppWidget(-1, providerInfo);
view.updateAppWidget(null);
}
if (mWallpaperColorResources != null) {
view.setColorResources(mWallpaperColorResources);
}
view.setTag(info);
addInScreenFromBind(view, info);
}
private void inflateAndAddPredictedIcon(WorkspaceItemInfo info) {
View view = PredictedAppIconInflater.inflate(mHomeElementInflater, mWorkspace, info);
CellLayout screen = mWorkspaceScreens.get(info.screenId);
View view = PredictedAppIconInflater.inflate(mHomeElementInflater, screen, info);
if (view != null) {
addInScreenFromBind(view, info);
}
@@ -432,11 +433,13 @@ public class LauncherPreviewRenderer extends ContextWrapper
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<>();
ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<>();
ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<>();
filterCurrentWorkspaceItems(0 /* currentScreenId */,
dataModel.workspaceItems, currentWorkspaceItems,
otherWorkspaceItems);
filterCurrentWorkspaceItems(0 /* currentScreenId */, dataModel.appWidgets,
currentAppWidgets, otherAppWidgets);
IntSet currentScreenIds = IntSet.wrap(mWorkspaceScreens.keySet());
filterCurrentWorkspaceItems(currentScreenIds, dataModel.workspaceItems,
currentWorkspaceItems, otherWorkspaceItems);
filterCurrentWorkspaceItems(currentScreenIds, dataModel.appWidgets, currentAppWidgets,
otherAppWidgets);
sortWorkspaceItemsSpatially(mIdp, currentWorkspaceItems);
for (ItemInfo itemInfo : currentWorkspaceItems) {
switch (itemInfo.itemType) {
@@ -489,12 +492,13 @@ public class LauncherPreviewRenderer extends ContextWrapper
// Add first page QSB
if (FeatureFlags.topQsbOnFirstScreenEnabled(mContext)) {
View qsb = mHomeElementInflater.inflate(
R.layout.search_container_workspace, mWorkspace, false);
CellLayout firstScreen = mWorkspaceScreens.get(FIRST_SCREEN_ID);
View qsb = mHomeElementInflater.inflate(R.layout.qsb_preview, firstScreen,
false);
CellLayout.LayoutParams lp =
new CellLayout.LayoutParams(0, 0, mWorkspace.getCountX(), 1);
new CellLayout.LayoutParams(0, 0, firstScreen.getCountX(), 1);
lp.canReorder = false;
mWorkspace.addViewToCellLayout(qsb, 0, R.id.search_container_workspace, lp, true);
firstScreen.addViewToCellLayout(qsb, 0, R.id.search_container_workspace, lp, true);
}
measureView(mRootView, mDp.widthPx, mDp.heightPx);
@@ -509,6 +513,32 @@ public class LauncherPreviewRenderer extends ContextWrapper
view.layout(0, 0, width, height);
}
private class LauncherPreviewAppWidgetHost extends AppWidgetHost {
private LauncherPreviewAppWidgetHost(Context context) {
super(context, LauncherAppWidgetHost.APPWIDGET_HOST_ID);
}
@Override
protected AppWidgetHostView onCreateView(
Context context,
int appWidgetId,
AppWidgetProviderInfo appWidget) {
return new LauncherPreviewAppWidgetHostView(LauncherPreviewRenderer.this);
}
}
private static class LauncherPreviewAppWidgetHostView extends BaseLauncherAppWidgetHostView {
private LauncherPreviewAppWidgetHostView(Context context) {
super(context);
}
@Override
protected boolean shouldAllowDirectClick() {
return false;
}
}
/** Root layout for launcher preview that intercepts all touch events. */
public static class LauncherPreviewLayout extends InsettableFrameLayout {
public LauncherPreviewLayout(Context context, AttributeSet attrs) {
@@ -142,7 +142,7 @@ public class PreloadIconDrawable extends FastBitmapDrawable {
mSystemBackgroundColor = preloadColors[PRELOAD_BACKGROUND_COLOR_INDEX];
mIsDarkMode = isDarkMode;
setInternalProgress(info.getProgressLevel());
setLevel(info.getProgressLevel());
setIsStartable(info.isAppStartable());
}
@@ -16,7 +16,6 @@
package com.android.launcher3.graphics;
import static com.android.launcher3.config.FeatureFlags.MULTI_DB_GRID_MIRATION_ALGO;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
@@ -38,18 +37,17 @@ import android.view.animation.AccelerateDecelerateInterpolator;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.graphics.LauncherPreviewRenderer.PreviewContext;
import com.android.launcher3.model.BgDataModel;
import com.android.launcher3.model.GridSizeMigrationTask;
import com.android.launcher3.model.GridSizeMigrationTaskV2;
import com.android.launcher3.model.LoaderTask;
import com.android.launcher3.model.ModelDelegate;
import com.android.launcher3.model.ModelPreload;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.RunnableList;
import com.android.launcher3.util.Themes;
@@ -150,7 +148,8 @@ public class PreviewSurfaceRenderer {
inflationContext = new ContextThemeWrapper(context,
Themes.getActivityThemeRes(context, mWallpaperColors.getColorHints()));
} else {
inflationContext = new ContextThemeWrapper(mContext, R.style.AppTheme);
inflationContext = new ContextThemeWrapper(mContext,
Themes.getActivityThemeRes(mContext));
}
if (migrated) {
@@ -163,10 +162,18 @@ public class PreviewSurfaceRenderer {
@Override
public void run() {
DeviceProfile deviceProfile = mIdp.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<>(), LauncherSettings.Favorites.PREVIEW_CONTENT_URI,
LauncherSettings.Favorites.SCREEN + " = 0 or "
+ LauncherSettings.Favorites.CONTAINER + " = "
+ LauncherSettings.Favorites.CONTAINER_HOTSEAT);
query);
MAIN_EXECUTOR.execute(() -> {
renderView(previewContext, mBgDataModel, mWidgetProvidersMap);
mOnDestroyCallbacks.add(previewContext::onDestroy);
@@ -174,33 +181,22 @@ public class PreviewSurfaceRenderer {
}
}.run();
} else {
new ModelPreload() {
@Override
public void onComplete(boolean isSuccess) {
if (isSuccess) {
MAIN_EXECUTOR.execute(() ->
renderView(inflationContext, getBgDataModel(), null));
} else {
Log.e(TAG, "Model loading failed");
}
LauncherAppState.getInstance(inflationContext).getModel().loadAsync(dataModel -> {
if (dataModel != null) {
MAIN_EXECUTOR.execute(() -> renderView(inflationContext, dataModel, null));
} else {
Log.e(TAG, "Model loading failed");
}
}.start(inflationContext);
});
}
}
@WorkerThread
private boolean doGridMigrationIfNecessary() {
boolean needsToMigrate =
MULTI_DB_GRID_MIRATION_ALGO.get()
? GridSizeMigrationTaskV2.needsToMigrate(mContext, mIdp)
: GridSizeMigrationTask.needsToMigrate(mContext, mIdp);
if (!needsToMigrate) {
if (!GridSizeMigrationTaskV2.needsToMigrate(mContext, mIdp)) {
return false;
}
return MULTI_DB_GRID_MIRATION_ALGO.get()
? GridSizeMigrationTaskV2.migrateGridIfNeeded(mContext, mIdp)
: GridSizeMigrationTask.migrateGridIfNeeded(mContext, mIdp);
return GridSizeMigrationTaskV2.migrateGridIfNeeded(mContext, mIdp);
}
@UiThread
+106 -4
View File
@@ -18,6 +18,9 @@ package com.android.launcher3.icons;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import static com.android.launcher3.widget.WidgetSections.NO_CATEGORY;
import static java.util.stream.Collectors.groupingBy;
import android.content.ComponentName;
import android.content.Context;
@@ -30,16 +33,20 @@ 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.Process;
import android.os.Trace;
import android.os.UserHandle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import androidx.annotation.NonNull;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherFiles;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.icons.ComponentWithLabel.ComponentCachingLogic;
@@ -47,6 +54,7 @@ import com.android.launcher3.icons.cache.BaseIconCache;
import com.android.launcher3.icons.cache.CachingLogic;
import com.android.launcher3.icons.cache.HandlerRunnable;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.IconRequestInfo;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.model.data.PackageItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
@@ -55,9 +63,16 @@ import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.util.InstantAppResolver;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.widget.WidgetSections;
import com.android.launcher3.widget.WidgetSections.WidgetSection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
import app.lawnchair.icons.LawnchairIconProvider;
@@ -136,6 +151,9 @@ public class IconCache extends BaseIconCache {
* Closes the cache DB. This will clear any in-memory cache.
*/
public void close() {
// This will clear all pending updates
getUpdateHandler();
mIconDb.close();
}
@@ -261,7 +279,8 @@ public class IconCache extends BaseIconCache {
getTitleAndIcon(appInfo, false);
return appInfo.bitmap;
} else {
PackageItemInfo pkgInfo = new PackageItemInfo(shortcutInfo.getPackage());
PackageItemInfo pkgInfo = new PackageItemInfo(shortcutInfo.getPackage(),
shortcutInfo.getUserHandle());
getTitleAndIconForApp(pkgInfo, false);
return pkgInfo.bitmap;
}
@@ -305,6 +324,87 @@ public class IconCache extends BaseIconCache {
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 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()
.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()
.collect(groupingBy(iconRequest ->
iconRequest.itemInfo.getTargetComponent()));
Trace.beginSection("loadIconSubsectionInBulk");
try (Cursor c = createBulkQueryCursor(
filteredList,
/* user = */ sectionKey.first,
/* useLowResIcons = */ sectionKey.second)) {
int componentNameColumnIndex = c.getColumnIndexOrThrow(IconDB.COLUMN_COMPONENT);
while (c.moveToNext()) {
ComponentName cn = ComponentName.unflattenFromString(
c.getString(componentNameColumnIndex));
List<IconRequestInfo<T>> duplicateIconRequests =
duplicateIconRequestsMap.get(cn);
if (cn != null) {
CacheEntry entry = cacheLocked(
cn,
/* user = */ sectionKey.first,
() -> duplicateIconRequests.get(0).launcherActivityInfo,
mLauncherActivityInfoCachingLogic,
c,
/* usePackageIcon= */ false,
/* useLowResIcons = */ sectionKey.second);
for (IconRequestInfo<T> iconRequest : duplicateIconRequests) {
applyCacheEntry(entry, iconRequest.itemInfo);
}
}
}
} catch (SQLiteException e) {
Log.d(TAG, "Error reading icon cache", e);
} finally {
Trace.endSection();
}
});
Trace.endSection();
}
/**
* Fill in {@param infoInOut} with the corresponding icon and label.
@@ -314,8 +414,10 @@ public class IconCache extends BaseIconCache {
CacheEntry entry = getEntryForPackageLocked(
infoInOut.packageName, infoInOut.user, useLowResIcon);
applyCacheEntry(entry, infoInOut);
if (infoInOut.category == PackageItemInfo.CONVERSATIONS) {
infoInOut.title = mContext.getString(R.string.widget_category_conversations);
if (infoInOut.widgetCategory != NO_CATEGORY) {
WidgetSection widgetSection = WidgetSections.getWidgetSections(mContext)
.get(infoInOut.widgetCategory);
infoInOut.title = mContext.getString(widgetSection.mSectionTitle);
infoInOut.contentDescription = mPackageManager.getUserBadgedLabel(
infoInOut.title, infoInOut.user);
}
@@ -36,10 +36,10 @@ import androidx.annotation.VisibleForTesting;
*/
public final class InstanceId implements Parcelable {
// At most 20 bits: ~1m possibilities, ~0.5% probability of collision in 100 values
static final int INSTANCE_ID_MAX = 1 << 20;
public static final int INSTANCE_ID_MAX = 1 << 20;
private final int mId;
InstanceId(int id) {
public InstanceId(int id) {
mId = min(max(0, id), INSTANCE_ID_MAX);
}
@@ -33,6 +33,7 @@ import com.android.launcher3.logger.LauncherAtom.FromState;
import com.android.launcher3.logger.LauncherAtom.ToState;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.util.ResourceBasedOverride;
import com.android.launcher3.views.ActivityContext;
/**
* Handles the user event logging in R+.
@@ -53,6 +54,9 @@ public class StatsLogManager implements ResourceBasedOverride {
public static final int LAUNCHER_STATE_UNCHANGED = 5;
private InstanceId mInstanceId;
protected @Nullable ActivityContext mActivityContext = null;
/**
* Returns event enum based on the two state transition information when swipe
* gesture happens(to be removed during UserEventDispatcher cleanup).
@@ -76,6 +80,22 @@ 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
* the constructor parameter for any event.
*
* <pre>
* &#064;UiEvent(doc = "Briefly describe the interaction when this event will be logged")
* UNIQUE_EVENT_NAME(RESERVE_NEW_UI_EVENT_ID);
* </pre>
*/
int RESERVE_NEW_UI_EVENT_ID = Integer.MIN_VALUE; // Negative IDs are ignored by the logger.
int getId();
}
@@ -265,6 +285,9 @@ public class StatsLogManager implements ResourceBasedOverride {
@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),
@@ -486,8 +509,19 @@ public class StatsLogManager implements ResourceBasedOverride {
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)
;
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 long pressed on the taskbar background to hide the taskbar")
LAUNCHER_TASKBAR_LONGPRESS_HIDE(896),
@UiEvent(doc = "User long pressed on the taskbar gesture handle to show the taskbar")
LAUNCHER_TASKBAR_LONGPRESS_SHOW(897),
@UiEvent(doc = "User clicks on the search icon on header to launch search in app.")
LAUNCHER_ALLAPPS_SEARCHINAPP_LAUNCH(913);
// ADD MORE
@@ -627,7 +661,7 @@ public class StatsLogManager implements ResourceBasedOverride {
public StatsLogger logger() {
StatsLogger logger = createLogger();
if (mInstanceId != null) {
return logger.withInstanceId(mInstanceId);
logger.withInstanceId(mInstanceId);
}
return logger;
}
@@ -650,7 +684,9 @@ public class StatsLogManager implements ResourceBasedOverride {
* Creates a new instance of {@link StatsLogManager} based on provided context.
*/
public static StatsLogManager newInstance(Context context) {
return Overrides.getObject(StatsLogManager.class,
StatsLogManager manager = Overrides.getObject(StatsLogManager.class,
context.getApplicationContext(), R.string.stats_log_manager_class);
manager.mActivityContext = ActivityContext.lookupContextNoThrow(context);
return manager;
}
}
@@ -15,6 +15,8 @@
*/
package com.android.launcher3.model;
import static com.android.launcher3.WorkspaceLayoutManager.FIRST_SCREEN_ID;
import android.content.Intent;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
@@ -27,6 +29,7 @@ import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel.CallbackTask;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.model.BgDataModel.Callbacks;
import com.android.launcher3.model.data.AppInfo;
@@ -38,6 +41,7 @@ import com.android.launcher3.pm.InstallSessionHelper;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.util.GridOccupancy;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.PackageManagerHelper;
import java.util.ArrayList;
@@ -287,28 +291,23 @@ public class AddWorkspaceItemsTask extends BaseModelUpdateTask {
// Find appropriate space for the item.
int screenId = 0;
int[] cordinates = new int[2];
int[] coordinates = new int[2];
boolean found = false;
int screenCount = workspaceScreens.size();
// First check the preferred screen.
int preferredScreenIndex = workspaceScreens.isEmpty() ? 0 : 1;
if (preferredScreenIndex < screenCount) {
screenId = workspaceScreens.get(preferredScreenIndex);
found = findNextAvailableIconSpaceInScreen(
app, screenItems.get(screenId), cordinates, spanX, spanY);
IntSet screensToExclude = new IntSet();
if (FeatureFlags.QSB_ON_FIRST_SCREEN) {
screensToExclude.add(FIRST_SCREEN_ID);
}
if (!found) {
// Search on any of the screens starting from the first screen.
for (int screen = 1; screen < screenCount; screen++) {
screenId = workspaceScreens.get(screen);
if (findNextAvailableIconSpaceInScreen(
app, screenItems.get(screenId), cordinates, spanX, spanY)) {
// We found a space for it
found = true;
break;
}
for (int screen = 0; screen < screenCount; screen++) {
screenId = workspaceScreens.get(screen);
if (!screensToExclude.contains(screenId) && findNextAvailableIconSpaceInScreen(
app, screenItems.get(screenId), coordinates, spanX, spanY)) {
// We found a space for it
found = true;
break;
}
}
@@ -324,11 +323,11 @@ public class AddWorkspaceItemsTask extends BaseModelUpdateTask {
// If we still can't find an empty space, then God help us all!!!
if (!findNextAvailableIconSpaceInScreen(
app, screenItems.get(screenId), cordinates, spanX, spanY)) {
app, screenItems.get(screenId), coordinates, spanX, spanY)) {
throw new RuntimeException("Can't find space to add the item");
}
}
return new int[] {screenId, cordinates[0], cordinates[1]};
return new int[] {screenId, coordinates[0], coordinates[1]};
}
private boolean findNextAvailableIconSpaceInScreen(
@@ -132,30 +132,54 @@ public class AllAppsList {
* If the app is already in the list, doesn't add it.
*/
public void add(AppInfo info, LauncherActivityInfo activityInfo) {
add(info, activityInfo, true);
}
public void add(AppInfo info, LauncherActivityInfo activityInfo, boolean loadIcon) {
if (!mAppFilter.shouldShowApp(info.componentName)) {
return;
}
if (findAppInfo(info.componentName, info.user) != null) {
return;
}
mIconCache.getTitleAndIcon(info, activityInfo, false /* useLowResIcon */);
info.sectionName = mIndex.computeSectionName(info.title);
if (loadIcon) {
mIconCache.getTitleAndIcon(info, activityInfo, false /* useLowResIcon */);
info.sectionName = mIndex.computeSectionName(info.title);
}
data.add(info);
mDataChanged = true;
}
public void addPromiseApp(Context context, PackageInstallInfo installInfo) {
// only if not yet installed
if (!new PackageManagerHelper(context)
.isAppInstalled(installInfo.packageName, installInfo.user)) {
AppInfo info = new AppInfo(installInfo);
mIconCache.getTitleAndIcon(info, info.usingLowResIcon());
info.sectionName = mIndex.computeSectionName(info.title);
@Nullable
public AppInfo addPromiseApp(Context context, PackageInstallInfo installInfo) {
return addPromiseApp(context, installInfo, true);
}
data.add(info);
mDataChanged = true;
@Nullable
public AppInfo addPromiseApp(
Context context, PackageInstallInfo installInfo, boolean loadIcon) {
// only if not yet installed
if (new PackageManagerHelper(context)
.isAppInstalled(installInfo.packageName, installInfo.user)) {
return null;
}
AppInfo promiseAppInfo = new AppInfo(installInfo);
if (loadIcon) {
mIconCache.getTitleAndIcon(promiseAppInfo, promiseAppInfo.usingLowResIcon());
promiseAppInfo.sectionName = mIndex.computeSectionName(promiseAppInfo.title);
}
data.add(promiseAppInfo);
mDataChanged = true;
return promiseAppInfo;
}
public void updateSectionName(AppInfo appInfo) {
appInfo.sectionName = mIndex.computeSectionName(appInfo.title);
}
/** Updates the given PackageInstallInfo's associated AppInfo's installation info. */
@@ -16,24 +16,28 @@
package com.android.launcher3.model;
import static com.android.launcher3.model.ItemInstallQueue.FLAG_LOADER_RUNNING;
import static com.android.launcher3.model.ModelUtils.filterCurrentWorkspaceItems;
import static com.android.launcher3.model.ModelUtils.sortWorkspaceItemsSpatially;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import android.os.Process;
import android.util.Log;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel.CallbackTask;
import com.android.launcher3.PagedView;
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.testing.TestProtocol;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.LooperExecutor;
import com.android.launcher3.util.LooperIdleLock;
import com.android.launcher3.util.ViewOnDrawExecutor;
import com.android.launcher3.util.RunnableList;
import java.util.ArrayList;
import java.util.Collections;
@@ -71,7 +75,7 @@ public abstract class BaseLoaderResults {
/**
* Binds all loaded data to actual views on the main thread.
*/
public void bindWorkspace() {
public void bindWorkspace(boolean incrementBindId) {
// Save a copy of all the bg-thread collections
ArrayList<ItemInfo> workspaceItems = new ArrayList<>();
ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<>();
@@ -83,7 +87,9 @@ public abstract class BaseLoaderResults {
appWidgets.addAll(mBgDataModel.appWidgets);
orderedScreenIds.addAll(mBgDataModel.collectWorkspaceScreens());
mBgDataModel.extraItems.forEach(extraItems::add);
mBgDataModel.lastBindId++;
if (incrementBindId) {
mBgDataModel.lastBindId++;
}
mMyBindingId = mBgDataModel.lastBindId;
}
@@ -160,20 +166,7 @@ public abstract class BaseLoaderResults {
}
private void bind() {
final int currentScreen;
{
// Create an anonymous scope to calculate currentScreen as it has to be a
// final variable.
int currScreen = mCallbacks.getPageToBindSynchronously();
if (currScreen >= mOrderedScreenIds.size()) {
// There may be no workspace screens (just hotseat items and an empty page).
currScreen = PagedView.INVALID_PAGE;
}
currentScreen = currScreen;
}
final boolean validFirstPage = currentScreen >= 0;
final int currentScreenId =
validFirstPage ? mOrderedScreenIds.get(currentScreen) : INVALID_SCREEN_ID;
IntSet currentScreenIds = mCallbacks.getPagesToBindSynchronously(mOrderedScreenIds);
// Separate the items that are on the current screen, and all the other remaining items
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<>();
@@ -181,9 +174,21 @@ public abstract class BaseLoaderResults {
ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<>();
ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<>();
filterCurrentWorkspaceItems(currentScreenId, mWorkspaceItems, currentWorkspaceItems,
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NULL_INT_SET, "bind (1) currentScreenIds: "
+ currentScreenIds
+ ", pointer: "
+ mCallbacks
+ ", name: "
+ mCallbacks.getClass().getName());
}
filterCurrentWorkspaceItems(currentScreenIds, mWorkspaceItems, currentWorkspaceItems,
otherWorkspaceItems);
filterCurrentWorkspaceItems(currentScreenId, mAppWidgets, currentAppWidgets,
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NULL_INT_SET, "bind (2) currentScreenIds: "
+ currentScreenIds);
}
filterCurrentWorkspaceItems(currentScreenIds, mAppWidgets, currentAppWidgets,
otherAppWidgets);
final InvariantDeviceProfile idp = mApp.getInvariantDeviceProfile();
sortWorkspaceItemsSpatially(idp, currentWorkspaceItems);
@@ -198,40 +203,29 @@ public abstract class BaseLoaderResults {
// Bind workspace screens
executeCallbacksTask(c -> c.bindScreens(mOrderedScreenIds), mUiExecutor);
Executor mainExecutor = mUiExecutor;
// Load items on the current page.
bindWorkspaceItems(currentWorkspaceItems, mainExecutor);
bindAppWidgets(currentAppWidgets, mainExecutor);
bindWorkspaceItems(currentWorkspaceItems, mUiExecutor);
bindAppWidgets(currentAppWidgets, mUiExecutor);
mExtraItems.forEach(item ->
executeCallbacksTask(c -> c.bindExtraContainerItems(item), mainExecutor));
executeCallbacksTask(c -> c.bindExtraContainerItems(item), mUiExecutor));
// In case of validFirstPage, only bind the first screen, and defer binding the
// remaining screens after first onDraw (and an optional the fade animation whichever
// happens later).
// This ensures that the first screen is immediately visible (eg. during rotation)
// In case of !validFirstPage, bind all pages one after other.
RunnableList pendingTasks = new RunnableList();
Executor pendingExecutor = pendingTasks::add;
bindWorkspaceItems(otherWorkspaceItems, pendingExecutor);
bindAppWidgets(otherAppWidgets, pendingExecutor);
executeCallbacksTask(c -> c.finishBindingItems(currentScreenIds), pendingExecutor);
pendingExecutor.execute(
() -> {
MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
ItemInstallQueue.INSTANCE.get(mApp.getContext())
.resumeModelPush(FLAG_LOADER_RUNNING);
});
final Executor deferredExecutor =
validFirstPage ? new ViewOnDrawExecutor() : mainExecutor;
executeCallbacksTask(c -> c.finishFirstPageBind(
validFirstPage ? (ViewOnDrawExecutor) deferredExecutor : null), mainExecutor);
bindWorkspaceItems(otherWorkspaceItems, deferredExecutor);
bindAppWidgets(otherAppWidgets, deferredExecutor);
// Tell the workspace that we're done binding items
executeCallbacksTask(c -> c.finishBindingItems(currentScreen), deferredExecutor);
if (validFirstPage) {
executeCallbacksTask(c -> {
// We are loading synchronously, which means, some of the pages will be
// bound after first draw. Inform the mCallbacks that page binding is
// not complete, and schedule the remaining pages.
c.onPageBoundSynchronously(currentScreen);
c.executeOnNextDraw((ViewOnDrawExecutor) deferredExecutor);
}, mUiExecutor);
}
executeCallbacksTask(
c -> {
MODEL_EXECUTOR.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
c.onInitialBindComplete(currentScreenIds, pendingTasks);
}, mUiExecutor);
}
private void bindWorkspaceItems(
@@ -90,7 +90,7 @@ public abstract class BaseModelUpdateTask implements ModelUpdateTask {
public ModelWriter getModelWriter() {
// Updates from model task, do not deal with icon position in hotseat. Also no need to
// verify changes as the ModelTasks always push the changes to callbacks
return mModel.getWriter(false /* hasVerticalHotseat */, false /* verifyChanges */);
return mModel.getWriter(false /* hasVerticalHotseat */, false /* verifyChanges */, null);
}
public void bindUpdatedWorkspaceItems(List<WorkspaceItemInfo> allUpdates) {
@@ -31,6 +31,8 @@ import android.text.TextUtils;
import android.util.ArraySet;
import android.util.Log;
import androidx.annotation.Nullable;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.Workspace;
@@ -49,7 +51,7 @@ import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.IntSparseArrayMap;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.ViewOnDrawExecutor;
import com.android.launcher3.util.RunnableList;
import com.android.launcher3.widget.model.WidgetsListBaseEntry;
import java.io.FileDescriptor;
@@ -217,6 +219,19 @@ public class BgDataModel {
}
public synchronized void addItem(Context context, ItemInfo item, boolean newItem) {
addItem(context, item, newItem, null);
}
public synchronized void addItem(
Context context, ItemInfo item, boolean newItem, @Nullable LoaderMemoryLogger logger) {
if (logger != null) {
logger.addLog(
Log.DEBUG,
TAG,
String.format("Adding item to ID map: %s", item.toString()),
/* stackTrace= */ null);
}
itemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
@@ -448,37 +463,50 @@ public class BgDataModel {
int FLAG_QUIET_MODE_CHANGE_PERMISSION = 1 << 2;
/**
* Returns the page number to bind first, synchronously if possible or -1
* Returns an IntSet of page ids to bind first, synchronously if possible
* or an empty IntSet
* @param orderedScreenIds All the page ids to be bound
*/
int getPageToBindSynchronously();
void clearPendingBinds();
void startBinding();
void bindItems(List<ItemInfo> shortcuts, boolean forceAnimateIcons);
void bindScreens(IntArray orderedScreenIds);
void finishFirstPageBind(ViewOnDrawExecutor executor);
void finishBindingItems(int pageBoundFirst);
void preAddApps();
void bindAppsAdded(IntArray newScreens,
ArrayList<ItemInfo> addNotAnimated, ArrayList<ItemInfo> addAnimated);
default IntSet getPagesToBindSynchronously(IntArray orderedScreenIds) {
return new IntSet();
}
default void clearPendingBinds() { }
default void startBinding() { }
default void bindItems(List<ItemInfo> shortcuts, boolean forceAnimateIcons) { }
default void bindScreens(IntArray orderedScreenIds) { }
default void finishBindingItems(IntSet pagesBoundFirst) { }
default void preAddApps() { }
default void bindAppsAdded(IntArray newScreens,
ArrayList<ItemInfo> addNotAnimated, ArrayList<ItemInfo> addAnimated) { }
/**
* Called when some persistent property of an item is modified
*/
default void bindItemsModified(List<ItemInfo> items) { }
/**
* Binds updated incremental download progress
*/
void bindIncrementalDownloadProgressUpdated(AppInfo app);
void bindWorkspaceItemsChanged(List<WorkspaceItemInfo> updated);
void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
void bindRestoreItemsChange(HashSet<ItemInfo> updates);
void bindWorkspaceComponentsRemoved(ItemInfoMatcher matcher);
void bindAllWidgets(List<WidgetsListBaseEntry> widgets);
void onPageBoundSynchronously(int page);
void executeOnNextDraw(ViewOnDrawExecutor executor);
void bindDeepShortcutMap(HashMap<ComponentKey, Integer> deepShortcutMap);
default void bindIncrementalDownloadProgressUpdated(AppInfo app) { }
default void bindWorkspaceItemsChanged(List<WorkspaceItemInfo> updated) { }
default void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets) { }
default void bindRestoreItemsChange(HashSet<ItemInfo> updates) { }
default void bindWorkspaceComponentsRemoved(ItemInfoMatcher matcher) { }
default void bindAllWidgets(List<WidgetsListBaseEntry> widgets) { }
default void onInitialBindComplete(IntSet boundPages, RunnableList pendingTasks) {
pendingTasks.executeAllAndDestroy();
}
default void bindDeepShortcutMap(HashMap<ComponentKey, Integer> deepShortcutMap) { }
/**
* Binds extra item provided any external source
*/
default void bindExtraContainerItems(FixedContainerItems item) { }
void bindAllApplications(AppInfo[] apps, int flags);
default void bindAllApplications(AppInfo[] apps, int flags) { }
}
}
@@ -0,0 +1,119 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.model;
import static com.android.launcher3.InvariantDeviceProfile.DeviceType;
import static com.android.launcher3.InvariantDeviceProfile.TYPE_PHONE;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_GRID_SIZE_2;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_GRID_SIZE_3;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_GRID_SIZE_4;
import static com.android.launcher3.logging.StatsLogManager.LauncherEvent.LAUNCHER_GRID_SIZE_5;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.Utilities;
import com.android.launcher3.logging.StatsLogManager.LauncherEvent;
import java.util.Locale;
import java.util.Objects;
/**
* Utility class representing persisted grid properties.
*/
public class DeviceGridState {
public static final String KEY_WORKSPACE_SIZE = "migration_src_workspace_size";
public static final String KEY_HOTSEAT_COUNT = "migration_src_hotseat_count";
public static final String KEY_DEVICE_TYPE = "migration_src_device_type";
private final String mGridSizeString;
private final int mNumHotseat;
private final @DeviceType int mDeviceType;
public DeviceGridState(InvariantDeviceProfile idp) {
mGridSizeString = String.format(Locale.ENGLISH, "%d,%d", idp.numColumns, idp.numRows);
mNumHotseat = idp.numDatabaseHotseatIcons;
mDeviceType = idp.deviceType;
}
public DeviceGridState(Context context) {
SharedPreferences prefs = Utilities.getPrefs(context);
mGridSizeString = prefs.getString(KEY_WORKSPACE_SIZE, "");
mNumHotseat = prefs.getInt(KEY_HOTSEAT_COUNT, -1);
mDeviceType = prefs.getInt(KEY_DEVICE_TYPE, TYPE_PHONE);
}
/**
* Returns the device type for the grid
*/
public @DeviceType int getDeviceType() {
return mDeviceType;
}
/**
* Stores the device state to shared preferences
*/
public void writeToPrefs(Context context) {
Utilities.getPrefs(context).edit()
.putString(KEY_WORKSPACE_SIZE, mGridSizeString)
.putInt(KEY_HOTSEAT_COUNT, mNumHotseat)
.putInt(KEY_DEVICE_TYPE, mDeviceType)
.apply();
}
/**
* Returns the logging event corresponding to the grid state
*/
public LauncherEvent getWorkspaceSizeEvent() {
if (!TextUtils.isEmpty(mGridSizeString)) {
switch (mGridSizeString.charAt(0)) {
case '5':
return LAUNCHER_GRID_SIZE_5;
case '4':
return LAUNCHER_GRID_SIZE_4;
case '3':
return LAUNCHER_GRID_SIZE_3;
case '2':
return LAUNCHER_GRID_SIZE_2;
}
}
return null;
}
@Override
public String toString() {
return "DeviceGridState{"
+ "mGridSizeString='" + mGridSizeString + '\''
+ ", mNumHotseat=" + mNumHotseat
+ ", mDeviceType=" + mDeviceType
+ '}';
}
/**
* Returns true if the database from another DeviceGridState can be loaded into the current
* DeviceGridState without migration, or false otherwise.
*/
public boolean isCompatible(DeviceGridState other) {
if (this == other) return true;
if (other == null) return false;
return mNumHotseat == other.mNumHotseat
&& Objects.equals(mGridSizeString, other.mGridSizeString);
}
}
@@ -23,14 +23,12 @@ import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
import android.os.Process;
import android.util.Log;
import androidx.annotation.IntDef;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.LauncherSettings.Settings;
import com.android.launcher3.pm.UserCache;
/**
@@ -84,49 +82,6 @@ public class GridBackupTable {
mOldGridY = gridY;
}
/**
* Create a backup from current workspace layout if one isn't created already (Note backup
* created this way is always sanitized). Otherwise restore from the backup instead.
*/
public boolean backupOrRestoreAsNeeded() {
// Check if backup table exists
if (!tableExists(mDb, BACKUP_TABLE_NAME)) {
if (Settings.call(mContext.getContentResolver(), Settings.METHOD_WAS_EMPTY_DB_CREATED)
.getBoolean(Settings.EXTRA_VALUE, false)) {
// No need to copy if empty DB was created.
return false;
}
doBackup(UserCache.INSTANCE.get(mContext).getSerialNumberForUser(
Process.myUserHandle()), 0);
return false;
}
return restoreIfBackupExists(Favorites.TABLE_NAME);
}
public boolean restoreToPreviewIfBackupExists() {
if (!tableExists(mDb, BACKUP_TABLE_NAME)) {
return false;
}
return restoreIfBackupExists(Favorites.PREVIEW_TABLE_NAME);
}
private boolean restoreIfBackupExists(String toTableName) {
if (loadDBProperties() != STATE_SANITIZED) {
return false;
}
long userSerial = UserCache.INSTANCE.get(mContext).getSerialNumberForUser(
Process.myUserHandle());
copyTable(mDb, BACKUP_TABLE_NAME, toTableName, userSerial);
Log.d(TAG, "Backup table found");
return true;
}
public int getRestoreHotseatAndGridSize(Point outGridSize) {
outGridSize.set(mRestoredGridX, mRestoredGridY);
return mRestoredHotseatSize;
}
/**
* Creates a new table and populates with copy of Favorites.TABLE_NAME
*/
File diff suppressed because it is too large. Load diff
@@ -16,9 +16,6 @@
package com.android.launcher3.model;
import static com.android.launcher3.InvariantDeviceProfile.KEY_MIGRATION_SRC_HOTSEAT_COUNT;
import static com.android.launcher3.InvariantDeviceProfile.KEY_MIGRATION_SRC_WORKSPACE_SIZE;
import static com.android.launcher3.Utilities.getPointString;
import static com.android.launcher3.provider.LauncherDbUtils.dropTable;
import android.content.ComponentName;
@@ -122,10 +119,15 @@ public class GridSizeMigrationTaskV2 {
* Check given a new IDP, if migration is necessary.
*/
public static boolean needsToMigrate(Context context, InvariantDeviceProfile idp) {
SharedPreferences prefs = Utilities.getPrefs(context);
String gridSizeString = getPointString(idp.numColumns, idp.numRows);
return !gridSizeString.equals(prefs.getString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, ""))
|| idp.numDatabaseHotseatIcons != prefs.getInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT, -1);
DeviceGridState idpGridState = new DeviceGridState(idp);
DeviceGridState contextGridState = new DeviceGridState(context);
boolean needsToMigrate = !idpGridState.isCompatible(contextGridState);
// TODO(b/198965093): Revert this change after bug is fixed
if (needsToMigrate) {
Log.d("b/198965093", "Migration is needed. idpGridState: " + idpGridState
+ ", contextGridState: " + contextGridState);
}
return needsToMigrate;
}
/** See {@link #migrateGridIfNeeded(Context, InvariantDeviceProfile)} */
@@ -138,15 +140,15 @@ public class GridSizeMigrationTaskV2 {
/**
* When migrating the grid for preview, we copy the table
* {@link LauncherSettings.Favorites.TABLE_NAME} into
* {@link LauncherSettings.Favorites.PREVIEW_TABLE_NAME}, run grid size migration from the
* {@link LauncherSettings.Favorites#TABLE_NAME} into
* {@link LauncherSettings.Favorites#PREVIEW_TABLE_NAME}, run grid size migration from the
* former to the later, then use the later table for preview.
*
* Similarly when doing the actual grid migration, the former grid option's table
* {@link LauncherSettings.Favorites.TABLE_NAME} is copied into the new grid option's
* {@link LauncherSettings.Favorites.TMP_TABLE}, we then run the grid size migration algorithm
* {@link LauncherSettings.Favorites#TABLE_NAME} is copied into the new grid option's
* {@link LauncherSettings.Favorites#TMP_TABLE}, we then run the grid size migration algorithm
* to migrate the later to the former, and load the workspace from the default
* {@link LauncherSettings.Favorites.TABLE_NAME}.
* {@link LauncherSettings.Favorites#TABLE_NAME}.
*
* @return false if the migration failed.
*/
@@ -161,10 +163,7 @@ public class GridSizeMigrationTaskV2 {
}
SharedPreferences prefs = Utilities.getPrefs(context);
String gridSizeString = getPointString(idp.numColumns, idp.numRows);
HashSet<String> validPackages = getValidPackages(context);
int srcHotseatCount = prefs.getInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT,
idp.numDatabaseHotseatIcons);
if (migrateForPreview) {
if (!LauncherSettings.Settings.call(
@@ -189,16 +188,16 @@ public class GridSizeMigrationTaskV2 {
DbReader srcReader = new DbReader(t.getDb(),
migrateForPreview ? LauncherSettings.Favorites.TABLE_NAME
: LauncherSettings.Favorites.TMP_TABLE,
context, validPackages, srcHotseatCount);
context, validPackages);
DbReader destReader = new DbReader(t.getDb(),
migrateForPreview ? LauncherSettings.Favorites.PREVIEW_TABLE_NAME
: LauncherSettings.Favorites.TABLE_NAME,
context, validPackages, idp.numDatabaseHotseatIcons);
context, validPackages);
Point targetSize = new Point(idp.numColumns, idp.numRows);
GridSizeMigrationTaskV2 task = new GridSizeMigrationTaskV2(context, t.getDb(),
srcReader, destReader, idp.numDatabaseHotseatIcons, targetSize);
task.migrate();
task.migrate(idp);
if (!migrateForPreview) {
dropTable(t.getDb(), LauncherSettings.Favorites.TMP_TABLE);
@@ -221,16 +220,13 @@ public class GridSizeMigrationTaskV2 {
if (!migrateForPreview) {
// Save current configuration, so that the migration does not run again.
prefs.edit()
.putString(KEY_MIGRATION_SRC_WORKSPACE_SIZE, gridSizeString)
.putInt(KEY_MIGRATION_SRC_HOTSEAT_COUNT, idp.numDatabaseHotseatIcons)
.apply();
new DeviceGridState(idp).writeToPrefs(context);
}
}
}
@VisibleForTesting
protected boolean migrate() {
protected boolean migrate(InvariantDeviceProfile idp) {
if (mHotseatDiff.isEmpty() && mWorkspaceDiff.isEmpty()) {
return false;
}
@@ -244,7 +240,14 @@ public class GridSizeMigrationTaskV2 {
Collections.sort(mWorkspaceDiff);
// Migrate workspace.
// First we create a collection of the screens
List<Integer> screens = new ArrayList<>();
for (int screenId = 0; screenId <= mDestReader.mLastScreenId; screenId++) {
screens.add(screenId);
}
// Then we place the items on the screens
for (int screenId : screens) {
if (DEBUG) {
Log.d(TAG, "Migrating " + screenId);
}
@@ -256,6 +259,8 @@ public class GridSizeMigrationTaskV2 {
}
}
// In case the new grid is smaller, there might be some leftover items that don't fit on
// any of the screens, in this case we add them to new screens until all of them are placed.
int screenId = mDestReader.mLastScreenId + 1;
while (!mWorkspaceDiff.isEmpty()) {
GridPlacementSolution workspaceSolution = new GridPlacementSolution(mDb, mSrcReader,
@@ -511,7 +516,6 @@ public class GridSizeMigrationTaskV2 {
private final String mTableName;
private final Context mContext;
private final HashSet<String> mValidPackages;
private final int mHotseatSize;
private int mLastScreenId = -1;
private final ArrayList<DbEntry> mHotseatEntries = new ArrayList<>();
@@ -520,12 +524,11 @@ public class GridSizeMigrationTaskV2 {
new ArrayMap<>();
DbReader(SQLiteDatabase db, String tableName, Context context,
HashSet<String> validPackages, int hotseatSize) {
HashSet<String> validPackages) {
mDb = db;
mTableName = tableName;
mContext = context;
mValidPackages = validPackages;
mHotseatSize = hotseatSize;
}
protected ArrayList<DbEntry> loadHotseatEntries() {
@@ -550,11 +553,6 @@ public class GridSizeMigrationTaskV2 {
entry.itemType = c.getInt(indexItemType);
entry.screenId = c.getInt(indexScreen);
if (entry.screenId >= mHotseatSize) {
entriesToRemove.add(entry.id);
continue;
}
try {
// calculate weight
switch (entry.itemType) {
@@ -16,13 +16,10 @@
package com.android.launcher3.model;
import static android.graphics.BitmapFactory.decodeByteArray;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
import android.content.pm.PackageManager;
@@ -45,11 +42,10 @@ import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.IconCache;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.IconRequestInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.shortcuts.ShortcutKey;
@@ -186,32 +182,22 @@ public class LoaderCursor extends CursorWrapper {
* Loads the icon from the cursor and updates the {@param info} if the icon is an app resource.
*/
protected boolean loadIcon(WorkspaceItemInfo info) {
try (LauncherIcons li = LauncherIcons.obtain(mContext)) {
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
String packageName = getString(iconPackageIndex);
String resourceName = getString(iconResourceIndex);
if (!TextUtils.isEmpty(packageName) || !TextUtils.isEmpty(resourceName)) {
info.iconResource = new ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
BitmapInfo iconInfo = li.createIconBitmap(info.iconResource);
if (iconInfo != null) {
info.bitmap = iconInfo;
return true;
}
}
}
return createIconRequestInfo(info, false).loadWorkspaceIcon(mContext);
}
// Failed to load from resource, try loading from DB.
byte[] data = getBlob(iconIndex);
try {
info.bitmap = li.createIconBitmap(decodeByteArray(data, 0, data.length));
return true;
} catch (Exception e) {
Log.e(TAG, "Failed to decode byte array for info " + info, e);
return false;
}
}
public IconRequestInfo<WorkspaceItemInfo> createIconRequestInfo(
WorkspaceItemInfo wai, boolean useLowResIcon) {
String packageName = itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT
? getString(iconPackageIndex) : null;
String resourceName = itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT
? getString(iconResourceIndex) : null;
byte[] iconBlob = itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT
|| itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT
|| restoreFlag != 0
? getBlob(iconIndex) : null;
return new IconRequestInfo<>(
wai, mActivityInfo, packageName, resourceName, iconBlob, useLowResIcon);
}
/**
@@ -264,6 +250,11 @@ public class LoaderCursor extends CursorWrapper {
*/
public WorkspaceItemInfo getAppShortcutInfo(
Intent intent, boolean allowMissingTarget, boolean useLowResIcon) {
return getAppShortcutInfo(intent, allowMissingTarget, useLowResIcon, true);
}
public WorkspaceItemInfo getAppShortcutInfo(
Intent intent, boolean allowMissingTarget, boolean useLowResIcon, boolean loadIcon) {
if (user == null) {
Log.d(TAG, "Null user found in getShortcutInfo");
return null;
@@ -290,9 +281,11 @@ public class LoaderCursor extends CursorWrapper {
info.user = user;
info.intent = newIntent;
mIconCache.getTitleAndIcon(info, mActivityInfo, useLowResIcon);
if (mIconCache.isDefaultIcon(info.bitmap, user)) {
loadIcon(info);
if (loadIcon) {
mIconCache.getTitleAndIcon(info, mActivityInfo, useLowResIcon);
if (mIconCache.isDefaultIcon(info.bitmap, user)) {
loadIcon(info);
}
}
if (mActivityInfo != null) {
@@ -392,18 +385,23 @@ public class LoaderCursor extends CursorWrapper {
info.cellY = getInt(cellYIndex);
}
public void checkAndAddItem(ItemInfo info, BgDataModel dataModel) {
checkAndAddItem(info, dataModel, null);
}
/**
* Adds the {@param info} to {@param dataModel} if it does not overlap with any other item,
* otherwise marks it for deletion.
*/
public void checkAndAddItem(ItemInfo info, BgDataModel dataModel) {
public void checkAndAddItem(
ItemInfo info, BgDataModel dataModel, LoaderMemoryLogger logger) {
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
// Ensure that it is a valid intent. An exception here will
// cause the item loading to get skipped
ShortcutKey.fromItemInfo(info);
}
if (checkItemPlacement(info)) {
dataModel.addItem(mContext, info, false);
dataModel.addItem(mContext, info, false, logger);
} else {
markDeleted("Item position overlap");
}
@@ -0,0 +1,91 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.model;
import android.util.Log;
import androidx.annotation.Nullable;
import java.util.ArrayList;
/**
* Helper logger that collects logs while {@code LoaderTask#run} executes and prints them all iff
* an exception is caught in {@code LoaderTask#run}.
*/
public class LoaderMemoryLogger {
private static final String TAG = "LoaderMemoryLogger";
private final ArrayList<LogEntry> mLogEntries = new ArrayList<>();
protected LoaderMemoryLogger() {}
protected void addLog(int logLevel, String tag, String log) {
addLog(logLevel, tag, log, null);
}
protected void addLog(
int logLevel, String tag, String log, Exception stackTrace) {
switch (logLevel) {
case Log.ASSERT:
case Log.ERROR:
case Log.DEBUG:
case Log.INFO:
case Log.VERBOSE:
case Log.WARN:
mLogEntries.add(new LogEntry(logLevel, tag, log, stackTrace));
break;
default:
throw new IllegalArgumentException("Invalid log level provided: " + logLevel);
}
}
protected void clearLogs() {
mLogEntries.clear();
}
protected void printLogs() {
for (LogEntry logEntry : mLogEntries) {
String tag = String.format("%s: %s", TAG, logEntry.mLogTag);
String logString = logEntry.mStackStrace == null
? logEntry.mLogString
: String.format(
"%s\n%s",
logEntry.mLogString,
Log.getStackTraceString(logEntry.mStackStrace));
Log.println(logEntry.mLogLevel, tag, logString);
}
clearLogs();
}
private static class LogEntry {
protected final int mLogLevel;
protected final String mLogTag;
protected final String mLogString;
@Nullable protected final Exception mStackStrace;
protected LogEntry(
int logLevel, String logTag, String logString, @Nullable Exception stackStrace) {
mLogLevel = logLevel;
mLogTag = logTag;
mLogString = logString;
mStackStrace = stackStrace;
}
}
}
+107 -32
View File
@@ -16,7 +16,6 @@
package com.android.launcher3.model;
import static com.android.launcher3.config.FeatureFlags.MULTI_DB_GRID_MIRATION_ALGO;
import static com.android.launcher3.model.BgDataModel.Callbacks.FLAG_HAS_SHORTCUT_PERMISSION;
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;
@@ -44,6 +43,7 @@ import android.content.pm.ShortcutInfo;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Trace;
import android.os.UserHandle;
import android.os.UserManager;
import android.text.TextUtils;
@@ -52,6 +52,8 @@ import android.util.Log;
import android.util.LongSparseArray;
import android.util.TimingLogger;
import androidx.annotation.Nullable;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherAppState;
@@ -73,6 +75,7 @@ import com.android.launcher3.icons.cache.IconCacheUpdateHandler;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.FolderInfo;
import com.android.launcher3.model.data.IconRequestInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
@@ -80,13 +83,14 @@ import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.pm.InstallSessionHelper;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.pm.UserCache;
import com.android.launcher3.provider.ImportDataTask;
import com.android.launcher3.qsb.QsbContainerView;
import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.shortcuts.ShortcutRequest;
import com.android.launcher3.shortcuts.ShortcutRequest.QueryResult;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.IOUtils;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
import com.android.launcher3.util.LooperIdleLock;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.PackageUserKey;
@@ -177,10 +181,13 @@ public class LoaderTask implements Runnable {
private void sendFirstScreenActiveInstallsBroadcast() {
ArrayList<ItemInfo> firstScreenItems = new ArrayList<>();
ArrayList<ItemInfo> allItems = mBgDataModel.getAllWorkspaceItems();
// Screen set is never empty
final int firstScreen = mBgDataModel.collectWorkspaceScreens().get(0);
filterCurrentWorkspaceItems(firstScreen, allItems, firstScreenItems,
// Screen set is never empty
IntArray allScreens = mBgDataModel.collectWorkspaceScreens();
final int firstScreen = allScreens.get(0);
IntSet firstScreens = IntSet.wrap(firstScreen);
filterCurrentWorkspaceItems(firstScreens, allItems, firstScreenItems,
new ArrayList<>() /* otherScreenItems are ignored */);
mFirstScreenBroadcast.sendBroadcasts(mApp.getContext(), firstScreenItems);
}
@@ -195,9 +202,15 @@ public class LoaderTask implements Runnable {
Object traceToken = TraceHelper.INSTANCE.beginSection(TAG);
TimingLogger logger = new TimingLogger(TAG, "run");
LoaderMemoryLogger memoryLogger = new LoaderMemoryLogger();
try (LauncherModel.LoaderTransaction transaction = mApp.getModel().beginLoader(this)) {
List<ShortcutInfo> allShortcuts = new ArrayList<>();
loadWorkspace(allShortcuts);
Trace.beginSection("LoadWorkspace");
try {
loadWorkspace(allShortcuts, memoryLogger);
} finally {
Trace.endSection();
}
logASplit(logger, "loadWorkspace");
// Sanitize data re-syncs widgets/shortcuts based on the workspace loaded from db.
@@ -211,7 +224,7 @@ public class LoaderTask implements Runnable {
}
verifyNotStopped();
mResults.bindWorkspace();
mResults.bindWorkspace(true /* incrementBindId */);
logASplit(logger, "bindWorkspace");
mModelDelegate.workspaceLoadComplete();
@@ -225,7 +238,13 @@ public class LoaderTask implements Runnable {
verifyNotStopped();
// second step
List<LauncherActivityInfo> allActivityList = loadAllApps();
Trace.beginSection("LoadAllApps");
List<LauncherActivityInfo> allActivityList;
try {
allActivityList = loadAllApps();
} finally {
Trace.endSection();
}
logASplit(logger, "loadAllApps");
verifyNotStopped();
@@ -298,9 +317,13 @@ public class LoaderTask implements Runnable {
mModelDelegate.modelLoadComplete();
transaction.commit();
memoryLogger.clearLogs();
} catch (CancellationException e) {
// Loader stopped, ignore
logASplit(logger, "Cancelled");
} catch (Exception e) {
memoryLogger.printLogs();
throw e;
} finally {
logger.dumpToLog();
}
@@ -312,13 +335,21 @@ public class LoaderTask implements Runnable {
this.notify();
}
private void loadWorkspace(List<ShortcutInfo> allDeepShortcuts) {
private void loadWorkspace(List<ShortcutInfo> allDeepShortcuts, LoaderMemoryLogger logger) {
loadWorkspace(allDeepShortcuts, LauncherSettings.Favorites.CONTENT_URI,
null /* selection */);
null /* selection */, logger);
}
protected void loadWorkspace(List<ShortcutInfo> allDeepShortcuts, Uri contentUri,
String selection) {
protected void loadWorkspace(
List<ShortcutInfo> allDeepShortcuts, Uri contentUri, String selection) {
loadWorkspace(allDeepShortcuts, contentUri, selection, null);
}
protected void loadWorkspace(
List<ShortcutInfo> allDeepShortcuts,
Uri contentUri,
String selection,
@Nullable LoaderMemoryLogger logger) {
final Context context = mApp.getContext();
final ContentResolver contentResolver = context.getContentResolver();
final PackageManagerHelper pmHelper = new PackageManagerHelper(context);
@@ -327,16 +358,7 @@ public class LoaderTask implements Runnable {
final WidgetManagerHelper widgetHelper = new WidgetManagerHelper(context);
boolean clearDb = false;
try {
ImportDataTask.performImportIfPossible(context);
} catch (Exception e) {
// Migration failed. Clear workspace.
clearDb = true;
}
if (!clearDb && (MULTI_DB_GRID_MIRATION_ALGO.get()
? !GridSizeMigrationTaskV2.migrateGridIfNeeded(context)
: !GridSizeMigrationTask.migrateGridIfNeeded(context))) {
if (!GridSizeMigrationTaskV2.migrateGridIfNeeded(context)) {
// Migration failed. Clear workspace.
clearDb = true;
}
@@ -421,6 +443,7 @@ public class LoaderTask implements Runnable {
LauncherAppWidgetProviderInfo widgetProviderInfo;
Intent intent;
String targetPkg;
List<IconRequestInfo<WorkspaceItemInfo>> iconRequestInfos = new ArrayList<>();
while (!mStopped && c.moveToNext()) {
try {
@@ -543,7 +566,10 @@ public class LoaderTask implements Runnable {
} else if (c.itemType ==
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = c.getAppShortcutInfo(
intent, allowMissingTarget, useLowResIcon);
intent,
allowMissingTarget,
useLowResIcon,
!FeatureFlags.ENABLE_BULK_WORKSPACE_ICON_LOADING.get());
} else if (c.itemType ==
LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
@@ -580,6 +606,7 @@ public class LoaderTask implements Runnable {
&& pmHelper.isAppSuspended(targetPkg, c.user)) {
disabledState |= FLAG_DISABLED_SUSPENDED;
}
info.options = c.getInt(optionsIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that
@@ -595,6 +622,8 @@ public class LoaderTask implements Runnable {
}
if (info != null) {
iconRequestInfos.add(c.createIconRequestInfo(info, useLowResIcon));
c.applyCommonProperties(info);
info.intent = intent;
@@ -628,7 +657,7 @@ public class LoaderTask implements Runnable {
}
}
c.checkAndAddItem(info, mBgDataModel);
c.checkAndAddItem(info, mBgDataModel, logger);
} else {
throw new RuntimeException("Unexpected null WorkspaceItemInfo");
}
@@ -647,7 +676,7 @@ public class LoaderTask implements Runnable {
// no special handling required for restored folders
c.markRestored();
c.checkAndAddItem(folderInfo, mBgDataModel);
c.checkAndAddItem(folderInfo, mBgDataModel, logger);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
@@ -798,8 +827,9 @@ public class LoaderTask implements Runnable {
if (appWidgetInfo.restoreStatus !=
LauncherAppWidgetInfo.RESTORE_COMPLETED) {
appWidgetInfo.pendingItemInfo = WidgetsModel.newPendingItemInfo(
appWidgetInfo.providerName);
appWidgetInfo.pendingItemInfo.user = appWidgetInfo.user;
mApp.getContext(),
appWidgetInfo.providerName,
appWidgetInfo.user);
mIconCache.getTitleAndIconForApp(
appWidgetInfo.pendingItemInfo, false);
}
@@ -812,6 +842,21 @@ public class LoaderTask implements Runnable {
Log.e(TAG, "Desktop items loading interrupted", e);
}
}
if (FeatureFlags.ENABLE_BULK_WORKSPACE_ICON_LOADING.get()) {
Trace.beginSection("LoadWorkspaceIconsInBulk");
try {
mIconCache.getTitlesAndIconsInBulk(iconRequestInfos);
for (IconRequestInfo<WorkspaceItemInfo> iconRequestInfo :
iconRequestInfos) {
WorkspaceItemInfo wai = iconRequestInfo.itemInfo;
if (mIconCache.isDefaultIcon(wai.bitmap, wai.user)) {
iconRequestInfo.loadWorkspaceIcon(mApp.getContext());
}
}
} finally {
Trace.endSection();
}
}
} finally {
IOUtils.closeSilently(c);
}
@@ -915,6 +960,8 @@ public class LoaderTask implements Runnable {
List<LauncherActivityInfo> allActivityList = new ArrayList<>();
// Clear the list of apps
mBgAllAppsList.clear();
List<IconRequestInfo<AppInfo>> iconRequestInfos = new ArrayList<>();
for (UserHandle user : profiles) {
// Query for the set of apps
final List<LauncherActivityInfo> apps = mLauncherApps.getActivityList(null, user);
@@ -927,18 +974,43 @@ public class LoaderTask implements Runnable {
// Create the ApplicationInfos
for (int i = 0; i < apps.size(); i++) {
LauncherActivityInfo app = apps.get(i);
// This builds the icon bitmaps.
mBgAllAppsList.add(new AppInfo(app, user, quietMode), app);
AppInfo appInfo = new AppInfo(app, user, quietMode);
iconRequestInfos.add(new IconRequestInfo<>(
appInfo, app, /* useLowResIcon= */ false));
mBgAllAppsList.add(
appInfo, app, !FeatureFlags.ENABLE_BULK_ALL_APPS_ICON_LOADING.get());
}
allActivityList.addAll(apps);
}
if (FeatureFlags.PROMISE_APPS_IN_ALL_APPS.get()) {
// get all active sessions and add them to the all apps list
for (PackageInstaller.SessionInfo info :
mSessionHelper.getAllVerifiedSessions()) {
mBgAllAppsList.addPromiseApp(mApp.getContext(),
PackageInstallInfo.fromInstallingState(info));
AppInfo promiseAppInfo = mBgAllAppsList.addPromiseApp(
mApp.getContext(),
PackageInstallInfo.fromInstallingState(info),
!FeatureFlags.ENABLE_BULK_ALL_APPS_ICON_LOADING.get());
if (promiseAppInfo != null) {
iconRequestInfos.add(new IconRequestInfo<>(
promiseAppInfo,
/* launcherActivityInfo= */ null,
promiseAppInfo.usingLowResIcon()));
}
}
}
if (FeatureFlags.ENABLE_BULK_ALL_APPS_ICON_LOADING.get()) {
Trace.beginSection("LoadAllAppsIconsInBulk");
try {
mIconCache.getTitlesAndIconsInBulk(iconRequestInfos);
iconRequestInfos.forEach(iconRequestInfo ->
mBgAllAppsList.updateSectionName(iconRequestInfo.itemInfo));
} finally {
Trace.endSection();
}
}
@@ -1001,7 +1073,10 @@ public class LoaderTask implements Runnable {
deviceProfile.getCellSize(cellSize);
FileLog.d(TAG, "DeviceProfile available width: " + deviceProfile.availableWidthPx
+ ", available height: " + deviceProfile.availableHeightPx
+ ", cellLayoutBorderSpacingPx: " + deviceProfile.cellLayoutBorderSpacingPx
+ ", cellLayoutBorderSpacePx Horizontal: "
+ deviceProfile.cellLayoutBorderSpacePx.x
+ ", cellLayoutBorderSpacePx Vertical: "
+ deviceProfile.cellLayoutBorderSpacePx.y
+ ", cellSize: " + cellSize);
}
@@ -40,19 +40,21 @@ public class ModelDelegate implements ResourceBasedOverride {
* Creates and initializes a new instance of the delegate
*/
public static ModelDelegate newInstance(
Context context, LauncherAppState app, AllAppsList appsList, BgDataModel dataModel) {
Context context, LauncherAppState app, AllAppsList appsList, BgDataModel dataModel,
boolean isPrimaryInstance) {
ModelDelegate delegate = Overrides.getObject(
ModelDelegate.class, context, R.string.model_delegate_class);
delegate.mApp = app;
delegate.mAppsList = appsList;
delegate.mDataModel = dataModel;
delegate.mIsPrimaryInstance = isPrimaryInstance;
return delegate;
}
protected LauncherAppState mApp;
protected AllAppsList mAppsList;
protected BgDataModel mDataModel;
protected boolean mIsPrimaryInstance;
public ModelDelegate() { }
@@ -1,76 +0,0 @@
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.model;
import static com.android.launcher3.util.Executors.MODEL_EXECUTOR;
import android.content.Context;
import android.util.Log;
import androidx.annotation.WorkerThread;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherModel.ModelUpdateTask;
import com.android.launcher3.model.BgDataModel.Callbacks;
import java.util.concurrent.Executor;
/**
* Utility class to preload LauncherModel
*/
public class ModelPreload implements ModelUpdateTask {
private static final String TAG = "ModelPreload";
private LauncherAppState mApp;
private LauncherModel mModel;
private BgDataModel mBgDataModel;
private AllAppsList mAllAppsList;
@Override
public final void init(LauncherAppState app, LauncherModel model, BgDataModel dataModel,
AllAppsList allAppsList, Executor uiExecutor) {
mApp = app;
mModel = model;
mBgDataModel = dataModel;
mAllAppsList = allAppsList;
}
@Override
public final void run() {
mModel.startLoaderForResultsIfNotLoaded(
new LoaderResults(mApp, mBgDataModel, mAllAppsList, new Callbacks[0]));
MODEL_EXECUTOR.post(() -> {
Log.d(TAG, "Preload completed : " + mModel.isModelLoaded());
onComplete(mModel.isModelLoaded());
});
}
public BgDataModel getBgDataModel() {
return mBgDataModel;
}
/**
* Called when the task is complete
*/
@WorkerThread
public void onComplete(boolean isSuccess) { }
public void start(Context context) {
LauncherAppState.getInstance(context).getModel().enqueueModelUpdateTask(this);
}
}
@@ -31,6 +31,7 @@ import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.WorkspaceItemInfo;
import com.android.launcher3.testing.TestProtocol;
import com.android.launcher3.util.IntArray;
import com.android.launcher3.util.IntSet;
@@ -51,7 +52,8 @@ public class ModelUtils {
* Filters the set of items who are directly or indirectly (via another container) on the
* specified screen.
*/
public static <T extends ItemInfo> void filterCurrentWorkspaceItems(int currentScreenId,
public static <T extends ItemInfo> void filterCurrentWorkspaceItems(
IntSet currentScreenIds,
ArrayList<T> allWorkspaceItems,
ArrayList<T> currentScreenItems,
ArrayList<T> otherScreenItems) {
@@ -65,7 +67,11 @@ public class ModelUtils {
(lhs, rhs) -> Integer.compare(lhs.container, rhs.container));
for (T info : allWorkspaceItems) {
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (info.screenId == currentScreenId) {
if (TestProtocol.sDebugTracing) {
Log.d(TestProtocol.NULL_INT_SET, "filterCurrentWorkspaceItems: "
+ currentScreenIds);
}
if (currentScreenIds.contains(info.screenId)) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
@@ -23,12 +23,13 @@ import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.Nullable;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherModel.CallbackTask;
import com.android.launcher3.LauncherProvider;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.LauncherSettings.Favorites;
@@ -36,19 +37,22 @@ import com.android.launcher3.LauncherSettings.Settings;
import com.android.launcher3.Utilities;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.model.BgDataModel.Callbacks;
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.ContentWriter;
import com.android.launcher3.util.Executors;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.LooperExecutor;
import com.android.launcher3.widget.LauncherAppWidgetHost;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@@ -63,7 +67,10 @@ public class ModelWriter {
private final Context mContext;
private final LauncherModel mModel;
private final BgDataModel mBgDataModel;
private final Handler mUiHandler;
private final LooperExecutor mUiExecutor;
@Nullable
private final Callbacks mOwner;
private final boolean mHasVerticalHotseat;
private final boolean mVerifyChanges;
@@ -73,13 +80,15 @@ public class ModelWriter {
private boolean mPreparingToUndo;
public ModelWriter(Context context, LauncherModel model, BgDataModel dataModel,
boolean hasVerticalHotseat, boolean verifyChanges) {
boolean hasVerticalHotseat, boolean verifyChanges,
@Nullable Callbacks owner) {
mContext = context;
mModel = model;
mBgDataModel = dataModel;
mHasVerticalHotseat = hasVerticalHotseat;
mVerifyChanges = verifyChanges;
mUiHandler = new Handler(Looper.getMainLooper());
mOwner = owner;
mUiExecutor = Executors.MAIN_EXECUTOR;
}
private void updateItemInfoProps(
@@ -155,6 +164,8 @@ public class ModelWriter {
public void moveItemInDatabase(final ItemInfo item,
int container, int screenId, int cellX, int cellY) {
updateItemInfoProps(item, container, screenId, cellX, cellY);
notifyItemModified(item);
enqueueDeleteRunnable(new UpdateItemRunnable(item, () ->
new ContentWriter(mContext)
.put(Favorites.CONTAINER, item.container)
@@ -171,6 +182,7 @@ public class ModelWriter {
public void moveItemsInDatabase(final ArrayList<ItemInfo> items, int container, int screen) {
ArrayList<ContentValues> contentValues = new ArrayList<>();
int count = items.size();
notifyOtherCallbacks(c -> c.bindItemsModified(items));
for (int i = 0; i < count; i++) {
ItemInfo item = items.get(i);
@@ -196,8 +208,9 @@ public class ModelWriter {
updateItemInfoProps(item, container, screenId, cellX, cellY);
item.spanX = spanX;
item.spanY = spanY;
notifyItemModified(item);
((Executor) MODEL_EXECUTOR).execute(new UpdateItemRunnable(item, () ->
MODEL_EXECUTOR.execute(new UpdateItemRunnable(item, () ->
new ContentWriter(mContext)
.put(Favorites.CONTAINER, item.container)
.put(Favorites.CELLX, item.cellX)
@@ -212,13 +225,18 @@ public class ModelWriter {
* Update an item to the database in a specified container.
*/
public void updateItemInDatabase(ItemInfo item) {
((Executor) MODEL_EXECUTOR).execute(new UpdateItemRunnable(item, () -> {
notifyItemModified(item);
MODEL_EXECUTOR.execute(new UpdateItemRunnable(item, () -> {
ContentWriter writer = new ContentWriter(mContext);
item.onAddToDatabase(writer);
return writer;
}));
}
private void notifyItemModified(ItemInfo item) {
notifyOtherCallbacks(c -> c.bindItemsModified(Collections.singletonList(item)));
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
@@ -229,10 +247,11 @@ public class ModelWriter {
final ContentResolver cr = mContext.getContentResolver();
item.id = Settings.call(cr, Settings.METHOD_NEW_ITEM_ID).getInt(Settings.EXTRA_VALUE);
notifyOtherCallbacks(c -> c.bindItems(Collections.singletonList(item), false));
ModelVerifier verifier = new ModelVerifier();
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
((Executor) MODEL_EXECUTOR).execute(() -> {
MODEL_EXECUTOR.execute(() -> {
// Write the item on background thread, as some properties might have been updated in
// the background.
final ContentWriter writer = new ContentWriter(mContext);
@@ -273,7 +292,8 @@ public class ModelWriter {
FileLog.d(TAG, "removing items from db " + items.stream().map(
(item) -> item.getTargetComponent() == null ? ""
: item.getTargetComponent().getPackageName()).collect(
Collectors.joining(",")), new Exception());
Collectors.joining(",")));
notifyDelete(items);
enqueueDeleteRunnable(() -> {
for (ItemInfo item : items) {
final Uri uri = Favorites.getContentUri(item.id);
@@ -290,6 +310,7 @@ public class ModelWriter {
*/
public void deleteFolderAndContentsFromDatabase(final FolderInfo info) {
ModelVerifier verifier = new ModelVerifier();
notifyDelete(Collections.singleton(info));
enqueueDeleteRunnable(() -> {
ContentResolver cr = mContext.getContentResolver();
@@ -308,6 +329,7 @@ public class ModelWriter {
* Deletes the widget info and the widget id.
*/
public void deleteWidgetInfo(final LauncherAppWidgetInfo info, LauncherAppWidgetHost host) {
notifyDelete(Collections.singleton(info));
if (host != null && !info.isCustomWidget() && info.isWidgetIdAllocated()) {
// Deleting an app widget ID is a void call but writes to disk before returning
// to the caller...
@@ -316,6 +338,10 @@ public class ModelWriter {
deleteItemFromDatabase(info);
}
private void notifyDelete(Collection<? extends ItemInfo> items) {
notifyOtherCallbacks(c -> c.bindWorkspaceComponentsRemoved(ItemInfoMatcher.ofItems(items)));
}
/**
* Delete operations tracked using {@link #enqueueDeleteRunnable} will only be called
* if {@link #commitDelete} is called. Note that one of {@link #commitDelete()} or
@@ -341,14 +367,14 @@ public class ModelWriter {
if (mPreparingToUndo) {
mDeleteRunnables.add(r);
} else {
((Executor) MODEL_EXECUTOR).execute(r);
MODEL_EXECUTOR.execute(r);
}
}
public void commitDelete() {
mPreparingToUndo = false;
for (Runnable runnable : mDeleteRunnables) {
((Executor) MODEL_EXECUTOR).execute(runnable);
MODEL_EXECUTOR.execute(runnable);
}
mDeleteRunnables.clear();
}
@@ -364,6 +390,20 @@ public class ModelWriter {
mModel.forceReload();
}
private void notifyOtherCallbacks(CallbackTask task) {
if (mOwner == null) {
// If the call is happening from a model, it will take care of updating the callbacks
return;
}
mUiExecutor.execute(() -> {
for (Callbacks c : mModel.getCallbacks()) {
if (c != mOwner) {
task.execute(c);
}
}
});
}
private class UpdateItemRunnable extends UpdateItemBaseRunnable {
private final ItemInfo mItem;
private final Supplier<ContentWriter> mWriter;
@@ -484,7 +524,7 @@ public class ModelWriter {
int executeId = mBgDataModel.lastBindId;
mUiHandler.post(() -> {
mUiExecutor.post(() -> {
int currentId = mBgDataModel.lastBindId;
if (currentId > executeId) {
// Model was already bound after job was executed.
@@ -21,7 +21,6 @@ import android.content.pm.PackageManager;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.model.data.AppInfo;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.model.data.ItemInfoWithIcon;
import com.android.launcher3.model.data.LauncherAppWidgetInfo;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.util.InstantAppResolver;
@@ -73,13 +72,7 @@ public class PackageInstallStateChangedTask extends BaseModelUpdateTask {
dataModel.forAllWorkspaceItemInfos(mInstallInfo.user, si -> {
if (si.hasPromiseIconUi()
&& mInstallInfo.packageName.equals(si.getTargetPackage())) {
int installProgress = mInstallInfo.progress;
si.setProgressLevel(installProgress, PackageInstallInfo.STATUS_INSTALLING);
if (mInstallInfo.state == PackageInstallInfo.STATUS_FAILED) {
// Mark this info as broken.
si.runtimeStatusFlags &= ~ItemInfoWithIcon.FLAG_INSTALL_SESSION_ACTIVE;
}
si.setProgressLevel(mInstallInfo);
updates.add(si);
}
});
@@ -129,7 +129,6 @@ public class PackageUpdatedTask extends BaseModelUpdateTask {
iconCache.updateIconsForPkg(packages[i], mUser);
activitiesLists.put(
packages[i], appsList.updatePackage(context, packages[i], mUser));
app.getWidgetCache().removePackage(packages[i], mUser);
// The update may have changed which shortcuts/widgets are available.
// Refresh the widgets for the package if we have an activity running.
@@ -161,7 +160,6 @@ public class PackageUpdatedTask extends BaseModelUpdateTask {
for (int i = 0; i < N; i++) {
if (DEBUG) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
appsList.removePackage(packages[i], mUser);
app.getWidgetCache().removePackage(packages[i], mUser);
}
flagOp = FlagOp.addFlag(WorkspaceItemInfo.FLAG_DISABLED_NOT_AVAILABLE);
break;
@@ -36,7 +36,7 @@ public class UserManagerState {
* Initialises the state values for all users
*/
public void init(UserCache userCache, UserManager userManager) {
for (UserHandle user : userCache.getUserProfiles()) {
for (UserHandle user : userManager.getUserProfiles()) {
long serialNo = userCache.getSerialNumberForUser(user);
boolean isUserQuiet = userManager.isQuietModeEnabled(user);
allUsers.put(serialNo, user);
@@ -0,0 +1,114 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.model.data;
import static android.graphics.BitmapFactory.decodeByteArray;
import android.content.Context;
import android.content.Intent;
import android.content.pm.LauncherActivityInfo;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.LauncherIcons;
/**
* Class representing one request for an icon to be queried in a sql database.
*
* @param <T> ItemInfoWithIcon subclass whose title and icon can be loaded and filled by an sql
* query.
*/
public class IconRequestInfo<T extends ItemInfoWithIcon> {
private static final String TAG = "IconRequestInfo";
@NonNull public final T itemInfo;
@Nullable public final LauncherActivityInfo launcherActivityInfo;
@Nullable public final String packageName;
@Nullable public final String resourceName;
@Nullable public final byte[] iconBlob;
public final boolean useLowResIcon;
public IconRequestInfo(
@NonNull T itemInfo,
@Nullable LauncherActivityInfo launcherActivityInfo,
boolean useLowResIcon) {
this(
itemInfo,
launcherActivityInfo,
/* packageName= */ null,
/* resourceName= */ null,
/* iconBlob= */ null,
useLowResIcon);
}
public IconRequestInfo(
@NonNull T itemInfo,
@Nullable LauncherActivityInfo launcherActivityInfo,
@Nullable String packageName,
@Nullable String resourceName,
@Nullable byte[] iconBlob,
boolean useLowResIcon) {
this.itemInfo = itemInfo;
this.launcherActivityInfo = launcherActivityInfo;
this.packageName = packageName;
this.resourceName = resourceName;
this.iconBlob = iconBlob;
this.useLowResIcon = useLowResIcon;
}
/** Loads */
public boolean loadWorkspaceIcon(Context context) {
if (!(itemInfo instanceof WorkspaceItemInfo)) {
throw new IllegalStateException(
"loadWorkspaceIcon should only be use for a WorkspaceItemInfos: " + itemInfo);
}
try (LauncherIcons li = LauncherIcons.obtain(context)) {
WorkspaceItemInfo info = (WorkspaceItemInfo) itemInfo;
if (itemInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
if (!TextUtils.isEmpty(packageName) || !TextUtils.isEmpty(resourceName)) {
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
BitmapInfo iconInfo = li.createIconBitmap(info.iconResource);
if (iconInfo != null) {
info.bitmap = iconInfo;
return true;
}
}
}
// Failed to load from resource, try loading from DB.
try {
if (iconBlob == null) {
return false;
}
info.bitmap = li.createIconBitmap(decodeByteArray(
iconBlob, 0, iconBlob.length));
return true;
} catch (Exception e) {
Log.e(TAG, "Failed to decode byte array for info " + info, e);
return false;
}
}
}
}
@@ -25,6 +25,7 @@ import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_SEARCH_
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_SETTINGS;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_SHORTCUTS;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_TASKSWITCHER;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_WALLPAPERS;
import static com.android.launcher3.LauncherSettings.Favorites.CONTAINER_WIDGETS_TRAY;
import static com.android.launcher3.LauncherSettings.Favorites.EXTENDED_CONTAINERS;
import static com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
@@ -55,6 +56,7 @@ import com.android.launcher3.logger.LauncherAtom.SettingsContainer;
import com.android.launcher3.logger.LauncherAtom.Shortcut;
import com.android.launcher3.logger.LauncherAtom.ShortcutsContainer;
import com.android.launcher3.logger.LauncherAtom.TaskSwitcherContainer;
import com.android.launcher3.logger.LauncherAtom.WallpapersContainer;
import com.android.launcher3.logger.LauncherAtomExtensions.ExtendedContainers;
import com.android.launcher3.model.ModelWriter;
import com.android.launcher3.util.ContentWriter;
@@ -164,6 +166,7 @@ public class ItemInfo {
public void copyFrom(ItemInfo info) {
id = info.id;
title = info.title;
cellX = info.cellX;
cellY = info.cellY;
spanX = info.spanX;
@@ -232,9 +235,9 @@ public class ItemInfo {
* Write the fields of this item to the DB
*/
public void onAddToDatabase(ContentWriter writer) {
if (screenId == Workspace.EXTRA_EMPTY_SCREEN_ID) {
if (Workspace.EXTRA_EMPTY_SCREEN_IDS.contains(screenId)) {
// We should never persist an item on the extra empty screen.
throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID");
throw new RuntimeException("Screen id should not be extra empty screen: " + screenId);
}
writeToValues(writer);
@@ -372,7 +375,8 @@ public class ItemInfo {
protected LauncherAtom.ItemInfo.Builder getDefaultItemInfoBuilder() {
LauncherAtom.ItemInfo.Builder itemBuilder = LauncherAtom.ItemInfo.newBuilder();
itemBuilder.setIsWork(user != Process.myUserHandle());
itemBuilder.setIsWork(!Process.myUserHandle().equals(user));
itemBuilder.setRank(rank);
return itemBuilder;
}
@@ -427,6 +431,10 @@ public class ItemInfo {
return ContainerInfo.newBuilder()
.setTaskSwitcherContainer(TaskSwitcherContainer.getDefaultInstance())
.build();
case CONTAINER_WALLPAPERS:
return ContainerInfo.newBuilder()
.setWallpapersContainer(WallpapersContainer.getDefaultInstance())
.build();
case EXTENDED_CONTAINERS:
return ContainerInfo.newBuilder()
.setExtendedContainers(getExtendedContainer())
@@ -24,6 +24,7 @@ import androidx.annotation.Nullable;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.FastBitmapDrawable;
import com.android.launcher3.logging.FileLog;
import com.android.launcher3.pm.PackageInstallInfo;
import com.android.launcher3.util.PackageManagerHelper;
@@ -179,6 +180,12 @@ public abstract class ItemInfoWithIcon extends ItemInfo {
*/
public void setProgressLevel(PackageInstallInfo installInfo) {
setProgressLevel(installInfo.progress, installInfo.state);
if (installInfo.state == PackageInstallInfo.STATUS_FAILED) {
FileLog.d(TAG,
"Icon info: " + this + " marked broken with install info: " + installInfo,
new Exception());
}
}
/**
@@ -16,47 +16,41 @@
package com.android.launcher3.model.data;
import androidx.annotation.IntDef;
import static com.android.launcher3.widget.WidgetSections.NO_CATEGORY;
import android.os.UserHandle;
import com.android.launcher3.LauncherSettings;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Objects;
/**
* Represents a {@link Package} in the widget tray section.
*/
public class PackageItemInfo extends ItemInfoWithIcon {
@Retention(RetentionPolicy.SOURCE)
@IntDef({NO_CATEGORY, CONVERSATIONS})
public @interface Category{}
/** The package is not categorized in the widget tray. */
public static final int NO_CATEGORY = 0;
/** The package is categorized to conversations widget in the widget tray. */
public static final int CONVERSATIONS = 1;
/**
* Package name of the {@link PackageItemInfo}.
*/
public final String packageName;
/** Represents a widget category shown in the widget tray section. */
@Category public final int category;
public final int widgetCategory;
public PackageItemInfo(String packageName) {
this(packageName, NO_CATEGORY);
public PackageItemInfo(String packageName, UserHandle user) {
this(packageName, NO_CATEGORY, user);
}
public PackageItemInfo(String packageName, @Category int category) {
public PackageItemInfo(String packageName, int widgetCategory, UserHandle user) {
this.packageName = packageName;
this.category = category;
this.widgetCategory = widgetCategory;
this.user = user;
this.itemType = LauncherSettings.Favorites.ITEM_TYPE_NON_ACTIONABLE;
}
public PackageItemInfo(PackageItemInfo copy) {
this.packageName = copy.packageName;
this.category = copy.category;
this.widgetCategory = copy.widgetCategory;
this.user = copy.user;
this.itemType = LauncherSettings.Favorites.ITEM_TYPE_NON_ACTIONABLE;
}
@@ -75,11 +69,13 @@ public class PackageItemInfo extends ItemInfoWithIcon {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PackageItemInfo that = (PackageItemInfo) o;
return Objects.equals(packageName, that.packageName);
return Objects.equals(packageName, that.packageName)
&& Objects.equals(user, that.user)
&& widgetCategory == that.widgetCategory;
}
@Override
public int hashCode() {
return Objects.hash(packageName, user);
return Objects.hash(packageName, user, widgetCategory);
}
}
@@ -25,8 +25,15 @@ import android.os.UserHandle;
import androidx.annotation.Nullable;
import com.android.launcher3.LauncherAppState;
import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.logger.LauncherAtom.ItemInfo;
import com.android.launcher3.logger.LauncherAtom.SearchActionItem;
import com.android.launcher3.model.AllAppsList;
import com.android.launcher3.model.BaseModelUpdateTask;
import com.android.launcher3.model.BgDataModel;
/**
* Represents a SearchAction with in launcher
@@ -38,13 +45,15 @@ public class SearchActionItemInfo extends ItemInfoWithIcon {
public static final int FLAG_BADGE_WITH_PACKAGE = 1 << 3;
public static final int FLAG_PRIMARY_ICON_FROM_TITLE = 1 << 4;
public static final int FLAG_BADGE_WITH_COMPONENT_NAME = 1 << 5;
public static final int FLAG_ALLOW_PINNING = 1 << 6;
public static final int FLAG_SEARCH_IN_APP = 1 << 7;
private final String mFallbackPackageName;
private String mFallbackPackageName;
private int mFlags = 0;
private final Icon mIcon;
private Icon mIcon;
// If true title does not contain any personal info and eligible for logging.
private final boolean mIsPersonalTitle;
private boolean mIsPersonalTitle;
private Intent mIntent;
private PendingIntent mPendingIntent;
@@ -52,6 +61,7 @@ public class SearchActionItemInfo extends ItemInfoWithIcon {
public SearchActionItemInfo(Icon icon, String packageName, UserHandle user,
CharSequence title, boolean isPersonalTitle) {
mIsPersonalTitle = isPersonalTitle;
this.itemType = LauncherSettings.Favorites.ITEM_TYPE_SEARCH_ACTION;
this.user = user == null ? Process.myUserHandle() : user;
this.title = title;
this.container = EXTENDED_CONTAINERS;
@@ -59,14 +69,18 @@ public class SearchActionItemInfo extends ItemInfoWithIcon {
mIcon = icon;
}
public SearchActionItemInfo(SearchActionItemInfo info) {
private SearchActionItemInfo(SearchActionItemInfo info) {
super(info);
mIcon = info.mIcon;
mFallbackPackageName = info.mFallbackPackageName;
mFlags = info.mFlags;
title = info.title;
this.container = EXTENDED_CONTAINERS;
this.mIsPersonalTitle = info.mIsPersonalTitle;
}
@Override
public void copyFrom(com.android.launcher3.model.data.ItemInfo info) {
super.copyFrom(info);
SearchActionItemInfo itemInfo = (SearchActionItemInfo) info;
this.mFallbackPackageName = itemInfo.mFallbackPackageName;
this.mIcon = itemInfo.mIcon;
this.mFlags = itemInfo.mFlags;
this.mIsPersonalTitle = itemInfo.mIsPersonalTitle;
}
/**
@@ -77,7 +91,7 @@ public class SearchActionItemInfo extends ItemInfoWithIcon {
}
public void setFlags(int flags) {
mFlags |= flags ;
mFlags |= flags;
}
@Override
@@ -134,4 +148,50 @@ public class SearchActionItemInfo extends ItemInfoWithIcon {
.setContainerInfo(getContainerInfo())
.build();
}
/**
* Returns true if result supports drag/drop to home screen
*/
public boolean supportsPinning() {
return hasFlags(FLAG_ALLOW_PINNING) && getIntentPackageName() != null;
}
/**
* Creates a {@link WorkspaceItemInfo} coorsponding to search action to be stored in launcher db
*/
public WorkspaceItemInfo createWorkspaceItem(LauncherModel model) {
WorkspaceItemInfo info = new WorkspaceItemInfo();
info.title = title;
info.bitmap = bitmap;
info.intent = mIntent;
if (hasFlags(FLAG_SHOULD_START_FOR_RESULT)) {
info.options |= WorkspaceItemInfo.FLAG_START_FOR_RESULT;
}
model.enqueueModelUpdateTask(new BaseModelUpdateTask() {
@Override
public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
model.updateAndBindWorkspaceItem(() -> {
PackageItemInfo pkgInfo = new PackageItemInfo(getIntentPackageName(), user);
app.getIconCache().getTitleAndIconForApp(pkgInfo, false);
try (LauncherIcons li = LauncherIcons.obtain(app.getContext())) {
info.bitmap = li.badgeBitmap(info.bitmap.icon, pkgInfo.bitmap);
}
return info;
});
}
});
return info;
}
@Nullable
private String getIntentPackageName() {
if (mIntent != null) {
if (mIntent.getPackage() != null) return mIntent.getPackage();
return mFallbackPackageName;
}
return null;
}
}
Loaded 100 of 825 files, more files were not shown because too many files have changed in this diff. Show more