folderItems = new ArrayList<>();
int type;
int folderDepth = parser.getDepth();
@@ -617,7 +614,7 @@ public class AutoInstallsLayout {
}
}
- protected static final void beginDocument(XmlPullParser parser, String firstElementName)
+ protected static void beginDocument(XmlPullParser parser, String firstElementName)
throws XmlPullParserException, IOException {
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG
@@ -671,7 +668,7 @@ public class AutoInstallsLayout {
return value;
}
- public static interface LayoutParserCallback {
+ public interface LayoutParserCallback {
long generateNewItemId();
long insertAndCheck(SQLiteDatabase db, ContentValues values);
diff --git a/src/com/android/launcher3/BaseActivity.java b/src/com/android/launcher3/BaseActivity.java
index 08cd955a54..2b59ede476 100644
--- a/src/com/android/launcher3/BaseActivity.java
+++ b/src/com/android/launcher3/BaseActivity.java
@@ -22,11 +22,13 @@ import android.content.ContextWrapper;
import android.view.View.AccessibilityDelegate;
import com.android.launcher3.logging.UserEventDispatcher;
+import com.android.launcher3.util.SystemUiController;
public abstract class BaseActivity extends Activity {
protected DeviceProfile mDeviceProfile;
protected UserEventDispatcher mUserEventDispatcher;
+ protected SystemUiController mSystemUiController;
public DeviceProfile getDeviceProfile() {
return mDeviceProfile;
@@ -54,4 +56,11 @@ public abstract class BaseActivity extends Activity {
}
return ((BaseActivity) ((ContextWrapper) context).getBaseContext());
}
+
+ public SystemUiController getSystemUiController() {
+ if (mSystemUiController == null) {
+ mSystemUiController = new SystemUiController(getWindow());
+ }
+ return mSystemUiController;
+ }
}
diff --git a/src/com/android/launcher3/BaseContainerView.java b/src/com/android/launcher3/BaseContainerView.java
index ac7cbafeab..c55a5860ef 100644
--- a/src/com/android/launcher3/BaseContainerView.java
+++ b/src/com/android/launcher3/BaseContainerView.java
@@ -113,20 +113,18 @@ public abstract class BaseContainerView extends FrameLayout
* Calculate the background padding as it can change due to insets/content padding change.
*/
private void updatePaddings() {
- Context context = getContext();
- int paddingLeft;
- int paddingRight;
- int paddingTop;
- int paddingBottom;
-
- DeviceProfile grid = Launcher.getLauncher(context).getDeviceProfile();
+ DeviceProfile grid = Launcher.getLauncher(getContext()).getDeviceProfile();
int[] padding = grid.getContainerPadding();
- paddingLeft = padding[0] + grid.edgeMarginPx;
- paddingRight = padding[1] + grid.edgeMarginPx;
+
+ int paddingLeft = padding[0];
+ int paddingRight = padding[1];
+ int paddingTop = 0;
+ int paddingBottom = 0;
+
if (!grid.isVerticalBarLayout()) {
+ paddingLeft += grid.edgeMarginPx;
+ paddingRight += grid.edgeMarginPx;
paddingTop = paddingBottom = grid.edgeMarginPx;
- } else {
- paddingTop = paddingBottom = 0;
}
updateBackground(paddingLeft, paddingTop, paddingRight, paddingBottom);
}
diff --git a/src/com/android/launcher3/BaseRecyclerView.java b/src/com/android/launcher3/BaseRecyclerView.java
index 6fdf454505..3ee6e51b8d 100644
--- a/src/com/android/launcher3/BaseRecyclerView.java
+++ b/src/com/android/launcher3/BaseRecyclerView.java
@@ -22,8 +22,9 @@ import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
+import android.widget.TextView;
-import com.android.launcher3.util.Thunk;
+import com.android.launcher3.views.RecyclerViewFastScroller;
/**
@@ -36,17 +37,7 @@ import com.android.launcher3.util.Thunk;
public abstract class BaseRecyclerView extends RecyclerView
implements RecyclerView.OnItemTouchListener {
- private static final int SCROLL_DELTA_THRESHOLD_DP = 4;
-
- /** Keeps the last known scrolling delta/velocity along y-axis. */
- @Thunk int mDy = 0;
- private float mDeltaThreshold;
-
- protected final BaseRecyclerViewFastScrollBar mScrollbar;
-
- private int mDownX;
- private int mDownY;
- private int mLastY;
+ protected RecyclerViewFastScroller mScrollbar;
public BaseRecyclerView(Context context) {
this(context, null);
@@ -58,32 +49,6 @@ public abstract class BaseRecyclerView extends RecyclerView
public BaseRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
- mDeltaThreshold = getResources().getDisplayMetrics().density * SCROLL_DELTA_THRESHOLD_DP;
- mScrollbar = new BaseRecyclerViewFastScrollBar(this, getResources());
-
- ScrollListener listener = new ScrollListener();
- setOnScrollListener(listener);
- }
-
- private class ScrollListener extends OnScrollListener {
- public ScrollListener() {
- // Do nothing
- }
-
- @Override
- public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
- mDy = dy;
-
- // TODO(winsonc): If we want to animate the section heads while scrolling, we can
- // initiate that here if the recycler view scroll state is not
- // RecyclerView.SCROLL_STATE_IDLE.
-
- onUpdateScrollbar(dy);
- }
- }
-
- public void reset() {
- mScrollbar.reattachThumbToScroll();
}
@Override
@@ -95,7 +60,9 @@ public abstract class BaseRecyclerView extends RecyclerView
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
- mScrollbar.setPopupView(((ViewGroup) getParent()).findViewById(R.id.fast_scroller_popup));
+ ViewGroup parent = (ViewGroup) getParent();
+ mScrollbar = parent.findViewById(R.id.fast_scroller);
+ mScrollbar.setRecyclerView(this, (TextView) parent.findViewById(R.id.fast_scroller_popup));
}
/**
@@ -117,56 +84,26 @@ public abstract class BaseRecyclerView extends RecyclerView
* it is already showing).
*/
private boolean handleTouchEvent(MotionEvent ev) {
- int action = ev.getAction();
- int x = (int) ev.getX();
- int y = (int) ev.getY();
- switch (action) {
- case MotionEvent.ACTION_DOWN:
- // Keep track of the down positions
- mDownX = x;
- mDownY = mLastY = y;
- if (shouldStopScroll(ev)) {
- stopScroll();
- }
- mScrollbar.handleTouchEvent(ev, mDownX, mDownY, mLastY);
- break;
- case MotionEvent.ACTION_MOVE:
- mLastY = y;
- mScrollbar.handleTouchEvent(ev, mDownX, mDownY, mLastY);
- break;
- case MotionEvent.ACTION_UP:
- case MotionEvent.ACTION_CANCEL:
- onFastScrollCompleted();
- mScrollbar.handleTouchEvent(ev, mDownX, mDownY, mLastY);
- break;
+ // Move to mScrollbar's coordinate system.
+ int left = getLeft() - mScrollbar.getLeft();
+ int top = getTop() - mScrollbar.getTop();
+ ev.offsetLocation(left, top);
+ try {
+ return mScrollbar.handleTouchEvent(ev);
+ } finally {
+ ev.offsetLocation(-left, -top);
}
- return mScrollbar.isDraggingThumb();
}
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// DO NOT REMOVE, NEEDED IMPLEMENTATION FOR M BUILDS
}
- /**
- * Returns whether this {@link MotionEvent} should trigger the scroll to be stopped.
- */
- protected boolean shouldStopScroll(MotionEvent ev) {
- if (ev.getAction() == MotionEvent.ACTION_DOWN) {
- if ((Math.abs(mDy) < mDeltaThreshold &&
- getScrollState() != RecyclerView.SCROLL_STATE_IDLE)) {
- // now the touch events are being passed to the {@link WidgetCell} until the
- // touch sequence goes over the touch slop.
- return true;
- }
- }
- return false;
- }
-
/**
* Returns the height of the fast scroll bar
*/
- protected int getScrollbarTrackHeight() {
- return getHeight();
+ public int getScrollbarTrackHeight() {
+ return getHeight() - getPaddingTop() - getPaddingBottom();
}
/**
@@ -184,25 +121,17 @@ public abstract class BaseRecyclerView extends RecyclerView
return availableScrollBarHeight;
}
- /**
- * Returns the track color (ignoring alpha), can be overridden by each subclass.
- */
- public int getFastScrollerTrackColor(int defaultTrackColor) {
- return defaultTrackColor;
- }
-
/**
* Returns the scrollbar for this recycler view.
*/
- public BaseRecyclerViewFastScrollBar getScrollBar() {
+ public RecyclerViewFastScroller getScrollBar() {
return mScrollbar;
}
@Override
protected void dispatchDraw(Canvas canvas) {
- super.dispatchDraw(canvas);
onUpdateScrollbar(0);
- mScrollbar.draw(canvas);
+ super.dispatchDraw(canvas);
}
/**
@@ -233,7 +162,7 @@ public abstract class BaseRecyclerView extends RecyclerView
/**
* @return whether fast scrolling is supported in the current state.
*/
- protected boolean supportsFastScrolling() {
+ public boolean supportsFastScrolling() {
return true;
}
@@ -249,16 +178,16 @@ public abstract class BaseRecyclerView extends RecyclerView
* Maps the touch (from 0..1) to the adapter position that should be visible.
* Override in each subclass of this base class.
*/
- protected abstract String scrollToPositionAtProgress(float touchFraction);
+ public abstract String scrollToPositionAtProgress(float touchFraction);
/**
* Updates the bounds for the scrollbar.
*
Override in each subclass of this base class.
*/
- protected abstract void onUpdateScrollbar(int dy);
+ public abstract void onUpdateScrollbar(int dy);
/**
*
Override in each subclass of this base class.
*/
- protected void onFastScrollCompleted() {}
+ public void onFastScrollCompleted() {}
}
\ No newline at end of file
diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java
index 3c3e224e46..6f2c897796 100644
--- a/src/com/android/launcher3/BubbleTextView.java
+++ b/src/com/android/launcher3/BubbleTextView.java
@@ -19,15 +19,16 @@ package com.android.launcher3;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
-import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
+import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
-import android.graphics.Region;
+import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
+import android.support.v4.graphics.ColorUtils;
import android.util.AttributeSet;
import android.util.Property;
import android.util.TypedValue;
@@ -43,7 +44,7 @@ import com.android.launcher3.IconCache.IconLoadRequest;
import com.android.launcher3.IconCache.ItemInfoUpdateReceiver;
import com.android.launcher3.badge.BadgeInfo;
import com.android.launcher3.badge.BadgeRenderer;
-import com.android.launcher3.folder.FolderIcon;
+import com.android.launcher3.folder.FolderIconPreviewVerifier;
import com.android.launcher3.graphics.DrawableFactory;
import com.android.launcher3.graphics.HolographicOutlineHelper;
import com.android.launcher3.graphics.IconPalette;
@@ -59,13 +60,6 @@ import java.text.NumberFormat;
*/
public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
- // Dimensions in DP
- private static final float AMBIENT_SHADOW_RADIUS = 2.5f;
- private static final float KEY_SHADOW_RADIUS = 1f;
- private static final float KEY_SHADOW_OFFSET = 0.5f;
- private static final int AMBIENT_SHADOW_COLOR = 0x33000000;
- private static final int KEY_SHADOW_COLOR = 0x66000000;
-
private static final int DISPLAY_WORKSPACE = 0;
private static final int DISPLAY_ALL_APPS = 1;
private static final int DISPLAY_FOLDER = 2;
@@ -75,24 +69,20 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
private final Launcher mLauncher;
private Drawable mIcon;
private final boolean mCenterVertically;
- private final Drawable mBackground;
- private OnLongClickListener mOnLongClickListener;
+
private final CheckLongPressHelper mLongPressHelper;
private final HolographicOutlineHelper mOutlineHelper;
private final StylusEventHelper mStylusEventHelper;
-
- private boolean mBackgroundSizeChanged;
+ private final float mSlop;
private Bitmap mPressedBackground;
- private float mSlop;
-
private final boolean mDeferShadowGenerationOnTouch;
- private final boolean mCustomShadowsEnabled;
private final boolean mLayoutHorizontal;
private final int mIconSize;
@ViewDebug.ExportedProperty(category = "launcher")
private int mTextColor;
+ private boolean mIsIconVisible = true;
private BadgeInfo mBadgeInfo;
private BadgeRenderer mBadgeRenderer;
@@ -116,6 +106,19 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
}
};
+ public static final Property TEXT_ALPHA_PROPERTY
+ = new Property(Integer.class, "textAlpha") {
+ @Override
+ public Integer get(BubbleTextView bubbleTextView) {
+ return bubbleTextView.getTextAlpha();
+ }
+
+ @Override
+ public void set(BubbleTextView bubbleTextView, Integer alpha) {
+ bubbleTextView.setTextAlpha(alpha);
+ }
+ };
+
@ViewDebug.ExportedProperty(category = "launcher")
private boolean mStayPressed;
@ViewDebug.ExportedProperty(category = "launcher")
@@ -137,10 +140,10 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
super(context, attrs, defStyle);
mLauncher = Launcher.getLauncher(context);
DeviceProfile grid = mLauncher.getDeviceProfile();
+ mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.BubbleTextView, defStyle, 0);
- mCustomShadowsEnabled = a.getBoolean(R.styleable.BubbleTextView_customShadows, false);
mLayoutHorizontal = a.getBoolean(R.styleable.BubbleTextView_layoutHorizontal, false);
mDeferShadowGenerationOnTouch =
a.getBoolean(R.styleable.BubbleTextView_deferShadowGeneration, false);
@@ -149,6 +152,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
int defaultIconSize = grid.iconSizePx;
if (display == DISPLAY_WORKSPACE) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.iconTextSizePx);
+ setCompoundDrawablePadding(grid.iconDrawablePaddingPx);
} else if (display == DISPLAY_ALL_APPS) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.allAppsIconTextSizePx);
setCompoundDrawablePadding(grid.allAppsIconDrawablePaddingPx);
@@ -164,23 +168,12 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
defaultIconSize);
a.recycle();
- if (mCustomShadowsEnabled) {
- // Draw the background itself as the parent is drawn twice.
- mBackground = getBackground();
- setBackground(null);
-
- // Set shadow layer as the larger shadow to that the textView does not clip the shadow.
- float density = getResources().getDisplayMetrics().density;
- setShadowLayer(density * AMBIENT_SHADOW_RADIUS, 0, 0, AMBIENT_SHADOW_COLOR);
- } else {
- mBackground = null;
- }
-
mLongPressHelper = new CheckLongPressHelper(this);
mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
mOutlineHelper = HolographicOutlineHelper.getInstance(getContext());
setAccessibilityDelegate(mLauncher.getAccessibilityDelegate());
+
}
public void applyFromShortcutInfo(ShortcutInfo info) {
@@ -206,6 +199,10 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
// Verify high res immediately
verifyHighRes();
+ if (info instanceof PromiseAppInfo) {
+ PromiseAppInfo promiseAppInfo = (PromiseAppInfo) info;
+ applyProgressLevel(promiseAppInfo.level);
+ }
applyBadgeState(info, false /* animate */);
}
@@ -237,19 +234,6 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
mLongPressHelper.setLongPressTimeout(longPressTimeout);
}
- @Override
- protected boolean setFrame(int left, int top, int right, int bottom) {
- if (getLeft() != left || getRight() != right || getTop() != top || getBottom() != bottom) {
- mBackgroundSizeChanged = true;
- }
- return super.setFrame(left, top, right, bottom);
- }
-
- @Override
- protected boolean verifyDrawable(Drawable who) {
- return who == mBackground || super.verifyDrawable(who);
- }
-
@Override
public void setTag(Object tag) {
if (tag != null) {
@@ -279,21 +263,6 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
return mIcon;
}
- /** Returns whether the layout is horizontal. */
- public boolean isLayoutHorizontal() {
- return mLayoutHorizontal;
- }
-
- @Override
- public void setOnLongClickListener(OnLongClickListener l) {
- super.setOnLongClickListener(l);
- mOnLongClickListener = l;
- }
-
- public OnLongClickListener getOnLongClickListener() {
- return mOnLongClickListener;
- }
-
@Override
public boolean onTouchEvent(MotionEvent event) {
// Call the superclass onTouchEvent first, because sometimes it changes the state to
@@ -391,54 +360,14 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
return result;
}
+ @SuppressWarnings("wrongcall")
+ protected void drawWithoutBadge(Canvas canvas) {
+ super.onDraw(canvas);
+ }
+
@Override
- public void draw(Canvas canvas) {
- if (!mCustomShadowsEnabled) {
- super.draw(canvas);
- drawBadgeIfNecessary(canvas);
- return;
- }
-
- final Drawable background = mBackground;
- if (background != null) {
- final int scrollX = getScrollX();
- final int scrollY = getScrollY();
-
- if (mBackgroundSizeChanged) {
- background.setBounds(0, 0, getRight() - getLeft(), getBottom() - getTop());
- mBackgroundSizeChanged = false;
- }
-
- if ((scrollX | scrollY) == 0) {
- background.draw(canvas);
- } else {
- canvas.translate(scrollX, scrollY);
- background.draw(canvas);
- canvas.translate(-scrollX, -scrollY);
- }
- }
-
- // If text is transparent, don't draw any shadow
- if ((getCurrentTextColor() >> 24) == 0) {
- getPaint().clearShadowLayer();
- super.draw(canvas);
- drawBadgeIfNecessary(canvas);
- return;
- }
-
- // We enhance the shadow by drawing the shadow twice
- float density = getResources().getDisplayMetrics().density;
- getPaint().setShadowLayer(density * AMBIENT_SHADOW_RADIUS, 0, 0, AMBIENT_SHADOW_COLOR);
- super.draw(canvas);
- canvas.save(Canvas.CLIP_SAVE_FLAG);
- canvas.clipRect(getScrollX(), getScrollY() + getExtendedPaddingTop(),
- getScrollX() + getWidth(),
- getScrollY() + getHeight(), Region.Op.INTERSECT);
- getPaint().setShadowLayer(
- density * KEY_SHADOW_RADIUS, 0.0f, density * KEY_SHADOW_OFFSET, KEY_SHADOW_COLOR);
- super.draw(canvas);
- canvas.restore();
-
+ public void onDraw(Canvas canvas) {
+ super.onDraw(canvas);
drawBadgeIfNecessary(canvas);
}
@@ -446,7 +375,7 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
* Draws the icon badge in the top right corner of the icon bounds.
* @param canvas The canvas to draw to.
*/
- private void drawBadgeIfNecessary(Canvas canvas) {
+ protected void drawBadgeIfNecessary(Canvas canvas) {
if (!mForceHideBadge && (hasBadge() || mBadgeScale > 0)) {
getIconBounds(mTempIconBounds);
mTempSpaceForBadgeOffset.set((getWidth() - mIconSize) / 2, getPaddingTop());
@@ -484,14 +413,6 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
outBounds.set(left, top, right, bottom);
}
- @Override
- protected void onAttachedToWindow() {
- super.onAttachedToWindow();
-
- if (mBackground != null) mBackground.setCallback(this);
- mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
- }
-
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mCenterVertically) {
@@ -505,12 +426,6 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
- @Override
- protected void onDetachedFromWindow() {
- super.onDetachedFromWindow();
- if (mBackground != null) mBackground.setCallback(null);
- }
-
@Override
public void setTextColor(int color) {
mTextColor = color;
@@ -524,14 +439,29 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
}
public void setTextVisibility(boolean visible) {
- Resources res = getResources();
if (visible) {
super.setTextColor(mTextColor);
} else {
- super.setTextColor(res.getColor(android.R.color.transparent));
+ setTextAlpha(0);
}
}
+ private void setTextAlpha(int alpha) {
+ super.setTextColor(ColorUtils.setAlphaComponent(mTextColor, alpha));
+ }
+
+ private int getTextAlpha() {
+ return Color.alpha(getCurrentTextColor());
+ }
+
+ /**
+ * Creates an animator to fade the text in or out.
+ * @param fadeIn Whether the text should fade in or fade out.
+ */
+ public ObjectAnimator createTextAlphaAnimator(boolean fadeIn) {
+ return ObjectAnimator.ofInt(this, TEXT_ALPHA_PROPERTY, fadeIn ? Color.alpha(mTextColor) : 0);
+ }
+
@Override
public void cancelLongPress() {
super.cancelLongPress();
@@ -547,27 +477,36 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
((info.hasStatusFlag(ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE) ?
info.getInstallProgress() : 0)) : 100;
- setContentDescription(progressLevel > 0 ?
- getContext().getString(R.string.app_downloading_title, info.title,
- NumberFormat.getPercentInstance().format(progressLevel * 0.01)) :
- getContext().getString(R.string.app_waiting_download_title, info.title));
+ PreloadIconDrawable preloadDrawable = applyProgressLevel(progressLevel);
+ if (preloadDrawable != null && promiseStateChanged) {
+ preloadDrawable.maybePerformFinishedAnimation();
+ }
+ }
+ }
+
+ public PreloadIconDrawable applyProgressLevel(int progressLevel) {
+ if (getTag() instanceof ItemInfoWithIcon) {
+ ItemInfoWithIcon info = (ItemInfoWithIcon) getTag();
+ setContentDescription(progressLevel > 0
+ ? getContext().getString(R.string.app_downloading_title, info.title,
+ NumberFormat.getPercentInstance().format(progressLevel * 0.01))
+ : getContext().getString(R.string.app_waiting_download_title, info.title));
if (mIcon != null) {
final PreloadIconDrawable preloadDrawable;
if (mIcon instanceof PreloadIconDrawable) {
preloadDrawable = (PreloadIconDrawable) mIcon;
+ preloadDrawable.setLevel(progressLevel);
} else {
preloadDrawable = DrawableFactory.get(getContext())
.newPendingIcon(info.iconBitmap, getContext());
+ preloadDrawable.setLevel(progressLevel);
setIcon(preloadDrawable);
}
-
- preloadDrawable.setLevel(progressLevel);
- if (promiseStateChanged) {
- preloadDrawable.maybePerformFinishedAnimation();
- }
+ return preloadDrawable;
}
}
+ return null;
}
public void applyBadgeState(ItemInfo itemInfo, boolean animate) {
@@ -603,7 +542,21 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
private void setIcon(Drawable icon) {
mIcon = icon;
mIcon.setBounds(0, 0, mIconSize, mIconSize);
- applyCompoundDrawables(mIcon);
+ if (mIsIconVisible) {
+ applyCompoundDrawables(mIcon);
+ }
+ }
+
+ public void setIconVisible(boolean visible) {
+ mIsIconVisible = visible;
+ mDisableRelayout = true;
+ Drawable icon = mIcon;
+ if (!visible) {
+ icon = new ColorDrawable(Color.TRANSPARENT);
+ icon.setBounds(0, 0, mIconSize, mIconSize);
+ }
+ applyCompoundDrawables(icon);
+ mDisableRelayout = false;
}
protected void applyCompoundDrawables(Drawable icon) {
@@ -634,7 +587,9 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
applyFromApplicationInfo((AppInfo) info);
} else if (info instanceof ShortcutInfo) {
applyFromShortcutInfo((ShortcutInfo) info);
- if ((info.rank < FolderIcon.NUM_ITEMS_IN_PREVIEW) && (info.container >= 0)) {
+ FolderIconPreviewVerifier verifier =
+ new FolderIconPreviewVerifier(mLauncher.getDeviceProfile().inv);
+ if (verifier.isItemInPreview(info.rank) && (info.container >= 0)) {
View folderIcon =
mLauncher.getWorkspace().getHomescreenIconByItemId(info.container);
if (folderIcon != null) {
@@ -666,6 +621,10 @@ public class BubbleTextView extends TextView implements ItemInfoUpdateReceiver {
}
}
+ public int getIconSize() {
+ return mIconSize;
+ }
+
/**
* Interface to be implemented by the grand parent to allow click shadow effect.
*/
diff --git a/src/com/android/launcher3/ButtonDropTarget.java b/src/com/android/launcher3/ButtonDropTarget.java
index 8a477d809f..e4a322622c 100644
--- a/src/com/android/launcher3/ButtonDropTarget.java
+++ b/src/com/android/launcher3/ButtonDropTarget.java
@@ -102,8 +102,8 @@ public abstract class ButtonDropTarget extends TextView
protected void setDrawable(int resId) {
// We do not set the drawable in the xml as that inflates two drawables corresponding to
// drawableLeft and drawableStart.
- mDrawable = getResources().getDrawable(resId);
- setCompoundDrawablesRelativeWithIntrinsicBounds(mDrawable, null, null, null);
+ setCompoundDrawablesRelativeWithIntrinsicBounds(resId, 0, 0, 0);
+ mDrawable = getCompoundDrawablesRelative()[0];
}
public void setDropTargetBar(DropTargetBar dropTargetBar) {
diff --git a/src/com/android/launcher3/CellLayout.java b/src/com/android/launcher3/CellLayout.java
index 8179dad29a..d99a30ae72 100644
--- a/src/com/android/launcher3/CellLayout.java
+++ b/src/com/android/launcher3/CellLayout.java
@@ -35,6 +35,7 @@ import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.support.annotation.IntDef;
import android.support.v4.view.ViewCompat;
+import android.util.ArrayMap;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
@@ -44,28 +45,27 @@ import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.DecelerateInterpolator;
-
import com.android.launcher3.BubbleTextView.BubbleTextShadowHandler;
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
import com.android.launcher3.accessibility.FolderAccessibilityHelper;
import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
import com.android.launcher3.anim.PropertyListBuilder;
-import com.android.launcher3.config.ProviderConfig;
+import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.folder.FolderIcon;
+import com.android.launcher3.folder.PreviewBackground;
import com.android.launcher3.graphics.DragPreviewProvider;
import com.android.launcher3.util.CellAndSpan;
import com.android.launcher3.util.GridOccupancy;
import com.android.launcher3.util.ParcelableSparseArray;
+import com.android.launcher3.util.Themes;
import com.android.launcher3.util.Thunk;
-
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
-import java.util.HashMap;
import java.util.Stack;
public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
@@ -75,7 +75,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
private static final String TAG = "CellLayout";
private static final boolean LOGD = false;
- private Launcher mLauncher;
+ private final Launcher mLauncher;
@ViewDebug.ExportedProperty(category = "launcher")
@Thunk int mCellWidth;
@ViewDebug.ExportedProperty(category = "launcher")
@@ -101,10 +101,10 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
private GridOccupancy mTmpOccupied;
private OnTouchListener mInterceptTouchListener;
- private StylusEventHelper mStylusEventHelper;
+ private final StylusEventHelper mStylusEventHelper;
- private ArrayList mFolderBackgrounds = new ArrayList();
- FolderIcon.PreviewBackground mFolderLeaveBehind = new FolderIcon.PreviewBackground();
+ private final ArrayList mFolderBackgrounds = new ArrayList<>();
+ final PreviewBackground mFolderLeaveBehind = new PreviewBackground();
private float mBackgroundAlpha;
@@ -121,9 +121,9 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
// These arrays are used to implement the drag visualization on x-large screens.
// They are used as circular arrays, indexed by mDragOutlineCurrent.
- @Thunk Rect[] mDragOutlines = new Rect[4];
- @Thunk float[] mDragOutlineAlphas = new float[mDragOutlines.length];
- private InterruptibleInOutAnimator[] mDragOutlineAnims =
+ @Thunk final Rect[] mDragOutlines = new Rect[4];
+ @Thunk final float[] mDragOutlineAlphas = new float[mDragOutlines.length];
+ private final InterruptibleInOutAnimator[] mDragOutlineAnims =
new InterruptibleInOutAnimator[mDragOutlines.length];
// Used as an index into the above 3 arrays; indicates which is the most current value.
@@ -132,8 +132,8 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
private final ClickShadowView mTouchFeedbackView;
- @Thunk HashMap mReorderAnimators = new HashMap<>();
- @Thunk HashMap mShakeAnimators = new HashMap<>();
+ @Thunk final ArrayMap mReorderAnimators = new ArrayMap<>();
+ @Thunk final ArrayMap mShakeAnimators = new ArrayMap<>();
private boolean mItemPlacementDirty = false;
@@ -142,8 +142,8 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
private boolean mDragging = false;
- private TimeInterpolator mEaseOutInterpolator;
- private ShortcutAndWidgetContainer mShortcutsAndWidgets;
+ private final TimeInterpolator mEaseOutInterpolator;
+ private final ShortcutAndWidgetContainer mShortcutsAndWidgets;
@Retention(RetentionPolicy.SOURCE)
@IntDef({WORKSPACE, HOTSEAT, FOLDER})
@@ -154,7 +154,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
@ContainerType private final int mContainerType;
- private final float mChildScale;
+ private final float mChildScale = 1f;
public static final int MODE_SHOW_REORDER_HINT = 0;
public static final int MODE_DRAG_OVER = 1;
@@ -168,10 +168,10 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
private static final int REORDER_ANIMATION_DURATION = 150;
@Thunk final float mReorderPreviewAnimationMagnitude;
- private ArrayList mIntersectingViews = new ArrayList();
- private Rect mOccupiedRect = new Rect();
- private int[] mDirectionVector = new int[2];
- int[] mPreviousReorderDirection = new int[2];
+ private final ArrayList mIntersectingViews = new ArrayList<>();
+ private final Rect mOccupiedRect = new Rect();
+ private final int[] mDirectionVector = new int[2];
+ final int[] mPreviousReorderDirection = new int[2];
private static final int INVALID_DIRECTION = -100;
private final Rect mTempRect = new Rect();
@@ -218,8 +218,6 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
mFolderLeaveBehind.delegateCellX = -1;
mFolderLeaveBehind.delegateCellY = -1;
- mChildScale = mContainerType == HOTSEAT ? grid.inv.hotseatScale : 1f;
-
setAlwaysDrawnWithCacheEnabled(false);
final Resources res = getResources();
@@ -235,7 +233,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
for (int i = 0; i < mDragOutlines.length; i++) {
mDragOutlines[i] = new Rect(-1, -1, -1, -1);
}
- mDragOutlinePaint.setColor(getResources().getColor(R.color.outline_color));
+ mDragOutlinePaint.setColor(Themes.getAttrColor(context, R.attr.workspaceTextColor));
// When dragging things around the home screens, we show a green outline of
// where the item will land. The outlines gradually fade out, leaving a trail
@@ -496,7 +494,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
}
for (int i = 0; i < mFolderBackgrounds.size(); i++) {
- FolderIcon.PreviewBackground bg = mFolderBackgrounds.get(i);
+ PreviewBackground bg = mFolderBackgrounds.get(i);
cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
canvas.save();
canvas.translate(mTempLocation[0], mTempLocation[1]);
@@ -522,7 +520,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
super.dispatchDraw(canvas);
for (int i = 0; i < mFolderBackgrounds.size(); i++) {
- FolderIcon.PreviewBackground bg = mFolderBackgrounds.get(i);
+ PreviewBackground bg = mFolderBackgrounds.get(i);
if (bg.isClipping) {
cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
canvas.save();
@@ -533,19 +531,16 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
}
}
- public void addFolderBackground(FolderIcon.PreviewBackground bg) {
+ public void addFolderBackground(PreviewBackground bg) {
mFolderBackgrounds.add(bg);
}
- public void removeFolderBackground(FolderIcon.PreviewBackground bg) {
+ public void removeFolderBackground(PreviewBackground bg) {
mFolderBackgrounds.remove(bg);
}
public void setFolderLeaveBehindCell(int x, int y) {
-
- DeviceProfile grid = mLauncher.getDeviceProfile();
View child = getChildAt(x, y);
-
- mFolderLeaveBehind.setup(getResources().getDisplayMetrics(), grid, null,
+ mFolderLeaveBehind.setup(mLauncher, null,
child.getMeasuredWidth(), child.getPaddingTop());
mFolderLeaveBehind.delegateCellX = x;
@@ -568,7 +563,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
try {
dispatchRestoreInstanceState(states);
} catch (IllegalArgumentException ex) {
- if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_DOGFOOD_BUILD) {
throw ex;
}
// Mismatched viewId / viewType preventing restore. Skip restore on production builds.
@@ -1102,7 +1097,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
result, resultSpan);
}
- private final Stack mTempRectStack = new Stack();
+ private final Stack mTempRectStack = new Stack<>();
private void lazyInitTempRectStack() {
if (mTempRectStack.isEmpty()) {
for (int i = 0; i < mCountX * mCountY; i++) {
@@ -1147,7 +1142,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
final int[] bestXY = result != null ? result : new int[2];
double bestDistance = Double.MAX_VALUE;
final Rect bestRect = new Rect(-1, -1, -1, -1);
- final Stack validRegions = new Stack();
+ final Stack validRegions = new Stack<>();
final int countX = mCountX;
final int countY = mCountY;
@@ -1349,14 +1344,14 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
final static int RIGHT = 1 << 2;
final static int BOTTOM = 1 << 3;
- ArrayList views;
- ItemConfiguration config;
- Rect boundingRect = new Rect();
+ final ArrayList views;
+ final ItemConfiguration config;
+ final Rect boundingRect = new Rect();
- int[] leftEdge = new int[mCountY];
- int[] rightEdge = new int[mCountY];
- int[] topEdge = new int[mCountX];
- int[] bottomEdge = new int[mCountX];
+ final int[] leftEdge = new int[mCountY];
+ final int[] rightEdge = new int[mCountY];
+ final int[] topEdge = new int[mCountX];
+ final int[] bottomEdge = new int[mCountX];
int dirtyEdges;
boolean boundingRectDirty;
@@ -1496,7 +1491,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
return boundingRect;
}
- PositionComparator comparator = new PositionComparator();
+ final PositionComparator comparator = new PositionComparator();
class PositionComparator implements Comparator {
int whichEdge = 0;
public int compare(View left, View right) {
@@ -1796,7 +1791,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
}
}
- solution.intersectingViews = new ArrayList(mIntersectingViews);
+ solution.intersectingViews = new ArrayList<>(mIntersectingViews);
// First we try to find a solution which respects the push mechanic. That is,
// we try to find a solution such that no displaced item travels through another item
@@ -1852,7 +1847,7 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
int result[] = new int[2];
result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
- boolean success = false;
+ boolean success;
// First we try the exact nearest position of the item being dragged,
// we will then want to try to move this around to other neighbouring positions
success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
@@ -1960,14 +1955,14 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
// Class which represents the reorder preview animations. These animations show that an item is
// in a temporary state, and hint at where the item will return to.
class ReorderPreviewAnimation {
- View child;
+ final View child;
float finalDeltaX;
float finalDeltaY;
float initDeltaX;
float initDeltaY;
- float finalScale;
+ final float finalScale;
float initScale;
- int mode;
+ final int mode;
boolean repeating = false;
private static final int PREVIEW_DURATION = 300;
private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
@@ -2417,9 +2412,9 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
}
private static class ItemConfiguration extends CellAndSpan {
- HashMap map = new HashMap();
- private HashMap savedMap = new HashMap();
- ArrayList sortedViews = new ArrayList();
+ final ArrayMap map = new ArrayMap<>();
+ private final ArrayMap savedMap = new ArrayMap<>();
+ final ArrayList sortedViews = new ArrayList<>();
ArrayList intersectingViews;
boolean isSolution = false;
@@ -2469,7 +2464,6 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
* @param pixelY The Y location at which you want to search for a vacant area.
* @param spanX Horizontal span of the object.
* @param spanY Vertical span of the object.
- * @param ignoreView Considers space occupied by this view as unoccupied
* @param result Previously returned value to possibly recycle.
* @return The X, Y cell of a vacant area that can contain this object,
* nearest the requested location.
@@ -2781,9 +2775,9 @@ public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
// cellX and cellY coordinates and which page was clicked. We then set this as a tag on
// the CellLayout that was long clicked
public static final class CellInfo extends CellAndSpan {
- public View cell;
- long screenId;
- long container;
+ public final View cell;
+ final long screenId;
+ final long container;
public CellInfo(View v, ItemInfo info) {
cellX = info.cellX;
diff --git a/src/com/android/launcher3/DefaultLayoutParser.java b/src/com/android/launcher3/DefaultLayoutParser.java
index 05911ab7fa..1ec30ba68d 100644
--- a/src/com/android/launcher3/DefaultLayoutParser.java
+++ b/src/com/android/launcher3/DefaultLayoutParser.java
@@ -13,18 +13,15 @@ import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.text.TextUtils;
+import android.util.ArrayMap;
import android.util.Log;
-
import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.util.Thunk;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
import java.io.IOException;
import java.net.URISyntaxException;
-import java.util.HashMap;
import java.util.List;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
/**
* Implements the layout parser with rules for internal layouts and partner layouts.
@@ -55,20 +52,20 @@ public class DefaultLayoutParser extends AutoInstallsLayout {
}
@Override
- protected HashMap getFolderElementsMap() {
+ protected ArrayMap getFolderElementsMap() {
return getFolderElementsMap(mSourceRes);
}
- @Thunk HashMap getFolderElementsMap(Resources res) {
- HashMap parsers = new HashMap();
+ @Thunk ArrayMap getFolderElementsMap(Resources res) {
+ ArrayMap parsers = new ArrayMap<>();
parsers.put(TAG_FAVORITE, new AppShortcutWithUriParser());
parsers.put(TAG_SHORTCUT, new UriShortcutParser(res));
return parsers;
}
@Override
- protected HashMap getLayoutElementsMap() {
- HashMap parsers = new HashMap();
+ protected ArrayMap getLayoutElementsMap() {
+ ArrayMap parsers = new ArrayMap<>();
parsers.put(TAG_FAVORITE, new AppShortcutWithUriParser());
parsers.put(TAG_APPWIDGET, new AppWidgetParser());
parsers.put(TAG_SHORTCUT, new UriShortcutParser(mSourceRes));
diff --git a/src/com/android/launcher3/DeferredHandler.java b/src/com/android/launcher3/DeferredHandler.java
deleted file mode 100644
index a43ab67239..0000000000
--- a/src/com/android/launcher3/DeferredHandler.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2008 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;
-
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.os.MessageQueue;
-
-import com.android.launcher3.util.Thunk;
-
-import java.util.LinkedList;
-
-/**
- * Queue of things to run on a looper thread. Items posted with {@link #post} will not
- * be actually enqued on the handler until after the last one has run, to keep from
- * starving the thread.
- *
- * This class is fifo.
- */
-public class DeferredHandler {
- @Thunk LinkedList mQueue = new LinkedList<>();
- private MessageQueue mMessageQueue = Looper.myQueue();
- private Impl mHandler = new Impl();
-
- @Thunk class Impl extends Handler implements MessageQueue.IdleHandler {
- public void handleMessage(Message msg) {
- Runnable r;
- synchronized (mQueue) {
- if (mQueue.size() == 0) {
- return;
- }
- r = mQueue.removeFirst();
- }
- r.run();
- synchronized (mQueue) {
- scheduleNextLocked();
- }
- }
-
- public boolean queueIdle() {
- handleMessage(null);
- return false;
- }
- }
-
- private class IdleRunnable implements Runnable {
- Runnable mRunnable;
-
- IdleRunnable(Runnable r) {
- mRunnable = r;
- }
-
- public void run() {
- mRunnable.run();
- }
- }
-
- public DeferredHandler() {
- }
-
- /** Schedule runnable to run after everything that's on the queue right now. */
- public void post(Runnable runnable) {
- synchronized (mQueue) {
- mQueue.add(runnable);
- if (mQueue.size() == 1) {
- scheduleNextLocked();
- }
- }
- }
-
- /** Schedule runnable to run when the queue goes idle. */
- public void postIdle(final Runnable runnable) {
- post(new IdleRunnable(runnable));
- }
-
- public void cancelAll() {
- synchronized (mQueue) {
- mQueue.clear();
- }
- }
-
- /** Runs all queued Runnables from the calling thread. */
- public void flush() {
- LinkedList queue = new LinkedList<>();
- synchronized (mQueue) {
- queue.addAll(mQueue);
- mQueue.clear();
- }
- for (Runnable r : queue) {
- r.run();
- }
- }
-
- void scheduleNextLocked() {
- if (mQueue.size() > 0) {
- Runnable peek = mQueue.getFirst();
- if (peek instanceof IdleRunnable) {
- mMessageQueue.addIdleHandler(mHandler);
- } else {
- mHandler.sendEmptyMessage(1);
- }
- }
- }
-}
-
diff --git a/src/com/android/launcher3/DeleteDropTarget.java b/src/com/android/launcher3/DeleteDropTarget.java
index 9097ed23d7..975675a6fc 100644
--- a/src/com/android/launcher3/DeleteDropTarget.java
+++ b/src/com/android/launcher3/DeleteDropTarget.java
@@ -40,7 +40,7 @@ public class DeleteDropTarget extends ButtonDropTarget {
// Get the hover color
mHoverColor = getResources().getColor(R.color.delete_target_hover_tint);
- setDrawable(R.drawable.ic_remove_launcher);
+ setDrawable(R.drawable.ic_remove_shadow);
}
@Override
diff --git a/src/com/android/launcher3/DeviceProfile.java b/src/com/android/launcher3/DeviceProfile.java
index e47031ae8c..dcfb268d15 100644
--- a/src/com/android/launcher3/DeviceProfile.java
+++ b/src/com/android/launcher3/DeviceProfile.java
@@ -19,6 +19,7 @@ package com.android.launcher3;
import android.appwidget.AppWidgetHostView;
import android.content.ComponentName;
import android.content.Context;
+import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.PointF;
@@ -32,7 +33,6 @@ import android.widget.FrameLayout;
import com.android.launcher3.CellLayout.ContainerType;
import com.android.launcher3.badge.BadgeRenderer;
-import com.android.launcher3.config.FeatureFlags;
import java.util.ArrayList;
@@ -80,9 +80,8 @@ public class DeviceProfile {
public final int workspaceSpringLoadedBottomSpace;
// Page indicator
- private final int pageIndicatorHeightPx;
- private final int pageIndicatorLandGutterLeftNavBarPx;
- private final int pageIndicatorLandGutterRightNavBarPx;
+ private final int pageIndicatorSizePx;
+ private final int pageIndicatorLandGutterPx;
private final int pageIndicatorLandWorkspaceOffsetPx;
// Workspace icons
@@ -93,6 +92,7 @@ public class DeviceProfile {
public int cellWidthPx;
public int cellHeightPx;
+ public int workspaceCellPaddingXPx;
// Folder
public int folderBackgroundOffset;
@@ -109,15 +109,17 @@ public class DeviceProfile {
public int folderChildDrawablePaddingPx;
// Hotseat
- public int hotseatCellWidthPx;
public int hotseatCellHeightPx;
- public int hotseatIconSizePx;
public int hotseatBarHeightPx;
- private int hotseatBarTopPaddingPx;
- private int hotseatBarBottomPaddingPx;
- private int hotseatLandGutterPx;
+ public int hotseatBarTopPaddingPx;
+ public int hotseatBarLeftNavBarRightPaddingPx;
+ public int hotseatBarRightNavBarRightPaddingPx;
+ public int hotseatBarBottomPaddingPx;
+ public int hotseatLandLeftNavBarGutterPx;
+ public int hotseatLandRightNavBarGutterPx;
// All apps
+ public int allAppsCellHeightPx;
public int allAppsNumCols;
public int allAppsNumPredictiveCols;
public int allAppsButtonVisualSize;
@@ -159,19 +161,22 @@ public class DeviceProfile {
transposeLayoutWithOrientation =
res.getBoolean(R.bool.hotseat_transpose_layout_with_orientation);
+ context = getContext(context, isVerticalBarLayout()
+ ? Configuration.ORIENTATION_LANDSCAPE
+ : Configuration.ORIENTATION_PORTRAIT);
+ res = context.getResources();
+
+
ComponentName cn = new ComponentName(context.getPackageName(),
this.getClass().getName());
defaultWidgetPadding = AppWidgetHostView.getDefaultPaddingForWidget(context, cn, null);
edgeMarginPx = res.getDimensionPixelSize(R.dimen.dynamic_grid_edge_margin);
desiredWorkspaceLeftRightMarginPx = edgeMarginPx;
- pageIndicatorHeightPx =
- res.getDimensionPixelSize(R.dimen.dynamic_grid_page_indicator_height);
- pageIndicatorLandGutterLeftNavBarPx = res.getDimensionPixelSize(
- R.dimen.dynamic_grid_page_indicator_gutter_width_left_nav_bar);
+ pageIndicatorSizePx = res.getDimensionPixelSize(R.dimen.dynamic_grid_page_indicator_size);
+ pageIndicatorLandGutterPx = res.getDimensionPixelSize(
+ R.dimen.dynamic_grid_page_indicator_gutter_width);
pageIndicatorLandWorkspaceOffsetPx =
res.getDimensionPixelSize(R.dimen.all_apps_caret_workspace_offset);
- pageIndicatorLandGutterRightNavBarPx = res.getDimensionPixelSize(
- R.dimen.dynamic_grid_page_indicator_gutter_width_right_nav_bar);
defaultPageSpacingPx =
res.getDimensionPixelSize(R.dimen.dynamic_grid_workspace_page_spacing);
topWorkspacePadding =
@@ -191,11 +196,26 @@ public class DeviceProfile {
dropTargetBarSizePx = res.getDimensionPixelSize(R.dimen.dynamic_grid_drop_target_size);
workspaceSpringLoadedBottomSpace =
res.getDimensionPixelSize(R.dimen.dynamic_grid_min_spring_loaded_space);
- hotseatBarHeightPx = res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_height);
+
+ workspaceCellPaddingXPx = res.getDimensionPixelSize(R.dimen.dynamic_grid_cell_padding_x);
+
hotseatBarTopPaddingPx =
res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_top_padding);
- hotseatBarBottomPaddingPx = 0;
- hotseatLandGutterPx = res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_gutter_width);
+ hotseatBarBottomPaddingPx =
+ res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_bottom_padding);
+ hotseatBarLeftNavBarRightPaddingPx = res.getDimensionPixelSize(
+ R.dimen.dynamic_grid_hotseat_land_left_nav_bar_right_padding);
+ hotseatBarRightNavBarRightPaddingPx = res.getDimensionPixelSize(
+ R.dimen.dynamic_grid_hotseat_land_right_nav_bar_right_padding);
+ hotseatBarHeightPx = isVerticalBarLayout()
+ ? res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_height)
+ : res.getDimensionPixelSize(R.dimen.dynamic_grid_hotseat_height)
+ + hotseatBarTopPaddingPx + hotseatBarBottomPaddingPx;
+
+ hotseatLandLeftNavBarGutterPx = res.getDimensionPixelSize(
+ R.dimen.dynamic_grid_hotseat_land_left_nav_bar_gutter_width);
+ hotseatLandRightNavBarGutterPx = res.getDimensionPixelSize(
+ R.dimen.dynamic_grid_hotseat_land_right_nav_bar_gutter_width);
// Determine sizes.
widthPx = width;
@@ -228,9 +248,6 @@ public class DeviceProfile {
profile.cellHeightPx = profile.iconSizePx + profile.iconDrawablePaddingPx
+ Utilities.calculateTextHeight(profile.iconTextSizePx);
- // The nav bar is black so we add bottom padding to visually center hotseat icons.
- profile.hotseatBarBottomPaddingPx = profile.hotseatBarTopPaddingPx;
-
// We use these scales to measure and layout the widgets using their full invariant profile
// sizes and then draw them scaled and centered to fit in their multi-window mode cellspans.
float appWidgetScaleX = (float) profile.getCellSize().x / getCellSize().x;
@@ -259,45 +276,51 @@ public class DeviceProfile {
private void computeAllAppsButtonSize(Context context) {
Resources res = context.getResources();
float padding = res.getInteger(R.integer.config_allAppsButtonPaddingPercent) / 100f;
- allAppsButtonVisualSize = (int) (hotseatIconSizePx * (1 - padding)) - context.getResources()
+ allAppsButtonVisualSize = (int) (iconSizePx * (1 - padding)) - context.getResources()
.getDimensionPixelSize(R.dimen.all_apps_button_scale_down);
}
private void updateAvailableDimensions(DisplayMetrics dm, Resources res) {
- updateIconSize(1f, iconDrawablePaddingOriginalPx, res, dm);
+ updateIconSize(1f, res, dm);
// Check to see if the icons fit within the available height. If not, then scale down.
float usedHeight = (cellHeightPx * inv.numRows);
int maxHeight = (availableHeightPx - getTotalWorkspacePadding().y);
if (usedHeight > maxHeight) {
float scale = maxHeight / usedHeight;
- updateIconSize(scale, 0, res, dm);
+ updateIconSize(scale, res, dm);
}
-
updateAvailableFolderCellDimensions(dm, res);
}
- private void updateIconSize(float scale, int drawablePadding, Resources res,
- DisplayMetrics dm) {
- iconSizePx = (int) (Utilities.pxFromDp(inv.iconSize, dm) * scale);
+ private void updateIconSize(float scale, Resources res, DisplayMetrics dm) {
+ float invIconSizePx = isVerticalBarLayout() ? inv.landscapeIconSize : inv.iconSize;
+ iconSizePx = (int) (Utilities.pxFromDp(invIconSizePx, dm) * scale);
iconTextSizePx = (int) (Utilities.pxFromSp(inv.iconTextSize, dm) * scale);
- iconDrawablePaddingPx = drawablePadding;
- hotseatIconSizePx = (int) (Utilities.pxFromDp(inv.hotseatIconSize, dm) * scale);
+ iconDrawablePaddingPx = (int) (iconDrawablePaddingOriginalPx * scale);
+
+ // All apps
+ allAppsIconTextSizePx = iconTextSizePx;
allAppsIconSizePx = iconSizePx;
allAppsIconDrawablePaddingPx = iconDrawablePaddingPx;
- allAppsIconTextSizePx = iconTextSizePx;
+ allAppsCellHeightPx = getCellSize().y;
- cellWidthPx = iconSizePx;
+ if (isVerticalBarLayout()) {
+ // Always hide the Workspace text with vertical bar layout.
+ iconTextSizePx = 0;
+ allAppsCellHeightPx += Utilities.calculateTextHeight(allAppsIconTextSizePx);
+ }
+
+ cellWidthPx = iconSizePx + iconDrawablePaddingPx;
cellHeightPx = iconSizePx + iconDrawablePaddingPx
+ Utilities.calculateTextHeight(iconTextSizePx);
// Hotseat
- hotseatCellWidthPx = iconSizePx;
- hotseatCellHeightPx = iconSizePx;
+ hotseatCellHeightPx = iconSizePx + iconDrawablePaddingPx;
if (!isVerticalBarLayout()) {
int expectedWorkspaceHeight = availableHeightPx - hotseatBarHeightPx
- - pageIndicatorHeightPx - topWorkspacePadding;
+ - pageIndicatorSizePx - topWorkspacePadding;
float minRequiredHeight = dropTargetBarSizePx + workspaceSpringLoadedBottomSpace;
workspaceSpringLoadShrinkFactor = Math.min(
res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f,
@@ -308,7 +331,7 @@ public class DeviceProfile {
}
// Folder icon
- folderBackgroundOffset = -edgeMarginPx;
+ folderBackgroundOffset = -iconDrawablePaddingPx;
folderIconSizePx = iconSizePx + 2 * -folderBackgroundOffset;
folderIconPreviewPadding = res.getDimensionPixelSize(R.dimen.folder_preview_padding);
}
@@ -401,22 +424,25 @@ public class DeviceProfile {
/**
* Returns the workspace padding in the specified orientation.
- * Note that it assumes that while in verticalBarLayout, the nav bar is on the right, as such
- * this value is not reliable.
- * Use {@link #getTotalWorkspacePadding()} instead.
*/
public Rect getWorkspacePadding(Rect recycle) {
Rect padding = recycle == null ? new Rect() : recycle;
if (isVerticalBarLayout()) {
if (mInsets.left > 0) {
- padding.set(mInsets.left + pageIndicatorLandGutterLeftNavBarPx, 0,
- hotseatBarHeightPx + hotseatLandGutterPx - mInsets.left, 2 * edgeMarginPx);
+ padding.set(mInsets.left + pageIndicatorLandGutterPx,
+ 0,
+ hotseatBarHeightPx + hotseatLandLeftNavBarGutterPx
+ + hotseatBarLeftNavBarRightPaddingPx - mInsets.left,
+ edgeMarginPx);
} else {
- padding.set(pageIndicatorLandGutterRightNavBarPx, 0,
- hotseatBarHeightPx + hotseatLandGutterPx, 2 * edgeMarginPx);
+ padding.set(pageIndicatorLandGutterPx,
+ 0,
+ hotseatBarHeightPx + hotseatLandRightNavBarGutterPx
+ + hotseatBarRightNavBarRightPaddingPx,
+ edgeMarginPx);
}
} else {
- int paddingBottom = hotseatBarHeightPx + pageIndicatorHeightPx;
+ int paddingBottom = hotseatBarHeightPx + pageIndicatorSizePx;
if (isTablet) {
// Pad the left and right of the workspace to ensure consistent spacing
// between all icons
@@ -458,7 +484,7 @@ public class DeviceProfile {
return new Rect(mInsets.left,
mInsets.top + dropTargetBarSizePx + edgeMarginPx,
mInsets.left + availableWidthPx,
- mInsets.top + availableHeightPx - hotseatBarHeightPx - pageIndicatorHeightPx -
+ mInsets.top + availableHeightPx - hotseatBarHeightPx - pageIndicatorSizePx -
edgeMarginPx);
}
}
@@ -522,7 +548,7 @@ public class DeviceProfile {
lp = (FrameLayout.LayoutParams) searchBar.getLayoutParams();
lp.width = searchBarBounds.x;
lp.height = searchBarBounds.y;
- lp.topMargin = mInsets.top + edgeMarginPx;
+ lp.topMargin = mInsets.top + edgeMarginPx / 2;
searchBar.setLayoutParams(lp);
// Layout the workspace
@@ -532,14 +558,6 @@ public class DeviceProfile {
workspacePadding.bottom);
workspace.setPageSpacing(getWorkspacePageSpacing());
- // Only display when enabled
- if (FeatureFlags.QSB_ON_FIRST_SCREEN) {
- View qsbContainer = launcher.getQsbContainer();
- lp = (FrameLayout.LayoutParams) qsbContainer.getLayoutParams();
- lp.topMargin = mInsets.top + workspacePadding.top;
- qsbContainer.setLayoutParams(lp);
- }
-
// Layout the hotseat
Hotseat hotseat = (Hotseat) launcher.findViewById(R.id.hotseat);
lp = (FrameLayout.LayoutParams) hotseat.getLayoutParams();
@@ -556,7 +574,12 @@ public class DeviceProfile {
lp.gravity = Gravity.RIGHT;
lp.width = hotseatBarHeightPx + mInsets.left + mInsets.right;
lp.height = LayoutParams.MATCH_PARENT;
- hotseat.getLayout().setPadding(mInsets.left, mInsets.top, mInsets.right,
+
+ int paddingRight = mInsets.left > 0
+ ? hotseatBarLeftNavBarRightPaddingPx
+ : hotseatBarRightNavBarRightPaddingPx;
+
+ hotseat.getLayout().setPadding(mInsets.left, mInsets.top, mInsets.right + paddingRight,
workspacePadding.bottom);
} else if (isTablet) {
// Pad the hotseat with the workspace padding calculated above
@@ -584,17 +607,15 @@ public class DeviceProfile {
lp = (FrameLayout.LayoutParams) pageIndicator.getLayoutParams();
if (isVerticalBarLayout()) {
if (mInsets.left > 0) {
- lp.leftMargin = mInsets.left + pageIndicatorLandGutterLeftNavBarPx -
- lp.width - pageIndicatorLandWorkspaceOffsetPx;
- } else if (mInsets.right > 0) {
- lp.leftMargin = pageIndicatorLandGutterRightNavBarPx - lp.width -
- pageIndicatorLandWorkspaceOffsetPx;
+ lp.leftMargin = mInsets.left;
+ } else {
+ lp.leftMargin = pageIndicatorLandWorkspaceOffsetPx;
}
lp.bottomMargin = workspacePadding.bottom;
} else {
// Put the page indicators above the hotseat
lp.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
- lp.height = pageIndicatorHeightPx;
+ lp.height = pageIndicatorSizePx;
lp.bottomMargin = hotseatBarHeightPx + mInsets.bottom;
}
pageIndicator.setLayoutParams(lp);
@@ -613,6 +634,12 @@ public class DeviceProfile {
overviewMode.setLayoutParams(lp);
}
+ // Layout the AllAppsRecyclerView
+ View view = launcher.findViewById(R.id.apps_list_view);
+ int paddingLeftRight = hasVerticalBarLayout ? 0 : edgeMarginPx;
+ view.setPadding(paddingLeftRight, view.getPaddingTop(), paddingLeftRight,
+ view.getPaddingBottom());
+
if (notifyListeners) {
for (int i = mListeners.size() - 1; i >= 0; i--) {
mListeners.get(i).onLauncherLayoutChanged();
@@ -656,9 +683,8 @@ public class DeviceProfile {
}
// In landscape, we match the width of the workspace
- int padding = (pageIndicatorLandGutterRightNavBarPx +
- hotseatBarHeightPx + hotseatLandGutterPx + mInsets.left) / 2;
- return new int[]{ padding, padding };
+ Rect padding = getWorkspacePadding(null);
+ return new int[] { padding.left - mInsets.left, padding.right + mInsets.left};
}
public boolean shouldIgnoreLongPressToOverview(float touchX) {
@@ -667,4 +693,11 @@ public class DeviceProfile {
boolean touchedRhsEdge = mInsets.right == 0 && touchX > (widthPx - edgeMarginPx);
return !inMultiWindowMode && (touchedLhsEdge || touchedRhsEdge);
}
+
+ private static Context getContext(Context c, int orientation) {
+ Configuration context = new Configuration(c.getResources().getConfiguration());
+ context.orientation = orientation;
+ return c.createConfigurationContext(context);
+
+ }
}
diff --git a/src/com/android/launcher3/FastBitmapDrawable.java b/src/com/android/launcher3/FastBitmapDrawable.java
index 199baaf588..1272e0ade9 100644
--- a/src/com/android/launcher3/FastBitmapDrawable.java
+++ b/src/com/android/launcher3/FastBitmapDrawable.java
@@ -36,8 +36,6 @@ import com.android.launcher3.graphics.IconPalette;
public class FastBitmapDrawable extends Drawable {
- private static final int[] STATE_PRESSED = new int[] {android.R.attr.state_pressed};
-
private static final float PRESSED_BRIGHTNESS = 100f / 255f;
private static final float DISABLED_DESATURATION = 1f;
private static final float DISABLED_BRIGHTNESS = 0.5f;
@@ -107,17 +105,6 @@ public class FastBitmapDrawable extends Drawable {
@Override
public void draw(Canvas canvas) {
- drawInternal(canvas);
- }
-
- public void drawWithBrightness(Canvas canvas, float brightness) {
- float oldBrightness = getBrightness();
- setBrightness(brightness);
- drawInternal(canvas);
- setBrightness(oldBrightness);
- }
-
- protected void drawInternal(Canvas canvas) {
canvas.drawBitmap(mBitmap, null, getBounds(), mPaint);
}
@@ -184,6 +171,11 @@ public class FastBitmapDrawable extends Drawable {
return true;
}
+ @Override
+ public ColorFilter getColorFilter() {
+ return mPaint.getColorFilter();
+ }
+
@Override
protected boolean onStateChange(int[] state) {
boolean isPressed = false;
diff --git a/src/com/android/launcher3/FocusHelper.java b/src/com/android/launcher3/FocusHelper.java
index b36734bab4..fe7acda17b 100644
--- a/src/com/android/launcher3/FocusHelper.java
+++ b/src/com/android/launcher3/FocusHelper.java
@@ -22,7 +22,7 @@ import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewGroup;
-import com.android.launcher3.config.ProviderConfig;
+import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderPagedView;
import com.android.launcher3.util.FocusLogic;
@@ -93,7 +93,7 @@ public class FocusHelper {
}
if (!(v.getParent() instanceof ShortcutAndWidgetContainer)) {
- if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_DOGFOOD_BUILD) {
throw new IllegalStateException("Parent of the focused item is not supported.");
} else {
return false;
diff --git a/src/com/android/launcher3/FolderInfo.java b/src/com/android/launcher3/FolderInfo.java
index 0041bb4d63..21254ab292 100644
--- a/src/com/android/launcher3/FolderInfo.java
+++ b/src/com/android/launcher3/FolderInfo.java
@@ -65,9 +65,17 @@ public class FolderInfo extends ItemInfo {
* @param item
*/
public void add(ShortcutInfo item, boolean animate) {
- contents.add(item);
+ add(item, contents.size(), animate);
+ }
+
+ /**
+ * Add an app or shortcut for a specified rank.
+ */
+ public void add(ShortcutInfo item, int rank, boolean animate) {
+ rank = Utilities.boundToRange(rank, 0, contents.size());
+ contents.add(rank, item);
for (int i = 0; i < listeners.size(); i++) {
- listeners.get(i).onAdd(item);
+ listeners.get(i).onAdd(item, rank);
}
itemsChanged(animate);
}
@@ -121,7 +129,7 @@ public class FolderInfo extends ItemInfo {
}
public interface FolderListener {
- public void onAdd(ShortcutInfo item);
+ public void onAdd(ShortcutInfo item, int rank);
public void onRemove(ShortcutInfo item);
public void onTitleChanged(CharSequence title);
public void onItemsChanged(boolean animate);
diff --git a/src/com/android/launcher3/Hotseat.java b/src/com/android/launcher3/Hotseat.java
index 47052a77e2..af3abebb4c 100644
--- a/src/com/android/launcher3/Hotseat.java
+++ b/src/com/android/launcher3/Hotseat.java
@@ -72,7 +72,9 @@ public class Hotseat extends FrameLayout
mBackgroundColor = ColorUtils.setAlphaComponent(
Themes.getAttrColor(context, android.R.attr.colorPrimary), 0);
mBackground = new ColorDrawable(mBackgroundColor);
- setBackground(mBackground);
+ if (!FeatureFlags.LAUNCHER3_GRADIENT_ALL_APPS) {
+ setBackground(mBackground);
+ }
}
public CellLayout getLayout() {
@@ -149,7 +151,6 @@ public class Hotseat extends FrameLayout
mLauncher.setAllAppsButton(allAppsButton);
allAppsButton.setOnTouchListener(mLauncher.getHapticFeedbackTouchListener());
allAppsButton.setOnClickListener(mLauncher);
- allAppsButton.setOnLongClickListener(mLauncher);
allAppsButton.setOnFocusChangeListener(mLauncher.mFocusHandler);
}
@@ -179,8 +180,12 @@ public class Hotseat extends FrameLayout
}
public void updateColor(ExtractedColors extractedColors, boolean animate) {
+ if (FeatureFlags.LAUNCHER3_GRADIENT_ALL_APPS) {
+ // not hotseat visible
+ return;
+ }
if (!mHasVerticalHotseat) {
- int color = extractedColors.getColor(ExtractedColors.HOTSEAT_INDEX, Color.TRANSPARENT);
+ int color = extractedColors.getColor(ExtractedColors.HOTSEAT_INDEX);
if (mBackgroundColorAnimator != null) {
mBackgroundColorAnimator.cancel();
}
diff --git a/src/com/android/launcher3/IconCache.java b/src/com/android/launcher3/IconCache.java
index 12170309b9..383e6efd07 100644
--- a/src/com/android/launcher3/IconCache.java
+++ b/src/com/android/launcher3/IconCache.java
@@ -32,10 +32,6 @@ import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Paint;
-import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
@@ -55,7 +51,6 @@ import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.util.Provider;
import com.android.launcher3.util.SQLiteCacheHelper;
-import com.android.launcher3.util.Themes;
import com.android.launcher3.util.Thunk;
import java.util.Collections;
@@ -100,24 +95,14 @@ public class IconCache {
@Thunk final UserManagerCompat mUserManager;
private final LauncherAppsCompat mLauncherApps;
private final HashMap mCache =
- new HashMap(INITIAL_ICON_CACHE_CAPACITY);
+ new HashMap<>(INITIAL_ICON_CACHE_CAPACITY);
private final int mIconDpi;
@Thunk final IconDB mIconDb;
@Thunk final Handler mWorkerHandler;
- // The background color used for activity icons. Since these icons are displayed in all-apps
- // and folders, this would be same as the light quantum panel background. This color
- // is used to convert icons to RGB_565.
- private final int mActivityBgColor;
- // The background color used for package icons. These are displayed in widget tray, which
- // has a dark quantum panel background.
- private final int mPackageBgColor;
private final BitmapFactory.Options mLowResOptions;
- private Canvas mLowResCanvas;
- private Paint mLowResPaint;
-
public IconCache(Context context, InvariantDeviceProfile inv) {
mContext = context;
mPackageManager = context.getPackageManager();
@@ -125,16 +110,11 @@ public class IconCache {
mLauncherApps = LauncherAppsCompat.getInstance(mContext);
mIconDpi = inv.fillResIconDpi;
mIconDb = new IconDB(context, inv.iconBitmapSize);
- mLowResCanvas = new Canvas();
- mLowResPaint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
mIconProvider = Utilities.getOverrideObject(
IconProvider.class, context, R.string.icon_provider_class);
mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
- mActivityBgColor = Themes.getColorPrimary(context, R.style.LauncherTheme);
- mPackageBgColor = Themes.getColorPrimary(context, R.style.WidgetContainerTheme);
-
mLowResOptions = new BitmapFactory.Options();
// Always prefer RGB_565 config for low res. If the bitmap has transparency, it will
// automatically be loaded as ALPHA_8888.
@@ -190,7 +170,11 @@ public class IconCache {
}
public Drawable getFullResIcon(LauncherActivityInfo info) {
- return mIconProvider.getIcon(info, mIconDpi);
+ return getFullResIcon(info, true);
+ }
+
+ public Drawable getFullResIcon(LauncherActivityInfo info, boolean flattenDrawable) {
+ return mIconProvider.getIcon(info, mIconDpi, flattenDrawable);
}
protected Bitmap makeDefaultIcon(UserHandle user) {
@@ -387,7 +371,7 @@ public class IconCache {
entry.contentDescription = mUserManager.getBadgedLabelForUser(entry.title, app.getUser());
mCache.put(key, entry);
- Bitmap lowResIcon = generateLowResIcon(entry.icon, mActivityBgColor);
+ Bitmap lowResIcon = generateLowResIcon(entry.icon);
ContentValues values = newContentValues(entry.icon, lowResIcon, entry.title.toString(),
app.getApplicationInfo().packageName);
addIconToDB(values, app.getComponentName(), info, userSerial);
@@ -637,7 +621,7 @@ public class IconCache {
// only keep the low resolution icon instead of the larger full-sized icon
Bitmap icon = LauncherIcons.createBadgedIconBitmap(
appInfo.loadIcon(mPackageManager), user, mContext, appInfo.targetSdkVersion);
- Bitmap lowResIcon = generateLowResIcon(icon, mPackageBgColor);
+ Bitmap lowResIcon = generateLowResIcon(icon);
entry.title = appInfo.loadLabel(mPackageManager);
entry.contentDescription = mUserManager.getBadgedLabelForUser(entry.title, user);
entry.icon = useLowResIcon ? lowResIcon : icon;
@@ -769,7 +753,7 @@ public class IconCache {
}
private static final class IconDB extends SQLiteCacheHelper {
- private final static int DB_VERSION = 13;
+ private final static int DB_VERSION = 16;
private final static int RELEASE_VERSION = DB_VERSION +
(FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION ? 0 : 1);
@@ -822,24 +806,10 @@ public class IconCache {
/**
* Generates a new low-res icon given a high-res icon.
*/
- private Bitmap generateLowResIcon(Bitmap icon, int lowResBackgroundColor) {
- if (lowResBackgroundColor == Color.TRANSPARENT) {
- return Bitmap.createScaledBitmap(icon,
- icon.getWidth() / LOW_RES_SCALE_FACTOR,
- icon.getHeight() / LOW_RES_SCALE_FACTOR, true);
- } else {
- Bitmap lowResIcon = Bitmap.createBitmap(icon.getWidth() / LOW_RES_SCALE_FACTOR,
- icon.getHeight() / LOW_RES_SCALE_FACTOR, Bitmap.Config.RGB_565);
- synchronized (this) {
- mLowResCanvas.setBitmap(lowResIcon);
- mLowResCanvas.drawColor(lowResBackgroundColor);
- mLowResCanvas.drawBitmap(icon, new Rect(0, 0, icon.getWidth(), icon.getHeight()),
- new Rect(0, 0, lowResIcon.getWidth(), lowResIcon.getHeight()),
- mLowResPaint);
- mLowResCanvas.setBitmap(null);
- }
- return lowResIcon;
- }
+ private Bitmap generateLowResIcon(Bitmap icon) {
+ return Bitmap.createScaledBitmap(icon,
+ icon.getWidth() / LOW_RES_SCALE_FACTOR,
+ icon.getHeight() / LOW_RES_SCALE_FACTOR, true);
}
private static Bitmap loadIconNoResize(Cursor c, int iconIndex, BitmapFactory.Options options) {
diff --git a/src/com/android/launcher3/IconProvider.java b/src/com/android/launcher3/IconProvider.java
index a5d399013e..6872515143 100644
--- a/src/com/android/launcher3/IconProvider.java
+++ b/src/com/android/launcher3/IconProvider.java
@@ -24,8 +24,11 @@ public class IconProvider {
return mSystemState;
}
-
- public Drawable getIcon(LauncherActivityInfo info, int iconDpi) {
+ /**
+ * @param flattenDrawable true if the caller does not care about the specification of the
+ * original icon as long as the flattened version looks the same.
+ */
+ public Drawable getIcon(LauncherActivityInfo info, int iconDpi, boolean flattenDrawable) {
return info.getIcon(iconDpi);
}
}
diff --git a/src/com/android/launcher3/InfoDropTarget.java b/src/com/android/launcher3/InfoDropTarget.java
index 0608fdd2e4..f088d11760 100644
--- a/src/com/android/launcher3/InfoDropTarget.java
+++ b/src/com/android/launcher3/InfoDropTarget.java
@@ -42,12 +42,10 @@ public class InfoDropTarget extends UninstallDropTarget {
}
@Override
- protected void onFinishInflate() {
- super.onFinishInflate();
+ protected void setupUi() {
// Get the hover color
mHoverColor = Themes.getColorAccent(getContext());
-
- setDrawable(R.drawable.ic_info_launcher);
+ setDrawable(R.drawable.ic_info_shadow);
}
@Override
@@ -67,6 +65,11 @@ public class InfoDropTarget extends UninstallDropTarget {
public static boolean startDetailsActivityForInfo(ItemInfo info, Launcher launcher,
DropTargetResultCallback callback, Rect sourceBounds, Bundle opts) {
+ if (info instanceof PromiseAppInfo) {
+ PromiseAppInfo promiseAppInfo = (PromiseAppInfo) info;
+ launcher.startActivity(promiseAppInfo.getMarketIntent());
+ return true;
+ }
boolean result = false;
ComponentName componentName = null;
if (info instanceof AppInfo) {
diff --git a/src/com/android/launcher3/InsettableFrameLayout.java b/src/com/android/launcher3/InsettableFrameLayout.java
index 154641cabe..be7649013c 100644
--- a/src/com/android/launcher3/InsettableFrameLayout.java
+++ b/src/com/android/launcher3/InsettableFrameLayout.java
@@ -9,9 +9,6 @@ import android.view.ViewDebug;
import android.view.ViewGroup;
import android.widget.FrameLayout;
-import com.android.launcher3.allapps.AllAppsContainerView;
-import com.android.launcher3.config.FeatureFlags;
-
public class InsettableFrameLayout extends FrameLayout implements
ViewGroup.OnHierarchyChangeListener, Insettable {
diff --git a/src/com/android/launcher3/InstallShortcutReceiver.java b/src/com/android/launcher3/InstallShortcutReceiver.java
index ce8557065e..0370777d17 100644
--- a/src/com/android/launcher3/InstallShortcutReceiver.java
+++ b/src/com/android/launcher3/InstallShortcutReceiver.java
@@ -34,6 +34,7 @@ import android.os.UserHandle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
+import android.util.Pair;
import com.android.launcher3.compat.LauncherAppsCompat;
import com.android.launcher3.compat.UserManagerCompat;
@@ -59,6 +60,16 @@ import java.util.List;
import java.util.Set;
public class InstallShortcutReceiver extends BroadcastReceiver {
+
+ public static final int FLAG_ACTIVITY_PAUSED = 1;
+ public static final int FLAG_LOADER_RUNNING = 2;
+ public static final int FLAG_DRAG_AND_DROP = 4;
+ public static final int FLAG_BULK_ADD = 4;
+
+ // Determines whether to defer installing shortcuts immediately until
+ // processAllPendingInstalls() is called.
+ private static int sInstallQueueDisabledFlags = 0;
+
private static final String TAG = "InstallShortcutReceiver";
private static final boolean DBG = false;
@@ -151,10 +162,6 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
}
}
- // Determines whether to defer installing shortcuts immediately until
- // processAllPendingInstalls() is called.
- private static boolean mUseInstallQueue = false;
-
public void onReceive(Context context, Intent data) {
if (!ACTION_INSTALL_SHORTCUT.equals(data.getAction())) {
return;
@@ -207,7 +214,11 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
public static ShortcutInfo fromShortcutIntent(Context context, Intent data) {
PendingInstallShortcutInfo info = createPendingInfo(context, data);
- return info == null ? null : (ShortcutInfo) info.getItemInfo();
+ return info == null ? null : (ShortcutInfo) info.getItemInfo().first;
+ }
+
+ public static ShortcutInfo fromActivityInfo(LauncherActivityInfo info, Context context) {
+ return (ShortcutInfo) (new PendingInstallShortcutInfo(info, context).getItemInfo().first);
}
public static void queueShortcut(ShortcutInfoCompat info, Context context) {
@@ -245,27 +256,28 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
private static void queuePendingShortcutInfo(PendingInstallShortcutInfo info, Context context) {
// Queue the item up for adding if launcher has not loaded properly yet
- LauncherAppState app = LauncherAppState.getInstance(context);
- boolean launcherNotLoaded = app.getModel().getCallback() == null;
-
addToInstallQueue(Utilities.getPrefs(context), info);
- if (!mUseInstallQueue && !launcherNotLoaded) {
- flushInstallQueue(context);
- }
+ flushInstallQueue(context);
}
- static void enableInstallQueue() {
- mUseInstallQueue = true;
+ public static void enableInstallQueue(int flag) {
+ sInstallQueueDisabledFlags |= flag;
}
- static void disableAndFlushInstallQueue(Context context) {
- mUseInstallQueue = false;
+ public static void disableAndFlushInstallQueue(int flag, Context context) {
+ sInstallQueueDisabledFlags &= ~flag;
flushInstallQueue(context);
}
static void flushInstallQueue(Context context) {
+ LauncherModel model = LauncherAppState.getInstance(context).getModel();
+ boolean launcherNotLoaded = model.getCallback() == null;
+ if (sInstallQueueDisabledFlags != 0 || launcherNotLoaded) {
+ return;
+ }
+
ArrayList items = getAndClearInstallQueue(context);
if (!items.isEmpty()) {
- LauncherAppState.getInstance(context).getModel().addAndBindAddedWorkspaceItems(
+ model.addAndBindAddedWorkspaceItems(
new LazyShortcutsProvider(context.getApplicationContext(), items));
}
}
@@ -439,7 +451,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
}
}
- public ItemInfo getItemInfo() {
+ public Pair getItemInfo() {
if (activityInfo != null) {
AppInfo appInfo = new AppInfo(mContext, activityInfo, user);
final LauncherAppState app = LauncherAppState.getInstance(mContext);
@@ -459,11 +471,11 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
}
});
}
- return si;
+ return Pair.create((ItemInfo) si, (Object) activityInfo);
} else if (shortcutInfo != null) {
ShortcutInfo si = new ShortcutInfo(shortcutInfo, mContext);
si.iconBitmap = LauncherIcons.createShortcutIcon(shortcutInfo, mContext);
- return si;
+ return Pair.create((ItemInfo) si, (Object) shortcutInfo);
} else if (providerInfo != null) {
LauncherAppWidgetProviderInfo info = LauncherAppWidgetProviderInfo
.fromProviderInfo(mContext, providerInfo);
@@ -475,9 +487,10 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
widgetInfo.minSpanY = info.minSpanY;
widgetInfo.spanX = Math.min(info.spanX, idp.numColumns);
widgetInfo.spanY = Math.min(info.spanY, idp.numRows);
- return widgetInfo;
+ return Pair.create((ItemInfo) widgetInfo, (Object) providerInfo);
} else {
- return createShortcutInfo(data, LauncherAppState.getInstance(mContext));
+ ShortcutInfo si = createShortcutInfo(data, LauncherAppState.getInstance(mContext));
+ return Pair.create((ItemInfo) si, null);
}
}
@@ -588,7 +601,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
return new PendingInstallShortcutInfo(info, original.mContext);
}
- private static class LazyShortcutsProvider extends Provider> {
+ private static class LazyShortcutsProvider extends Provider>> {
private final Context mContext;
private final ArrayList mPendingItems;
@@ -603,9 +616,9 @@ public class InstallShortcutReceiver extends BroadcastReceiver {
* packageManager and icon cache.
*/
@Override
- public ArrayList get() {
+ public ArrayList> get() {
Preconditions.assertNonUiThread();
- ArrayList installQueue = new ArrayList<>();
+ ArrayList> installQueue = new ArrayList<>();
LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(mContext);
for (PendingInstallShortcutInfo pendingInfo : mPendingItems) {
// If the intent specifies a package, make sure the package exists
diff --git a/src/com/android/launcher3/InvariantDeviceProfile.java b/src/com/android/launcher3/InvariantDeviceProfile.java
index 9e214d1ec2..d7bebd1b19 100644
--- a/src/com/android/launcher3/InvariantDeviceProfile.java
+++ b/src/com/android/launcher3/InvariantDeviceProfile.java
@@ -28,7 +28,6 @@ import android.view.Display;
import android.view.WindowManager;
import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.config.ProviderConfig;
import com.android.launcher3.util.Thunk;
import org.xmlpull.v1.XmlPullParser;
@@ -77,6 +76,7 @@ public class InvariantDeviceProfile {
public int numFolderRows;
public int numFolderColumns;
public float iconSize;
+ public float landscapeIconSize;
public int iconBitmapSize;
public int fillResIconDpi;
public float iconTextSize;
@@ -85,8 +85,6 @@ public class InvariantDeviceProfile {
* Number of icons inside the hotseat area.
*/
public int numHotseatIcons;
- float hotseatIconSize;
- public float hotseatScale;
int defaultLayoutId;
public DeviceProfile landscapeProfile;
@@ -100,12 +98,12 @@ public class InvariantDeviceProfile {
public InvariantDeviceProfile(InvariantDeviceProfile p) {
this(p.name, p.minWidthDps, p.minHeightDps, p.numRows, p.numColumns,
p.numFolderRows, p.numFolderColumns, p.minAllAppsPredictionColumns,
- p.iconSize, p.iconTextSize, p.numHotseatIcons, p.hotseatIconSize,
+ p.iconSize, p.landscapeIconSize, p.iconTextSize, p.numHotseatIcons,
p.defaultLayoutId);
}
InvariantDeviceProfile(String n, float w, float h, int r, int c, int fr, int fc, int maapc,
- float is, float its, int hs, float his, int dlId) {
+ float is, float lis, float its, int hs, int dlId) {
name = n;
minWidthDps = w;
minHeightDps = h;
@@ -115,12 +113,10 @@ public class InvariantDeviceProfile {
numFolderColumns = fc;
minAllAppsPredictionColumns = maapc;
iconSize = is;
+ landscapeIconSize = lis;
iconTextSize = its;
numHotseatIcons = hs;
- hotseatIconSize = his;
defaultLayoutId = dlId;
-
- hotseatScale = hotseatIconSize / iconSize;
}
@TargetApi(23)
@@ -153,17 +149,15 @@ public class InvariantDeviceProfile {
minAllAppsPredictionColumns = closestProfile.minAllAppsPredictionColumns;
iconSize = interpolatedDeviceProfileOut.iconSize;
+ landscapeIconSize = interpolatedDeviceProfileOut.landscapeIconSize;
iconBitmapSize = Utilities.pxFromDp(iconSize, dm);
iconTextSize = interpolatedDeviceProfileOut.iconTextSize;
- hotseatIconSize = interpolatedDeviceProfileOut.hotseatIconSize;
fillResIconDpi = getLauncherIconDensity(iconBitmapSize);
// If the partner customization apk contains any grid overrides, apply them
// Supported overrides: numRows, numColumns, iconSize
applyPartnerDeviceProfileOverrides(context, dm);
- hotseatScale = hotseatIconSize / iconSize;
-
Point realSize = new Point();
display.getRealSize(realSize);
// The real size never changes. smallSide and largeSide will remain the
@@ -211,9 +205,9 @@ public class InvariantDeviceProfile {
a.getInt(R.styleable.InvariantDeviceProfile_numFolderColumns, numColumns),
a.getInt(R.styleable.InvariantDeviceProfile_minAllAppsPredictionColumns, numColumns),
iconSize,
+ a.getFloat(R.styleable.InvariantDeviceProfile_landscapeIconSize, iconSize),
a.getFloat(R.styleable.InvariantDeviceProfile_iconTextSize, 0),
a.getInt(R.styleable.InvariantDeviceProfile_numHotseatIcons, numColumns),
- a.getFloat(R.styleable.InvariantDeviceProfile_hotseatIconSize, iconSize),
a.getResourceId(R.styleable.InvariantDeviceProfile_defaultLayoutId, 0)));
a.recycle();
}
@@ -305,19 +299,19 @@ public class InvariantDeviceProfile {
private void add(InvariantDeviceProfile p) {
iconSize += p.iconSize;
+ landscapeIconSize += p.landscapeIconSize;
iconTextSize += p.iconTextSize;
- hotseatIconSize += p.hotseatIconSize;
}
private InvariantDeviceProfile multiply(float w) {
iconSize *= w;
+ landscapeIconSize *= w;
iconTextSize *= w;
- hotseatIconSize *= w;
return this;
}
public int getAllAppsButtonRank() {
- if (ProviderConfig.IS_DOGFOOD_BUILD && FeatureFlags.NO_ALL_APPS_ICON) {
+ if (FeatureFlags.IS_DOGFOOD_BUILD && FeatureFlags.NO_ALL_APPS_ICON) {
throw new IllegalAccessError("Accessing all apps rank when all-apps is disabled");
}
return numHotseatIcons / 2;
diff --git a/src/com/android/launcher3/ItemInfo.java b/src/com/android/launcher3/ItemInfo.java
index 0779a3d206..11c5309f22 100644
--- a/src/com/android/launcher3/ItemInfo.java
+++ b/src/com/android/launcher3/ItemInfo.java
@@ -39,8 +39,10 @@ public class ItemInfo {
/**
* One of {@link LauncherSettings.Favorites#ITEM_TYPE_APPLICATION},
* {@link LauncherSettings.Favorites#ITEM_TYPE_SHORTCUT},
- * {@link LauncherSettings.Favorites#ITEM_TYPE_FOLDER}, or
- * {@link LauncherSettings.Favorites#ITEM_TYPE_APPWIDGET}.
+ * {@link LauncherSettings.Favorites#ITEM_TYPE_DEEP_SHORTCUT}
+ * {@link LauncherSettings.Favorites#ITEM_TYPE_FOLDER},
+ * {@link LauncherSettings.Favorites#ITEM_TYPE_APPWIDGET} or
+ * {@link LauncherSettings.Favorites#ITEM_TYPE_CUSTOM_APPWIDGET}.
*/
public int itemType;
@@ -53,7 +55,9 @@ public class ItemInfo {
public long container = NO_ID;
/**
- * Indicates the screen in which the shortcut appears.
+ * Indicates the screen in which the shortcut appears if the container types is
+ * {@link LauncherSettings.Favorites#CONTAINER_DESKTOP}. (i.e., ignore if the container type is
+ * {@link LauncherSettings.Favorites#CONTAINER_HOTSEAT})
*/
public long screenId = -1;
@@ -178,15 +182,12 @@ public class ItemInfo {
protected String dumpProperties() {
return "id=" + id
- + " type=" + itemType
- + " container=" + container
+ + " type=" + LauncherSettings.Favorites.itemTypeToString(itemType)
+ + " container=" + LauncherSettings.Favorites.containerToString((int)container)
+ " screen=" + screenId
- + " cellX=" + cellX
- + " cellY=" + cellY
- + " spanX=" + spanX
- + " spanY=" + spanY
- + " minSpanX=" + minSpanX
- + " minSpanY=" + minSpanY
+ + " cell(" + cellX + "," + cellY + ")"
+ + " span(" + spanX + "," + spanY + ")"
+ + " minSpan(" + minSpanX + "," + minSpanY + ")"
+ " rank=" + rank
+ " user=" + user
+ " title=" + title;
diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java
index 2de10030d9..26c5c9d00e 100644
--- a/src/com/android/launcher3/Launcher.java
+++ b/src/com/android/launcher3/Launcher.java
@@ -18,7 +18,9 @@ package com.android.launcher3;
import android.Manifest;
import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
+import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
@@ -65,6 +67,7 @@ import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.KeyboardShortcutGroup;
import android.view.KeyboardShortcutInfo;
+import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
@@ -76,27 +79,26 @@ import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.OvershootInterpolator;
import android.view.inputmethod.InputMethodManager;
-import android.widget.TextView;
import android.widget.Toast;
import com.android.launcher3.DropTarget.DragObject;
import com.android.launcher3.LauncherSettings.Favorites;
+import com.android.launcher3.Workspace.ItemOperator;
import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
import com.android.launcher3.allapps.AllAppsContainerView;
import com.android.launcher3.allapps.AllAppsTransitionController;
-import com.android.launcher3.allapps.DefaultAppSearchController;
import com.android.launcher3.anim.AnimationLayerSet;
import com.android.launcher3.compat.AppWidgetManagerCompat;
import com.android.launcher3.compat.LauncherAppsCompat;
-import com.android.launcher3.compat.PinItemRequestCompat;
+import com.android.launcher3.compat.LauncherAppsCompatVO;
import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.config.ProviderConfig;
import com.android.launcher3.dragndrop.DragController;
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.dragndrop.DragView;
import com.android.launcher3.dragndrop.PinItemDragListener;
import com.android.launcher3.dynamicui.ExtractedColors;
+import com.android.launcher3.dynamicui.WallpaperColorInfo;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.keyboard.CustomActionsPopup;
@@ -123,7 +125,9 @@ import com.android.launcher3.util.MultiHashMap;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.util.PendingRequestArgs;
+import com.android.launcher3.util.SystemUiController;
import com.android.launcher3.util.TestingUtils;
+import com.android.launcher3.util.Themes;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.util.ViewOnDrawExecutor;
import com.android.launcher3.widget.PendingAddShortcutInfo;
@@ -147,7 +151,8 @@ import java.util.Set;
public class Launcher extends BaseActivity
implements LauncherExterns, View.OnClickListener, OnLongClickListener,
LauncherModel.Callbacks, View.OnTouchListener, LauncherProviderChangeListener,
- AccessibilityManager.AccessibilityStateChangeListener {
+ AccessibilityManager.AccessibilityStateChangeListener,
+ WallpaperColorInfo.OnThemeChangeListener {
public static final String TAG = "Launcher";
static final boolean LOGD = false;
@@ -157,14 +162,15 @@ public class Launcher extends BaseActivity
private static final int REQUEST_CREATE_SHORTCUT = 1;
private static final int REQUEST_CREATE_APPWIDGET = 5;
+
private static final int REQUEST_PICK_APPWIDGET = 9;
private static final int REQUEST_PICK_WALLPAPER = 10;
private static final int REQUEST_BIND_APPWIDGET = 11;
- private static final int REQUEST_BIND_PENDING_APPWIDGET = 14;
- private static final int REQUEST_RECONFIGURE_APPWIDGET = 12;
+ private static final int REQUEST_BIND_PENDING_APPWIDGET = 12;
+ private static final int REQUEST_RECONFIGURE_APPWIDGET = 13;
- private static final int REQUEST_PERMISSION_CALL_PHONE = 13;
+ private static final int REQUEST_PERMISSION_CALL_PHONE = 14;
private static final float BOUNCE_ANIMATION_TENSION = 1.3f;
@@ -209,22 +215,23 @@ public class Launcher extends BaseActivity
private static final int ACTIVITY_START_DELAY = 1000;
// How long to wait before the new-shortcut animation automatically pans the workspace
- private static int NEW_APPS_PAGE_MOVE_DELAY = 500;
- private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 5;
- @Thunk static int NEW_APPS_ANIMATION_DELAY = 500;
+ private static final int NEW_APPS_PAGE_MOVE_DELAY = 500;
+ private static final int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 5;
+ @Thunk static final int NEW_APPS_ANIMATION_DELAY = 500;
+
+ private final ExtractedColors mExtractedColors = new ExtractedColors();
@Thunk Workspace mWorkspace;
private View mLauncherView;
@Thunk DragLayer mDragLayer;
private DragController mDragController;
- private View mQsbContainer;
public View mWeightWatcher;
private AppWidgetManagerCompat mAppWidgetManager;
private LauncherAppWidgetHost mAppWidgetHost;
- private int[] mTmpAddItemCellCoordinates = new int[2];
+ private final int[] mTmpAddItemCellCoordinates = new int[2];
@Thunk Hotseat mHotseat;
private ViewGroup mOverviewPanel;
@@ -254,19 +261,19 @@ public class Launcher extends BaseActivity
private boolean mPaused = true;
private boolean mOnResumeNeedsLoad;
- private ArrayList mBindOnResumeCallbacks = new ArrayList();
- private ArrayList mOnResumeCallbacks = new ArrayList();
+ private final ArrayList mBindOnResumeCallbacks = new ArrayList<>();
+ private final ArrayList mOnResumeCallbacks = new ArrayList<>();
private ViewOnDrawExecutor mPendingExecutor;
private LauncherModel mModel;
private ModelWriter mModelWriter;
private IconCache mIconCache;
- private ExtractedColors mExtractedColors;
private LauncherAccessibilityDelegate mAccessibilityDelegate;
- private Handler mHandler = new Handler();
+ private final Handler mHandler = new Handler();
private boolean mIsResumeFromActionScreenOff;
private boolean mHasFocus = false;
- private boolean mAttached = false;
+
+ private ObjectAnimator mScrimAnimator;
private PopupDataProvider mPopupDataProvider;
@@ -276,7 +283,7 @@ public class Launcher extends BaseActivity
// match the sensor state.
private static final int RESTORE_SCREEN_ORIENTATION_DELAY = 500;
- private final ArrayList mSynchronouslyBoundPages = new ArrayList();
+ private final ArrayList mSynchronouslyBoundPages = new ArrayList<>();
// We only want to get the SharedPreferences once since it does an FS stat each time we get
// it from the context.
@@ -289,8 +296,8 @@ public class Launcher extends BaseActivity
// the press state and keep this reference to reset the press state when we return to launcher.
private BubbleTextView mWaitingForResume;
- protected static HashMap sCustomAppWidgets =
- new HashMap();
+ protected static final HashMap sCustomAppWidgets =
+ new HashMap<>();
static {
if (TestingUtils.ENABLE_CUSTOM_WIDGET_TEST) {
@@ -303,7 +310,7 @@ public class Launcher extends BaseActivity
// simply unregister this runnable.
private Runnable mExitSpringLoadedModeRunnable;
- @Thunk Runnable mBuildLayersRunnable = new Runnable() {
+ @Thunk final Runnable mBuildLayersRunnable = new Runnable() {
public void run() {
if (mWorkspace != null) {
mWorkspace.buildPageHardwareLayers();
@@ -359,6 +366,10 @@ public class Launcher extends BaseActivity
mLauncherCallbacks.preOnCreate();
}
+ WallpaperColorInfo wallpaperColorInfo = WallpaperColorInfo.getInstance(this);
+ wallpaperColorInfo.setOnThemeChangeListener(this);
+ overrideTheme(wallpaperColorInfo.isDark(), wallpaperColorInfo.supportsDarkText());
+
super.onCreate(savedInstanceState);
LauncherAppState app = LauncherAppState.getInstance(this);
@@ -393,11 +404,10 @@ public class Launcher extends BaseActivity
// LauncherModel load.
mPaused = false;
- mLauncherView = getLayoutInflater().inflate(R.layout.launcher, null);
+ mLauncherView = LayoutInflater.from(this).inflate(R.layout.launcher, null);
setupViews();
mDeviceProfile.layout(this, false /* notifyListeners */);
- mExtractedColors = new ExtractedColors();
loadExtractedColorsAndColorItems();
mPopupDataProvider = new PopupDataProvider(this);
@@ -456,6 +466,25 @@ public class Launcher extends BaseActivity
if (mLauncherCallbacks != null) {
mLauncherCallbacks.onCreate(savedInstanceState);
}
+
+ // Listen for broadcasts screen off
+ registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
+
+ getSystemUiController().updateUiState(SystemUiController.UI_STATE_BASE_WINDOW,
+ Themes.getAttrBoolean(this, R.attr.isWorkspaceDarkText));
+ }
+
+ @Override
+ public void onThemeChanged() {
+ recreate();
+ }
+
+ protected void overrideTheme(boolean isDark, boolean supportsDarkText) {
+ if (isDark) {
+ setTheme(R.style.LauncherThemeDark);
+ } else if (supportsDarkText) {
+ setTheme(R.style.LauncherThemeDarkText);
+ }
}
@Override
@@ -466,6 +495,11 @@ public class Launcher extends BaseActivity
@Override
public void onExtractedColorsChanged() {
loadExtractedColorsAndColorItems();
+ mExtractedColors.notifyChange();
+ }
+
+ public ExtractedColors getExtractedColors() {
+ return mExtractedColors;
}
@Override
@@ -481,46 +515,6 @@ public class Launcher extends BaseActivity
mExtractedColors.load(this);
mHotseat.updateColor(mExtractedColors, !mPaused);
mWorkspace.getPageIndicator().updateColor(mExtractedColors);
- boolean lightStatusBar = (FeatureFlags.LIGHT_STATUS_BAR
- && mExtractedColors.getColor(ExtractedColors.STATUS_BAR_INDEX,
- ExtractedColors.DEFAULT_DARK) == ExtractedColors.DEFAULT_LIGHT);
- // It's possible that All Apps is visible when this is run,
- // so always use light status bar in that case. Only change nav bar color to status bar
- // color when All Apps is visible.
- activateLightSystemBars(lightStatusBar || isAllAppsVisible(), true, isAllAppsVisible());
- }
- }
-
- // TODO: use platform flag on API >= 26
- private static final int SYSTEM_UI_FLAG_LIGHT_NAV_BAR = 0x10;
-
- /**
- * Sets the status and/or nav bar to be light or not. Light status bar means dark icons.
- * @param isLight make sure the system bar is light.
- * @param statusBar if true, make the status bar theme match the isLight param.
- * @param navBar if true, make the nav bar theme match the isLight param.
- */
- public void activateLightSystemBars(boolean isLight, boolean statusBar, boolean navBar) {
- int oldSystemUiFlags = getWindow().getDecorView().getSystemUiVisibility();
- int newSystemUiFlags = oldSystemUiFlags;
- if (isLight) {
- if (statusBar) {
- newSystemUiFlags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
- }
- if (navBar && Utilities.isAtLeastO()) {
- newSystemUiFlags |= SYSTEM_UI_FLAG_LIGHT_NAV_BAR;
- }
- } else {
- if (statusBar) {
- newSystemUiFlags &= ~(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
- }
- if (navBar && Utilities.isAtLeastO()) {
- newSystemUiFlags &= ~(SYSTEM_UI_FLAG_LIGHT_NAV_BAR);
- }
- }
-
- if (newSystemUiFlags != oldSystemUiFlags) {
- getWindow().getDecorView().setSystemUiVisibility(newSystemUiFlags);
}
}
@@ -550,47 +544,6 @@ public class Launcher extends BaseActivity
public boolean setLauncherCallbacks(LauncherCallbacks callbacks) {
mLauncherCallbacks = callbacks;
- mLauncherCallbacks.setLauncherSearchCallback(new Launcher.LauncherSearchCallbacks() {
- private boolean mWorkspaceImportanceStored = false;
- private boolean mHotseatImportanceStored = false;
- private int mWorkspaceImportanceForAccessibility =
- View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
- private int mHotseatImportanceForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
-
- @Override
- public void onSearchOverlayOpened() {
- if (mWorkspaceImportanceStored || mHotseatImportanceStored) {
- return;
- }
- // The underlying workspace and hotseat are temporarily suppressed by the search
- // overlay. So they shouldn't be accessible.
- if (mWorkspace != null) {
- mWorkspaceImportanceForAccessibility =
- mWorkspace.getImportantForAccessibility();
- mWorkspace.setImportantForAccessibility(
- View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
- mWorkspaceImportanceStored = true;
- }
- if (mHotseat != null) {
- mHotseatImportanceForAccessibility = mHotseat.getImportantForAccessibility();
- mHotseat.setImportantForAccessibility(
- View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
- mHotseatImportanceStored = true;
- }
- }
-
- @Override
- public void onSearchOverlayClosed() {
- if (mWorkspaceImportanceStored && mWorkspace != null) {
- mWorkspace.setImportantForAccessibility(mWorkspaceImportanceForAccessibility);
- }
- if (mHotseatImportanceStored && mHotseat != null) {
- mHotseat.setImportantForAccessibility(mHotseatImportanceForAccessibility);
- }
- mWorkspaceImportanceStored = false;
- mHotseatImportanceStored = false;
- }
- });
return true;
}
@@ -952,6 +905,24 @@ public class Launcher extends BaseActivity
if (!isWorkspaceLoading()) {
NotificationListener.setNotificationsChangedListener(mPopupDataProvider);
}
+
+ if (mIsResumeFromActionScreenOff && mDragLayer.getBackground() != null) {
+ if (mScrimAnimator != null) {
+ mScrimAnimator.cancel();
+ }
+ mDragLayer.getBackground().setAlpha(0);
+ mScrimAnimator = ObjectAnimator.ofInt(mDragLayer.getBackground(),
+ LauncherAnimUtils.DRAWABLE_ALPHA, 0, 255);
+ mScrimAnimator.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ mScrimAnimator = null;
+ }
+ });
+ mScrimAnimator.setDuration(600);
+ mScrimAnimator.setStartDelay(getWindow().getTransitionBackgroundFadeDuration());
+ mScrimAnimator.start();
+ }
}
@Override
@@ -977,8 +948,7 @@ public class Launcher extends BaseActivity
// Don't update the predicted apps if the user is returning to launcher in the apps
// view after launching an app, as they may be depending on the UI to be static to
// switch to another app, otherwise, if it was
- showAppsView(false /* animated */, !launchedFromApp /* updatePredictedApps */,
- mAppsView.shouldRestoreImeState() /* focusSearchBar */);
+ showAppsView(false /* animated */, !launchedFromApp /* updatePredictedApps */);
} else if (mOnResumeState == State.WIDGETS) {
showWidgetsView(false, false);
}
@@ -1051,13 +1021,12 @@ public class Launcher extends BaseActivity
updateInteraction(Workspace.State.NORMAL, mWorkspace.getState());
mWorkspace.onResume();
- if (!isWorkspaceLoading()) {
- // Process any items that were added while Launcher was away.
- InstallShortcutReceiver.disableAndFlushInstallQueue(this);
+ // Process any items that were added while Launcher was away.
+ InstallShortcutReceiver.disableAndFlushInstallQueue(
+ InstallShortcutReceiver.FLAG_ACTIVITY_PAUSED, this);
- // Refresh shortcuts if the permission changed.
- mModel.refreshShortcutsIfRequired();
- }
+ // Refresh shortcuts if the permission changed.
+ mModel.refreshShortcutsIfRequired();
if (shouldShowDiscoveryBounce()) {
mAllAppsController.showDiscoveryBounce();
@@ -1072,7 +1041,7 @@ public class Launcher extends BaseActivity
@Override
protected void onPause() {
// Ensure that items added to Launcher are queued until Launcher returns
- InstallShortcutReceiver.enableInstallQueue();
+ InstallShortcutReceiver.enableInstallQueue(InstallShortcutReceiver.FLAG_ACTIVITY_PAUSED);
super.onPause();
mPaused = true;
@@ -1093,13 +1062,13 @@ public class Launcher extends BaseActivity
public interface CustomContentCallbacks {
// Custom content is completely shown. {@code fromResume} indicates whether this was caused
// by a onResume or by scrolling otherwise.
- public void onShow(boolean fromResume);
+ void onShow(boolean fromResume);
// Custom content is completely hidden
- public void onHide();
+ void onHide();
// Custom content scroll progress changed. From 0 (not showing) to 1 (fully showing).
- public void onScrollProgressChanged(float progress);
+ void onScrollProgressChanged(float progress);
// Indicates whether the user is allowed to scroll away from the custom content.
boolean isScrollingAllowed();
@@ -1110,40 +1079,28 @@ public class Launcher extends BaseActivity
/**
* Touch interaction leading to overscroll has begun
*/
- public void onScrollInteractionBegin();
+ void onScrollInteractionBegin();
/**
* Touch interaction related to overscroll has ended
*/
- public void onScrollInteractionEnd();
+ void onScrollInteractionEnd();
/**
* Scroll progress, between 0 and 100, when the user scrolls beyond the leftmost
* screen (or in the case of RTL, the rightmost screen).
*/
- public void onScrollChange(float progress, boolean rtl);
+ void onScrollChange(float progress, boolean rtl);
/**
* Called when the launcher is ready to use the overlay
* @param callbacks A set of callbacks provided by Launcher in relation to the overlay
*/
- public void setOverlayCallbacks(LauncherOverlayCallbacks callbacks);
- }
-
- public interface LauncherSearchCallbacks {
- /**
- * Called when the search overlay is shown.
- */
- public void onSearchOverlayOpened();
-
- /**
- * Called when the search overlay is dismissed.
- */
- public void onSearchOverlayClosed();
+ void setOverlayCallbacks(LauncherOverlayCallbacks callbacks);
}
public interface LauncherOverlayCallbacks {
- public void onScrollChanged(float progress);
+ void onScrollChanged(float progress);
}
class LauncherOverlayCallbacksImpl implements LauncherOverlayCallbacks {
@@ -1297,9 +1254,7 @@ public class Launcher extends BaseActivity
private void setupViews() {
mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
mFocusHandler = mDragLayer.getFocusIndicatorHelper();
- mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
- mQsbContainer = mDragLayer.findViewById(mDeviceProfile.isVerticalBarLayout()
- ? R.id.workspace_blocked_row : R.id.qsb_container);
+ mWorkspace = mDragLayer.findViewById(R.id.workspace);
mWorkspace.initParentViews(mDragLayer);
mLauncherView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
@@ -1329,16 +1284,11 @@ public class Launcher extends BaseActivity
mDragController.addDragListener(mWorkspace);
// Get the search/delete/uninstall bar
- mDropTargetBar = (DropTargetBar) mDragLayer.findViewById(R.id.drop_target_bar);
+ mDropTargetBar = mDragLayer.findViewById(R.id.drop_target_bar);
// Setup Apps and Widgets
mAppsView = (AllAppsContainerView) findViewById(R.id.apps_view);
mWidgetsView = (WidgetsContainerView) findViewById(R.id.widgets_view);
- if (mLauncherCallbacks != null && mLauncherCallbacks.getAllAppsSearchBarController() != null) {
- mAppsView.setSearchBarController(mLauncherCallbacks.getAllAppsSearchBarController());
- } else {
- mAppsView.setSearchBarController(new DefaultAppSearchController());
- }
// Setup the drag controller (drop targets have to be added in reverse order in priority)
mDragController.setMoveTarget(mWorkspace);
@@ -1429,34 +1379,33 @@ public class Launcher extends BaseActivity
* @return A View inflated from layoutResId.
*/
public View createShortcut(ViewGroup parent, ShortcutInfo info) {
- BubbleTextView favorite = (BubbleTextView) getLayoutInflater().inflate(R.layout.app_icon,
- parent, false);
+ BubbleTextView favorite = (BubbleTextView) LayoutInflater.from(parent.getContext())
+ .inflate(R.layout.app_icon, parent, false);
favorite.applyFromShortcutInfo(info);
- favorite.setCompoundDrawablePadding(mDeviceProfile.iconDrawablePaddingPx);
favorite.setOnClickListener(this);
favorite.setOnFocusChangeListener(mFocusHandler);
return favorite;
}
/**
- * Add a shortcut to the workspace.
+ * Add a shortcut to the workspace or to a Folder.
*
* @param data The intent describing the shortcut.
*/
private void completeAddShortcut(Intent data, long container, long screenId, int cellX,
int cellY, PendingRequestArgs args) {
- int[] cellXY = mTmpAddItemCellCoordinates;
- CellLayout layout = getCellLayout(container, screenId);
-
- if (args.getRequestCode() != REQUEST_CREATE_SHORTCUT ||
- args.getPendingIntent().getComponent() == null) {
+ if (args.getRequestCode() != REQUEST_CREATE_SHORTCUT
+ || args.getPendingIntent().getComponent() == null) {
return;
}
+ int[] cellXY = mTmpAddItemCellCoordinates;
+ CellLayout layout = getCellLayout(container, screenId);
+
ShortcutInfo info = null;
if (Utilities.isAtLeastO()) {
- info = LauncherAppsCompat.createShortcutInfoFromPinItemRequest(
- this, PinItemRequestCompat.getPinItemRequest(data), 0);
+ info = LauncherAppsCompatVO.createShortcutInfoFromPinItemRequest(
+ this, LauncherAppsCompatVO.getPinItemRequest(data), 0);
}
if (info == null) {
@@ -1475,36 +1424,55 @@ public class Launcher extends BaseActivity
}
}
- final View view = createShortcut(info);
- boolean foundCellSpan = false;
- // First we check if we already know the exact location where we want to add this item.
- if (cellX >= 0 && cellY >= 0) {
- cellXY[0] = cellX;
- cellXY[1] = cellY;
- foundCellSpan = true;
+ if (container < 0) {
+ // Adding a shortcut to the Workspace.
+ final View view = createShortcut(info);
+ boolean foundCellSpan = false;
+ // First we check if we already know the exact location where we want to add this item.
+ if (cellX >= 0 && cellY >= 0) {
+ cellXY[0] = cellX;
+ cellXY[1] = cellY;
+ foundCellSpan = true;
- // If appropriate, either create a folder or add to an existing folder
- if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
- true, null,null)) {
- return;
- }
- DragObject dragObject = new DragObject();
- dragObject.dragInfo = info;
- if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
- true)) {
+ // If appropriate, either create a folder or add to an existing folder
+ if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
+ true, null, null)) {
+ return;
+ }
+ DragObject dragObject = new DragObject();
+ dragObject.dragInfo = info;
+ if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
+ true)) {
+ return;
+ }
+ } else {
+ foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
+ }
+
+ if (!foundCellSpan) {
+ mWorkspace.onNoCellFound(layout);
return;
}
+
+ getModelWriter().addItemToDatabase(info, container, screenId, cellXY[0], cellXY[1]);
+ mWorkspace.addInScreen(view, info);
} else {
- foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
- }
+ // Adding a shortcut to a Folder.
+ final long folderIconId = container;
+ FolderIcon folderIcon = (FolderIcon) mWorkspace.getFirstMatch(new ItemOperator() {
+ @Override
+ public boolean evaluate(ItemInfo info, View view) {
+ return info != null && info.id == folderIconId;
+ }
+ });
- if (!foundCellSpan) {
- mWorkspace.onNoCellFound(layout);
- return;
+ if (folderIcon != null) {
+ FolderInfo folderInfo = (FolderInfo) folderIcon.getTag();
+ folderInfo.add(info, args.rank, false);
+ } else {
+ Log.e(TAG, "Could not find folder with id " + folderIconId + " to add shortcut.");
+ }
}
-
- getModelWriter().addItemToDatabase(info, container, screenId, cellXY[0], cellXY[1]);
- mWorkspace.addInScreen(view, info);
}
/**
@@ -1592,13 +1560,7 @@ public class Launcher extends BaseActivity
public void onAttachedToWindow() {
super.onAttachedToWindow();
- // Listen for broadcasts related to user-presence
- final IntentFilter filter = new IntentFilter();
- filter.addAction(Intent.ACTION_SCREEN_OFF);
- registerReceiver(mReceiver, filter);
FirstFrameAnimatorHelper.initializeDrawListener(getWindow().getDecorView());
- mAttached = true;
-
if (mLauncherCallbacks != null) {
mLauncherCallbacks.onAttachedToWindow();
}
@@ -1607,10 +1569,6 @@ public class Launcher extends BaseActivity
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
- if (mAttached) {
- unregisterReceiver(mReceiver);
- mAttached = false;
- }
if (mLauncherCallbacks != null) {
mLauncherCallbacks.onDetachedFromWindow();
@@ -1648,7 +1606,6 @@ public class Launcher extends BaseActivity
}
}
});
- return;
}
});
}
@@ -1672,10 +1629,6 @@ public class Launcher extends BaseActivity
return mWorkspace;
}
- public View getQsbContainer() {
- return mQsbContainer;
- }
-
public Hotseat getHotseat() {
return mHotseat;
}
@@ -1767,7 +1720,7 @@ public class Launcher extends BaseActivity
// Reset the apps view
if (!alreadyOnHome && mAppsView != null) {
- mAppsView.scrollToTop();
+ mAppsView.reset();
}
// Reset the widgets view
@@ -1789,8 +1742,9 @@ public class Launcher extends BaseActivity
// as slow logic in the callbacks eat into the time the scroller expects for the snapToPage
// animation.
if (isActionMain) {
- boolean callbackAllowsMoveToDefaultScreen = mLauncherCallbacks != null ?
- mLauncherCallbacks.shouldMoveToDefaultScreenOnHomeIntent() : true;
+ boolean callbackAllowsMoveToDefaultScreen =
+ mLauncherCallbacks == null || mLauncherCallbacks
+ .shouldMoveToDefaultScreenOnHomeIntent();
if (shouldMoveToDefaultScreen && !mWorkspace.isTouchActive()
&& callbackAllowsMoveToDefaultScreen) {
@@ -1851,6 +1805,7 @@ public class Launcher extends BaseActivity
public void onDestroy() {
super.onDestroy();
+ unregisterReceiver(mReceiver);
mWorkspace.removeCallbacks(mBuildLayersRunnable);
mWorkspace.removeFolderListeners();
@@ -1878,6 +1833,8 @@ public class Launcher extends BaseActivity
((AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE))
.removeAccessibilityStateChangeListener(this);
+ WallpaperColorInfo.getInstance(this).setOnThemeChangeListener(null);
+
LauncherAnimUtils.onDestroyActivity();
if (mLauncherCallbacks != null) {
@@ -2361,18 +2318,7 @@ public class Launcher extends BaseActivity
if (!isAppsViewVisible()) {
getUserEventDispatcher().logActionOnControl(Action.Touch.TAP,
ControlType.ALL_APPS_BUTTON);
- showAppsView(true /* animated */, true /* updatePredictedApps */,
- false /* focusSearchBar */);
- }
- }
-
- protected void onLongClickAllAppsButton(View v) {
- if (LOGD) Log.d(TAG, "onLongClickAllAppsButton");
- if (!isAppsViewVisible()) {
- getUserEventDispatcher().logActionOnControl(Action.Touch.LONGPRESS,
- ControlType.ALL_APPS_BUTTON);
- showAppsView(true /* animated */,
- true /* updatePredictedApps */, true /* focusSearchBar */);
+ showAppsView(true /* animated */, true /* updatePredictedApps */);
}
}
@@ -2469,7 +2415,13 @@ public class Launcher extends BaseActivity
private void startAppShortcutOrInfoActivity(View v) {
ItemInfo item = (ItemInfo) v.getTag();
- Intent intent = item.getIntent();
+ Intent intent;
+ if (item instanceof PromiseAppInfo) {
+ PromiseAppInfo promiseAppInfo = (PromiseAppInfo) item;
+ intent = promiseAppInfo.getMarketIntent();
+ } else {
+ intent = item.getIntent();
+ }
if (intent == null) {
throw new IllegalArgumentException("Input must have a valid intent");
}
@@ -2530,8 +2482,8 @@ public class Launcher extends BaseActivity
.putExtra(Utilities.EXTRA_WALLPAPER_OFFSET, offset);
String pickerPackage = getString(R.string.wallpaper_picker_package);
- boolean hasTargetPackage = TextUtils.isEmpty(pickerPackage);
- if (!hasTargetPackage) {
+ boolean hasTargetPackage = !TextUtils.isEmpty(pickerPackage);
+ if (hasTargetPackage) {
intent.setPackage(pickerPackage);
}
@@ -2673,9 +2625,9 @@ public class Launcher extends BaseActivity
if (Utilities.ATLEAST_MARSHMALLOW) {
int left = 0, top = 0;
int width = v.getMeasuredWidth(), height = v.getMeasuredHeight();
- if (v instanceof TextView) {
+ if (v instanceof BubbleTextView) {
// Launch from center of icon, not entire view
- Drawable icon = Workspace.getTextViewIcon((TextView) v);
+ Drawable icon = ((BubbleTextView) v).getIcon();
if (icon != null) {
Rect bounds = icon.getBounds();
left = (width - bounds.width()) / 2;
@@ -2754,13 +2706,6 @@ public class Launcher extends BaseActivity
if (isWorkspaceLocked()) return false;
if (mState != State.WORKSPACE) return false;
- if ((FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP && v instanceof PageIndicator) ||
- (v == mAllAppsButton && mAllAppsButton != null)) {
- onLongClickAllAppsButton(v);
- return true;
- }
-
-
boolean ignoreLongPressToOverview =
mDeviceProfile.shouldIgnoreLongPressToOverview(mLastDispatchTouchEventX);
@@ -2960,13 +2905,12 @@ public class Launcher extends BaseActivity
/**
* Shows the apps view.
*/
- public void showAppsView(boolean animated, boolean updatePredictedApps,
- boolean focusSearchBar) {
+ public void showAppsView(boolean animated, boolean updatePredictedApps) {
markAppsViewShown();
if (updatePredictedApps) {
tryAndUpdatePredictedApps();
}
- showAppsOrWidgets(State.APPS, animated, focusSearchBar);
+ showAppsOrWidgets(State.APPS, animated);
}
/**
@@ -2977,7 +2921,7 @@ public class Launcher extends BaseActivity
if (resetPageToZero) {
mWidgetsView.scrollToTop();
}
- showAppsOrWidgets(State.WIDGETS, animated, false);
+ showAppsOrWidgets(State.WIDGETS, animated);
mWidgetsView.post(new Runnable() {
@Override
@@ -2994,7 +2938,7 @@ public class Launcher extends BaseActivity
*/
// TODO: calling method should use the return value so that when {@code false} is returned
// the workspace transition doesn't fall into invalid state.
- private boolean showAppsOrWidgets(State toState, boolean animated, boolean focusSearchBar) {
+ private boolean showAppsOrWidgets(State toState, boolean animated) {
if (!(mState == State.WORKSPACE ||
mState == State.APPS_SPRING_LOADED ||
mState == State.WIDGETS_SPRING_LOADED ||
@@ -3012,7 +2956,7 @@ public class Launcher extends BaseActivity
}
if (toState == State.APPS) {
- mStateTransitionAnimation.startAnimationToAllApps(animated, focusSearchBar);
+ mStateTransitionAnimation.startAnimationToAllApps(animated);
} else {
mStateTransitionAnimation.startAnimationToWidgets(animated);
}
@@ -3085,8 +3029,7 @@ public class Launcher extends BaseActivity
public void exitSpringLoadedDragMode() {
if (mState == State.APPS_SPRING_LOADED) {
- showAppsView(true /* animated */,
- false /* updatePredictedApps */, false /* focusSearchBar */);
+ showAppsView(true /* animated */, false /* updatePredictedApps */);
} else if (mState == State.WIDGETS_SPRING_LOADED) {
showWidgetsView(true, false);
} else if (mState == State.WORKSPACE_SPRING_LOADED) {
@@ -3252,7 +3195,7 @@ public class Launcher extends BaseActivity
orderedScreenIds.indexOf(Workspace.FIRST_SCREEN_ID) != 0) {
orderedScreenIds.remove(Workspace.FIRST_SCREEN_ID);
orderedScreenIds.add(0, Workspace.FIRST_SCREEN_ID);
- mModel.updateWorkspaceScreenOrder(this, orderedScreenIds);
+ LauncherModel.updateWorkspaceScreenOrder(this, orderedScreenIds);
} else if (!FeatureFlags.QSB_ON_FIRST_SCREEN && orderedScreenIds.isEmpty()) {
// If there are no screens, we need to have an empty screen
mWorkspace.addExtraEmptyScreen();
@@ -3339,7 +3282,7 @@ public class Launcher extends BaseActivity
// Get the list of added items and intersect them with the set of items here
final AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
- final Collection bounceAnims = new ArrayList();
+ final Collection bounceAnims = new ArrayList<>();
final boolean animateIcons = forceAnimateIcons && canRunNewAppsAnimation();
Workspace workspace = mWorkspace;
long newItemsScreenId = -1;
@@ -3397,7 +3340,7 @@ public class Launcher extends BaseActivity
Object tag = v.getTag();
String desc = "Collision while binding workspace item: " + item
+ ". Collides with " + tag;
- if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_DOGFOOD_BUILD) {
throw (new RuntimeException(desc));
} else {
Log.d(TAG, desc);
@@ -3600,6 +3543,9 @@ public class Launcher extends BaseActivity
LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
info.restoreStatus = finalRestoreFlag;
+ if (info.restoreStatus == LauncherAppWidgetInfo.RESTORE_COMPLETED) {
+ info.pendingItemInfo = null;
+ }
mWorkspace.reinflateWidgetsIfNecessary();
getModelWriter().updateItemInDatabase(info);
@@ -3678,7 +3624,8 @@ public class Launcher extends BaseActivity
mPendingActivityResult = null;
}
- InstallShortcutReceiver.disableAndFlushInstallQueue(this);
+ InstallShortcutReceiver.disableAndFlushInstallQueue(
+ InstallShortcutReceiver.FLAG_LOADER_RUNNING, this);
NotificationListener.setNotificationsChangedListener(mPopupDataProvider);
@@ -3719,7 +3666,7 @@ public class Launcher extends BaseActivity
* multiple calls to bind the same list.)
*/
@Thunk ArrayList mTmpAppsList;
- private Runnable mBindAllApplicationsRunnable = new Runnable() {
+ private final Runnable mBindAllApplicationsRunnable = new Runnable() {
public void run() {
bindAllApplications(mTmpAppsList);
mTmpAppsList = null;
@@ -3774,6 +3721,22 @@ public class Launcher extends BaseActivity
}
}
+ @Override
+ public void bindPromiseAppProgressUpdated(final PromiseAppInfo app) {
+ Runnable r = new Runnable() {
+ public void run() {
+ bindPromiseAppProgressUpdated(app);
+ }
+ };
+ if (waitUntilResume(r)) {
+ return;
+ }
+
+ if (mAppsView != null) {
+ mAppsView.updatePromiseAppProgress(app);
+ }
+ }
+
@Override
public void bindWidgetsRestored(final ArrayList widgets) {
Runnable r = new Runnable() {
@@ -3907,7 +3870,7 @@ public class Launcher extends BaseActivity
}
}
- private Runnable mBindAllWidgetsRunnable = new Runnable() {
+ private final Runnable mBindAllWidgetsRunnable = new Runnable() {
public void run() {
bindAllWidgets(mAllWidgets);
}
@@ -3947,7 +3910,7 @@ public class Launcher extends BaseActivity
* refreshes the widgets and shortcuts associated with the given package/user
*/
public void refreshAndBindWidgetsForPackageUser(@Nullable PackageUserKey packageUser) {
- mModel.refreshAndBindWidgetsAndShortcuts(this, mWidgetsView.isEmpty(), packageUser);
+ mModel.refreshAndBindWidgetsAndShortcuts(packageUser);
}
public void lockScreenOrientation() {
@@ -3978,7 +3941,7 @@ public class Launcher extends BaseActivity
}
private boolean shouldShowDiscoveryBounce() {
- if (mState != mState.WORKSPACE) {
+ if (mState != State.WORKSPACE) {
return false;
}
if (mLauncherCallbacks != null && mLauncherCallbacks.shouldShowDiscoveryBounce()) {
@@ -3987,10 +3950,7 @@ public class Launcher extends BaseActivity
if (!mIsResumeFromActionScreenOff) {
return false;
}
- if (mSharedPrefs.getBoolean(APPS_VIEW_SHOWN, false)) {
- return false;
- }
- return true;
+ return !mSharedPrefs.getBoolean(APPS_VIEW_SHOWN, false);
}
protected void moveWorkspaceToDefaultScreen() {
@@ -4079,7 +4039,7 @@ public class Launcher extends BaseActivity
switch (keyCode) {
case KeyEvent.KEYCODE_A:
if (mState == State.WORKSPACE) {
- showAppsView(true, true, false);
+ showAppsView(true, true);
return true;
}
break;
@@ -4126,9 +4086,8 @@ public class Launcher extends BaseActivity
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (Utilities.ALLOW_ROTATION_PREFERENCE_KEY.equals(key)) {
- // Finish this instance of the activity. When the activity is recreated,
- // it will initialize the rotation preference again.
- finish();
+ // Recreate the activity so that it initializes the rotation preference again.
+ recreate();
}
}
}
diff --git a/src/com/android/launcher3/LauncherAnimUtils.java b/src/com/android/launcher3/LauncherAnimUtils.java
index aa7f5ee5fe..cfb9b570b0 100644
--- a/src/com/android/launcher3/LauncherAnimUtils.java
+++ b/src/com/android/launcher3/LauncherAnimUtils.java
@@ -21,11 +21,10 @@ import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
+import android.graphics.drawable.Drawable;
import android.util.Property;
import android.view.View;
-import android.view.ViewGroup;
import android.view.ViewTreeObserver;
-import android.widget.ViewAnimator;
import java.util.HashSet;
import java.util.WeakHashMap;
@@ -130,4 +129,16 @@ public class LauncherAnimUtils {
return anim;
}
+ public static final Property DRAWABLE_ALPHA =
+ new Property(Integer.TYPE, "drawableAlpha") {
+ @Override
+ public Integer get(Drawable drawable) {
+ return drawable.getAlpha();
+ }
+
+ @Override
+ public void set(Drawable drawable, Integer alpha) {
+ drawable.setAlpha(alpha);
+ }
+ };
}
diff --git a/src/com/android/launcher3/LauncherAppState.java b/src/com/android/launcher3/LauncherAppState.java
index 180c202fa4..cf20febd5b 100644
--- a/src/com/android/launcher3/LauncherAppState.java
+++ b/src/com/android/launcher3/LauncherAppState.java
@@ -26,7 +26,7 @@ import android.util.Log;
import com.android.launcher3.compat.LauncherAppsCompat;
import com.android.launcher3.compat.PackageInstallerCompat;
import com.android.launcher3.compat.UserManagerCompat;
-import com.android.launcher3.config.ProviderConfig;
+import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.dynamicui.ExtractionUtils;
import com.android.launcher3.util.ConfigMonitor;
import com.android.launcher3.util.Preconditions;
@@ -37,7 +37,7 @@ import java.util.concurrent.ExecutionException;
public class LauncherAppState {
- public static final boolean PROFILE_STARTUP = ProviderConfig.IS_DOGFOOD_BUILD;
+ public static final boolean PROFILE_STARTUP = FeatureFlags.IS_DOGFOOD_BUILD;
// We do not need any synchronization for this variable as its only written on UI thread.
private static LauncherAppState INSTANCE;
@@ -93,9 +93,7 @@ public class LauncherAppState {
mInvariantDeviceProfile = new InvariantDeviceProfile(mContext);
mIconCache = new IconCache(mContext, mInvariantDeviceProfile);
mWidgetCache = new WidgetPreviewLoader(mContext, mIconCache);
-
- mModel = new LauncherModel(this, mIconCache,
- Utilities.getOverrideObject(AppFilter.class, mContext, R.string.app_filter_class));
+ mModel = new LauncherModel(this, mIconCache, AppFilter.newInstance(mContext));
LauncherAppsCompat.getInstance(mContext).addOnAppsChangedCallback(mModel);
diff --git a/src/com/android/launcher3/LauncherAppWidgetHostView.java b/src/com/android/launcher3/LauncherAppWidgetHostView.java
index 13cc7ba077..c7b778252a 100644
--- a/src/com/android/launcher3/LauncherAppWidgetHostView.java
+++ b/src/com/android/launcher3/LauncherAppWidgetHostView.java
@@ -23,7 +23,6 @@ import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Handler;
import android.os.SystemClock;
-import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
@@ -40,9 +39,7 @@ import android.widget.RemoteViews;
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.dragndrop.DragLayer.TouchCompleteListener;
-import java.lang.reflect.Method;
import java.util.ArrayList;
-import java.util.concurrent.Executor;
/**
* {@inheritDoc}
@@ -50,8 +47,6 @@ import java.util.concurrent.Executor;
public class LauncherAppWidgetHostView extends AppWidgetHostView
implements TouchCompleteListener, View.OnLongClickListener {
- private static final String TAG = "LauncherWidgetHostView";
-
// Related to the auto-advancing of widgets
private static final long ADVANCE_INTERVAL = 20000;
private static final long ADVANCE_STAGGER = 250;
@@ -98,13 +93,7 @@ public class LauncherAppWidgetHostView extends AppWidgetHostView
setBackgroundResource(R.drawable.widget_internal_focus_bg);
if (Utilities.isAtLeastO()) {
- try {
- Method asyncMethod = AppWidgetHostView.class
- .getMethod("setExecutor", Executor.class);
- asyncMethod.invoke(this, Utilities.THREAD_POOL_EXECUTOR);
- } catch (Exception e) {
- Log.e(TAG, "Unable to set async executor", e);
- }
+ setExecutor(Utilities.THREAD_POOL_EXECUTOR);
}
}
diff --git a/src/com/android/launcher3/LauncherAppWidgetInfo.java b/src/com/android/launcher3/LauncherAppWidgetInfo.java
index 1e0f28546b..6f23e56b34 100644
--- a/src/com/android/launcher3/LauncherAppWidgetInfo.java
+++ b/src/com/android/launcher3/LauncherAppWidgetInfo.java
@@ -21,6 +21,7 @@ import android.content.ComponentName;
import android.content.Intent;
import android.os.Process;
+import com.android.launcher3.model.PackageItemInfo;
import com.android.launcher3.util.ContentWriter;
/**
@@ -95,6 +96,11 @@ public class LauncherAppWidgetInfo extends ItemInfo {
*/
public Intent bindOptions;
+ /**
+ * Nonnull for pending widgets. We use this to get the icon and title for the widget.
+ */
+ public PackageItemInfo pendingItemInfo;
+
private boolean mHasNotifiedInitialWidgetSizeChanged;
public LauncherAppWidgetInfo(int appWidgetId, ComponentName providerName) {
diff --git a/src/com/android/launcher3/LauncherCallbacks.java b/src/com/android/launcher3/LauncherCallbacks.java
index 2bac11f975..d66b14c7dc 100644
--- a/src/com/android/launcher3/LauncherCallbacks.java
+++ b/src/com/android/launcher3/LauncherCallbacks.java
@@ -17,13 +17,10 @@
package com.android.launcher3;
import android.content.Intent;
-import android.graphics.Rect;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
-import com.android.launcher3.allapps.AllAppsSearchBarController;
-import com.android.launcher3.logging.UserEventDispatcher;
import com.android.launcher3.util.ComponentKey;
import java.io.FileDescriptor;
@@ -44,69 +41,60 @@ public interface LauncherCallbacks {
* Activity life-cycle methods. These methods are triggered after
* the code in the corresponding Launcher method is executed.
*/
- public void preOnCreate();
- public void onCreate(Bundle savedInstanceState);
- public void preOnResume();
- public void onResume();
- public void onStart();
- public void onStop();
- public void onPause();
- public void onDestroy();
- public void onSaveInstanceState(Bundle outState);
- public void onPostCreate(Bundle savedInstanceState);
- public void onNewIntent(Intent intent);
- public void onActivityResult(int requestCode, int resultCode, Intent data);
- public void onRequestPermissionsResult(int requestCode, String[] permissions,
+ void preOnCreate();
+ void onCreate(Bundle savedInstanceState);
+ void preOnResume();
+ void onResume();
+ void onStart();
+ void onStop();
+ void onPause();
+ void onDestroy();
+ void onSaveInstanceState(Bundle outState);
+ void onPostCreate(Bundle savedInstanceState);
+ void onNewIntent(Intent intent);
+ void onActivityResult(int requestCode, int resultCode, Intent data);
+ void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults);
- public void onWindowFocusChanged(boolean hasFocus);
- public void onAttachedToWindow();
- public void onDetachedFromWindow();
- public boolean onPrepareOptionsMenu(Menu menu);
- public void dump(String prefix, FileDescriptor fd, PrintWriter w, String[] args);
- public void onHomeIntent();
- public boolean handleBackPressed();
- public void onTrimMemory(int level);
+ void onWindowFocusChanged(boolean hasFocus);
+ void onAttachedToWindow();
+ void onDetachedFromWindow();
+ boolean onPrepareOptionsMenu(Menu menu);
+ void dump(String prefix, FileDescriptor fd, PrintWriter w, String[] args);
+ void onHomeIntent();
+ boolean handleBackPressed();
+ void onTrimMemory(int level);
/*
* Extension points for providing custom behavior on certain user interactions.
*/
- public void onLauncherProviderChange();
- public void finishBindingItems(final boolean upgradePath);
- public void bindAllApplications(ArrayList apps);
- public void onInteractionBegin();
- public void onInteractionEnd();
+ void onLauncherProviderChange();
+ void finishBindingItems(final boolean upgradePath);
+ void bindAllApplications(ArrayList apps);
+ void onInteractionBegin();
+ void onInteractionEnd();
@Deprecated
- public void onWorkspaceLockedChanged();
+ void onWorkspaceLockedChanged();
/**
* Starts a search with {@param initialQuery}. Return false if search was not started.
*/
- public boolean startSearch(
+ boolean startSearch(
String initialQuery, boolean selectInitialQuery, Bundle appSearchData);
- public boolean hasCustomContentToLeft();
- public void populateCustomContentContainer();
- public View getQsbBar();
- public Bundle getAdditionalSearchWidgetOptions();
+ boolean hasCustomContentToLeft();
+ void populateCustomContentContainer();
+ View getQsbBar();
+ Bundle getAdditionalSearchWidgetOptions();
/*
* Extensions points for adding / replacing some other aspects of the Launcher experience.
*/
- public boolean shouldMoveToDefaultScreenOnHomeIntent();
- public boolean hasSettings();
- public AllAppsSearchBarController getAllAppsSearchBarController();
- public List getPredictedApps();
- public static final int SEARCH_BAR_HEIGHT_NORMAL = 0, SEARCH_BAR_HEIGHT_TALL = 1;
+ boolean shouldMoveToDefaultScreenOnHomeIntent();
+ boolean hasSettings();
+ List getPredictedApps();
+ int SEARCH_BAR_HEIGHT_NORMAL = 0, SEARCH_BAR_HEIGHT_TALL = 1;
/** Must return one of {@link #SEARCH_BAR_HEIGHT_NORMAL} or {@link #SEARCH_BAR_HEIGHT_TALL} */
- public int getSearchBarHeight();
+ int getSearchBarHeight();
- /**
- * Sets the callbacks to allow reacting the actions of search overlays of the launcher.
- *
- * @param callbacks A set of callbacks to the Launcher, is actually a LauncherSearchCallback,
- * but for implementation purposes is passed around as an object.
- */
- public void setLauncherSearchCallback(Object callbacks);
-
- public boolean shouldShowDiscoveryBounce();
+ boolean shouldShowDiscoveryBounce();
}
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java
index b2f628417e..82bee0e4c6 100644
--- a/src/com/android/launcher3/LauncherModel.java
+++ b/src/com/android/launcher3/LauncherModel.java
@@ -16,7 +16,6 @@
package com.android.launcher3;
-import android.appwidget.AppWidgetProviderInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProviderOperation;
@@ -24,57 +23,40 @@ import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.LauncherActivityInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Process;
-import android.os.SystemClock;
-import android.os.Trace;
import android.os.UserHandle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
-import android.util.LongSparseArray;
-import android.util.MutableInt;
+import android.util.Pair;
-import com.android.launcher3.compat.AppWidgetManagerCompat;
import com.android.launcher3.compat.LauncherAppsCompat;
-import com.android.launcher3.compat.PackageInstallerCompat;
import com.android.launcher3.compat.PackageInstallerCompat.PackageInstallInfo;
import com.android.launcher3.compat.UserManagerCompat;
-import com.android.launcher3.config.ProviderConfig;
import com.android.launcher3.dynamicui.ExtractionUtils;
-import com.android.launcher3.folder.Folder;
-import com.android.launcher3.folder.FolderIcon;
import com.android.launcher3.graphics.LauncherIcons;
-import com.android.launcher3.logging.FileLog;
import com.android.launcher3.model.AddWorkspaceItemsTask;
import com.android.launcher3.model.BgDataModel;
import com.android.launcher3.model.CacheDataUpdatedTask;
-import com.android.launcher3.model.ExtendedModelTask;
-import com.android.launcher3.model.GridSizeMigrationTask;
-import com.android.launcher3.model.LoaderCursor;
+import com.android.launcher3.model.BaseModelUpdateTask;
+import com.android.launcher3.model.LoaderResults;
+import com.android.launcher3.model.LoaderTask;
import com.android.launcher3.model.ModelWriter;
import com.android.launcher3.model.PackageInstallStateChangedTask;
import com.android.launcher3.model.PackageItemInfo;
import com.android.launcher3.model.PackageUpdatedTask;
-import com.android.launcher3.model.SdCardAvailableReceiver;
import com.android.launcher3.model.ShortcutsChangedTask;
import com.android.launcher3.model.UserLockStateChangedTask;
import com.android.launcher3.model.WidgetItem;
-import com.android.launcher3.model.WidgetsModel;
-import com.android.launcher3.provider.ImportDataTask;
import com.android.launcher3.provider.LauncherDbUtils;
import com.android.launcher3.shortcuts.DeepShortcutManager;
import com.android.launcher3.shortcuts.ShortcutInfoCompat;
-import com.android.launcher3.shortcuts.ShortcutKey;
import com.android.launcher3.util.ComponentKey;
-import com.android.launcher3.util.ManagedProfileHeuristic;
import com.android.launcher3.util.MultiHashMap;
-import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.util.Provider;
@@ -85,14 +67,9 @@ import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
-import java.util.Map;
-import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
@@ -103,21 +80,16 @@ import java.util.concurrent.Executor;
*/
public class LauncherModel extends BroadcastReceiver
implements LauncherAppsCompat.OnAppsChangedCallbackCompat {
- static final boolean DEBUG_LOADERS = false;
private static final boolean DEBUG_RECEIVER = false;
static final String TAG = "Launcher.Model";
- private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
- private static final long INVALID_SCREEN_ID = -1L;
-
+ private final MainThreadExecutor mUiExecutor = new MainThreadExecutor();
@Thunk final LauncherAppState mApp;
@Thunk final Object mLock = new Object();
- @Thunk DeferredHandler mHandler = new DeferredHandler();
- @Thunk LoaderTask mLoaderTask;
+ @Thunk
+ LoaderTask mLoaderTask;
@Thunk boolean mIsLoaderTaskRunning;
- @Thunk boolean mHasLoaderCompletedOnce;
- @Thunk boolean mIsManagedHeuristicAppsUpdated;
@Thunk static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
static {
@@ -136,33 +108,10 @@ public class LauncherModel extends BroadcastReceiver
}
}
- /**
- * Set of runnables to be called on the background thread after the workspace binding
- * is complete.
- */
- static final ArrayList mBindCompleteRunnables = new ArrayList();
-
@Thunk WeakReference mCallbacks;
// < only access in worker thread >
private final AllAppsList mBgAllAppsList;
- // Entire list of widgets.
- private final WidgetsModel mBgWidgetsModel;
-
- private boolean mHasShortcutHostPermission;
- // Runnable to check if the shortcuts permission has changed.
- private final Runnable mShortcutPermissionCheckRunnable = new Runnable() {
- @Override
- public void run() {
- if (mModelLoaded) {
- boolean hasShortcutHostPermission =
- DeepShortcutManager.getInstance(mApp.getContext()).hasHostPermission();
- if (hasShortcutHostPermission != mHasShortcutHostPermission) {
- forceReload();
- }
- }
- }
- };
/**
* All the static data should be accessed on the background thread, A lock should be acquired
@@ -170,12 +119,19 @@ public class LauncherModel extends BroadcastReceiver
*/
static final BgDataModel sBgDataModel = new BgDataModel();
- // only access in worker thread >
-
- private final IconCache mIconCache;
-
- private final LauncherAppsCompat mLauncherApps;
- private final UserManagerCompat mUserManager;
+ // Runnable to check if the shortcuts permission has changed.
+ private final Runnable mShortcutPermissionCheckRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (mModelLoaded) {
+ boolean hasShortcutHostPermission =
+ DeepShortcutManager.getInstance(mApp.getContext()).hasHostPermission();
+ if (hasShortcutHostPermission != sBgDataModel.hasShortcutHostPermission) {
+ forceReload();
+ }
+ }
+ }
+ };
public interface Callbacks {
public boolean setLoadOnResume();
@@ -194,6 +150,7 @@ public class LauncherModel extends BroadcastReceiver
ArrayList addAnimated,
ArrayList addedApps);
public void bindAppsUpdated(ArrayList apps);
+ public void bindPromiseAppProgressUpdated(PromiseAppInfo app);
public void bindShortcutsChanged(ArrayList updated,
ArrayList removed, UserHandle user);
public void bindWidgetsRestored(ArrayList widgets);
@@ -210,25 +167,8 @@ public class LauncherModel extends BroadcastReceiver
}
LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) {
- Context context = app.getContext();
mApp = app;
mBgAllAppsList = new AllAppsList(iconCache, appFilter);
- mBgWidgetsModel = new WidgetsModel(iconCache, appFilter);
- mIconCache = iconCache;
-
- mLauncherApps = LauncherAppsCompat.getInstance(context);
- mUserManager = UserManagerCompat.getInstance(context);
- }
-
- /** Runs the specified runnable immediately if called from the main thread, otherwise it is
- * posted on the main thread handler. */
- private void runOnMainThread(Runnable r) {
- if (sWorkerThread.getThreadId() == Process.myTid()) {
- // If we are on the worker thread, post onto the main handler
- mHandler.post(r);
- } else {
- r.run();
- }
}
/** Runs the specified runnable immediately if called from the worker thread, otherwise it is
@@ -256,18 +196,11 @@ public class LauncherModel extends BroadcastReceiver
CacheDataUpdatedTask.OP_SESSION_UPDATE, Process.myUserHandle(), packages));
}
- /**
- * Adds the provided items to the workspace.
- */
- public void addAndBindAddedWorkspaceItems(List workspaceApps) {
- addAndBindAddedWorkspaceItems(Provider.of(workspaceApps));
- }
-
/**
* Adds the provided items to the workspace.
*/
public void addAndBindAddedWorkspaceItems(
- Provider> appsProvider) {
+ Provider>> appsProvider) {
enqueueModelUpdateTask(new AddWorkspaceItemsTask(appsProvider));
}
@@ -380,8 +313,6 @@ public class LauncherModel extends BroadcastReceiver
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
Preconditions.assertUIThread();
- // Remove any queued UI runnables
- mHandler.cancelAll();
mCallbacks = new WeakReference<>(callbacks);
}
}
@@ -493,7 +424,7 @@ public class LauncherModel extends BroadcastReceiver
public void forceReload() {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mModelLoaded to true later
- stopLoaderLocked();
+ stopLoader();
mModelLoaded = false;
}
@@ -519,16 +450,6 @@ public class LauncherModel extends BroadcastReceiver
}
}
- /**
- * If there is already a loader task running, tell it to stop.
- */
- private void stopLoaderLocked() {
- LoaderTask oldTask = mLoaderTask;
- if (oldTask != null) {
- oldTask.stopLocked();
- }
- }
-
public boolean isCurrentCallbacks(Callbacks callbacks) {
return (mCallbacks != null && mCallbacks.get() == callbacks);
}
@@ -539,42 +460,61 @@ public class LauncherModel extends BroadcastReceiver
*/
public boolean startLoader(int synchronousBindPage) {
// Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems
- InstallShortcutReceiver.enableInstallQueue();
+ InstallShortcutReceiver.enableInstallQueue(InstallShortcutReceiver.FLAG_LOADER_RUNNING);
synchronized (mLock) {
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
final Callbacks oldCallbacks = mCallbacks.get();
// Clear any pending bind-runnables from the synchronized load process.
- runOnMainThread(new Runnable() {
- public void run() {
- oldCallbacks.clearPendingBinds();
- }
- });
+ mUiExecutor.execute(new Runnable() {
+ public void run() {
+ oldCallbacks.clearPendingBinds();
+ }
+ });
// If there is already one running, tell it to stop.
- stopLoaderLocked();
- mLoaderTask = new LoaderTask(mApp.getContext(), synchronousBindPage);
- if (synchronousBindPage != PagedView.INVALID_RESTORE_PAGE
- && mModelLoaded && !mIsLoaderTaskRunning) {
- mLoaderTask.runBindSynchronousPage(synchronousBindPage);
+ stopLoader();
+ LoaderResults loaderResults = new LoaderResults(mApp, sBgDataModel,
+ mBgAllAppsList, synchronousBindPage, mCallbacks);
+ if (mModelLoaded && !mIsLoaderTaskRunning) {
+ // 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();
+ // For now, continue posting the binding of AllApps as there are other
+ // issues that arise from that.
+ loaderResults.bindAllApps();
+ loaderResults.bindDeepShortcuts();
+ loaderResults.bindWidgets();
return true;
} else {
- sWorkerThread.setPriority(Thread.NORM_PRIORITY);
- sWorker.post(mLoaderTask);
+ startLoaderForResults(loaderResults);
}
}
}
return false;
}
+ /**
+ * If there is already a loader task running, tell it to stop.
+ */
public void stopLoader() {
synchronized (mLock) {
- if (mLoaderTask != null) {
- mLoaderTask.stopLocked();
+ LoaderTask oldTask = mLoaderTask;
+ mLoaderTask = null;
+ if (oldTask != null) {
+ oldTask.stopLocked();
}
}
}
+ public void startLoaderForResults(LoaderResults results) {
+ synchronized (mLock) {
+ stopLoader();
+ mLoaderTask = new LoaderTask(mApp, mBgAllAppsList, sBgDataModel, results);
+ runOnWorkerThread(mLoaderTask);
+ }
+ }
+
/**
* Loads the workspace screen ids in an ordered list.
*/
@@ -587,1230 +527,61 @@ public class LauncherModel extends BroadcastReceiver
screensUri, null, null, null, LauncherSettings.WorkspaceScreens.SCREEN_RANK));
}
- /**
- * Runnable for the thread that loads the contents of the launcher:
- * - workspace icons
- * - widgets
- * - all apps icons
- * - deep shortcuts within apps
- */
- private class LoaderTask implements Runnable {
- private Context mContext;
- private int mPageToBindFirst;
-
- @Thunk boolean mIsLoadingAndBindingWorkspace;
- private boolean mStopped;
- @Thunk boolean mLoadAndBindStepFinished;
-
- LoaderTask(Context context, int pageToBindFirst) {
- mContext = context;
- mPageToBindFirst = pageToBindFirst;
- }
-
- private void waitForIdle() {
- // Wait until the either we're stopped or the other threads are done.
- // This way we don't start loading all apps until the workspace has settled
- // down.
- synchronized (LoaderTask.this) {
- final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
-
- mHandler.postIdle(new Runnable() {
- public void run() {
- synchronized (LoaderTask.this) {
- mLoadAndBindStepFinished = true;
- if (DEBUG_LOADERS) {
- Log.d(TAG, "done with previous binding step");
- }
- LoaderTask.this.notify();
- }
+ public void onInstallSessionCreated(final PackageInstallInfo sessionInfo) {
+ enqueueModelUpdateTask(new BaseModelUpdateTask() {
+ @Override
+ public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
+ apps.addPromiseApp(app.getContext(), sessionInfo);
+ if (!apps.added.isEmpty()) {
+ final ArrayList arrayList = new ArrayList<>(apps.added);
+ apps.added.clear();
+ scheduleCallbackTask(new CallbackTask() {
+ @Override
+ public void execute(Callbacks callbacks) {
+ callbacks.bindAppsAdded(null, null, null, arrayList);
}
});
-
- while (!mStopped && !mLoadAndBindStepFinished) {
- try {
- // Just in case mFlushingWorkerThread changes but we aren't woken up,
- // wait no longer than 1sec at a time
- this.wait(1000);
- } catch (InterruptedException ex) {
- // Ignore
- }
- }
- if (DEBUG_LOADERS) {
- Log.d(TAG, "waited "
- + (SystemClock.uptimeMillis()-workspaceWaitTime)
- + "ms for previous step to finish binding");
}
}
- }
+ });
+ }
- void runBindSynchronousPage(int synchronousBindPage) {
- if (synchronousBindPage == PagedView.INVALID_RESTORE_PAGE) {
- // Ensure that we have a valid page index to load synchronously
- throw new RuntimeException("Should not call runBindSynchronousPage() without " +
- "valid page index");
- }
- if (!mModelLoaded) {
- // Ensure that we don't try and bind a specified page when the pages have not been
- // loaded already (we should load everything asynchronously in that case)
- throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
- }
+ public class LoaderTransaction implements AutoCloseable {
+
+ private final LoaderTask mTask;
+
+ private LoaderTransaction(LoaderTask task) throws CancellationException {
synchronized (mLock) {
- if (mIsLoaderTaskRunning) {
- // Ensure that we are never running the background loading at this point since
- // we also touch the background collections
- throw new RuntimeException("Error! Background loading is already running");
- }
- }
-
- // XXX: Throw an exception if we are already loading (since we touch the worker thread
- // data structures, we can't allow any other thread to touch that data, but because
- // this call is synchronous, we can get away with not locking).
-
- // The LauncherModel is static in the LauncherAppState and mHandler may have queued
- // operations from the previous activity. We need to ensure that all queued operations
- // are executed before any synchronous binding work is done.
- mHandler.flush();
-
- // Divide the set of loaded items into those that we are binding synchronously, and
- // everything else that is to be bound normally (asynchronously).
- bindWorkspace(synchronousBindPage);
- // XXX: For now, continue posting the binding of AllApps as there are other issues that
- // arise from that.
- onlyBindAllApps();
-
- bindDeepShortcuts();
- }
-
- private void verifyNotStopped() throws CancellationException {
- synchronized (LoaderTask.this) {
- if (mStopped) {
- throw new CancellationException("Loader stopped");
- }
- }
- }
-
- public void run() {
- synchronized (mLock) {
- if (mStopped) {
- return;
+ if (mLoaderTask != task) {
+ throw new CancellationException("Loader already stopped");
}
+ mTask = task;
mIsLoaderTaskRunning = true;
- }
-
- try {
- if (DEBUG_LOADERS) Log.d(TAG, "step 1.1: loading workspace");
- // Set to false in bindWorkspace()
- mIsLoadingAndBindingWorkspace = true;
- loadWorkspace();
-
- verifyNotStopped();
- if (DEBUG_LOADERS) Log.d(TAG, "step 1.2: bind workspace workspace");
- bindWorkspace(mPageToBindFirst);
-
- // Take a break
- if (DEBUG_LOADERS) Log.d(TAG, "step 1 completed, wait for idle");
- waitForIdle();
- verifyNotStopped();
-
- // second step
- if (DEBUG_LOADERS) Log.d(TAG, "step 2.1: loading all apps");
- loadAllApps();
-
- verifyNotStopped();
- if (DEBUG_LOADERS) Log.d(TAG, "step 2.2: Update icon cache");
- updateIconCache();
-
- // Take a break
- if (DEBUG_LOADERS) Log.d(TAG, "step 2 completed, wait for idle");
- waitForIdle();
- verifyNotStopped();
-
- // third step
- if (DEBUG_LOADERS) Log.d(TAG, "step 3.1: loading deep shortcuts");
- loadDeepShortcuts();
-
- verifyNotStopped();
- if (DEBUG_LOADERS) Log.d(TAG, "step 3.2: bind deep shortcuts");
- bindDeepShortcuts();
-
- // Take a break
- if (DEBUG_LOADERS) Log.d(TAG, "step 3 completed, wait for idle");
- waitForIdle();
- verifyNotStopped();
-
- // fourth step
- if (DEBUG_LOADERS) Log.d(TAG, "step 4.1: loading widgets");
- refreshAndBindWidgetsAndShortcuts(getCallback(), false /* bindFirst */,
- null /* packageUser */);
-
- synchronized (mLock) {
- // Everything loaded bind the data.
- mModelLoaded = true;
- mHasLoaderCompletedOnce = true;
- }
- } catch (CancellationException e) {
- // Loader stopped, ignore
- } finally {
- // Clear out this reference, otherwise we end up holding it until all of the
- // callback runnables are done.
- mContext = null;
-
- synchronized (mLock) {
- // If we are still the last one to be scheduled, remove ourselves.
- if (mLoaderTask == this) {
- mLoaderTask = null;
- }
- mIsLoaderTaskRunning = false;
- }
+ mModelLoaded = false;
}
}
- public void stopLocked() {
- synchronized (LoaderTask.this) {
- mStopped = true;
- this.notify();
- }
- }
-
- /**
- * Gets the callbacks object. If we've been stopped, or if the launcher object
- * has somehow been garbage collected, return null instead. Pass in the Callbacks
- * object that was around when the deferred message was scheduled, and if there's
- * a new Callbacks object around then also return null. This will save us from
- * calling onto it with data that will be ignored.
- */
- Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
+ public void commit() {
synchronized (mLock) {
- if (mStopped) {
- return null;
- }
-
- if (mCallbacks == null) {
- return null;
- }
-
- final Callbacks callbacks = mCallbacks.get();
- if (callbacks != oldCallbacks) {
- return null;
- }
- if (callbacks == null) {
- Log.w(TAG, "no mCallbacks");
- return null;
- }
-
- return callbacks;
+ // Everything loaded bind the data.
+ mModelLoaded = true;
}
}
- private void loadWorkspace() {
- if (LauncherAppState.PROFILE_STARTUP) {
- Trace.beginSection("Loading Workspace");
- }
-
- final Context context = mContext;
- final ContentResolver contentResolver = context.getContentResolver();
- final PackageManagerHelper pmHelper = new PackageManagerHelper(context);
- final boolean isSafeMode = pmHelper.isSafeMode();
- final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
- final DeepShortcutManager shortcutManager = DeepShortcutManager.getInstance(context);
- final boolean isSdCardReady = Utilities.isBootCompleted();
- final MultiHashMap pendingPackages = new MultiHashMap<>();
-
- boolean clearDb = false;
- try {
- ImportDataTask.performImportIfPossible(context);
- } catch (Exception e) {
- // Migration failed. Clear workspace.
- clearDb = true;
- }
-
- if (!clearDb && GridSizeMigrationTask.ENABLED &&
- !GridSizeMigrationTask.migrateGridIfNeeded(mContext)) {
- // Migration failed. Clear workspace.
- clearDb = true;
- }
-
- if (clearDb) {
- Log.d(TAG, "loadWorkspace: resetting launcher database");
- LauncherSettings.Settings.call(contentResolver,
- LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
- }
-
- Log.d(TAG, "loadWorkspace: loading default favorites");
- LauncherSettings.Settings.call(contentResolver,
- LauncherSettings.Settings.METHOD_LOAD_DEFAULT_FAVORITES);
-
- synchronized (sBgDataModel) {
- sBgDataModel.clear();
-
- final HashMap installingPkgs = PackageInstallerCompat
- .getInstance(mContext).updateAndGetActiveSessionCache();
- sBgDataModel.workspaceScreens.addAll(loadWorkspaceScreensDb(mContext));
-
- Map shortcutKeyToPinnedShortcuts = new HashMap<>();
- final LoaderCursor c = new LoaderCursor(contentResolver.query(
- LauncherSettings.Favorites.CONTENT_URI, null, null, null, null), mApp);
-
- HashMap widgetProvidersMap = null;
-
- try {
- final int appWidgetIdIndex = c.getColumnIndexOrThrow(
- LauncherSettings.Favorites.APPWIDGET_ID);
- final int appWidgetProviderIndex = c.getColumnIndexOrThrow(
- LauncherSettings.Favorites.APPWIDGET_PROVIDER);
- final int spanXIndex = c.getColumnIndexOrThrow
- (LauncherSettings.Favorites.SPANX);
- final int spanYIndex = c.getColumnIndexOrThrow(
- LauncherSettings.Favorites.SPANY);
- final int rankIndex = c.getColumnIndexOrThrow(
- LauncherSettings.Favorites.RANK);
- final int optionsIndex = c.getColumnIndexOrThrow(
- LauncherSettings.Favorites.OPTIONS);
-
- final LongSparseArray allUsers = c.allUsers;
- final LongSparseArray quietMode = new LongSparseArray<>();
- final LongSparseArray unlockedUsers = new LongSparseArray<>();
- for (UserHandle user : mUserManager.getUserProfiles()) {
- long serialNo = mUserManager.getSerialNumberForUser(user);
- allUsers.put(serialNo, user);
- quietMode.put(serialNo, mUserManager.isQuietModeEnabled(user));
-
- boolean userUnlocked = mUserManager.isUserUnlocked(user);
-
- // We can only query for shortcuts when the user is unlocked.
- if (userUnlocked) {
- List pinnedShortcuts =
- shortcutManager.queryForPinnedShortcuts(null, user);
- if (shortcutManager.wasLastCallSuccess()) {
- for (ShortcutInfoCompat shortcut : pinnedShortcuts) {
- shortcutKeyToPinnedShortcuts.put(ShortcutKey.fromInfo(shortcut),
- shortcut);
- }
- } else {
- // Shortcut manager can fail due to some race condition when the
- // lock state changes too frequently. For the purpose of the loading
- // shortcuts, consider the user is still locked.
- userUnlocked = false;
- }
- }
- unlockedUsers.put(serialNo, userUnlocked);
- }
-
- ShortcutInfo info;
- LauncherAppWidgetInfo appWidgetInfo;
- Intent intent;
- String targetPkg;
-
- while (!mStopped && c.moveToNext()) {
- try {
- if (c.user == null) {
- // User has been deleted, remove the item.
- c.markDeleted("User has been deleted");
- continue;
- }
-
- boolean allowMissingTarget = false;
- switch (c.itemType) {
- case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
- case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
- case LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT:
- intent = c.parseIntent();
- if (intent == null) {
- c.markDeleted("Invalid or null intent");
- continue;
- }
-
- int disabledState = quietMode.get(c.serialNumber) ?
- ShortcutInfo.FLAG_DISABLED_QUIET_USER : 0;
- ComponentName cn = intent.getComponent();
- targetPkg = cn == null ? intent.getPackage() : cn.getPackageName();
-
- if (!Process.myUserHandle().equals(c.user)) {
- if (c.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
- c.markDeleted("Legacy shortcuts are only allowed for default user");
- continue;
- } else if (c.restoreFlag != 0) {
- // Don't restore items for other profiles.
- c.markDeleted("Restore from managed profile not supported");
- continue;
- }
- }
- if (TextUtils.isEmpty(targetPkg) &&
- c.itemType != LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
- c.markDeleted("Only legacy shortcuts can have null package");
- continue;
- }
-
- // If there is no target package, its an implicit intent
- // (legacy shortcut) which is always valid
- boolean validTarget = TextUtils.isEmpty(targetPkg) ||
- launcherApps.isPackageEnabledForProfile(targetPkg, c.user);
-
- if (cn != null && validTarget) {
- // If the apk is present and the shortcut points to a specific
- // component.
-
- // If the component is already present
- if (launcherApps.isActivityEnabledForProfile(cn, c.user)) {
- // no special handling necessary for this item
- c.markRestored();
- } else {
- if (c.hasRestoreFlag(ShortcutInfo.FLAG_AUTOINTALL_ICON)) {
- // We allow auto install apps to have their intent
- // updated after an install.
- intent = pmHelper.getAppLaunchIntent(targetPkg, c.user);
- if (intent != null) {
- c.restoreFlag = 0;
- c.updater().put(
- LauncherSettings.Favorites.INTENT,
- intent.toUri(0)).commit();
- cn = intent.getComponent();
- } else {
- c.markDeleted("Unable to find a launch target");
- continue;
- }
- } else {
- // The app is installed but the component is no
- // longer available.
- c.markDeleted("Invalid component removed: " + cn);
- continue;
- }
- }
- }
- // else if cn == null => can't infer much, leave it
- // else if !validPkg => could be restored icon or missing sd-card
-
- if (!TextUtils.isEmpty(targetPkg) && !validTarget) {
- // Points to a valid app (superset of cn != null) but the apk
- // is not available.
-
- if (c.restoreFlag != 0) {
- // Package is not yet available but might be
- // installed later.
- FileLog.d(TAG, "package not yet restored: " + targetPkg);
-
- if (c.hasRestoreFlag(ShortcutInfo.FLAG_RESTORE_STARTED)) {
- // Restore has started once.
- } else if (installingPkgs.containsKey(targetPkg)) {
- // App restore has started. Update the flag
- c.restoreFlag |= ShortcutInfo.FLAG_RESTORE_STARTED;
- c.updater().commit();
- } else {
- c.markDeleted("Unrestored app removed: " + targetPkg);
- continue;
- }
- } else if (pmHelper.isAppOnSdcard(targetPkg, c.user)) {
- // Package is present but not available.
- disabledState |= ShortcutInfo.FLAG_DISABLED_NOT_AVAILABLE;
- // Add the icon on the workspace anyway.
- allowMissingTarget = true;
- } else if (!isSdCardReady) {
- // SdCard is not ready yet. Package might get available,
- // once it is ready.
- Log.d(TAG, "Missing pkg, will check later: " + targetPkg);
- pendingPackages.addToList(c.user, targetPkg);
- // Add the icon on the workspace anyway.
- allowMissingTarget = true;
- } else {
- // Do not wait for external media load anymore.
- c.markDeleted("Invalid package removed: " + targetPkg);
- continue;
- }
- }
-
- if (validTarget) {
- // The shortcut points to a valid target (either no target
- // or something which is ready to be used)
- c.markRestored();
- }
-
- boolean useLowResIcon = !c.isOnWorkspaceOrHotseat() &&
- c.getInt(rankIndex) >= FolderIcon.NUM_ITEMS_IN_PREVIEW;
-
- if (c.restoreFlag != 0) {
- // Already verified above that user is same as default user
- info = c.getRestoredItemInfo(intent);
- } else if (c.itemType ==
- LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
- info = c.getAppShortcutInfo(
- intent, allowMissingTarget, useLowResIcon);
- } else if (c.itemType ==
- LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
-
- ShortcutKey key = ShortcutKey.fromIntent(intent, c.user);
- if (unlockedUsers.get(c.serialNumber)) {
- ShortcutInfoCompat pinnedShortcut =
- shortcutKeyToPinnedShortcuts.get(key);
- if (pinnedShortcut == null) {
- // The shortcut is no longer valid.
- c.markDeleted("Pinned shortcut not found");
- continue;
- }
- info = new ShortcutInfo(pinnedShortcut, context);
- info.iconBitmap = LauncherIcons
- .createShortcutIcon(pinnedShortcut, context);
- if (pmHelper.isAppSuspended(
- pinnedShortcut.getPackage(), info.user)) {
- info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SUSPENDED;
- }
- intent = info.intent;
- } else {
- // Create a shortcut info in disabled mode for now.
- info = c.loadSimpleShortcut();
- info.isDisabled |= ShortcutInfo.FLAG_DISABLED_LOCKED_USER;
- }
- } else { // item type == ITEM_TYPE_SHORTCUT
- info = c.loadSimpleShortcut();
-
- // Shortcuts are only available on the primary profile
- if (!TextUtils.isEmpty(targetPkg)
- && pmHelper.isAppSuspended(targetPkg, c.user)) {
- disabledState |= ShortcutInfo.FLAG_DISABLED_SUSPENDED;
- }
-
- // App shortcuts that used to be automatically added to Launcher
- // didn't always have the correct intent flags set, so do that
- // here
- if (intent.getAction() != null &&
- intent.getCategories() != null &&
- intent.getAction().equals(Intent.ACTION_MAIN) &&
- intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
- intent.addFlags(
- Intent.FLAG_ACTIVITY_NEW_TASK |
- Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
- }
- }
-
- if (info != null) {
- c.applyCommonProperties(info);
-
- info.intent = intent;
- info.rank = c.getInt(rankIndex);
- info.spanX = 1;
- info.spanY = 1;
- info.isDisabled |= disabledState;
- if (isSafeMode && !Utilities.isSystemApp(context, intent)) {
- info.isDisabled |= ShortcutInfo.FLAG_DISABLED_SAFEMODE;
- }
-
- if (c.restoreFlag != 0 && !TextUtils.isEmpty(targetPkg)) {
- Integer progress = installingPkgs.get(targetPkg);
- if (progress != null) {
- info.setInstallProgress(progress);
- } else {
- info.status &= ~ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE;
- }
- }
-
- c.checkAndAddItem(info, sBgDataModel);
- } else {
- throw new RuntimeException("Unexpected null ShortcutInfo");
- }
- break;
-
- case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
- FolderInfo folderInfo = sBgDataModel.findOrMakeFolder(c.id);
- c.applyCommonProperties(folderInfo);
-
- // Do not trim the folder label, as is was set by the user.
- folderInfo.title = c.getString(c.titleIndex);
- folderInfo.spanX = 1;
- folderInfo.spanY = 1;
- folderInfo.options = c.getInt(optionsIndex);
-
- // no special handling required for restored folders
- c.markRestored();
-
- c.checkAndAddItem(folderInfo, sBgDataModel);
- break;
-
- case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
- case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
- // Read all Launcher-specific widget details
- boolean customWidget = c.itemType ==
- LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
-
- int appWidgetId = c.getInt(appWidgetIdIndex);
- String savedProvider = c.getString(appWidgetProviderIndex);
-
- final ComponentName component =
- ComponentName.unflattenFromString(savedProvider);
-
- final boolean isIdValid = !c.hasRestoreFlag(
- LauncherAppWidgetInfo.FLAG_ID_NOT_VALID);
- final boolean wasProviderReady = !c.hasRestoreFlag(
- LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY);
-
- if (widgetProvidersMap == null) {
- widgetProvidersMap = AppWidgetManagerCompat
- .getInstance(mContext).getAllProvidersMap();
- }
- final AppWidgetProviderInfo provider = widgetProvidersMap.get(
- new ComponentKey(
- ComponentName.unflattenFromString(savedProvider),
- c.user));
-
- final boolean isProviderReady = isValidProvider(provider);
- if (!isSafeMode && !customWidget &&
- wasProviderReady && !isProviderReady) {
- c.markDeleted(
- "Deleting widget that isn't installed anymore: "
- + provider);
- } else {
- if (isProviderReady) {
- appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
- provider.provider);
-
- // The provider is available. So the widget is either
- // available or not available. We do not need to track
- // any future restore updates.
- int status = c.restoreFlag &
- ~LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
- if (!wasProviderReady) {
- // If provider was not previously ready, update the
- // status and UI flag.
-
- // Id would be valid only if the widget restore broadcast was received.
- if (isIdValid) {
- status |= LauncherAppWidgetInfo.FLAG_UI_NOT_READY;
- } else {
- status &= ~LauncherAppWidgetInfo
- .FLAG_PROVIDER_NOT_READY;
- }
- }
- appWidgetInfo.restoreStatus = status;
- } else {
- Log.v(TAG, "Widget restore pending id=" + c.id
- + " appWidgetId=" + appWidgetId
- + " status =" + c.restoreFlag);
- appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
- component);
- appWidgetInfo.restoreStatus = c.restoreFlag;
- Integer installProgress = installingPkgs.get(component.getPackageName());
-
- if (c.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_RESTORE_STARTED)) {
- // Restore has started once.
- } else if (installProgress != null) {
- // App restore has started. Update the flag
- appWidgetInfo.restoreStatus |=
- LauncherAppWidgetInfo.FLAG_RESTORE_STARTED;
- } else if (!isSafeMode) {
- c.markDeleted("Unrestored widget removed: " + component);
- continue;
- }
-
- appWidgetInfo.installProgress =
- installProgress == null ? 0 : installProgress;
- }
- if (appWidgetInfo.hasRestoreFlag(
- LauncherAppWidgetInfo.FLAG_DIRECT_CONFIG)) {
- appWidgetInfo.bindOptions = c.parseIntent();
- }
-
- c.applyCommonProperties(appWidgetInfo);
- appWidgetInfo.spanX = c.getInt(spanXIndex);
- appWidgetInfo.spanY = c.getInt(spanYIndex);
- appWidgetInfo.user = c.user;
-
- if (!c.isOnWorkspaceOrHotseat()) {
- c.markDeleted("Widget found where container != " +
- "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
- continue;
- }
-
- if (!customWidget) {
- String providerName =
- appWidgetInfo.providerName.flattenToString();
- if (!providerName.equals(savedProvider) ||
- (appWidgetInfo.restoreStatus != c.restoreFlag)) {
- c.updater()
- .put(LauncherSettings.Favorites.APPWIDGET_PROVIDER,
- providerName)
- .put(LauncherSettings.Favorites.RESTORED,
- appWidgetInfo.restoreStatus)
- .commit();
- }
- }
- c.checkAndAddItem(appWidgetInfo, sBgDataModel);
- }
- break;
- }
- } catch (Exception e) {
- Log.e(TAG, "Desktop items loading interrupted", e);
- }
- }
- } finally {
- Utilities.closeSilently(c);
- }
-
- // Break early if we've stopped loading
- if (mStopped) {
- sBgDataModel.clear();
- return;
- }
-
- // Remove dead items
- if (c.commitDeleted()) {
- // Remove any empty folder
- ArrayList deletedFolderIds = (ArrayList) LauncherSettings.Settings
- .call(contentResolver,
- LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS)
- .getSerializable(LauncherSettings.Settings.EXTRA_VALUE);
- for (long folderId : deletedFolderIds) {
- sBgDataModel.workspaceItems.remove(sBgDataModel.folders.get(folderId));
- sBgDataModel.folders.remove(folderId);
- sBgDataModel.itemsIdMap.remove(folderId);
- }
-
- // Remove any ghost widgets
- LauncherSettings.Settings.call(contentResolver,
- LauncherSettings.Settings.METHOD_REMOVE_GHOST_WIDGETS);
- }
-
- // Unpin shortcuts that don't exist on the workspace.
- HashSet pendingShortcuts =
- InstallShortcutReceiver.getPendingShortcuts(context);
- for (ShortcutKey key : shortcutKeyToPinnedShortcuts.keySet()) {
- MutableInt numTimesPinned = sBgDataModel.pinnedShortcutCounts.get(key);
- if ((numTimesPinned == null || numTimesPinned.value == 0)
- && !pendingShortcuts.contains(key)) {
- // Shortcut is pinned but doesn't exist on the workspace; unpin it.
- shortcutManager.unpinShortcut(key);
- }
- }
-
- // Sort all the folder items and make sure the first 3 items are high resolution.
- for (FolderInfo folder : sBgDataModel.folders) {
- Collections.sort(folder.contents, Folder.ITEM_POS_COMPARATOR);
- int pos = 0;
- for (ShortcutInfo info : folder.contents) {
- if (info.usingLowResIcon &&
- info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
- mIconCache.getTitleAndIcon(info, false);
- }
- pos ++;
- if (pos >= FolderIcon.NUM_ITEMS_IN_PREVIEW) {
- break;
- }
- }
- }
-
- c.commitRestoredItems();
- if (!isSdCardReady && !pendingPackages.isEmpty()) {
- context.registerReceiver(
- new SdCardAvailableReceiver(
- LauncherModel.this, mContext, pendingPackages),
- new IntentFilter(Intent.ACTION_BOOT_COMPLETED),
- null,
- sWorker);
- }
-
- // Remove any empty screens
- ArrayList unusedScreens = new ArrayList<>(sBgDataModel.workspaceScreens);
- for (ItemInfo item: sBgDataModel.itemsIdMap) {
- long screenId = item.screenId;
- if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
- unusedScreens.contains(screenId)) {
- unusedScreens.remove(screenId);
- }
- }
-
- // If there are any empty screens remove them, and update.
- if (unusedScreens.size() != 0) {
- sBgDataModel.workspaceScreens.removeAll(unusedScreens);
- updateWorkspaceScreenOrder(context, sBgDataModel.workspaceScreens);
- }
- }
- if (LauncherAppState.PROFILE_STARTUP) {
- Trace.endSection();
- }
- }
-
- /** Filters the set of items who are directly or indirectly (via another container) on the
- * specified screen. */
- private void filterCurrentWorkspaceItems(long currentScreenId,
- ArrayList allWorkspaceItems,
- ArrayList currentScreenItems,
- ArrayList otherScreenItems) {
- // Purge any null ItemInfos
- Iterator iter = allWorkspaceItems.iterator();
- while (iter.hasNext()) {
- ItemInfo i = iter.next();
- if (i == null) {
- iter.remove();
- }
- }
-
- // Order the set of items by their containers first, this allows use to walk through the
- // list sequentially, build up a list of containers that are in the specified screen,
- // as well as all items in those containers.
- Set itemsOnScreen = new HashSet();
- Collections.sort(allWorkspaceItems, new Comparator() {
- @Override
- public int compare(ItemInfo lhs, ItemInfo rhs) {
- return Utilities.longCompare(lhs.container, rhs.container);
- }
- });
- for (ItemInfo info : allWorkspaceItems) {
- if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
- if (info.screenId == currentScreenId) {
- currentScreenItems.add(info);
- itemsOnScreen.add(info.id);
- } else {
- otherScreenItems.add(info);
- }
- } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
- currentScreenItems.add(info);
- itemsOnScreen.add(info.id);
- } else {
- if (itemsOnScreen.contains(info.container)) {
- currentScreenItems.add(info);
- itemsOnScreen.add(info.id);
- } else {
- otherScreenItems.add(info);
- }
- }
- }
- }
-
- /** Filters the set of widgets which are on the specified screen. */
- private void filterCurrentAppWidgets(long currentScreenId,
- ArrayList appWidgets,
- ArrayList currentScreenWidgets,
- ArrayList otherScreenWidgets) {
-
- for (LauncherAppWidgetInfo widget : appWidgets) {
- if (widget == null) continue;
- if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
- widget.screenId == currentScreenId) {
- currentScreenWidgets.add(widget);
- } else {
- otherScreenWidgets.add(widget);
- }
- }
- }
-
- /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
- * right) */
- private void sortWorkspaceItemsSpatially(ArrayList workspaceItems) {
- final InvariantDeviceProfile profile = mApp.getInvariantDeviceProfile();
- final int screenCols = profile.numColumns;
- final int screenCellCount = profile.numColumns * profile.numRows;
- Collections.sort(workspaceItems, new Comparator() {
- @Override
- public int compare(ItemInfo lhs, ItemInfo rhs) {
- if (lhs.container == rhs.container) {
- // Within containers, order by their spatial position in that container
- switch ((int) lhs.container) {
- case LauncherSettings.Favorites.CONTAINER_DESKTOP: {
- long lr = (lhs.screenId * screenCellCount +
- lhs.cellY * screenCols + lhs.cellX);
- long rr = (rhs.screenId * screenCellCount +
- rhs.cellY * screenCols + rhs.cellX);
- return Utilities.longCompare(lr, rr);
- }
- case LauncherSettings.Favorites.CONTAINER_HOTSEAT: {
- // We currently use the screen id as the rank
- return Utilities.longCompare(lhs.screenId, rhs.screenId);
- }
- default:
- if (ProviderConfig.IS_DOGFOOD_BUILD) {
- throw new RuntimeException("Unexpected container type when " +
- "sorting workspace items.");
- }
- return 0;
- }
- } else {
- // Between containers, order by hotseat, desktop
- return Utilities.longCompare(lhs.container, rhs.container);
- }
- }
- });
- }
-
- private void bindWorkspaceScreens(final Callbacks oldCallbacks,
- final ArrayList orderedScreens) {
- final Runnable r = new Runnable() {
- @Override
- public void run() {
- Callbacks callbacks = tryGetCallbacks(oldCallbacks);
- if (callbacks != null) {
- callbacks.bindScreens(orderedScreens);
- }
- }
- };
- runOnMainThread(r);
- }
-
- private void bindWorkspaceItems(final Callbacks oldCallbacks,
- final ArrayList workspaceItems,
- final ArrayList appWidgets,
- final Executor executor) {
-
- // Bind the workspace items
- int N = workspaceItems.size();
- for (int i = 0; i < N; i += ITEMS_CHUNK) {
- final int start = i;
- final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
- final Runnable r = new Runnable() {
- @Override
- public void run() {
- Callbacks callbacks = tryGetCallbacks(oldCallbacks);
- if (callbacks != null) {
- callbacks.bindItems(workspaceItems, start, start+chunkSize,
- false);
- }
- }
- };
- executor.execute(r);
- }
-
- // Bind the widgets, one at a time
- N = appWidgets.size();
- for (int i = 0; i < N; i++) {
- final LauncherAppWidgetInfo widget = appWidgets.get(i);
- final Runnable r = new Runnable() {
- public void run() {
- Callbacks callbacks = tryGetCallbacks(oldCallbacks);
- if (callbacks != null) {
- callbacks.bindAppWidget(widget);
- }
- }
- };
- executor.execute(r);
- }
- }
-
- /**
- * Binds all loaded data to actual views on the main thread.
- */
- private void bindWorkspace(int synchronizeBindPage) {
- final long t = SystemClock.uptimeMillis();
- Runnable r;
-
- // Don't use these two variables in any of the callback runnables.
- // Otherwise we hold a reference to them.
- final Callbacks oldCallbacks = mCallbacks.get();
- if (oldCallbacks == null) {
- // This launcher has exited and nobody bothered to tell us. Just bail.
- Log.w(TAG, "LoaderTask running with no launcher");
- return;
- }
-
- // Save a copy of all the bg-thread collections
- ArrayList workspaceItems = new ArrayList<>();
- ArrayList appWidgets = new ArrayList<>();
- ArrayList orderedScreenIds = new ArrayList<>();
-
- synchronized (sBgDataModel) {
- workspaceItems.addAll(sBgDataModel.workspaceItems);
- appWidgets.addAll(sBgDataModel.appWidgets);
- orderedScreenIds.addAll(sBgDataModel.workspaceScreens);
- }
-
- final int currentScreen;
- {
- int currScreen = synchronizeBindPage != PagedView.INVALID_RESTORE_PAGE
- ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen();
- if (currScreen >= orderedScreenIds.size()) {
- // There may be no workspace screens (just hotseat items and an empty page).
- currScreen = PagedView.INVALID_RESTORE_PAGE;
- }
- currentScreen = currScreen;
- }
- final boolean validFirstPage = currentScreen >= 0;
- final long currentScreenId =
- validFirstPage ? orderedScreenIds.get(currentScreen) : INVALID_SCREEN_ID;
-
- // Separate the items that are on the current screen, and all the other remaining items
- ArrayList currentWorkspaceItems = new ArrayList<>();
- ArrayList otherWorkspaceItems = new ArrayList<>();
- ArrayList currentAppWidgets = new ArrayList<>();
- ArrayList otherAppWidgets = new ArrayList<>();
-
- filterCurrentWorkspaceItems(currentScreenId, workspaceItems, currentWorkspaceItems,
- otherWorkspaceItems);
- filterCurrentAppWidgets(currentScreenId, appWidgets, currentAppWidgets,
- otherAppWidgets);
- sortWorkspaceItemsSpatially(currentWorkspaceItems);
- sortWorkspaceItemsSpatially(otherWorkspaceItems);
-
- // Tell the workspace that we're about to start binding items
- r = new Runnable() {
- public void run() {
- Callbacks callbacks = tryGetCallbacks(oldCallbacks);
- if (callbacks != null) {
- callbacks.clearPendingBinds();
- callbacks.startBinding();
- }
- }
- };
- runOnMainThread(r);
-
- bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
-
- Executor mainExecutor = new DeferredMainThreadExecutor();
- // Load items on the current page.
- bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, mainExecutor);
-
- // 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.
- final Executor deferredExecutor =
- validFirstPage ? new ViewOnDrawExecutor(mHandler) : mainExecutor;
-
- mainExecutor.execute(new Runnable() {
- @Override
- public void run() {
- Callbacks callbacks = tryGetCallbacks(oldCallbacks);
- if (callbacks != null) {
- callbacks.finishFirstPageBind(
- validFirstPage ? (ViewOnDrawExecutor) deferredExecutor : null);
- }
- }
- });
-
- bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, deferredExecutor);
-
- // Tell the workspace that we're done binding items
- r = new Runnable() {
- public void run() {
- Callbacks callbacks = tryGetCallbacks(oldCallbacks);
- if (callbacks != null) {
- callbacks.finishBindingItems();
- }
-
- mIsLoadingAndBindingWorkspace = false;
-
- // Run all the bind complete runnables after workspace is bound.
- if (!mBindCompleteRunnables.isEmpty()) {
- synchronized (mBindCompleteRunnables) {
- for (final Runnable r : mBindCompleteRunnables) {
- runOnWorkerThread(r);
- }
- mBindCompleteRunnables.clear();
- }
- }
-
- // If we're profiling, ensure this is the last thing in the queue.
- if (DEBUG_LOADERS) {
- Log.d(TAG, "bound workspace in "
- + (SystemClock.uptimeMillis()-t) + "ms");
- }
-
- }
- };
- deferredExecutor.execute(r);
-
- if (validFirstPage) {
- r = new Runnable() {
- public void run() {
- Callbacks callbacks = tryGetCallbacks(oldCallbacks);
- if (callbacks != null) {
- // We are loading synchronously, which means, some of the pages will be
- // bound after first draw. Inform the callbacks that page binding is
- // not complete, and schedule the remaining pages.
- if (currentScreen != PagedView.INVALID_RESTORE_PAGE) {
- callbacks.onPageBoundSynchronously(currentScreen);
- }
- callbacks.executeOnNextDraw((ViewOnDrawExecutor) deferredExecutor);
- }
- }
- };
- runOnMainThread(r);
- }
- }
-
- private void updateIconCache() {
- // Ignore packages which have a promise icon.
- HashSet packagesToIgnore = new HashSet<>();
- synchronized (sBgDataModel) {
- for (ItemInfo info : sBgDataModel.itemsIdMap) {
- if (info instanceof ShortcutInfo) {
- ShortcutInfo si = (ShortcutInfo) info;
- if (si.isPromise() && si.getTargetComponent() != null) {
- packagesToIgnore.add(si.getTargetComponent().getPackageName());
- }
- } else if (info instanceof LauncherAppWidgetInfo) {
- LauncherAppWidgetInfo lawi = (LauncherAppWidgetInfo) info;
- if (lawi.hasRestoreFlag(LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY)) {
- packagesToIgnore.add(lawi.providerName.getPackageName());
- }
- }
- }
- }
- mIconCache.updateDbIcons(packagesToIgnore);
- }
-
- private void onlyBindAllApps() {
- final Callbacks oldCallbacks = mCallbacks.get();
- if (oldCallbacks == null) {
- // This launcher has exited and nobody bothered to tell us. Just bail.
- Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
- return;
- }
-
- // shallow copy
- @SuppressWarnings("unchecked")
- final ArrayList list
- = (ArrayList) mBgAllAppsList.data.clone();
- Runnable r = new Runnable() {
- public void run() {
- final long t = SystemClock.uptimeMillis();
- final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
- if (callbacks != null) {
- callbacks.bindAllApplications(list);
- }
- if (DEBUG_LOADERS) {
- Log.d(TAG, "bound all " + list.size() + " apps from cache in "
- + (SystemClock.uptimeMillis() - t) + "ms");
- }
- }
- };
- runOnMainThread(r);
- }
-
- private void scheduleManagedHeuristicRunnable(final ManagedProfileHeuristic heuristic,
- final UserHandle user, final List apps) {
- if (heuristic != null) {
- // Assume the app lists now is updated.
- mIsManagedHeuristicAppsUpdated = false;
- final Runnable managedHeuristicRunnable = new Runnable() {
- @Override
- public void run() {
- if (mIsManagedHeuristicAppsUpdated) {
- // If app list is updated, we need to reschedule it otherwise old app
- // list will override everything in processUserApps().
- sWorker.post(new Runnable() {
- public void run() {
- final List updatedApps =
- mLauncherApps.getActivityList(null, user);
- scheduleManagedHeuristicRunnable(heuristic, user,
- updatedApps);
- }
- });
- } else {
- heuristic.processUserApps(apps);
- }
- }
- };
- runOnMainThread(new Runnable() {
- @Override
- public void run() {
- // Check isLoadingWorkspace on the UI thread, as it is updated on the UI
- // thread.
- if (mIsLoadingAndBindingWorkspace) {
- synchronized (mBindCompleteRunnables) {
- mBindCompleteRunnables.add(managedHeuristicRunnable);
- }
- } else {
- runOnWorkerThread(managedHeuristicRunnable);
- }
- }
- });
- }
- }
-
- private void loadAllApps() {
- final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
-
- final Callbacks oldCallbacks = mCallbacks.get();
- if (oldCallbacks == null) {
- // This launcher has exited and nobody bothered to tell us. Just bail.
- Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
- return;
- }
-
- final List profiles = mUserManager.getUserProfiles();
-
- // Clear the list of apps
- mBgAllAppsList.clear();
- for (UserHandle user : profiles) {
- // Query for the set of apps
- final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
- final List apps = mLauncherApps.getActivityList(null, user);
- if (DEBUG_LOADERS) {
- Log.d(TAG, "getActivityList took "
- + (SystemClock.uptimeMillis()-qiaTime) + "ms for user " + user);
- Log.d(TAG, "getActivityList got " + apps.size() + " apps for user " + user);
- }
- // Fail if we don't have any apps
- // TODO: Fix this. Only fail for the current user.
- if (apps == null || apps.isEmpty()) {
- return;
- }
- boolean quietMode = mUserManager.isQuietModeEnabled(user);
- // 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);
- }
- final ManagedProfileHeuristic heuristic = ManagedProfileHeuristic.get(mContext, user);
- if (heuristic != null) {
- scheduleManagedHeuristicRunnable(heuristic, user, apps);
- }
- }
- // Huh? Shouldn't this be inside the Runnable below?
- final ArrayList added = mBgAllAppsList.added;
- mBgAllAppsList.added = new ArrayList();
-
- // Post callback on main thread
- mHandler.post(new Runnable() {
- public void run() {
-
- final long bindTime = SystemClock.uptimeMillis();
- final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
- if (callbacks != null) {
- callbacks.bindAllApplications(added);
- if (DEBUG_LOADERS) {
- Log.d(TAG, "bound " + added.size() + " apps in "
- + (SystemClock.uptimeMillis() - bindTime) + "ms");
- }
- } else {
- Log.i(TAG, "not binding apps: no Launcher activity");
- }
- }
- });
- // Cleanup any data stored for a deleted user.
- ManagedProfileHeuristic.processAllUsers(profiles, mContext);
- if (DEBUG_LOADERS) {
- Log.d(TAG, "Icons processed in "
- + (SystemClock.uptimeMillis() - loadTime) + "ms");
- }
- }
-
- private void loadDeepShortcuts() {
- sBgDataModel.deepShortcutMap.clear();
- DeepShortcutManager shortcutManager = DeepShortcutManager.getInstance(mContext);
- mHasShortcutHostPermission = shortcutManager.hasHostPermission();
- if (mHasShortcutHostPermission) {
- for (UserHandle user : mUserManager.getUserProfiles()) {
- if (mUserManager.isUserUnlocked(user)) {
- List shortcuts =
- shortcutManager.queryForAllShortcuts(user);
- sBgDataModel.updateDeepShortcutMap(null, user, shortcuts);
- }
+ @Override
+ public void close() {
+ synchronized (mLock) {
+ // If we are still the last one to be scheduled, remove ourselves.
+ if (mLoaderTask == mTask) {
+ mLoaderTask = null;
}
+ mIsLoaderTaskRunning = false;
}
}
}
- public void bindDeepShortcuts() {
- final MultiHashMap shortcutMapCopy =
- sBgDataModel.deepShortcutMap.clone();
- Runnable r = new Runnable() {
- @Override
- public void run() {
- Callbacks callbacks = getCallback();
- if (callbacks != null) {
- callbacks.bindDeepShortcutMap(shortcutMapCopy);
- }
- }
- };
- runOnMainThread(r);
+ public LoaderTransaction beginLoader(LoaderTask task) throws CancellationException {
+ return new LoaderTransaction(task);
}
/**
@@ -1835,14 +606,8 @@ public class LauncherModel extends BroadcastReceiver
CacheDataUpdatedTask.OP_CACHE_UPDATE, user, updatedPackages));
}
- void enqueueModelUpdateTask(BaseModelUpdateTask task) {
- if (!mModelLoaded && mLoaderTask == null) {
- if (DEBUG_LOADERS) {
- Log.d(TAG, "enqueueModelUpdateTask Ignoring task since loader is pending=" + task);
- }
- return;
- }
- task.init(this);
+ public void enqueueModelUpdateTask(ModelUpdateTask task) {
+ task.init(mApp, this, sBgDataModel, mBgAllAppsList, mUiExecutor);
runOnWorkerThread(task);
}
@@ -1858,51 +623,14 @@ public class LauncherModel extends BroadcastReceiver
/**
* A runnable which changes/updates the data model of the launcher based on certain events.
*/
- public static abstract class BaseModelUpdateTask implements Runnable {
-
- private LauncherModel mModel;
- private DeferredHandler mUiHandler;
-
- /* package private */
- void init(LauncherModel model) {
- mModel = model;
- mUiHandler = mModel.mHandler;
- }
-
- @Override
- public void run() {
- if (!mModel.mHasLoaderCompletedOnce) {
- // Loader has not yet run.
- return;
- }
- execute(mModel.mApp, sBgDataModel, mModel.mBgAllAppsList);
- }
+ public interface ModelUpdateTask extends Runnable {
/**
- * Execute the actual task. Called on the worker thread.
+ * Called before the task is posted to initialize the internal state.
*/
- public abstract void execute(
- LauncherAppState app, BgDataModel dataModel, AllAppsList apps);
+ void init(LauncherAppState app, LauncherModel model,
+ BgDataModel dataModel, AllAppsList allAppsList, Executor uiExecutor);
- /**
- * Schedules a {@param task} to be executed on the current callbacks.
- */
- public final void scheduleCallbackTask(final CallbackTask task) {
- final Callbacks callbacks = mModel.getCallback();
- mUiHandler.post(new Runnable() {
- public void run() {
- Callbacks cb = mModel.getCallback();
- if (callbacks == cb && cb != null) {
- task.execute(callbacks);
- }
- }
- });
- }
-
- public ModelWriter getModelWriter() {
- // Updates from model task, do not deal with icon position in hotseat.
- return mModel.getWriter(false /* hasVerticalHotseat */);
- }
}
public void updateAndBindShortcutInfo(final ShortcutInfo si, final ShortcutInfoCompat info) {
@@ -1920,7 +648,7 @@ public class LauncherModel extends BroadcastReceiver
* Utility method to update a shortcut on the background thread.
*/
public void updateAndBindShortcutInfo(final Provider shortcutProvider) {
- enqueueModelUpdateTask(new ExtendedModelTask() {
+ enqueueModelUpdateTask(new BaseModelUpdateTask() {
@Override
public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
ShortcutInfo info = shortcutProvider.get();
@@ -1931,43 +659,16 @@ public class LauncherModel extends BroadcastReceiver
});
}
- private void bindWidgetsModel(final Callbacks callbacks) {
- final MultiHashMap widgets
- = mBgWidgetsModel.getWidgetsMap().clone();
- mHandler.post(new Runnable() {
+ public void refreshAndBindWidgetsAndShortcuts(@Nullable final PackageUserKey packageUser) {
+ enqueueModelUpdateTask(new BaseModelUpdateTask() {
@Override
- public void run() {
- Callbacks cb = getCallback();
- if (callbacks == cb && cb != null) {
- callbacks.bindAllWidgets(widgets);
- }
+ public void execute(LauncherAppState app, BgDataModel dataModel, AllAppsList apps) {
+ dataModel.widgetsModel.update(app, packageUser);
+ bindUpdatedWidgets(dataModel);
}
});
}
- public void refreshAndBindWidgetsAndShortcuts(final Callbacks callbacks,
- final boolean bindFirst, @Nullable final PackageUserKey packageUser) {
- runOnWorkerThread(new Runnable() {
- @Override
- public void run() {
- if (bindFirst && !mBgWidgetsModel.isEmpty()) {
- bindWidgetsModel(callbacks);
- }
- ArrayList widgets = mBgWidgetsModel.update(
- mApp.getContext(), packageUser);
- bindWidgetsModel(callbacks);
-
- // update the Widget entries inside DB on the worker thread.
- mApp.getWidgetCache().removeObsoletePreviews(widgets, packageUser);
- }
- });
- }
-
- static boolean isValidProvider(AppWidgetProviderInfo provider) {
- return (provider != null) && (provider.provider != null)
- && (provider.provider.getPackageName() != null);
- }
-
public void dumpState(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
if (args.length > 0 && TextUtils.equals(args[0], "--all")) {
writer.println(prefix + "All apps list: size=" + mBgAllAppsList.data.size());
@@ -1983,23 +684,6 @@ public class LauncherModel extends BroadcastReceiver
return mCallbacks != null ? mCallbacks.get() : null;
}
- /**
- * @return {@link FolderInfo} if its already loaded.
- */
- public FolderInfo findFolderById(Long folderId) {
- synchronized (sBgDataModel) {
- return sBgDataModel.folders.get(folderId);
- }
- }
-
- @Thunk class DeferredMainThreadExecutor implements Executor {
-
- @Override
- public void execute(Runnable command) {
- runOnMainThread(command);
- }
- }
-
/**
* @return the looper for the worker thread which can be used to start background tasks.
*/
diff --git a/src/com/android/launcher3/LauncherProvider.java b/src/com/android/launcher3/LauncherProvider.java
index 3150d5b0e3..4813571f54 100644
--- a/src/com/android/launcher3/LauncherProvider.java
+++ b/src/com/android/launcher3/LauncherProvider.java
@@ -16,6 +16,7 @@
package com.android.launcher3;
+import android.annotation.TargetApi;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
@@ -38,6 +39,7 @@ import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.os.Binder;
+import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
@@ -53,43 +55,39 @@ import com.android.launcher3.LauncherSettings.Favorites;
import com.android.launcher3.LauncherSettings.WorkspaceScreens;
import com.android.launcher3.compat.UserManagerCompat;
import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.config.ProviderConfig;
import com.android.launcher3.dynamicui.ExtractionUtils;
import com.android.launcher3.graphics.IconShapeOverride;
import com.android.launcher3.logging.FileLog;
+import com.android.launcher3.model.DbDowngradeHelper;
import com.android.launcher3.provider.LauncherDbUtils;
+import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
import com.android.launcher3.provider.RestoreDbTask;
import com.android.launcher3.util.ManagedProfileHeuristic;
import com.android.launcher3.util.NoLocaleSqliteContext;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.util.Thunk;
+import java.io.File;
import java.io.FileDescriptor;
import java.io.PrintWriter;
-import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
+import java.util.LinkedHashSet;
public class LauncherProvider extends ContentProvider {
private static final String TAG = "LauncherProvider";
private static final boolean LOGD = false;
+ private static final String DOWNGRADE_SCHEMA_FILE = "downgrade_schema.json";
+
/**
* Represents the schema of the database. Changes in scheme need not be backwards compatible.
*/
- private static final int SCHEMA_VERSION = 27;
- /**
- * Represents the actual data. It could include additional validations and normalizations added
- * overtime. These must be backwards compatible, else we risk breaking old devices during
- * restore or binary version downgrade.
- */
- private static final int DATA_VERSION = 3;
+ public static final int SCHEMA_VERSION = 27;
- private static final String PREF_KEY_DATA_VERISON = "provider_data_version";
-
- public static final String AUTHORITY = ProviderConfig.AUTHORITY;
+ public static final String AUTHORITY = (BuildConfig.APPLICATION_ID + ".settings").intern();
static final String EMPTY_DATABASE_CREATED = "EMPTY_DATABASE_CREATED";
@@ -114,7 +112,7 @@ public class LauncherProvider extends ContentProvider {
@Override
public boolean onCreate() {
- if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_DOGFOOD_BUILD) {
Log.d(TAG, "Launcher process started");
}
mListenerHandler = new Handler(mListenerWrapper);
@@ -305,8 +303,7 @@ public class LauncherProvider extends ContentProvider {
SqlArguments args = new SqlArguments(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
- db.beginTransaction();
- try {
+ try (SQLiteTransaction t = new SQLiteTransaction(db)) {
int numValues = values.length;
for (int i = 0; i < numValues; i++) {
addModifiedTime(values[i]);
@@ -314,9 +311,7 @@ public class LauncherProvider extends ContentProvider {
return 0;
}
}
- db.setTransactionSuccessful();
- } finally {
- db.endTransaction();
+ t.commit();
}
notifyListeners();
@@ -328,15 +323,11 @@ public class LauncherProvider extends ContentProvider {
public ContentProviderResult[] applyBatch(ArrayList operations)
throws OperationApplicationException {
createDbIfNotExists();
- SQLiteDatabase db = mOpenHelper.getWritableDatabase();
- db.beginTransaction();
- try {
+ try (SQLiteTransaction t = new SQLiteTransaction(mOpenHelper.getWritableDatabase())) {
ContentProviderResult[] result = super.applyBatch(operations);
- db.setTransactionSuccessful();
+ t.commit();
reloadLauncherIfExternal();
return result;
- } finally {
- db.endTransaction();
}
}
@@ -442,31 +433,26 @@ public class LauncherProvider extends ContentProvider {
private ArrayList deleteEmptyFolders() {
ArrayList folderIds = new ArrayList<>();
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
- db.beginTransaction();
- try {
+ try (SQLiteTransaction t = new SQLiteTransaction(db)) {
// Select folders whose id do not match any container value.
String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
+ LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
+ LauncherSettings.Favorites._ID + " NOT IN (SELECT " +
LauncherSettings.Favorites.CONTAINER + " FROM "
+ Favorites.TABLE_NAME + ")";
- Cursor c = db.query(Favorites.TABLE_NAME,
+ try (Cursor c = db.query(Favorites.TABLE_NAME,
new String[] {LauncherSettings.Favorites._ID},
- selection, null, null, null, null);
- while (c.moveToNext()) {
- folderIds.add(c.getLong(0));
+ selection, null, null, null, null)) {
+ LauncherDbUtils.iterateCursor(c, 0, folderIds);
}
- c.close();
if (!folderIds.isEmpty()) {
db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
LauncherSettings.Favorites._ID, folderIds), null);
}
- db.setTransactionSuccessful();
+ t.commit();
} catch (SQLException ex) {
Log.e(TAG, ex.getMessage(), ex);
folderIds.clear();
- } finally {
- db.endTransaction();
}
return folderIds;
}
@@ -714,50 +700,30 @@ public class LauncherProvider extends ContentProvider {
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
- SharedPreferences prefs = mContext
- .getSharedPreferences(LauncherFiles.DEVICE_PREFERENCES_KEY, 0);
- int oldVersion = prefs.getInt(PREF_KEY_DATA_VERISON, 0);
- if (oldVersion != DATA_VERSION) {
- // Only run the data upgrade path for an existing db.
- if (!Utilities.getPrefs(mContext).getBoolean(EMPTY_DATABASE_CREATED, false)) {
- db.beginTransaction();
- try {
- onDataUpgrade(db, oldVersion);
- db.setTransactionSuccessful();
- } catch (Exception e) {
- Log.d(TAG, "Error updating data version, ignoring", e);
- return;
- } finally {
- db.endTransaction();
- }
- }
- prefs.edit().putInt(PREF_KEY_DATA_VERISON, DATA_VERSION).apply();
+
+ File schemaFile = mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE);
+ if (!schemaFile.exists()) {
+ handleOneTimeDataUpgrade(db);
}
+ DbDowngradeHelper.updateSchemaFile(schemaFile, SCHEMA_VERSION, mContext,
+ R.raw.downgrade_schema);
}
/**
- * Called when the data is updated as part of app update. It can be called multiple times
- * with old version, even though it had been run before. The changes made here must be
- * backwards compatible, else we risk breaking old devices during restore or binary
- * version downgrade.
+ * One-time data updated before support of onDowngrade was added. This update is backwards
+ * compatible and can safely be run multiple times.
+ * Note: No new logic should be added here after release, as the new logic might not get
+ * executed on an existing device.
+ * TODO: Move this to db upgrade path, once the downgrade path is released.
*/
- protected void onDataUpgrade(SQLiteDatabase db, int oldVersion) {
- switch (oldVersion) {
- case 0:
- case 1: {
- // Remove "profile extra"
- UserManagerCompat um = UserManagerCompat.getInstance(mContext);
- for (UserHandle user : um.getUserProfiles()) {
- long serial = um.getSerialNumberForUser(user);
- String sql = "update favorites set intent = replace(intent, "
- + "';l.profile=" + serial + ";', ';') where itemType = 0;";
- db.execSQL(sql);
- }
- }
- case 2:
- case 3:
- // data updated
- return;
+ protected void handleOneTimeDataUpgrade(SQLiteDatabase db) {
+ // Remove "profile extra"
+ UserManagerCompat um = UserManagerCompat.getInstance(mContext);
+ for (UserHandle user : um.getUserProfiles()) {
+ long serial = um.getSerialNumberForUser(user);
+ String sql = "update favorites set intent = replace(intent, "
+ + "';l.profile=" + serial + ";', ';') where itemType = 0;";
+ db.execSQL(sql);
}
}
@@ -774,35 +740,29 @@ public class LauncherProvider extends ContentProvider {
addWorkspacesTable(db, false);
}
case 13: {
- db.beginTransaction();
- try {
+ try (SQLiteTransaction t = new SQLiteTransaction(db)) {
// Insert new column for holding widget provider name
db.execSQL("ALTER TABLE favorites " +
"ADD COLUMN appWidgetProvider TEXT;");
- db.setTransactionSuccessful();
+ t.commit();
} catch (SQLException ex) {
Log.e(TAG, ex.getMessage(), ex);
// Old version remains, which means we wipe old data
break;
- } finally {
- db.endTransaction();
}
}
case 14: {
- db.beginTransaction();
- try {
+ try (SQLiteTransaction t = new SQLiteTransaction(db)) {
// Insert new column for holding update timestamp
db.execSQL("ALTER TABLE favorites " +
"ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
db.execSQL("ALTER TABLE workspaceScreens " +
"ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
- db.setTransactionSuccessful();
+ t.commit();
} catch (SQLException ex) {
Log.e(TAG, ex.getMessage(), ex);
// Old version remains, which means we wipe old data
break;
- } finally {
- db.endTransaction();
}
}
case 15: {
@@ -870,29 +830,25 @@ public class LauncherProvider extends ContentProvider {
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- if (oldVersion == 28 && newVersion == 27) {
- // TODO: remove this check. This is only applicable for internal development/testing
- // and for any released version of Launcher.
- return;
+ try {
+ DbDowngradeHelper.parse(mContext.getFileStreamPath(DOWNGRADE_SCHEMA_FILE))
+ .onDowngrade(db, oldVersion, newVersion);
+ } catch (Exception e) {
+ Log.d(TAG, "Unable to downgrade from: " + oldVersion + " to " + newVersion +
+ ". Wiping databse.", e);
+ createEmptyDB(db);
}
- // This shouldn't happen -- throw our hands up in the air and start over.
- Log.w(TAG, "Database version downgrade from: " + oldVersion + " to " + newVersion +
- ". Wiping databse.");
- createEmptyDB(db);
}
/**
* Clears all the data for a fresh start.
*/
public void createEmptyDB(SQLiteDatabase db) {
- db.beginTransaction();
- try {
+ try (SQLiteTransaction t = new SQLiteTransaction(db)) {
db.execSQL("DROP TABLE IF EXISTS " + Favorites.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
onCreate(db);
- db.setTransactionSuccessful();
- } finally {
- db.endTransaction();
+ t.commit();
}
}
@@ -900,40 +856,39 @@ public class LauncherProvider extends ContentProvider {
* Removes widgets which are registered to the Launcher's host, but are not present
* in our model.
*/
+ @TargetApi(Build.VERSION_CODES.O)
public void removeGhostWidgets(SQLiteDatabase db) {
// Get all existing widget ids.
final AppWidgetHost host = newLauncherWidgetHost();
final int[] allWidgets;
try {
- Method getter = AppWidgetHost.class.getDeclaredMethod("getAppWidgetIds");
- getter.setAccessible(true);
- allWidgets = (int[]) getter.invoke(host);
- } catch (Exception e) {
+ // Although the method was defined in O, it has existed since the beginning of time,
+ // so it might work on older platforms as well.
+ allWidgets = host.getAppWidgetIds();
+ } catch (IncompatibleClassChangeError e) {
Log.e(TAG, "getAppWidgetIds not supported", e);
return;
}
- try {
- Cursor c = db.query(Favorites.TABLE_NAME,
- new String[] {Favorites.APPWIDGET_ID },
- "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null);
- HashSet validWidgets = new HashSet<>();
+ final HashSet validWidgets = new HashSet<>();
+ try (Cursor c = db.query(Favorites.TABLE_NAME,
+ new String[] {Favorites.APPWIDGET_ID },
+ "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
while (c.moveToNext()) {
validWidgets.add(c.getInt(0));
}
- c.close();
-
- for (int widgetId : allWidgets) {
- if (!validWidgets.contains(widgetId)) {
- try {
- FileLog.d(TAG, "Deleting invalid widget " + widgetId);
- host.deleteAppWidgetId(widgetId);
- } catch (RuntimeException e) {
- // Ignore
- }
- }
- }
} catch (SQLException ex) {
Log.w(TAG, "Error getting widgets list", ex);
+ return;
+ }
+ for (int widgetId : allWidgets) {
+ if (!validWidgets.contains(widgetId)) {
+ try {
+ FileLog.d(TAG, "Deleting invalid widget " + widgetId);
+ host.deleteAppWidgetId(widgetId);
+ } catch (RuntimeException e) {
+ // Ignore
+ }
+ }
}
}
@@ -942,22 +897,16 @@ public class LauncherProvider extends ContentProvider {
* launcher activity target with {@link Favorites#ITEM_TYPE_APPLICATION}.
*/
@Thunk void convertShortcutsToLauncherActivities(SQLiteDatabase db) {
- db.beginTransaction();
- Cursor c = null;
- SQLiteStatement updateStmt = null;
-
- try {
- // Only consider the primary user as other users can't have a shortcut.
- long userSerial = getDefaultUserSerial();
- c = db.query(Favorites.TABLE_NAME, new String[] {
- Favorites._ID,
- Favorites.INTENT,
- }, "itemType=" + Favorites.ITEM_TYPE_SHORTCUT + " AND profileId=" + userSerial,
- null, null, null, null);
-
- updateStmt = db.compileStatement("UPDATE favorites SET itemType="
- + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?");
-
+ try (SQLiteTransaction t = new SQLiteTransaction(db);
+ // Only consider the primary user as other users can't have a shortcut.
+ Cursor c = db.query(Favorites.TABLE_NAME,
+ new String[] { Favorites._ID, Favorites.INTENT},
+ "itemType=" + Favorites.ITEM_TYPE_SHORTCUT +
+ " AND profileId=" + getDefaultUserSerial(),
+ null, null, null, null);
+ SQLiteStatement updateStmt = db.compileStatement("UPDATE favorites SET itemType="
+ + Favorites.ITEM_TYPE_APPLICATION + " WHERE _id=?")
+ ) {
final int idIndex = c.getColumnIndexOrThrow(Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(Favorites.INTENT);
@@ -979,17 +928,9 @@ public class LauncherProvider extends ContentProvider {
updateStmt.bindLong(1, id);
updateStmt.executeUpdateDelete();
}
- db.setTransactionSuccessful();
+ t.commit();
} catch (SQLException ex) {
Log.w(TAG, "Error deduping shortcuts", ex);
- } finally {
- db.endTransaction();
- if (c != null) {
- c.close();
- }
- if (updateStmt != null) {
- updateStmt.close();
- }
}
}
@@ -997,26 +938,17 @@ public class LauncherProvider extends ContentProvider {
* Recreates workspace table and migrates data to the new table.
*/
public boolean recreateWorkspaceTable(SQLiteDatabase db) {
- db.beginTransaction();
- try {
- Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
+ try (SQLiteTransaction t = new SQLiteTransaction(db)) {
+ final ArrayList sortedIDs;
+
+ try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
new String[] {LauncherSettings.WorkspaceScreens._ID},
null, null, null, null,
- LauncherSettings.WorkspaceScreens.SCREEN_RANK);
- ArrayList sortedIDs = new ArrayList();
- long maxId = 0;
- try {
- while (c.moveToNext()) {
- Long id = c.getLong(0);
- if (!sortedIDs.contains(id)) {
- sortedIDs.add(id);
- maxId = Math.max(maxId, id);
- }
- }
- } finally {
- c.close();
+ LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
+ // Use LinkedHashSet so that ordering is preserved
+ sortedIDs = new ArrayList<>(
+ LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet()));
}
-
db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
addWorkspacesTable(db, false);
@@ -1029,21 +961,18 @@ public class LauncherProvider extends ContentProvider {
addModifiedTime(values);
db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
}
- db.setTransactionSuccessful();
- mMaxScreenId = maxId;
+ t.commit();
+ mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
} catch (SQLException ex) {
// Old version remains, which means we wipe old data
Log.e(TAG, ex.getMessage(), ex);
return false;
- } finally {
- db.endTransaction();
}
return true;
}
@Thunk boolean updateFolderItemsRank(SQLiteDatabase db, boolean addRankColumn) {
- db.beginTransaction();
- try {
+ try (SQLiteTransaction t = new SQLiteTransaction(db)) {
if (addRankColumn) {
// Insert new column for holding rank
db.execSQL("ALTER TABLE favorites ADD COLUMN rank INTEGER NOT NULL DEFAULT 0;");
@@ -1062,13 +991,11 @@ public class LauncherProvider extends ContentProvider {
}
c.close();
- db.setTransactionSuccessful();
+ t.commit();
} catch (SQLException ex) {
// Old version remains, which means we wipe old data
Log.e(TAG, ex.getMessage(), ex);
return false;
- } finally {
- db.endTransaction();
}
return true;
}
@@ -1078,16 +1005,13 @@ public class LauncherProvider extends ContentProvider {
}
private boolean addIntegerColumn(SQLiteDatabase db, String columnName, long defaultValue) {
- db.beginTransaction();
- try {
+ try (SQLiteTransaction t = new SQLiteTransaction(db)) {
db.execSQL("ALTER TABLE favorites ADD COLUMN "
+ columnName + " INTEGER NOT NULL DEFAULT " + defaultValue + ";");
- db.setTransactionSuccessful();
+ t.commit();
} catch (SQLException ex) {
Log.e(TAG, ex.getMessage(), ex);
return false;
- } finally {
- db.endTransaction();
}
return true;
}
diff --git a/src/com/android/launcher3/LauncherSettings.java b/src/com/android/launcher3/LauncherSettings.java
index b25b256af9..87f62eb01b 100644
--- a/src/com/android/launcher3/LauncherSettings.java
+++ b/src/com/android/launcher3/LauncherSettings.java
@@ -22,8 +22,6 @@ import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
-import com.android.launcher3.config.ProviderConfig;
-
/**
* Settings related utilities.
*/
@@ -101,7 +99,7 @@ public class LauncherSettings {
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI = Uri.parse("content://" +
- ProviderConfig.AUTHORITY + "/" + TABLE_NAME);
+ LauncherProvider.AUTHORITY + "/" + TABLE_NAME);
/**
* The rank of this screen -- ie. how it is ordered relative to the other screens.
@@ -121,7 +119,7 @@ public class LauncherSettings {
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI = Uri.parse("content://" +
- ProviderConfig.AUTHORITY + "/" + TABLE_NAME);
+ LauncherProvider.AUTHORITY + "/" + TABLE_NAME);
/**
* The content:// style URL for a given row, identified by its id.
@@ -131,7 +129,7 @@ public class LauncherSettings {
* @return The unique content URL for the specified row.
*/
public static Uri getContentUri(long id) {
- return Uri.parse("content://" + ProviderConfig.AUTHORITY +
+ return Uri.parse("content://" + LauncherProvider.AUTHORITY +
"/" + TABLE_NAME + "/" + id);
}
@@ -155,6 +153,18 @@ public class LauncherSettings {
}
}
+ static final String itemTypeToString(int type) {
+ switch(type) {
+ case ITEM_TYPE_APPLICATION: return "APP";
+ case ITEM_TYPE_SHORTCUT: return "SHORTCUT";
+ case ITEM_TYPE_FOLDER: return "FOLDER";
+ case ITEM_TYPE_APPWIDGET: return "WIDGET";
+ case ITEM_TYPE_CUSTOM_APPWIDGET: return "CUSTOMWIDGET";
+ case ITEM_TYPE_DEEP_SHORTCUT: return "DEEPSHORTCUT";
+ default: return String.valueOf(type);
+ }
+ }
+
/**
* The screen holding the favorite (if container is CONTAINER_DESKTOP)
* Type: INTEGER
@@ -280,7 +290,7 @@ public class LauncherSettings {
public static final class Settings {
public static final Uri CONTENT_URI = Uri.parse("content://" +
- ProviderConfig.AUTHORITY + "/settings");
+ LauncherProvider.AUTHORITY + "/settings");
public static final String METHOD_CLEAR_EMPTY_DB_FLAG = "clear_empty_db_flag";
public static final String METHOD_WAS_EMPTY_DB_CREATED = "get_empty_db_flag";
diff --git a/src/com/android/launcher3/LauncherStateTransitionAnimation.java b/src/com/android/launcher3/LauncherStateTransitionAnimation.java
index 39c466db88..e7349f040d 100644
--- a/src/com/android/launcher3/LauncherStateTransitionAnimation.java
+++ b/src/com/android/launcher3/LauncherStateTransitionAnimation.java
@@ -31,8 +31,8 @@ import android.view.animation.AccelerateInterpolator;
import com.android.launcher3.allapps.AllAppsContainerView;
import com.android.launcher3.allapps.AllAppsTransitionController;
import com.android.launcher3.anim.AnimationLayerSet;
+import com.android.launcher3.anim.CircleRevealOutlineProvider;
import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.util.CircleRevealOutlineProvider;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.widget.WidgetsContainerView;
@@ -127,12 +127,8 @@ public class LauncherStateTransitionAnimation {
/**
* Starts an animation to the apps view.
- *
- * @param startSearchAfterTransition Immediately starts app search after the transition to
- * All Apps is completed.
*/
- public void startAnimationToAllApps(
- final boolean animated, final boolean startSearchAfterTransition) {
+ public void startAnimationToAllApps(final boolean animated) {
final AllAppsContainerView toView = mLauncher.getAppsView();
final View buttonView = mLauncher.getStartViewForAllAppsRevealAnimation();
PrivateTransitionCallbacks cb = new PrivateTransitionCallbacks(1f) {
@@ -156,9 +152,6 @@ public class LauncherStateTransitionAnimation {
@Override
void onTransitionComplete() {
mLauncher.getUserEventDispatcher().resetElapsedContainerMillis();
- if (startSearchAfterTransition) {
- toView.startAppsSearch();
- }
}
};
int animType = CIRCULAR_REVEAL;
diff --git a/src/com/android/launcher3/MainThreadExecutor.java b/src/com/android/launcher3/MainThreadExecutor.java
index 4ca0a59d81..5094682333 100644
--- a/src/com/android/launcher3/MainThreadExecutor.java
+++ b/src/com/android/launcher3/MainThreadExecutor.java
@@ -18,14 +18,14 @@ package com.android.launcher3;
import android.os.Looper;
-import com.android.launcher3.util.LooperExecuter;
+import com.android.launcher3.util.LooperExecutor;
/**
* An executor service that executes its tasks on the main thread.
*
* Shutting down this executor is not supported.
*/
-public class MainThreadExecutor extends LooperExecuter {
+public class MainThreadExecutor extends LooperExecutor {
public MainThreadExecutor() {
super(Looper.getMainLooper());
diff --git a/src/com/android/launcher3/PagedView.java b/src/com/android/launcher3/PagedView.java
index fb6a611e75..255677a539 100644
--- a/src/com/android/launcher3/PagedView.java
+++ b/src/com/android/launcher3/PagedView.java
@@ -50,6 +50,7 @@ import android.view.animation.Interpolator;
import com.android.launcher3.anim.PropertyListBuilder;
import com.android.launcher3.pageindicators.PageIndicator;
import com.android.launcher3.util.LauncherEdgeEffect;
+import com.android.launcher3.util.Themes;
import com.android.launcher3.util.Thunk;
import java.util.ArrayList;
@@ -226,11 +227,10 @@ public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarc
mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * density);
setOnHierarchyChangeListener(this);
setWillNotDraw(false);
- }
- protected void setEdgeGlowColor(int color) {
- mEdgeGlowLeft.setColor(color);
- mEdgeGlowRight.setColor(color);
+ int edgeEffectColor = Themes.getAttrColor(getContext(), android.R.attr.colorEdgeEffect);
+ mEdgeGlowLeft.setColor(edgeEffectColor);
+ mEdgeGlowRight.setColor(edgeEffectColor);
}
protected void setDefaultInterpolator(Interpolator interpolator) {
@@ -1599,7 +1599,7 @@ public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarc
mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
- Math.abs(velocityX) > mFlingThresholdVelocity;
+ shouldFlingForVelocity(velocityX);
if (!mFreeScroll) {
// In the case that the page is moved far to one direction and then is flung
@@ -1705,6 +1705,10 @@ public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarc
return true;
}
+ protected boolean shouldFlingForVelocity(int velocityX) {
+ return Math.abs(velocityX) > mFlingThresholdVelocity;
+ }
+
private void resetTouchState() {
releaseVelocityTracker();
endReordering();
diff --git a/src/com/android/launcher3/PendingAppWidgetHostView.java b/src/com/android/launcher3/PendingAppWidgetHostView.java
index b163464ddb..de424aba1f 100644
--- a/src/com/android/launcher3/PendingAppWidgetHostView.java
+++ b/src/com/android/launcher3/PendingAppWidgetHostView.java
@@ -80,10 +80,13 @@ public class PendingAppWidgetHostView extends LauncherAppWidgetHostView
updateAppWidget(null);
setOnClickListener(mLauncher);
- // Load icon
- PackageItemInfo item = new PackageItemInfo(info.providerName.getPackageName());
- item.user = info.user;
- cache.updateIconInBackground(this, item);
+ if (info.pendingItemInfo == null) {
+ info.pendingItemInfo = new PackageItemInfo(info.providerName.getPackageName());
+ info.pendingItemInfo.user = info.user;
+ cache.updateIconInBackground(this, info.pendingItemInfo);
+ } else {
+ reapplyItemInfo(info.pendingItemInfo);
+ }
}
@Override
diff --git a/src/com/android/launcher3/PinchAnimationManager.java b/src/com/android/launcher3/PinchAnimationManager.java
index f8196e5f6d..c3d3bb3dfa 100644
--- a/src/com/android/launcher3/PinchAnimationManager.java
+++ b/src/com/android/launcher3/PinchAnimationManager.java
@@ -56,11 +56,10 @@ public class PinchAnimationManager {
private static final LinearInterpolator INTERPOLATOR = new LinearInterpolator();
private static final int INDEX_HOTSEAT = 0;
- private static final int INDEX_QSB = 1;
- private static final int INDEX_OVERVIEW_PANEL_BUTTONS = 2;
- private static final int INDEX_SCRIM = 3;
+ private static final int INDEX_OVERVIEW_PANEL_BUTTONS = 1;
+ private static final int INDEX_SCRIM = 2;
- private final Animator[] mAnimators = new Animator[4];
+ private final Animator[] mAnimators = new Animator[3];
private Launcher mLauncher;
private Workspace mWorkspace;
@@ -196,8 +195,6 @@ public class PinchAnimationManager {
private void animateHotseatAndQsb(boolean show) {
startAnimator(INDEX_HOTSEAT,
mWorkspace.createHotseatAlphaAnimator(show ? 1 : 0), THRESHOLD_ANIM_DURATION);
- startAnimator(INDEX_QSB, mWorkspace.mQsbAlphaController.animateAlphaAtIndex(
- show ? 1 : 0, Workspace.QSB_ALPHA_INDEX_STATE_CHANGE), THRESHOLD_ANIM_DURATION);
}
private void animateOverviewPanelButtons(boolean show) {
diff --git a/src/com/android/launcher3/PromiseAppInfo.java b/src/com/android/launcher3/PromiseAppInfo.java
new file mode 100644
index 0000000000..07515d08aa
--- /dev/null
+++ b/src/com/android/launcher3/PromiseAppInfo.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.launcher3;
+
+import android.content.Intent;
+import android.support.annotation.NonNull;
+
+import com.android.launcher3.compat.PackageInstallerCompat;
+import com.android.launcher3.util.PackageManagerHelper;
+
+public class PromiseAppInfo extends AppInfo {
+
+ public int level = 0;
+
+ public PromiseAppInfo(@NonNull PackageInstallerCompat.PackageInstallInfo installInfo) {
+ componentName = installInfo.componentName;
+ intent = new Intent(Intent.ACTION_MAIN)
+ .addCategory(Intent.CATEGORY_LAUNCHER)
+ .setComponent(componentName)
+ .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
+ | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
+ }
+
+ @Override
+ public ShortcutInfo makeShortcut() {
+ ShortcutInfo shortcut = new ShortcutInfo(this);
+ shortcut.setInstallProgress(level);
+ // We need to update the component name when the apk is installed
+ shortcut.status |= ShortcutInfo.FLAG_AUTOINSTALL_ICON;
+ // Since the user is manually placing it on homescreen, it should not be auto-removed later
+ shortcut.status |= ShortcutInfo.FLAG_RESTORE_STARTED;
+ return shortcut;
+ }
+
+ public Intent getMarketIntent() {
+ return PackageManagerHelper.getMarketIntent(componentName.getPackageName());
+ }
+}
diff --git a/src/com/android/launcher3/SessionCommitReceiver.java b/src/com/android/launcher3/SessionCommitReceiver.java
index 61bcc178cf..8caba75cd5 100644
--- a/src/com/android/launcher3/SessionCommitReceiver.java
+++ b/src/com/android/launcher3/SessionCommitReceiver.java
@@ -67,18 +67,19 @@ public class SessionCommitReceiver extends BroadcastReceiver {
SessionInfo info = intent.getParcelableExtra(PackageInstaller.EXTRA_SESSION);
UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
- if (TextUtils.isEmpty(info.getAppPackageName()) ||
- info.getInstallReason() != PackageManager.INSTALL_REASON_USER) {
- return;
+ if (Process.myUserHandle().equals(user)) {
+ if (TextUtils.isEmpty(info.getAppPackageName()) ||
+ info.getInstallReason() != PackageManager.INSTALL_REASON_USER) {
+ return;
+ }
}
- if (!Process.myUserHandle().equals(user)) {
- // Managed profile is handled using ManagedProfileHeuristic
- return;
- }
+ queueAppIconAddition(context, info.getAppPackageName(), user);
+ }
+ public static void queueAppIconAddition(Context context, String packageName, UserHandle user) {
List activities = LauncherAppsCompat.getInstance(context)
- .getActivityList(info.getAppPackageName(), user);
+ .getActivityList(packageName, user);
if (activities == null || activities.isEmpty()) {
// no activity found
return;
diff --git a/src/com/android/launcher3/SettingsActivity.java b/src/com/android/launcher3/SettingsActivity.java
index 0902b2029d..b7b75f87d8 100644
--- a/src/com/android/launcher3/SettingsActivity.java
+++ b/src/com/android/launcher3/SettingsActivity.java
@@ -26,7 +26,6 @@ import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.provider.Settings;
import android.provider.Settings.System;
-import android.support.v4.os.BuildCompat;
import com.android.launcher3.graphics.IconShapeOverride;
@@ -85,7 +84,7 @@ public class SettingsActivity extends Activity {
}
Preference iconBadgingPref = findPreference(ICON_BADGING_PREFERENCE_KEY);
- if (!BuildCompat.isAtLeastO()) {
+ if (!Utilities.isAtLeastO()) {
getPreferenceScreen().removePreference(
findPreference(SessionCommitReceiver.ADD_ICON_PREFERENCE_KEY));
getPreferenceScreen().removePreference(iconBadgingPref);
diff --git a/src/com/android/launcher3/ShortcutAndWidgetContainer.java b/src/com/android/launcher3/ShortcutAndWidgetContainer.java
index f8742f8958..fd708c0fd5 100644
--- a/src/com/android/launcher3/ShortcutAndWidgetContainer.java
+++ b/src/com/android/launcher3/ShortcutAndWidgetContainer.java
@@ -120,7 +120,9 @@ public class ShortcutAndWidgetContainer extends ViewGroup {
// Center the icon/folder
int cHeight = getCellContentHeight();
int cellPaddingY = (int) Math.max(0, ((lp.height - cHeight) / 2f));
- int cellPaddingX = (int) (profile.edgeMarginPx / 2f);
+ int cellPaddingX = mContainerType == CellLayout.WORKSPACE
+ ? profile.workspaceCellPaddingXPx
+ : (int) (profile.edgeMarginPx / 2f);
child.setPadding(cellPaddingX, cellPaddingY, cellPaddingX, 0);
}
} else {
diff --git a/src/com/android/launcher3/ShortcutInfo.java b/src/com/android/launcher3/ShortcutInfo.java
index 6f0417c08a..f0d9367afe 100644
--- a/src/com/android/launcher3/ShortcutInfo.java
+++ b/src/com/android/launcher3/ShortcutInfo.java
@@ -45,10 +45,10 @@ public class ShortcutInfo extends ItemInfoWithIcon {
* be present along with {@link #FLAG_RESTORED_ICON}, and is set during default layout
* parsing.
*/
- public static final int FLAG_AUTOINTALL_ICON = 2; //0B10;
+ public static final int FLAG_AUTOINSTALL_ICON = 2; //0B10;
/**
- * The icon is being installed. If {@link #FLAG_RESTORED_ICON} or {@link #FLAG_AUTOINTALL_ICON}
+ * The icon is being installed. If {@link #FLAG_RESTORED_ICON} or {@link #FLAG_AUTOINSTALL_ICON}
* is set, then the icon is either being installed or is in a broken state.
*/
public static final int FLAG_INSTALL_SESSION_ACTIVE = 4; // 0B100;
@@ -185,7 +185,7 @@ public class ShortcutInfo extends ItemInfoWithIcon {
public final boolean isPromise() {
- return hasStatusFlag(FLAG_RESTORED_ICON | FLAG_AUTOINTALL_ICON);
+ return hasStatusFlag(FLAG_RESTORED_ICON | FLAG_AUTOINSTALL_ICON);
}
public int getInstallProgress() {
diff --git a/src/com/android/launcher3/UninstallDropTarget.java b/src/com/android/launcher3/UninstallDropTarget.java
index 0fac29f30a..45c14d6bba 100644
--- a/src/com/android/launcher3/UninstallDropTarget.java
+++ b/src/com/android/launcher3/UninstallDropTarget.java
@@ -28,10 +28,13 @@ public class UninstallDropTarget extends ButtonDropTarget {
@Override
protected void onFinishInflate() {
super.onFinishInflate();
+ setupUi();
+ }
+
+ protected void setupUi() {
// Get the hover color
mHoverColor = getResources().getColor(R.color.uninstall_target_hover_tint);
-
- setDrawable(R.drawable.ic_uninstall_launcher);
+ setDrawable(R.drawable.ic_uninstall_shadow);
}
@Override
diff --git a/src/com/android/launcher3/Utilities.java b/src/com/android/launcher3/Utilities.java
index b5c44bb020..9100fe28d9 100644
--- a/src/com/android/launcher3/Utilities.java
+++ b/src/com/android/launcher3/Utilities.java
@@ -28,6 +28,7 @@ import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
+import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
@@ -37,7 +38,6 @@ import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.PowerManager;
import android.os.TransactionTooLargeException;
-import android.support.v4.os.BuildCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
@@ -51,7 +51,7 @@ import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
-import com.android.launcher3.config.ProviderConfig;
+import com.android.launcher3.config.FeatureFlags;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
@@ -85,7 +85,7 @@ public final class Utilities {
private static final Matrix sInverseMatrix = new Matrix();
public static boolean isAtLeastO() {
- return BuildCompat.isAtLeastO();
+ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
}
public static final boolean ATLEAST_NOUGAT_MR1 =
@@ -110,6 +110,7 @@ public final class Utilities {
public static final String EXTRA_WALLPAPER_OFFSET = "com.android.launcher3.WALLPAPER_OFFSET";
public static final int COLOR_EXTRACTION_JOB_ID = 1;
+ public static final int WALLPAPER_COMPAT_JOB_ID = 2;
// These values are same as that in {@link AsyncTask}.
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
@@ -260,7 +261,7 @@ public final class Utilities {
return scale;
}
- static boolean isSystemApp(Context context, Intent intent) {
+ public static boolean isSystemApp(Context context, Intent intent) {
PackageManager pm = context.getPackageManager();
ComponentName cn = intent.getComponent();
String packageName = null;
@@ -550,6 +551,11 @@ public final class Utilities {
LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
}
+ public static SharedPreferences getDevicePrefs(Context context) {
+ return context.getSharedPreferences(
+ LauncherFiles.DEVICE_PREFERENCES_KEY, Context.MODE_PRIVATE);
+ }
+
public static boolean isPowerSaverOn(Context context) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
return powerManager.isPowerSaveMode();
@@ -571,7 +577,7 @@ public final class Utilities {
try {
c.close();
} catch (IOException e) {
- if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_DOGFOOD_BUILD) {
Log.d(TAG, "Error closing", e);
}
}
@@ -647,4 +653,28 @@ public final class Utilities {
hashSet.add(elem);
return hashSet;
}
+
+ /**
+ * @return creates a new alpha mask bitmap out of an existing bitmap
+ */
+ public static Bitmap convertToAlphaMask(Bitmap b, int applyAlpha) {
+ Bitmap a = Bitmap.createBitmap(b.getWidth(), b.getHeight(), Bitmap.Config.ALPHA_8);
+ Canvas c = new Canvas(a);
+ Paint paint = new Paint();
+ paint.setAlpha(applyAlpha);
+ c.drawBitmap(b, 0f, 0f, paint);
+ return a;
+ }
+
+ /**
+ * @return a new white 1x1 bitmap with ALPHA_8
+ */
+ public static Bitmap createOnePixBitmap() {
+ Bitmap a = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8);
+ Canvas c = new Canvas(a);
+ Paint paint = new Paint();
+ paint.setColor(Color.WHITE);
+ c.drawPaint(paint);
+ return a;
+ }
}
diff --git a/src/com/android/launcher3/WidgetPreviewLoader.java b/src/com/android/launcher3/WidgetPreviewLoader.java
index c525cd4bc0..ad1be7e903 100644
--- a/src/com/android/launcher3/WidgetPreviewLoader.java
+++ b/src/com/android/launcher3/WidgetPreviewLoader.java
@@ -27,7 +27,6 @@ import android.os.CancellationSignal;
import android.os.Handler;
import android.os.UserHandle;
import android.support.annotation.Nullable;
-import android.support.v4.graphics.ColorUtils;
import android.util.Log;
import android.util.LongSparseArray;
@@ -112,7 +111,7 @@ public class WidgetPreviewLoader {
* sizes (landscape vs portrait).
*/
private static class CacheDb extends SQLiteCacheHelper {
- private static final int DB_VERSION = 6;
+ private static final int DB_VERSION = 8;
private static final String TABLE_NAME = "shortcut_and_widget_previews";
private static final String COLUMN_COMPONENT = "componentName";
@@ -388,10 +387,10 @@ public class WidgetPreviewLoader {
drawable.setBounds(x, 0, x + previewWidth, previewHeight);
drawable.draw(c);
} else {
- final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
- RectF boxRect = drawBoxWithShadow(c, p, previewWidth, previewHeight);
+ RectF boxRect = drawBoxWithShadow(c, previewWidth, previewHeight);
// Draw horizontal and vertical lines to represent individual columns.
+ final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(mContext.getResources()
.getDimension(R.dimen.widget_preview_cell_divider_width));
@@ -431,28 +430,19 @@ public class WidgetPreviewLoader {
return preview;
}
- private RectF drawBoxWithShadow(Canvas c, Paint p, int width, int height) {
+ private RectF drawBoxWithShadow(Canvas c, int width, int height) {
Resources res = mContext.getResources();
- float shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
- float keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
- float corner = res.getDimension(R.dimen.widget_preview_corner_radius);
- RectF bounds = new RectF(shadowBlur, shadowBlur,
- width - shadowBlur, height - shadowBlur - keyShadowDistance);
- p.setColor(Color.WHITE);
+ ShadowGenerator.Builder builder = new ShadowGenerator.Builder(Color.WHITE);
+ builder.shadowBlur = res.getDimension(R.dimen.widget_preview_shadow_blur);
+ builder.radius = res.getDimension(R.dimen.widget_preview_corner_radius);
+ builder.keyShadowDistance = res.getDimension(R.dimen.widget_preview_key_shadow_distance);
- // Key shadow
- p.setShadowLayer(shadowBlur, 0, keyShadowDistance,
- ShadowGenerator.KEY_SHADOW_ALPHA << 24);
- c.drawRoundRect(bounds, corner, corner, p);
-
- // Ambient shadow
- p.setShadowLayer(shadowBlur, 0, 0,
- ColorUtils.setAlphaComponent(Color.BLACK, ShadowGenerator.AMBIENT_SHADOW_ALPHA));
- c.drawRoundRect(bounds, corner, corner, p);
-
- p.clearShadowLayer();
- return bounds;
+ builder.bounds.set(builder.shadowBlur, builder.shadowBlur,
+ width - builder.shadowBlur,
+ height - builder.shadowBlur - builder.keyShadowDistance);
+ builder.drawShadow(c);
+ return builder.bounds;
}
private Bitmap generateShortcutPreview(BaseActivity launcher, ShortcutConfigActivityInfo info,
@@ -478,16 +468,16 @@ public class WidgetPreviewLoader {
c.setBitmap(preview);
c.drawColor(0, PorterDuff.Mode.CLEAR);
}
- Paint p = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
- RectF boxRect = drawBoxWithShadow(c, p, size, size);
+ RectF boxRect = drawBoxWithShadow(c, size, size);
Bitmap icon = LauncherIcons.createScaledBitmapWithoutShadow(
- mutateOnMainThread(info.getFullResIcon(mIconCache)), mContext, Build.VERSION_CODES.O);
+ mutateOnMainThread(info.getFullResIcon(mIconCache)), mContext, 0);
Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
boxRect.set(0, 0, iconSize, iconSize);
boxRect.offset(padding, padding);
- c.drawBitmap(icon, src, boxRect, p);
+ c.drawBitmap(icon, src, boxRect,
+ new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
c.setBitmap(null);
return preview;
}
diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java
index 36f2880cb9..767e33278b 100644
--- a/src/com/android/launcher3/Workspace.java
+++ b/src/com/android/launcher3/Workspace.java
@@ -43,6 +43,7 @@ import android.util.AttributeSet;
import android.util.Log;
import android.util.Property;
import android.util.SparseArray;
+import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewDebug;
@@ -50,9 +51,7 @@ import android.view.ViewGroup;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
-import android.widget.TextView;
import android.widget.Toast;
-
import com.android.launcher3.Launcher.CustomContentCallbacks;
import com.android.launcher3.Launcher.LauncherOverlay;
import com.android.launcher3.UninstallDropTarget.DropTargetSource;
@@ -64,7 +63,6 @@ import com.android.launcher3.anim.AnimationLayerSet;
import com.android.launcher3.badge.FolderBadgeInfo;
import com.android.launcher3.compat.AppWidgetManagerCompat;
import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.config.ProviderConfig;
import com.android.launcher3.dragndrop.DragController;
import com.android.launcher3.dragndrop.DragLayer;
import com.android.launcher3.dragndrop.DragOptions;
@@ -72,6 +70,7 @@ import com.android.launcher3.dragndrop.DragView;
import com.android.launcher3.dragndrop.SpringLoadedDragController;
import com.android.launcher3.folder.Folder;
import com.android.launcher3.folder.FolderIcon;
+import com.android.launcher3.folder.PreviewBackground;
import com.android.launcher3.graphics.DragPreviewProvider;
import com.android.launcher3.graphics.PreloadIconDrawable;
import com.android.launcher3.popup.PopupContainerWithArrow;
@@ -80,14 +79,12 @@ import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
import com.android.launcher3.util.ItemInfoMatcher;
import com.android.launcher3.util.LongArrayMap;
-import com.android.launcher3.util.MultiStateAlphaController;
import com.android.launcher3.util.PackageUserKey;
import com.android.launcher3.util.Thunk;
import com.android.launcher3.util.VerticalFlingDetector;
import com.android.launcher3.util.WallpaperOffsetInterpolator;
import com.android.launcher3.widget.PendingAddShortcutInfo;
import com.android.launcher3.widget.PendingAddWidgetInfo;
-
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
@@ -111,7 +108,7 @@ public class Workspace extends PagedView
* {@link #isFinishedSwitchingState()} ()} to return true. */
private static final float FINISHED_SWITCHING_STATE_TRANSITION_PROGRESS = 0.5f;
- private static boolean ENFORCE_DRAG_EVENT_ORDER = false;
+ private static final boolean ENFORCE_DRAG_EVENT_ORDER = false;
private static final int SNAP_OFF_EMPTY_SCREEN_DURATION = 400;
private static final int FADE_EMPTY_SCREEN_DURATION = 150;
@@ -137,8 +134,8 @@ public class Workspace extends PagedView
private ShortcutAndWidgetContainer mDragSourceInternal;
- @Thunk LongArrayMap mWorkspaceScreens = new LongArrayMap<>();
- @Thunk ArrayList mScreenOrder = new ArrayList();
+ @Thunk final LongArrayMap mWorkspaceScreens = new LongArrayMap<>();
+ @Thunk final ArrayList mScreenOrder = new ArrayList<>();
@Thunk Runnable mRemoveEmptyScreenRunnable;
@Thunk boolean mDeferRemoveExtraEmptyScreen = false;
@@ -174,7 +171,7 @@ public class Workspace extends PagedView
*/
private CellLayout mDropToLayout = null;
- @Thunk Launcher mLauncher;
+ @Thunk final Launcher mLauncher;
@Thunk DragController mDragController;
// These are temporary variables to prevent having to allocate a new object just to
@@ -183,10 +180,10 @@ public class Workspace extends PagedView
private final int[] mTempXY = new int[2];
@Thunk float[] mDragViewVisualCenter = new float[2];
- private float[] mTempTouchCoordinates = new float[2];
+ private final float[] mTempTouchCoordinates = new float[2];
private SpringLoadedDragController mSpringLoadedDragController;
- private float mOverviewModeShrinkFactor;
+ private final float mOverviewModeShrinkFactor;
// State variable that indicates whether the pages are small (ie when you're
// in all apps or customize mode)
@@ -226,21 +223,13 @@ public class Workspace extends PagedView
/**
* These values correspond to {@link Direction#X} & {@link Direction#Y}
*/
- private float[] mPageAlpha = new float[] {1, 1};
+ private final float[] mPageAlpha = new float[] {1, 1};
/**
* Hotseat alpha can be changed when moving horizontally, vertically, changing states.
* The values correspond to {@link Direction#X}, {@link Direction#Y} &
* {@link #HOTSEAT_STATE_ALPHA_INDEX} respectively.
*/
- private float[] mHotseatAlpha = new float[] {1, 1, 1};
-
- public static final int QSB_ALPHA_INDEX_STATE_CHANGE = 0;
- public static final int QSB_ALPHA_INDEX_Y_TRANSLATION = 1;
- public static final int QSB_ALPHA_INDEX_PAGE_SCROLL = 2;
- public static final int QSB_ALPHA_INDEX_OVERLAY_SCROLL = 3;
-
-
- MultiStateAlphaController mQsbAlphaController;
+ private final float[] mHotseatAlpha = new float[] {1, 1, 1};
@ViewDebug.ExportedProperty(category = "launcher")
private State mState = State.NORMAL;
@@ -252,7 +241,7 @@ public class Workspace extends PagedView
private boolean mStripScreensOnPageStopMoving = false;
private DragPreviewProvider mOutlineProvider = null;
- private boolean mWorkspaceFadeInAdjacentScreens;
+ private final boolean mWorkspaceFadeInAdjacentScreens;
final WallpaperOffsetInterpolator mWallpaperOffset;
private boolean mUnlockWallpaperFromDefaultPageOnLayout;
@@ -265,7 +254,7 @@ public class Workspace extends PagedView
public static final int REORDER_TIMEOUT = 350;
private final Alarm mFolderCreationAlarm = new Alarm();
private final Alarm mReorderAlarm = new Alarm();
- private FolderIcon.PreviewBackground mFolderCreateBg;
+ private PreviewBackground mFolderCreateBg;
private FolderIcon mDragOverFolderIcon = null;
private boolean mCreateUserFolderOnDrop = false;
private boolean mAddToExistingFolderOnDrop = false;
@@ -297,7 +286,7 @@ public class Workspace extends PagedView
@Thunk int mLastReorderY = -1;
private SparseArray mSavedStates;
- private final ArrayList mRestoredPages = new ArrayList();
+ private final ArrayList mRestoredPages = new ArrayList<>();
private float mCurrentScale;
private float mTransitionProgress;
@@ -316,14 +305,11 @@ public class Workspace extends PagedView
private boolean mForceDrawAdjacentPages = false;
// Total over scrollX in the overlay direction.
private float mOverlayTranslation;
- private int mFirstPageScrollX;
- private boolean mIgnoreQsbScroll;
// Handles workspace state transitions
- private WorkspaceStateTransitionAnimation mStateTransitionAnimation;
+ private final WorkspaceStateTransitionAnimation mStateTransitionAnimation;
private AccessibilityDelegate mPagesAccessibilityDelegate;
- private OnStateChangeListener mOnStateChangeListener;
/**
* Used to inflate the Workspace from XML.
@@ -378,10 +364,6 @@ public class Workspace extends PagedView
}
}
- public void setOnStateChangeListener(OnStateChangeListener listener) {
- mOnStateChangeListener = listener;
- }
-
/**
* Estimates the size of an item using spans: hSpan, vSpan.
*
@@ -451,7 +433,7 @@ public class Workspace extends PagedView
mLauncher.lockScreenOrientation();
mLauncher.onInteractionBegin();
// Prevent any Un/InstallShortcutReceivers from updating the db while we are dragging
- InstallShortcutReceiver.enableInstallQueue();
+ InstallShortcutReceiver.enableInstallQueue(InstallShortcutReceiver.FLAG_DRAG_AND_DROP);
// Do not add a new page if it is a accessible drag which was not started by the workspace.
// We do not support accessibility drag from other sources and instead provide a direct
@@ -504,7 +486,8 @@ public class Workspace extends PagedView
mLauncher.unlockScreenOrientation(false);
// Re-enable any Un/InstallShortcutReceiver and now process any queued items
- InstallShortcutReceiver.disableAndFlushInstallQueue(getContext());
+ InstallShortcutReceiver.disableAndFlushInstallQueue(
+ InstallShortcutReceiver.FLAG_DRAG_AND_DROP, getContext());
mOutlineProvider = null;
mDragInfo = null;
@@ -529,15 +512,12 @@ public class Workspace extends PagedView
// Set the wallpaper dimensions when Launcher starts up
setWallpaperDimension();
-
- setEdgeGlowColor(getResources().getColor(R.color.workspace_edge_effect_color));
}
@Override
public void initParentViews(View parent) {
super.initParentViews(parent);
mPageIndicator.setAccessibilityDelegate(new OverviewAccessibilityDelegate());
- mQsbAlphaController = new MultiStateAlphaController(mLauncher.getQsbContainer(), 4);
}
private int getDefaultPage() {
@@ -577,11 +557,6 @@ public class Workspace extends PagedView
return mTouchState != TOUCH_STATE_REST;
}
- private int getEmbeddedQsbId() {
- return mLauncher.getDeviceProfile().isVerticalBarLayout()
- ? R.id.qsb_container : R.id.workspace_blocked_row;
- }
-
/**
* Initializes and binds the first page
* @param qsb an existing qsb to recycle or null.
@@ -623,41 +598,17 @@ public class Workspace extends PagedView
if (qsb == null) {
// In transposed layout, we add the QSB in the Grid. As workspace does not touch the
// edges, we do not need a full width QSB.
- qsb = mLauncher.getLayoutInflater().inflate(
- mLauncher.getDeviceProfile().isVerticalBarLayout()
- ? R.layout.qsb_container : R.layout.qsb_blocker_view,
- firstPage, false);
+ qsb = LayoutInflater.from(getContext())
+ .inflate(R.layout.qsb_container,firstPage, false);
}
CellLayout.LayoutParams lp = new CellLayout.LayoutParams(0, 0, firstPage.getCountX(), 1);
lp.canReorder = false;
- if (!firstPage.addViewToCellLayout(qsb, 0, getEmbeddedQsbId(), lp, true)) {
+ if (!firstPage.addViewToCellLayout(qsb, 0, R.id.qsb_container, lp, true)) {
Log.e(TAG, "Failed to add to item at (0, 0) to CellLayout");
}
}
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
-
- // Update the QSB to match the cell height. This is treating the QSB essentially as a child
- // of workspace despite that it's not a true child.
- // Note that it relies on the strict ordering of measuring the workspace before the QSB
- // at the dragLayer level.
- // Only measure the QSB when the view is enabled
- if (FeatureFlags.QSB_ON_FIRST_SCREEN && getChildCount() > 0) {
- CellLayout firstPage = (CellLayout) getChildAt(0);
- int cellHeight = firstPage.getCellHeight();
-
- View qsbContainer = mLauncher.getQsbContainer();
- ViewGroup.LayoutParams lp = qsbContainer.getLayoutParams();
- if (cellHeight > 0 && lp.height != cellHeight) {
- lp.height = cellHeight;
- qsbContainer.setLayoutParams(lp);
- }
- }
- }
-
public void removeAllWorkspaceScreens() {
// Disable all layout transitions before removing all pages to ensure that we don't get the
// transition animations competing with us changing the scroll when we add pages or the
@@ -671,7 +622,7 @@ public class Workspace extends PagedView
}
// Recycle the QSB widget
- View qsb = findViewById(getEmbeddedQsbId());
+ View qsb = findViewById(R.id.qsb_container);
if (qsb != null) {
((ViewGroup) qsb.getParent()).removeView(qsb);
}
@@ -709,7 +660,7 @@ public class Workspace extends PagedView
// Inflate the cell layout, but do not add it automatically so that we can get the newly
// created CellLayout.
- CellLayout newScreen = (CellLayout) mLauncher.getLayoutInflater().inflate(
+ CellLayout newScreen = (CellLayout) LayoutInflater.from(getContext()).inflate(
R.layout.workspace_screen, this, false /* attachToRoot */);
newScreen.setOnLongClickListener(mLongClickListener);
newScreen.setOnClickListener(mLauncher);
@@ -727,7 +678,7 @@ public class Workspace extends PagedView
public void createCustomContentContainer() {
CellLayout customScreen = (CellLayout)
- mLauncher.getLayoutInflater().inflate(R.layout.workspace_screen, this, false);
+ LayoutInflater.from(getContext()).inflate(R.layout.workspace_screen, this, false);
customScreen.disableDragTarget();
customScreen.disableJailContent();
@@ -854,7 +805,7 @@ public class Workspace extends PagedView
mScreenOrder.add(EXTRA_EMPTY_SCREEN_ID);
// Update the model if we have changed any screens
- mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
+ LauncherModel.updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
}
}
@@ -956,7 +907,6 @@ public class Workspace extends PagedView
return -1;
}
- int index = getPageIndexForScreenId(EXTRA_EMPTY_SCREEN_ID);
CellLayout cl = mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID);
mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID);
mScreenOrder.remove(EXTRA_EMPTY_SCREEN_ID);
@@ -968,7 +918,7 @@ public class Workspace extends PagedView
mScreenOrder.add(newId);
// Update the model for the new screen
- mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
+ LauncherModel.updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
return newId;
}
@@ -1013,7 +963,7 @@ public class Workspace extends PagedView
}
int currentPage = getNextPage();
- ArrayList removeScreens = new ArrayList();
+ ArrayList removeScreens = new ArrayList<>();
int total = mWorkspaceScreens.size();
for (int i = 0; i < total; i++) {
long id = mWorkspaceScreens.keyAt(i);
@@ -1057,7 +1007,7 @@ public class Workspace extends PagedView
if (!removeScreens.isEmpty()) {
// Update the model if we have changed any screens
- mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
+ LauncherModel.updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
}
if (pageShift >= 0) {
@@ -1082,7 +1032,7 @@ public class Workspace extends PagedView
/**
* Adds the specified child in the specified screen based on the {@param info}
- * See {@link #addInScreen}.
+ * See {@link #addInScreen(View, long, long, int, int, int, int)}.
*/
public void addInScreen(View child, ItemInfo info) {
addInScreen(child, info.container, info.screenId, info.cellX, info.cellY,
@@ -1407,17 +1357,9 @@ public class Workspace extends PagedView
super.scrollTo(x, y);
}
- private void onWorkspaceOverallScrollChanged() {
- if (!mIgnoreQsbScroll) {
- mLauncher.getQsbContainer().setTranslationX(
- mOverlayTranslation + mFirstPageScrollX - getScrollX());
- }
- }
-
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
- onWorkspaceOverallScrollChanged();
// Update the page indicator progress.
boolean isTransitioning = mIsSwitchingState
@@ -1465,6 +1407,13 @@ public class Workspace extends PagedView
}
}
+ @Override
+ protected boolean shouldFlingForVelocity(int velocityX) {
+ // When the overlay is moving, the fling or settle transition is controlled by the overlay.
+ return Float.compare(mOverlayTranslation, 0) == 0 &&
+ super.shouldFlingForVelocity(velocityX);
+ }
+
private final Interpolator mAlphaInterpolator = new DecelerateInterpolator(3f);
/**
@@ -1491,9 +1440,6 @@ public class Workspace extends PagedView
// device I've tried, translating the launcher causes things to get quite laggy.
setWorkspaceTranslationAndAlpha(Direction.X, transX, alpha);
setHotseatTranslationAndAlpha(Direction.X, transX, alpha);
- onWorkspaceOverallScrollChanged();
-
- mQsbAlphaController.setAlphaAtIndex(alpha, QSB_ALPHA_INDEX_OVERLAY_SCROLL);
}
/**
@@ -1503,9 +1449,6 @@ public class Workspace extends PagedView
*/
public void setWorkspaceYTranslationAndAlpha(float translation, float alpha) {
setWorkspaceTranslationAndAlpha(Direction.Y, translation, alpha);
-
- mLauncher.getQsbContainer().setTranslationY(translation);
- mQsbAlphaController.setAlphaAtIndex(alpha, QSB_ALPHA_INDEX_Y_TRANSLATION);
}
/**
@@ -1701,10 +1644,6 @@ public class Workspace extends PagedView
float scrollProgress = getScrollProgress(screenCenter, child, i);
float alpha = 1 - Math.abs(scrollProgress);
child.getShortcutsAndWidgets().setAlpha(alpha);
-
- if (isQsbContainerPage(i)) {
- mQsbAlphaController.setAlphaAtIndex(alpha, QSB_ALPHA_INDEX_PAGE_SCROLL);
- }
}
}
}
@@ -1798,34 +1737,6 @@ public class Workspace extends PagedView
mWallpaperOffset.jumpToFinal();
}
super.onLayout(changed, left, top, right, bottom);
- mFirstPageScrollX = getScrollForPage(0);
- onWorkspaceOverallScrollChanged();
-
- final LayoutTransition transition = getLayoutTransition();
- // If the transition is running defer updating max scroll, as some empty pages could
- // still be present, and a max scroll change could cause sudden jumps in scroll.
- if (transition != null && transition.isRunning()) {
- transition.addTransitionListener(new LayoutTransition.TransitionListener() {
-
- @Override
- public void startTransition(LayoutTransition transition, ViewGroup container,
- View view, int transitionType) {
- mIgnoreQsbScroll = true;
- }
-
- @Override
- public void endTransition(LayoutTransition transition, ViewGroup container,
- View view, int transitionType) {
- // Wait until all transitions are complete.
- if (!transition.isRunning()) {
- mIgnoreQsbScroll = false;
- transition.removeTransitionListener(this);
- mFirstPageScrollX = getScrollForPage(0);
- onWorkspaceOverallScrollChanged();
- }
- }
- });
- }
updatePageAlphaValues();
}
@@ -1985,7 +1896,7 @@ public class Workspace extends PagedView
mScreenOrder.add(getIdForScreen(cl));
}
mLauncher.getUserEventDispatcher().logOverviewReorder();
- mLauncher.getModel().updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
+ LauncherModel.updateWorkspaceScreenOrder(mLauncher, mScreenOrder);
// Re-enable auto layout transitions for page deletion.
enableLayoutTransitions();
@@ -2064,10 +1975,6 @@ public class Workspace extends PagedView
mLauncher.notifyWidgetProvidersChanged();
}
- if (mOnStateChangeListener != null) {
- mOnStateChangeListener.prepareStateChange(toState, animated ? workspaceAnim : null);
- }
-
onPrepareStateTransition(mState.hasMultipleVisiblePages);
StateTransitionListener listener = new StateTransitionListener();
@@ -2175,27 +2082,9 @@ public class Workspace extends PagedView
}
}
- /**
- * Returns the drawable for the given text view.
- */
- public static Drawable getTextViewIcon(TextView tv) {
- final Drawable[] drawables = tv.getCompoundDrawables();
- for (int i = 0; i < drawables.length; i++) {
- if (drawables[i] != null) {
- return drawables[i];
- }
- }
- return null;
- }
-
public void startDrag(CellLayout.CellInfo cellInfo, DragOptions options) {
View child = cellInfo.cell;
- // Make sure the drag was started by a long press as opposed to a long click.
- if (!child.isInTouchMode()) {
- return;
- }
-
mDragInfo = cellInfo;
child.setVisibility(INVISIBLE);
@@ -2316,8 +2205,8 @@ public class Workspace extends PagedView
mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter);
}
- int spanX = 1;
- int spanY = 1;
+ int spanX;
+ int spanY;
if (mDragInfo != null) {
final CellLayout.CellInfo dragCellInfo = mDragInfo;
spanX = dragCellInfo.spanX;
@@ -2472,7 +2361,7 @@ public class Workspace extends PagedView
// In order to keep everything continuous, we hand off the currently rendered
// folder background to the newly created icon. This preserves animation state.
fi.setFolderBackground(mFolderCreateBg);
- mFolderCreateBg = new FolderIcon.PreviewBackground();
+ mFolderCreateBg = new PreviewBackground();
fi.performCreateAnimation(destInfo, v, sourceInfo, dragView, folderLocation, scale,
postAnimationRunnable);
} else {
@@ -2620,7 +2509,7 @@ public class Workspace extends PagedView
CellLayout parentCell = getParentCellLayoutForView(cell);
if (parentCell != null) {
parentCell.removeView(cell);
- } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ } else if (FeatureFlags.IS_DOGFOOD_BUILD) {
throw new NullPointerException("mDragInfo.cell has null parent");
}
addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1],
@@ -2953,7 +2842,7 @@ public class Workspace extends PagedView
ItemInfo item = d.dragInfo;
if (item == null) {
- if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_DOGFOOD_BUILD) {
throw new NullPointerException("DragObject has null info");
}
return;
@@ -3149,22 +3038,19 @@ public class Workspace extends PagedView
}
class FolderCreationAlarmListener implements OnAlarmListener {
- CellLayout layout;
- int cellX;
- int cellY;
+ final CellLayout layout;
+ final int cellX;
+ final int cellY;
- FolderIcon.PreviewBackground bg = new FolderIcon.PreviewBackground();
+ final PreviewBackground bg = new PreviewBackground();
public FolderCreationAlarmListener(CellLayout layout, int cellX, int cellY) {
this.layout = layout;
this.cellX = cellX;
this.cellY = cellY;
- DeviceProfile grid = mLauncher.getDeviceProfile();
BubbleTextView cell = (BubbleTextView) layout.getChildAt(cellX, cellY);
-
- bg.setup(getResources().getDisplayMetrics(), grid, null,
- cell.getMeasuredWidth(), cell.getPaddingTop());
+ bg.setup(mLauncher, null, cell.getMeasuredWidth(), cell.getPaddingTop());
// The full preview background should appear behind the icon
bg.isClipping = false;
@@ -3179,10 +3065,10 @@ public class Workspace extends PagedView
}
class ReorderAlarmListener implements OnAlarmListener {
- float[] dragViewCenter;
- int minSpanX, minSpanY, spanX, spanY;
- DragObject dragObject;
- View child;
+ final float[] dragViewCenter;
+ final int minSpanX, minSpanY, spanX, spanY;
+ final DragObject dragObject;
+ final View child;
public ReorderAlarmListener(float[] dragViewCenter, int minSpanX, int minSpanY, int spanX,
int spanY, DragObject dragObject, View child) {
@@ -3274,7 +3160,7 @@ public class Workspace extends PagedView
boolean findNearestVacantCell = true;
if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
- mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
+ mTargetCell = findNearestArea(touchXY[0], touchXY[1], spanX, spanY,
cellLayout, mTargetCell);
float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
mDragViewVisualCenter[1], mTargetCell);
@@ -3340,7 +3226,7 @@ public class Workspace extends PagedView
animationStyle, finalView, true);
} else {
// This is for other drag/drop cases, like dragging from All Apps
- View view = null;
+ View view;
switch (info.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
@@ -3364,7 +3250,7 @@ public class Workspace extends PagedView
// First we find the cell nearest to point at which the item is
// dropped, without any consideration to whether there is an item there.
if (touchXY != null) {
- mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY,
+ mTargetCell = findNearestArea(touchXY[0], touchXY[1], spanX, spanY,
cellLayout, mTargetCell);
float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0],
mDragViewVisualCenter[1], mTargetCell);
@@ -3610,13 +3496,13 @@ public class Workspace extends PagedView
mDragInfo.container, mDragInfo.screenId);
if (cellLayout != null) {
cellLayout.onDropChild(mDragInfo.cell);
- } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ } else if (FeatureFlags.IS_DOGFOOD_BUILD) {
throw new RuntimeException("Invalid state: cellLayout == null in "
+ "Workspace#onDropCompleted. Please file a bug. ");
- };
+ }
}
if ((d.cancelled || (beingCalledAfterUninstall && !mUninstallSuccessful))
- && mDragInfo.cell != null) {
+ && mDragInfo != null && mDragInfo.cell != null) {
mDragInfo.cell.setVisibility(VISIBLE);
}
mDragInfo = null;
@@ -3636,7 +3522,7 @@ public class Workspace extends PagedView
CellLayout parentCell = getParentCellLayoutForView(v);
if (parentCell != null) {
parentCell.removeView(v);
- } else if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ } else if (FeatureFlags.IS_DOGFOOD_BUILD) {
// When an app is uninstalled using the drop target, we wait until resume to remove
// the icon. We also remove all the corresponding items from the workspace at
// {@link Launcher#bindComponentsRemoved}. That call can come before or after
@@ -3765,7 +3651,7 @@ public class Workspace extends PagedView
* Returns a list of all the CellLayouts in the workspace.
*/
ArrayList getWorkspaceAndHotseatCellLayouts() {
- ArrayList layouts = new ArrayList();
+ ArrayList layouts = new ArrayList<>();
int screenCount = getChildCount();
for (int screen = 0; screen < screenCount; screen++) {
layouts.add(((CellLayout) getChildAt(screen)));
@@ -3907,7 +3793,7 @@ public class Workspace extends PagedView
* @param view view for the shortcut
* @return true if done, false to continue the map
*/
- public boolean evaluate(ItemInfo info, View view);
+ boolean evaluate(ItemInfo info, View view);
}
/**
@@ -3949,7 +3835,7 @@ public class Workspace extends PagedView
void updateShortcuts(ArrayList shortcuts) {
int total = shortcuts.size();
- final HashSet updates = new HashSet(total);
+ final HashSet updates = new HashSet<>(total);
final HashSet folderIds = new HashSet<>();
for (int i = 0; i < total; i++) {
@@ -3965,7 +3851,7 @@ public class Workspace extends PagedView
updates.contains(info)) {
ShortcutInfo si = (ShortcutInfo) info;
BubbleTextView shortcut = (BubbleTextView) v;
- Drawable oldIcon = getTextViewIcon(shortcut);
+ Drawable oldIcon = shortcut.getIcon();
boolean oldPromiseState = (oldIcon instanceof PreloadIconDrawable)
&& ((PreloadIconDrawable) oldIcon).hasNotCompleted();
shortcut.applyFromShortcutInfo(si, si.isPromise() != oldPromiseState);
@@ -4189,8 +4075,8 @@ public class Workspace extends PagedView
private boolean mRefreshPending;
- public DeferredWidgetRefresh(ArrayList infos,
- LauncherAppWidgetHost host) {
+ DeferredWidgetRefresh(ArrayList infos,
+ LauncherAppWidgetHost host) {
mInfos = infos;
mHost = host;
mHandler = new Handler();
@@ -4227,20 +4113,6 @@ public class Workspace extends PagedView
}
}
- public interface OnStateChangeListener {
-
- /**
- * Called when the workspace state is changing.
- * @param toState final state
- * @param targetAnim animation which will be played during the transition or null.
- */
- void prepareStateChange(State toState, AnimatorSet targetAnim);
- }
-
- public static final boolean isQsbContainerPage(int pageNo) {
- return pageNo == 0;
- }
-
private class StateTransitionListener extends AnimatorListenerAdapter
implements AnimatorUpdateListener {
@Override
diff --git a/src/com/android/launcher3/WorkspaceStateTransitionAnimation.java b/src/com/android/launcher3/WorkspaceStateTransitionAnimation.java
index 482a2c93b8..32deaf2862 100644
--- a/src/com/android/launcher3/WorkspaceStateTransitionAnimation.java
+++ b/src/com/android/launcher3/WorkspaceStateTransitionAnimation.java
@@ -355,27 +355,10 @@ public class WorkspaceStateTransitionAnimation {
cl.setBackgroundAlpha(finalBackgroundAlpha);
cl.setShortcutAndWidgetAlpha(finalAlpha);
}
-
- if (Workspace.isQsbContainerPage(i) &&
- states.stateIsNormal && mWorkspaceFadeInAdjacentScreens) {
- if (animated) {
- Animator anim = mWorkspace.mQsbAlphaController
- .animateAlphaAtIndex(finalAlpha, Workspace.QSB_ALPHA_INDEX_PAGE_SCROLL);
- anim.setDuration(duration);
- anim.setInterpolator(mZoomInInterpolator);
- mStateAnimator.play(anim);
- } else {
- mWorkspace.mQsbAlphaController.setAlphaAtIndex(
- finalAlpha, Workspace.QSB_ALPHA_INDEX_PAGE_SCROLL);
- }
- }
}
final ViewGroup overviewPanel = mLauncher.getOverviewPanel();
- Animator qsbAlphaAnimation = mWorkspace.mQsbAlphaController
- .animateAlphaAtIndex(finalQsbAlpha, Workspace.QSB_ALPHA_INDEX_STATE_CHANGE);
-
if (animated) {
Animator scale = LauncherAnimUtils.ofPropertyValuesHolder(mWorkspace,
new PropertyListBuilder().scale(mNewScale)
@@ -393,7 +376,6 @@ public class WorkspaceStateTransitionAnimation {
// For animation optimization, we may need to provide the Launcher transition
// with a set of views on which to force build and manage layers in certain scenarios.
layerViews.addView(overviewPanel);
- layerViews.addView(mLauncher.getQsbContainer());
layerViews.addView(mLauncher.getHotseat());
layerViews.addView(mWorkspace.getPageIndicator());
@@ -407,11 +389,9 @@ public class WorkspaceStateTransitionAnimation {
overviewPanelAlpha.setDuration(duration);
hotseatAlpha.setDuration(duration);
- qsbAlphaAnimation.setDuration(duration);
mStateAnimator.play(overviewPanelAlpha);
mStateAnimator.play(hotseatAlpha);
- mStateAnimator.play(qsbAlphaAnimation);
mStateAnimator.addListener(new AnimatorListenerAdapter() {
boolean canceled = false;
@Override
@@ -439,7 +419,6 @@ public class WorkspaceStateTransitionAnimation {
AlphaUpdateListener.updateVisibility(overviewPanel, accessibilityEnabled);
mWorkspace.getPageIndicator().setShouldAutoHide(!states.stateIsSpringLoaded);
- qsbAlphaAnimation.end();
mWorkspace.createHotseatAlphaAnimator(finalHotseatAlpha).end();
mWorkspace.updateCustomContentVisibility();
mWorkspace.setScaleX(mNewScale);
diff --git a/src/com/android/launcher3/accessibility/FolderAccessibilityHelper.java b/src/com/android/launcher3/accessibility/FolderAccessibilityHelper.java
index d271f1d4ed..9c23c1980d 100644
--- a/src/com/android/launcher3/accessibility/FolderAccessibilityHelper.java
+++ b/src/com/android/launcher3/accessibility/FolderAccessibilityHelper.java
@@ -17,8 +17,8 @@
package com.android.launcher3.accessibility;
import com.android.launcher3.CellLayout;
-import com.android.launcher3.folder.FolderPagedView;
import com.android.launcher3.R;
+import com.android.launcher3.folder.FolderPagedView;
/**
* Implementation of {@link DragAndDropAccessibilityDelegate} to support DnD in a folder.
diff --git a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
index 70e578163a..34335330be 100644
--- a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
@@ -18,7 +18,6 @@ import com.android.launcher3.AppInfo;
import com.android.launcher3.AppWidgetResizeFrame;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.CellLayout;
-import com.android.launcher3.popup.PopupContainerWithArrow;
import com.android.launcher3.DeleteDropTarget;
import com.android.launcher3.DropTarget.DragObject;
import com.android.launcher3.FolderInfo;
@@ -27,7 +26,6 @@ import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.LauncherAppWidgetHostView;
import com.android.launcher3.LauncherAppWidgetInfo;
-import com.android.launcher3.LauncherModel;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.PendingAddItemInfo;
import com.android.launcher3.R;
@@ -37,6 +35,7 @@ import com.android.launcher3.Workspace;
import com.android.launcher3.dragndrop.DragController.DragListener;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.folder.Folder;
+import com.android.launcher3.popup.PopupContainerWithArrow;
import com.android.launcher3.shortcuts.DeepShortcutManager;
import com.android.launcher3.util.Thunk;
diff --git a/src/com/android/launcher3/accessibility/WorkspaceAccessibilityHelper.java b/src/com/android/launcher3/accessibility/WorkspaceAccessibilityHelper.java
index 9a23aa8138..e6f120fe64 100644
--- a/src/com/android/launcher3/accessibility/WorkspaceAccessibilityHelper.java
+++ b/src/com/android/launcher3/accessibility/WorkspaceAccessibilityHelper.java
@@ -27,9 +27,9 @@ import com.android.launcher3.CellLayout;
import com.android.launcher3.FolderInfo;
import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
-import com.android.launcher3.accessibility.LauncherAccessibilityDelegate.DragType;
import com.android.launcher3.R;
import com.android.launcher3.ShortcutInfo;
+import com.android.launcher3.accessibility.LauncherAccessibilityDelegate.DragType;
import com.android.launcher3.dragndrop.DragLayer;
/**
diff --git a/src/com/android/launcher3/allapps/AllAppsBackgroundDrawable.java b/src/com/android/launcher3/allapps/AllAppsBackgroundDrawable.java
index c71bc3166b..3830a9333d 100644
--- a/src/com/android/launcher3/allapps/AllAppsBackgroundDrawable.java
+++ b/src/com/android/launcher3/allapps/AllAppsBackgroundDrawable.java
@@ -23,9 +23,12 @@ import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
+import android.view.ContextThemeWrapper;
import android.view.Gravity;
+import com.android.launcher3.LauncherAnimUtils;
import com.android.launcher3.R;
+import com.android.launcher3.util.Themes;
/**
* This is a custom composite drawable that has a fixed virtual size and dynamically lays out its
@@ -35,7 +38,7 @@ import com.android.launcher3.R;
public class AllAppsBackgroundDrawable extends Drawable {
/**
- * A helper class to positon and orient a drawable to be drawn.
+ * A helper class to position and orient a drawable to be drawn.
*/
protected static class TransformedImageDrawable {
private Drawable mImage;
@@ -48,9 +51,9 @@ public class AllAppsBackgroundDrawable extends Drawable {
* @param gravity If one of the Gravity center values, the x and y offset will take the width
* and height of the image into account to center the image to the offset.
*/
- public TransformedImageDrawable(Resources res, int resourceId, float xPct, float yPct,
+ public TransformedImageDrawable(Context context, int resourceId, float xPct, float yPct,
int gravity) {
- mImage = res.getDrawable(resourceId);
+ mImage = context.getDrawable(resourceId);
mXPercent = xPct;
mYPercent = yPct;
mGravity = gravity;
@@ -97,19 +100,24 @@ public class AllAppsBackgroundDrawable extends Drawable {
public AllAppsBackgroundDrawable(Context context) {
Resources res = context.getResources();
- mHand = new TransformedImageDrawable(res, R.drawable.ic_all_apps_bg_hand,
- 0.575f, 0.f, Gravity.CENTER_HORIZONTAL);
- mIcons = new TransformedImageDrawable[4];
- mIcons[0] = new TransformedImageDrawable(res, R.drawable.ic_all_apps_bg_icon_1,
- 0.375f, 0, Gravity.CENTER_HORIZONTAL);
- mIcons[1] = new TransformedImageDrawable(res, R.drawable.ic_all_apps_bg_icon_2,
- 0.3125f, 0.2f, Gravity.CENTER_HORIZONTAL);
- mIcons[2] = new TransformedImageDrawable(res, R.drawable.ic_all_apps_bg_icon_3,
- 0.475f, 0.26f, Gravity.CENTER_HORIZONTAL);
- mIcons[3] = new TransformedImageDrawable(res, R.drawable.ic_all_apps_bg_icon_4,
- 0.7f, 0.125f, Gravity.CENTER_HORIZONTAL);
mWidth = res.getDimensionPixelSize(R.dimen.all_apps_background_canvas_width);
mHeight = res.getDimensionPixelSize(R.dimen.all_apps_background_canvas_height);
+
+ context = new ContextThemeWrapper(context,
+ Themes.getAttrBoolean(context, R.attr.isMainColorDark)
+ ? R.style.AllAppsEmptySearchBackground_Dark
+ : R.style.AllAppsEmptySearchBackground);
+ mHand = new TransformedImageDrawable(context, R.drawable.ic_all_apps_bg_hand,
+ 0.575f, 0.f, Gravity.CENTER_HORIZONTAL);
+ mIcons = new TransformedImageDrawable[4];
+ mIcons[0] = new TransformedImageDrawable(context, R.drawable.ic_all_apps_bg_icon_1,
+ 0.375f, 0, Gravity.CENTER_HORIZONTAL);
+ mIcons[1] = new TransformedImageDrawable(context, R.drawable.ic_all_apps_bg_icon_2,
+ 0.3125f, 0.2f, Gravity.CENTER_HORIZONTAL);
+ mIcons[2] = new TransformedImageDrawable(context, R.drawable.ic_all_apps_bg_icon_3,
+ 0.475f, 0.26f, Gravity.CENTER_HORIZONTAL);
+ mIcons[3] = new TransformedImageDrawable(context, R.drawable.ic_all_apps_bg_icon_4,
+ 0.7f, 0.125f, Gravity.CENTER_HORIZONTAL);
}
/**
@@ -119,7 +127,8 @@ public class AllAppsBackgroundDrawable extends Drawable {
int finalAlphaI = (int) (finalAlpha * 255f);
if (getAlpha() != finalAlphaI) {
mBackgroundAnim = cancelAnimator(mBackgroundAnim);
- mBackgroundAnim = ObjectAnimator.ofInt(this, "alpha", finalAlphaI);
+ mBackgroundAnim = ObjectAnimator.ofInt(this, LauncherAnimUtils.DRAWABLE_ALPHA,
+ finalAlphaI);
mBackgroundAnim.setDuration(duration);
mBackgroundAnim.start();
}
diff --git a/src/com/android/launcher3/allapps/AllAppsContainerView.java b/src/com/android/launcher3/allapps/AllAppsContainerView.java
index 2c7d156297..47b68a2ee1 100644
--- a/src/com/android/launcher3/allapps/AllAppsContainerView.java
+++ b/src/com/android/launcher3/allapps/AllAppsContainerView.java
@@ -20,15 +20,10 @@ import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.InsetDrawable;
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
+import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Selection;
-import android.text.Spannable;
-import android.text.SpannableString;
import android.text.SpannableStringBuilder;
-import android.text.TextUtils;
-import android.text.method.TextKeyListener;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
@@ -42,25 +37,22 @@ import com.android.launcher3.DeleteDropTarget;
import com.android.launcher3.DeviceProfile;
import com.android.launcher3.DragSource;
import com.android.launcher3.DropTarget;
-import com.android.launcher3.ExtendedEditText;
import com.android.launcher3.Insettable;
import com.android.launcher3.ItemInfo;
import com.android.launcher3.Launcher;
+import com.android.launcher3.PromiseAppInfo;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
+import com.android.launcher3.anim.SpringAnimationHandler;
import com.android.launcher3.config.FeatureFlags;
-import com.android.launcher3.discovery.AppDiscoveryItem;
-import com.android.launcher3.discovery.AppDiscoveryUpdateState;
import com.android.launcher3.dragndrop.DragController;
import com.android.launcher3.dragndrop.DragOptions;
import com.android.launcher3.folder.Folder;
-import com.android.launcher3.graphics.TintedDrawableSpan;
import com.android.launcher3.keyboard.FocusedItemDecorator;
import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
import com.android.launcher3.util.ComponentKey;
import com.android.launcher3.util.PackageUserKey;
-import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@@ -68,26 +60,24 @@ import java.util.Set;
* The all apps view container.
*/
public class AllAppsContainerView extends BaseContainerView implements DragSource,
- View.OnLongClickListener, AllAppsSearchBarController.Callbacks, Insettable {
+ View.OnLongClickListener, Insettable {
private final Launcher mLauncher;
private final AlphabeticalAppsList mApps;
private final AllAppsGridAdapter mAdapter;
- private final RecyclerView.LayoutManager mLayoutManager;
+ private final LinearLayoutManager mLayoutManager;
private AllAppsRecyclerView mAppsRecyclerView;
- private AllAppsSearchBarController mSearchBarController;
-
+ private SearchUiManager mSearchUiManager;
private View mSearchContainer;
- private int mSearchContainerMinHeight;
- private ExtendedEditText mSearchInput;
- private HeaderElevationController mElevationController;
private SpannableStringBuilder mSearchQueryBuilder = null;
private int mNumAppsPerRow;
private int mNumPredictedAppsPerRow;
+ private SpringAnimationHandler mSpringAnimationHandler;
+
public AllAppsContainerView(Context context) {
this(context, null);
}
@@ -102,11 +92,10 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
mLauncher = Launcher.getLauncher(context);
mApps = new AlphabeticalAppsList(context);
mAdapter = new AllAppsGridAdapter(mLauncher, mApps, mLauncher, this);
+ mSpringAnimationHandler = mAdapter.getSpringAnimationHandler();
mApps.setAdapter(mAdapter);
mLayoutManager = mAdapter.getLayoutManager();
mSearchQueryBuilder = new SpannableStringBuilder();
- mSearchContainerMinHeight
- = getResources().getDimensionPixelSize(R.dimen.all_apps_search_bar_height);
Selection.setSelection(mSearchQueryBuilder, 0);
}
@@ -148,7 +137,7 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
*/
public void addApps(List apps) {
mApps.addApps(apps);
- mSearchBarController.refreshSearchResult();
+ mSearchUiManager.refreshSearchResult();
}
/**
@@ -156,7 +145,18 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
*/
public void updateApps(List apps) {
mApps.updateApps(apps);
- mSearchBarController.refreshSearchResult();
+ mSearchUiManager.refreshSearchResult();
+ }
+
+ public void updatePromiseAppProgress(PromiseAppInfo app) {
+ int childCount = mAppsRecyclerView.getChildCount();
+ for (int i = 0; i < childCount; i++) {
+ View child = mAppsRecyclerView.getChildAt(i);
+ if (child instanceof BubbleTextView && child.getTag() == app) {
+ BubbleTextView bubbleTextView = (BubbleTextView) child;
+ bubbleTextView.applyProgressLevel(app.level);
+ }
+ }
}
/**
@@ -164,53 +164,26 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
*/
public void removeApps(List apps) {
mApps.removeApps(apps);
- mSearchBarController.refreshSearchResult();
- }
-
- public void setSearchBarVisible(boolean visible) {
- if (visible) {
- mSearchBarController.setVisibility(View.VISIBLE);
- } else {
- mSearchBarController.setVisibility(View.INVISIBLE);
- }
- }
-
- /**
- * Sets the search bar that shows above the a-z list.
- */
- public void setSearchBarController(AllAppsSearchBarController searchController) {
- if (mSearchBarController != null) {
- throw new RuntimeException("Expected search bar controller to only be set once");
- }
- mSearchBarController = searchController;
- mSearchBarController.initialize(mApps, mSearchInput, mLauncher, this);
- mAdapter.setSearchController(mSearchBarController);
- }
-
- /**
- * Scrolls this list view to the top.
- */
- public void scrollToTop() {
- mAppsRecyclerView.scrollToTop();
+ mSearchUiManager.refreshSearchResult();
}
/**
* Returns whether the view itself will handle the touch event or not.
*/
public boolean shouldContainerScroll(MotionEvent ev) {
- int[] point = new int[2];
- point[0] = (int) ev.getX();
- point[1] = (int) ev.getY();
- Utilities.mapCoordInSelfToDescendant(mAppsRecyclerView, this, point);
-
// IF the MotionEvent is inside the search box, and the container keeps on receiving
// touch input, container should move down.
if (mLauncher.getDragLayer().isEventOverView(mSearchContainer, ev)) {
return true;
}
+ int[] point = new int[2];
+ point[0] = (int) ev.getX();
+ point[1] = (int) ev.getY();
+ Utilities.mapCoordInSelfToDescendant(
+ mAppsRecyclerView.getScrollBar(), mLauncher.getDragLayer(), point);
// IF the MotionEvent is inside the thumb, container should not be pulled down.
- if (mAppsRecyclerView.getScrollBar().isNearThumb(point[0], point[1])) {
+ if (mAppsRecyclerView.getScrollBar().shouldBlockIntercept(point[0], point[1])) {
return false;
}
@@ -222,23 +195,13 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
return false;
}
- /**
- * Focuses the search field and begins an app search.
- */
- public void startAppsSearch() {
- if (mSearchBarController != null) {
- mSearchBarController.focusSearchField();
- }
- }
-
/**
* Resets the state of AllApps.
*/
public void reset() {
// Reset the search bar and base recycler view after transitioning home
- scrollToTop();
- mSearchBarController.reset();
- mAppsRecyclerView.reset();
+ mAppsRecyclerView.scrollToTop();
+ mSearchUiManager.reset();
}
@Override
@@ -256,28 +219,21 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
}
});
- mSearchContainer = findViewById(R.id.search_container);
- mSearchInput = (ExtendedEditText) findViewById(R.id.search_box_input);
-
- // Update the hint to contain the icon.
- // Prefix the original hint with two spaces. The first space gets replaced by the icon
- // using span. The second space is used for a singe space character between the hint
- // and the icon.
- SpannableString spanned = new SpannableString(" " + mSearchInput.getHint());
- spanned.setSpan(new TintedDrawableSpan(getContext(), R.drawable.ic_allapps_search),
- 0, 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
- mSearchInput.setHint(spanned);
-
- mElevationController = new HeaderElevationController(mSearchContainer);
-
// Load the all apps recycler view
mAppsRecyclerView = (AllAppsRecyclerView) findViewById(R.id.apps_list_view);
mAppsRecyclerView.setApps(mApps);
mAppsRecyclerView.setLayoutManager(mLayoutManager);
mAppsRecyclerView.setAdapter(mAdapter);
mAppsRecyclerView.setHasFixedSize(true);
- mAppsRecyclerView.addOnScrollListener(mElevationController);
- mAppsRecyclerView.setElevationController(mElevationController);
+ if (FeatureFlags.LAUNCHER3_PHYSICS) {
+ mAppsRecyclerView.setSpringAnimationHandler(mSpringAnimationHandler);
+ mAppsRecyclerView.addOnScrollListener(new SpringMotionOnScrollListener());
+ }
+
+ mSearchContainer = findViewById(R.id.search_container);
+ mSearchUiManager = (SearchUiManager) mSearchContainer;
+ mSearchUiManager.initialize(mApps, mAppsRecyclerView);
+
FocusedItemDecorator focusedItemDecorator = new FocusedItemDecorator(mAppsRecyclerView);
mAppsRecyclerView.addItemDecoration(focusedItemDecorator);
@@ -291,18 +247,21 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
}
}
+ public SearchUiManager getSearchUiManager() {
+ return mSearchUiManager;
+ }
+
@Override
public View getTouchDelegateTargetView() {
return mAppsRecyclerView;
}
- @Override
- public void onBoundsChanged(Rect newBounds) { }
-
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
DeviceProfile grid = mLauncher.getDeviceProfile();
+ // Update the number of items in the grid before we measure the view
grid.updateAppsViewNumCols();
+
if (FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP) {
if (mNumAppsPerRow != grid.inv.numColumns ||
mNumPredictedAppsPerRow != grid.inv.numColumns) {
@@ -313,22 +272,11 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
mAdapter.setNumAppsPerRow(mNumAppsPerRow);
mApps.setNumAppsPerRow(mNumAppsPerRow, mNumPredictedAppsPerRow);
}
- if (!grid.isVerticalBarLayout()) {
- MarginLayoutParams searchContainerLp =
- (MarginLayoutParams) mSearchContainer.getLayoutParams();
-
- searchContainerLp.height = mLauncher.getDragLayer().getInsets().top
- + mSearchContainerMinHeight;
- mSearchContainer.setLayoutParams(searchContainerLp);
- }
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// --- remove START when {@code FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP} is enabled. ---
-
- // Update the number of items in the grid before we measure the view
- grid.updateAppsViewNumCols();
if (mNumAppsPerRow != grid.allAppsNumCols ||
mNumPredictedAppsPerRow != grid.allAppsNumPredictiveCols) {
mNumAppsPerRow = grid.allAppsNumCols;
@@ -345,31 +293,13 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
- // Determine if the key event was actual text, if so, focus the search bar and then dispatch
- // the key normally so that it can process this key event
- if (!mSearchBarController.isSearchFieldFocused() &&
- event.getAction() == KeyEvent.ACTION_DOWN) {
- final int unicodeChar = event.getUnicodeChar();
- final boolean isKeyNotWhitespace = unicodeChar > 0 &&
- !Character.isWhitespace(unicodeChar) && !Character.isSpaceChar(unicodeChar);
- if (isKeyNotWhitespace) {
- boolean gotKey = TextKeyListener.getInstance().onKeyDown(this, mSearchQueryBuilder,
- event.getKeyCode(), event);
- if (gotKey && mSearchQueryBuilder.length() > 0) {
- mSearchBarController.focusSearchField();
- }
- }
- }
-
+ mSearchUiManager.preDispatchKeyEvent(event);
return super.dispatchKeyEvent(event);
}
@Override
public boolean onLongClick(final View v) {
- // Return early if this is not initiated from a touch
- if (!v.isInTouchMode()) return false;
// When we have exited all apps or are in transition, disregard long clicks
-
if (!mLauncher.isAppsViewVisible() ||
mLauncher.getWorkspace().isSwitchingState()) return false;
// Return if global dragging is not enabled or we are already dragging
@@ -427,48 +357,18 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
}
}
- @Override
- public void onSearchResult(String query, ArrayList apps) {
- if (apps != null) {
- mApps.setOrderedFilter(apps);
- mAppsRecyclerView.onSearchResultsChanged();
- mAdapter.setLastSearchQuery(query);
- }
- }
-
- @Override
- public void onAppDiscoverySearchUpdate(@Nullable AppDiscoveryItem app,
- @NonNull AppDiscoveryUpdateState state) {
- if (!mLauncher.isDestroyed()) {
- mApps.onAppDiscoverySearchUpdate(app, state);
- mAppsRecyclerView.onSearchResultsChanged();
- }
- }
-
- @Override
- public void clearSearchResult() {
- if (mApps.setOrderedFilter(null)) {
- mAppsRecyclerView.onSearchResultsChanged();
- }
-
- // Clear the search query
- mSearchQueryBuilder.clear();
- mSearchQueryBuilder.clearSpans();
- Selection.setSelection(mSearchQueryBuilder, 0);
- }
-
@Override
public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
targetParent.containerType = mAppsRecyclerView.getContainerType(v);
}
- public boolean shouldRestoreImeState() {
- return !TextUtils.isEmpty(mSearchInput.getText());
- }
-
@Override
public void setInsets(Rect insets) {
DeviceProfile grid = mLauncher.getDeviceProfile();
+ mAppsRecyclerView.setPadding(
+ mAppsRecyclerView.getPaddingLeft(), mAppsRecyclerView.getPaddingTop(),
+ mAppsRecyclerView.getPaddingRight(), insets.bottom);
+
if (grid.isVerticalBarLayout()) {
ViewGroup.MarginLayoutParams mlp = (MarginLayoutParams) getLayoutParams();
mlp.leftMargin = insets.left;
@@ -480,7 +380,8 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
ViewGroup.LayoutParams navBarBgLp = navBarBg.getLayoutParams();
navBarBgLp.height = insets.bottom;
navBarBg.setLayoutParams(navBarBgLp);
- navBarBg.setVisibility(View.VISIBLE);
+ navBarBg.setVisibility(FeatureFlags.LAUNCHER3_GRADIENT_ALL_APPS
+ ? View.INVISIBLE : View.VISIBLE);
}
}
@@ -498,4 +399,39 @@ public class AllAppsContainerView extends BaseContainerView implements DragSourc
}
}
}
+
+ public SpringAnimationHandler getSpringAnimationHandler() {
+ return mSpringAnimationHandler;
+ }
+
+ public class SpringMotionOnScrollListener extends RecyclerView.OnScrollListener {
+
+ private int mScrollState = RecyclerView.SCROLL_STATE_IDLE;
+
+ @Override
+ public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
+ if (mScrollState == RecyclerView.SCROLL_STATE_DRAGGING
+ || (dx == 0 && dy == 0)) {
+ if (mSpringAnimationHandler.isRunning()){
+ mSpringAnimationHandler.skipToEnd();
+ }
+ return;
+ }
+
+ int first = mLayoutManager.findFirstVisibleItemPosition();
+ int last = mLayoutManager.findLastVisibleItemPosition();
+
+ // We only show the spring animation when at the top or bottom, so we wait until the
+ // first or last row is visible to ensure that all animations run in sync.
+ if ((first == 0 && dy < 0) || (last == mAdapter.getItemCount() - 1 && dy > 0)) {
+ mSpringAnimationHandler.animateToFinalPosition(0);
+ }
+ }
+
+ @Override
+ public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
+ super.onScrollStateChanged(recyclerView, newState);
+ mScrollState = newState;
+ }
+ }
}
diff --git a/src/com/android/launcher3/allapps/AllAppsFastScrollHelper.java b/src/com/android/launcher3/allapps/AllAppsFastScrollHelper.java
index a1ff8223a2..e08cb15cd2 100644
--- a/src/com/android/launcher3/allapps/AllAppsFastScrollHelper.java
+++ b/src/com/android/launcher3/allapps/AllAppsFastScrollHelper.java
@@ -16,11 +16,7 @@
package com.android.launcher3.allapps;
import android.support.v7.widget.RecyclerView;
-import android.view.View;
-import com.android.launcher3.BaseRecyclerViewFastScrollBar;
-import com.android.launcher3.BubbleTextView;
-import com.android.launcher3.FastBitmapDrawable;
import com.android.launcher3.util.Thunk;
import java.util.HashSet;
@@ -210,7 +206,9 @@ public class AllAppsFastScrollHelper implements AllAppsGridAdapter.BindViewCallb
for (RecyclerView.ViewHolder viewHolder : mTrackedFastScrollViews) {
int pos = viewHolder.getAdapterPosition();
boolean isActive = false;
- if (mCurrentFastScrollSection != null && pos > -1) {
+ if (mCurrentFastScrollSection != null
+ && pos > RecyclerView.NO_POSITION
+ && pos < mApps.getAdapterItems().size()) {
AlphabeticalAppsList.AdapterItem item = mApps.getAdapterItems().get(pos);
isActive = item != null &&
mCurrentFastScrollSection.equals(item.sectionName) &&
diff --git a/src/com/android/launcher3/allapps/AllAppsGridAdapter.java b/src/com/android/launcher3/allapps/AllAppsGridAdapter.java
index 59cac8d26a..1054a56333 100644
--- a/src/com/android/launcher3/allapps/AllAppsGridAdapter.java
+++ b/src/com/android/launcher3/allapps/AllAppsGridAdapter.java
@@ -18,7 +18,8 @@ package com.android.launcher3.allapps;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
-import android.graphics.Point;
+import android.support.animation.DynamicAnimation;
+import android.support.animation.SpringAnimation;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityRecordCompat;
@@ -33,13 +34,17 @@ import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.widget.TextView;
-import com.android.launcher3.discovery.AppDiscoveryAppInfo;
import com.android.launcher3.AppInfo;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
+import com.android.launcher3.Utilities;
import com.android.launcher3.allapps.AlphabeticalAppsList.AdapterItem;
+import com.android.launcher3.anim.SpringAnimationHandler;
+import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.discovery.AppDiscoveryAppInfo;
import com.android.launcher3.discovery.AppDiscoveryItemView;
+import com.android.launcher3.util.PackageManagerHelper;
import java.util.List;
@@ -64,21 +69,20 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter mSpringAnimationHandler;
+
public AllAppsGridAdapter(Launcher launcher, AlphabeticalAppsList apps, View.OnClickListener
iconClickListener, View.OnLongClickListener iconLongClickListener) {
Resources res = launcher.getResources();
@@ -219,6 +220,14 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter(
+ SpringAnimationHandler.Y_DIRECTION, new AllAppsSpringAnimationFactory());
+ }
+ }
+
+ public SpringAnimationHandler getSpringAnimationHandler() {
+ return mSpringAnimationHandler;
}
public static boolean isDividerViewType(int viewType) {
@@ -241,8 +250,8 @@ public class AllAppsGridAdapter extends RecyclerView.Adapter {
+ private static final float DEFAULT_MAX_VALUE_PX = 100;
+ private static final float DEFAULT_MIN_VALUE_PX = -DEFAULT_MAX_VALUE_PX;
+
+ // Damping ratio range is [0, 1]
+ private static final float SPRING_DAMPING_RATIO = 0.55f;
+
+ // Stiffness is a non-negative number.
+ private static final float MIN_SPRING_STIFFNESS = 580f;
+ private static final float MAX_SPRING_STIFFNESS = 900f;
+
+ // The amount by which each adjacent rows' stiffness will differ.
+ private static final float ROW_STIFFNESS_COEFFICIENT = 50f;
+
+ @Override
+ public SpringAnimation initialize(ViewHolder vh) {
+ return SpringAnimationHandler.forView(vh.itemView, DynamicAnimation.TRANSLATION_Y, 0);
+ }
+
+ /**
+ * @param spring A new or recycled SpringAnimation.
+ * @param vh The ViewHolder that {@param spring} is related to.
+ */
+ @Override
+ public void update(SpringAnimation spring, ViewHolder vh) {
+ int numPredictedApps = Math.min(mAppsPerRow, mApps.getPredictedApps().size());
+ int appPosition = getAppPosition(vh.getAdapterPosition(), numPredictedApps,
+ mAppsPerRow);
+
+ int col = appPosition % mAppsPerRow;
+ int row = appPosition / mAppsPerRow;
+
+ int numTotalRows = mApps.getNumAppRows() - 1; // zero-based count
+ if (row > (numTotalRows / 2)) {
+ // Mirror the rows so that the top row acts the same as the bottom row.
+ row = Math.abs(numTotalRows - row);
+ }
+
+ // We manipulate the stiffness, min, and max values based on the items distance to the
+ // first row and the items distance to the center column to create the ^-shaped motion
+ // effect.
+ float rowFactor = (1 + row) * 0.5f;
+ float colFactor = getColumnFactor(col, mAppsPerRow);
+
+ float minValue = DEFAULT_MIN_VALUE_PX * (rowFactor + colFactor);
+ float maxValue = DEFAULT_MAX_VALUE_PX * (rowFactor + colFactor);
+
+ float stiffness = Utilities.boundToRange(
+ MAX_SPRING_STIFFNESS - (row * ROW_STIFFNESS_COEFFICIENT),
+ MIN_SPRING_STIFFNESS,
+ MAX_SPRING_STIFFNESS);
+
+ spring.setMinValue(minValue)
+ .setMaxValue(maxValue)
+ .getSpring()
+ .setStiffness(stiffness)
+ .setDampingRatio(SPRING_DAMPING_RATIO);
+ }
+
+ /**
+ * @return The app position is the position of the app in the Adapter if we ignored all
+ * other view types.
+ *
+ * The first app is at position 0, and the first app each following row is at a
+ * position that is a multiple of {@param appsPerRow}.
+ *
+ * ie. If there are 5 apps per row, and there are two rows of apps:
+ * 0 1 2 3 4
+ * 5 6 7 8 9
+ */
+ private int getAppPosition(int position, int numPredictedApps, int appsPerRow) {
+ int appPosition = position;
+ int numDividerViews = 1 + (numPredictedApps == 0 ? 0 : 1);
+
+ int allAppsStartAt = numDividerViews + numPredictedApps;
+ if (numDividerViews == 1 || position < allAppsStartAt) {
+ appPosition -= 1;
+ } else {
+ // We cannot assume that the predicted row will always be full.
+ int numPredictedAppsOffset = appsPerRow - numPredictedApps;
+ appPosition = position + numPredictedAppsOffset - numDividerViews;
+ }
+
+ return appPosition;
+ }
+
+ /**
+ * Increase the column factor as the distance increases between the column and the center
+ * column(s).
+ */
+ private float getColumnFactor(int col, int numCols) {
+ float centerColumn = numCols / 2;
+ int distanceToCenter = (int) Math.abs(col - centerColumn);
+
+ boolean evenNumberOfColumns = numCols % 2 == 0;
+ if (evenNumberOfColumns && col < centerColumn) {
+ distanceToCenter -= 1;
+ }
+
+ float factor = 0;
+ while (distanceToCenter > 0) {
+ if (distanceToCenter == 1) {
+ factor += 0.2f;
+ } else {
+ factor += 0.1f;
+ }
+ --distanceToCenter;
+ }
+
+ return factor;
+ }
+ }
}
diff --git a/src/com/android/launcher3/allapps/AllAppsRecyclerView.java b/src/com/android/launcher3/allapps/AllAppsRecyclerView.java
index 64e2fcb3d4..2b2fddcdd2 100644
--- a/src/com/android/launcher3/allapps/AllAppsRecyclerView.java
+++ b/src/com/android/launcher3/allapps/AllAppsRecyclerView.java
@@ -28,8 +28,8 @@ import android.view.View;
import com.android.launcher3.BaseRecyclerView;
import com.android.launcher3.BubbleTextView;
import com.android.launcher3.DeviceProfile;
-import com.android.launcher3.Launcher;
import com.android.launcher3.R;
+import com.android.launcher3.anim.SpringAnimationHandler;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.graphics.DrawableFactory;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
@@ -53,7 +53,7 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
private AllAppsBackgroundDrawable mEmptySearchBackground;
private int mEmptySearchBackgroundTopOffset;
- private HeaderElevationController mElevationController;
+ private SpringAnimationHandler mSpringAnimationHandler;
public AllAppsRecyclerView(Context context) {
this(context, null);
@@ -72,11 +72,22 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
super(context, attrs, defStyleAttr);
Resources res = getResources();
addOnItemTouchListener(this);
- mScrollbar.setDetachThumbOnFastScroll();
mEmptySearchBackgroundTopOffset = res.getDimensionPixelSize(
R.dimen.all_apps_empty_search_bg_top_offset);
}
+ public void setSpringAnimationHandler(SpringAnimationHandler springAnimationHandler) {
+ mSpringAnimationHandler = springAnimationHandler;
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent e) {
+ if (FeatureFlags.LAUNCHER3_PHYSICS && mSpringAnimationHandler != null) {
+ mSpringAnimationHandler.addMovement(e);
+ }
+ return super.onTouchEvent(e);
+ }
+
/**
* Sets the list of apps in this view, used to determine the fastscroll position.
*/
@@ -85,8 +96,8 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
mFastScrollHelper = new AllAppsFastScrollHelper(this, apps);
}
- public void setElevationController(HeaderElevationController elevationController) {
- mElevationController = elevationController;
+ public AlphabeticalAppsList getApps() {
+ return mApps;
}
/**
@@ -98,7 +109,6 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
RecyclerView.RecycledViewPool pool = getRecycledViewPool();
int approxRows = (int) Math.ceil(grid.availableHeightPx / grid.allAppsIconSizePx);
pool.setMaxRecycledViews(AllAppsGridAdapter.VIEW_TYPE_EMPTY_SEARCH, 1);
- pool.setMaxRecycledViews(AllAppsGridAdapter.VIEW_TYPE_SEARCH_DIVIDER, 1);
pool.setMaxRecycledViews(AllAppsGridAdapter.VIEW_TYPE_SEARCH_MARKET_DIVIDER, 1);
pool.setMaxRecycledViews(AllAppsGridAdapter.VIEW_TYPE_SEARCH_MARKET, 1);
pool.setMaxRecycledViews(AllAppsGridAdapter.VIEW_TYPE_ICON, approxRows * mNumAppsPerRow);
@@ -124,8 +134,6 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
putSameHeightFor(adapter, widthMeasureSpec, heightMeasureSpec,
AllAppsGridAdapter.VIEW_TYPE_PREDICTION_DIVIDER,
AllAppsGridAdapter.VIEW_TYPE_SEARCH_MARKET_DIVIDER);
- putSameHeightFor(adapter, widthMeasureSpec, heightMeasureSpec,
- AllAppsGridAdapter.VIEW_TYPE_SEARCH_DIVIDER);
putSameHeightFor(adapter, widthMeasureSpec, heightMeasureSpec,
AllAppsGridAdapter.VIEW_TYPE_SEARCH_MARKET);
putSameHeightFor(adapter, widthMeasureSpec, heightMeasureSpec,
@@ -152,13 +160,10 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
*/
public void scrollToTop() {
// Ensure we reattach the scrollbar if it was previously detached while fast-scrolling
- if (mScrollbar.isThumbDetached()) {
+ if (mScrollbar != null) {
mScrollbar.reattachThumbToScroll();
}
scrollToPosition(0);
- if (mElevationController != null) {
- mElevationController.reset();
- }
}
@Override
@@ -349,7 +354,7 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
}
@Override
- protected boolean supportsFastScrolling() {
+ public boolean supportsFastScrolling() {
// Only allow fast scrolling when the user is not searching, since the results are not
// grouped in a meaningful order
return !mApps.hasFilter();
@@ -369,7 +374,8 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
if (position == NO_POSITION) {
return -1;
}
- return getCurrentScrollY(position, getLayoutManager().getDecoratedTop(child));
+ return getPaddingTop() +
+ getCurrentScrollY(position, getLayoutManager().getDecoratedTop(child));
}
public int getCurrentScrollY(int position, int offset) {
@@ -399,14 +405,7 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
}
mCachedScrollPositions.put(position, y);
}
-
- return getPaddingTop() + y - offset;
- }
-
- @Override
- protected int getScrollbarTrackHeight() {
- return super.getScrollbarTrackHeight()
- - Launcher.getLauncher(getContext()).getDragLayer().getInsets().bottom;
+ return y - offset;
}
/**
@@ -415,9 +414,8 @@ public class AllAppsRecyclerView extends BaseRecyclerView {
*/
@Override
protected int getAvailableScrollHeight() {
- int paddedHeight = getCurrentScrollY(mApps.getAdapterItems().size(), 0);
- int totalHeight = paddedHeight + getPaddingBottom();
- return totalHeight - getScrollbarTrackHeight();
+ return getPaddingTop() + getCurrentScrollY(mApps.getAdapterItems().size(), 0)
+ - getHeight() + getPaddingBottom();
}
/**
diff --git a/src/com/android/launcher3/allapps/AllAppsRecyclerViewContainerView.java b/src/com/android/launcher3/allapps/AllAppsRecyclerViewContainerView.java
index 6587ad78c9..517dc947e0 100644
--- a/src/com/android/launcher3/allapps/AllAppsRecyclerViewContainerView.java
+++ b/src/com/android/launcher3/allapps/AllAppsRecyclerViewContainerView.java
@@ -20,7 +20,6 @@ import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
-import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.android.launcher3.BubbleTextView;
diff --git a/src/com/android/launcher3/allapps/AllAppsTransitionController.java b/src/com/android/launcher3/allapps/AllAppsTransitionController.java
index 30ed180e7e..4d112c632a 100644
--- a/src/com/android/launcher3/allapps/AllAppsTransitionController.java
+++ b/src/com/android/launcher3/allapps/AllAppsTransitionController.java
@@ -22,8 +22,13 @@ import com.android.launcher3.LauncherAnimUtils;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.Workspace;
+import com.android.launcher3.anim.SpringAnimationHandler;
+import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.graphics.GradientView;
+import com.android.launcher3.graphics.ScrimView;
import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
+import com.android.launcher3.util.SystemUiController;
import com.android.launcher3.util.Themes;
import com.android.launcher3.util.TouchController;
@@ -38,12 +43,13 @@ import com.android.launcher3.util.TouchController;
* closer to top or closer to the page indicator.
*/
public class AllAppsTransitionController implements TouchController, VerticalPullDetector.Listener,
- View.OnLayoutChangeListener {
+ SearchUiManager.OnScrollRangeChangeListener {
private static final String TAG = "AllAppsTrans";
private static final boolean DBG = false;
- private final Interpolator mAccelInterpolator = new AccelerateInterpolator(2f);
+ private final Interpolator mWorkspaceAccelnterpolator = new AccelerateInterpolator(2f);
+ private final Interpolator mHotseatAccelInterpolator = new AccelerateInterpolator(1.5f);
private final Interpolator mDecelInterpolator = new DecelerateInterpolator(3f);
private final Interpolator mFastOutSlowInInterpolator = new FastOutSlowInInterpolator();
private final VerticalPullDetector.ScrollInterpolator mScrollInterpolator
@@ -65,6 +71,7 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
private final Launcher mLauncher;
private final VerticalPullDetector mDetector;
private final ArgbEvaluator mEvaluator;
+ private final boolean mIsDarkTheme;
// Animation in this class is controlled by a single variable {@link mProgress}.
// Visually, it represents top y coordinate of the all apps container if multiplied with
@@ -87,10 +94,15 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
private AnimatorSet mCurrentAnimation;
private boolean mNoIntercept;
+ private boolean mTouchEventStartedOnHotseat;
// Used in discovery bounce animation to provide the transition without workspace changing.
private boolean mIsTranslateWithoutWorkspace = false;
private AnimatorSet mDiscoBounceAnimation;
+ private GradientView mGradientView;
+ private ScrimView mScrimView;
+
+ private SpringAnimationHandler mSpringAnimationHandler;
public AllAppsTransitionController(Launcher l) {
mLauncher = l;
@@ -101,12 +113,14 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
mEvaluator = new ArgbEvaluator();
mAllAppsBackgroundColor = Themes.getAttrColor(l, android.R.attr.colorPrimary);
+ mIsDarkTheme = Themes.getAttrBoolean(mLauncher, R.attr.isMainColorDark);
}
@Override
public boolean onControllerInterceptTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
mNoIntercept = false;
+ mTouchEventStartedOnHotseat = mLauncher.getDragLayer().isEventOverHotseat(ev);
if (!mLauncher.isAllAppsVisible() && mLauncher.getWorkspace().workspaceInModalState()) {
mNoIntercept = true;
} else if (mLauncher.isAllAppsVisible() &&
@@ -153,6 +167,9 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
@Override
public boolean onControllerTouchEvent(MotionEvent ev) {
+ if (hasSpringAnimationHandler()) {
+ mSpringAnimationHandler.addMovement(ev);
+ }
return mDetector.onTouchEvent(ev);
}
@@ -171,6 +188,9 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
mCurrentAnimation = LauncherAnimUtils.createAnimatorSet();
mShiftStart = mAppsView.getTranslationY();
preparePull(start);
+ if (hasSpringAnimationHandler()) {
+ mSpringAnimationHandler.skipToEnd();
+ }
}
@Override
@@ -193,6 +213,9 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
return; // early termination.
}
+ final int containerType = mTouchEventStartedOnHotseat
+ ? ContainerType.HOTSEAT : ContainerType.WORKSPACE;
+
if (fling) {
if (velocity < 0) {
calculateDuration(velocity, mAppsView.getTranslationY());
@@ -201,11 +224,12 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
mLauncher.getUserEventDispatcher().logActionOnContainer(
Action.Touch.FLING,
Action.Direction.UP,
- ContainerType.HOTSEAT);
+ containerType);
+ }
+ mLauncher.showAppsView(true /* animated */, false /* updatePredictedApps */);
+ if (hasSpringAnimationHandler()) {
+ mSpringAnimationHandler.animateToFinalPosition(0);
}
- mLauncher.showAppsView(true /* animated */,
- false /* updatePredictedApps */,
- false /* focusSearchBar */);
} else {
calculateDuration(velocity, Math.abs(mShiftRange - mAppsView.getTranslationY()));
mLauncher.showWorkspace(true);
@@ -221,11 +245,9 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
mLauncher.getUserEventDispatcher().logActionOnContainer(
Action.Touch.SWIPE,
Action.Direction.UP,
- ContainerType.HOTSEAT);
+ containerType);
}
- mLauncher.showAppsView(true, /* animated */
- false /* updatePredictedApps */,
- false /* focusSearchBar */);
+ mLauncher.showAppsView(true, /* animated */ false /* updatePredictedApps */);
}
}
}
@@ -247,20 +269,45 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
if (!mLauncher.isAllAppsVisible()) {
mLauncher.tryAndUpdatePredictedApps();
mAppsView.setVisibility(View.VISIBLE);
- mAppsView.setRevealDrawableColor(mHotseatBackgroundColor);
+ if (!FeatureFlags.LAUNCHER3_GRADIENT_ALL_APPS) {
+ mAppsView.setRevealDrawableColor(mHotseatBackgroundColor);
+ }
}
}
}
private void updateLightStatusBar(float shift) {
// Do not modify status bar on landscape as all apps is not full bleed.
- if (mLauncher.getDeviceProfile().isVerticalBarLayout()) {
+ if (!FeatureFlags.LAUNCHER3_GRADIENT_ALL_APPS
+ && mLauncher.getDeviceProfile().isVerticalBarLayout()) {
return;
}
- // Use a light status bar (dark icons) if all apps is behind at least half of the status
- // bar. If the status bar is already light due to wallpaper extraction, keep it that way.
- boolean forceLight = shift <= mStatusBarHeight / 2;
- mLauncher.activateLightSystemBars(forceLight, true /* statusBar */, true /* navBar */);
+
+ // Use a light system UI (dark icons) if all apps is behind at least half of the status bar.
+ boolean forceChange = shift <= mStatusBarHeight / 2;
+ if (forceChange) {
+ mLauncher.getSystemUiController().updateUiState(
+ SystemUiController.UI_STATE_ALL_APPS, !mIsDarkTheme);
+ } else {
+ mLauncher.getSystemUiController().updateUiState(
+ SystemUiController.UI_STATE_ALL_APPS, 0);
+ }
+ }
+
+ private void updateAllAppsBg(float progress) {
+ // gradient
+ if (mGradientView == null) {
+ mGradientView = (GradientView) mLauncher.findViewById(R.id.gradient_bg);
+ mGradientView.setVisibility(View.VISIBLE);
+ }
+ mGradientView.setProgress(progress);
+
+ // scrim
+ if (mScrimView == null) {
+ mScrimView = (ScrimView) mLauncher.findViewById(R.id.scrim_bg);
+ mScrimView.setVisibility(View.VISIBLE);
+ }
+ mScrimView.setProgress(progress);
}
/**
@@ -273,31 +320,37 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
float workspaceHotseatAlpha = Utilities.boundToRange(progress, 0f, 1f);
float alpha = 1 - workspaceHotseatAlpha;
- float interpolation = mAccelInterpolator.getInterpolation(workspaceHotseatAlpha);
+ float workspaceAlpha = mWorkspaceAccelnterpolator.getInterpolation(workspaceHotseatAlpha);
+ float hotseatAlpha = mHotseatAccelInterpolator.getInterpolation(workspaceHotseatAlpha);
int color = (Integer) mEvaluator.evaluate(mDecelInterpolator.getInterpolation(alpha),
mHotseatBackgroundColor, mAllAppsBackgroundColor);
int bgAlpha = Color.alpha((int) mEvaluator.evaluate(alpha,
mHotseatBackgroundColor, mAllAppsBackgroundColor));
- mAppsView.setRevealDrawableColor(ColorUtils.setAlphaComponent(color, bgAlpha));
+ if (FeatureFlags.LAUNCHER3_GRADIENT_ALL_APPS) {
+ updateAllAppsBg(alpha);
+ } else {
+ mAppsView.setRevealDrawableColor(ColorUtils.setAlphaComponent(color, bgAlpha));
+ }
+
mAppsView.getContentView().setAlpha(alpha);
mAppsView.setTranslationY(shiftCurrent);
if (!mLauncher.getDeviceProfile().isVerticalBarLayout()) {
mWorkspace.setHotseatTranslationAndAlpha(Workspace.Direction.Y, -mShiftRange + shiftCurrent,
- interpolation);
+ hotseatAlpha);
} else {
mWorkspace.setHotseatTranslationAndAlpha(Workspace.Direction.Y,
PARALLAX_COEFFICIENT * (-mShiftRange + shiftCurrent),
- interpolation);
+ hotseatAlpha);
}
if (mIsTranslateWithoutWorkspace) {
return;
}
mWorkspace.setWorkspaceYTranslationAndAlpha(
- PARALLAX_COEFFICIENT * (-mShiftRange + shiftCurrent), interpolation);
+ PARALLAX_COEFFICIENT * (-mShiftRange + shiftCurrent), workspaceAlpha);
if (!mDetector.isDraggingState()) {
mContainerVelocity = mDetector.computeVelocity(shiftCurrent - shiftPrevious,
@@ -451,6 +504,9 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
public void finishPullUp() {
mHotseat.setVisibility(View.INVISIBLE);
+ if (hasSpringAnimationHandler()) {
+ mSpringAnimationHandler.reset();
+ }
setProgress(0f);
}
@@ -459,6 +515,9 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
mHotseat.setBackgroundTransparent(false /* transparent */);
mHotseat.setVisibility(View.VISIBLE);
mAppsView.reset();
+ if (hasSpringAnimationHandler()) {
+ mSpringAnimationHandler.reset();
+ }
setProgress(1f);
}
@@ -486,21 +545,20 @@ public class AllAppsTransitionController implements TouchController, VerticalPul
mAppsView = appsView;
mHotseat = hotseat;
mWorkspace = workspace;
- mHotseat.addOnLayoutChangeListener(this);
mHotseat.bringToFront();
mCaretController = new AllAppsCaretController(
mWorkspace.getPageIndicator().getCaretDrawable(), mLauncher);
+ mAppsView.getSearchUiManager().addOnScrollRangeChangeListener(this);
+ mSpringAnimationHandler = mAppsView.getSpringAnimationHandler();
+ }
+
+ private boolean hasSpringAnimationHandler() {
+ return FeatureFlags.LAUNCHER3_PHYSICS && mSpringAnimationHandler != null;
}
@Override
- public void onLayoutChange(View v, int left, int top, int right, int bottom,
- int oldLeft, int oldTop, int oldRight, int oldBottom) {
- if (!mLauncher.getDeviceProfile().isVerticalBarLayout()) {
- mShiftRange = top;
- } else {
- mShiftRange = bottom;
- }
+ public void onScrollRangeChanged(int scrollRange) {
+ mShiftRange = scrollRange;
setProgress(mProgress);
}
-
}
diff --git a/src/com/android/launcher3/allapps/AlphabeticalAppsList.java b/src/com/android/launcher3/allapps/AlphabeticalAppsList.java
index f5cf7effba..608e898ae8 100644
--- a/src/com/android/launcher3/allapps/AlphabeticalAppsList.java
+++ b/src/com/android/launcher3/allapps/AlphabeticalAppsList.java
@@ -24,7 +24,7 @@ import android.util.Log;
import com.android.launcher3.AppInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.compat.AlphabeticIndexCompat;
-import com.android.launcher3.config.ProviderConfig;
+import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.discovery.AppDiscoveryAppInfo;
import com.android.launcher3.discovery.AppDiscoveryItem;
import com.android.launcher3.discovery.AppDiscoveryUpdateState;
@@ -138,13 +138,6 @@ public class AlphabeticalAppsList {
return item;
}
- public static AdapterItem asSearchDivider(int pos) {
- AdapterItem item = new AdapterItem();
- item.viewType = AllAppsGridAdapter.VIEW_TYPE_SEARCH_DIVIDER;
- item.position = pos;
- return item;
- }
-
public static AdapterItem asMarketDivider(int pos) {
AdapterItem item = new AdapterItem();
item.viewType = AllAppsGridAdapter.VIEW_TYPE_SEARCH_MARKET_DIVIDER;
@@ -225,6 +218,13 @@ public class AlphabeticalAppsList {
return mApps;
}
+ /**
+ * Returns the predicted apps.
+ */
+ public List getPredictedApps() {
+ return mPredictedApps;
+ }
+
/**
* Returns fast scroller sections of all the current filtered applications.
*/
@@ -429,9 +429,6 @@ public class AlphabeticalAppsList {
}
}
- // Add the search divider
- mAdapterItems.add(AdapterItem.asSearchDivider(position++));
-
// Process the predicted app components
mPredictedApps.clear();
if (mPredictedAppComponents != null && !mPredictedAppComponents.isEmpty() && !hasFilter()) {
@@ -440,7 +437,7 @@ public class AlphabeticalAppsList {
if (info != null) {
mPredictedApps.add(info);
} else {
- if (ProviderConfig.IS_DOGFOOD_BUILD) {
+ if (FeatureFlags.IS_DOGFOOD_BUILD) {
Log.e(TAG, "Predicted app not found: " + ck);
}
}
@@ -606,6 +603,10 @@ public class AlphabeticalAppsList {
return result;
}
+ public AppInfo findApp(ComponentKey key) {
+ return mComponentToAppMap.get(key);
+ }
+
/**
* Returns the cached section name for the given title, recomputing and updating the cache if
* the title has no cached section name.
diff --git a/src/com/android/launcher3/allapps/LandscapeFastScroller.java b/src/com/android/launcher3/allapps/LandscapeFastScroller.java
new file mode 100644
index 0000000000..cdde657601
--- /dev/null
+++ b/src/com/android/launcher3/allapps/LandscapeFastScroller.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.launcher3.allapps;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.MotionEvent;
+
+import com.android.launcher3.views.RecyclerViewFastScroller;
+
+/**
+ * Extension of {@link RecyclerViewFastScroller} to be used in landscape layout.
+ */
+public class LandscapeFastScroller extends RecyclerViewFastScroller {
+
+ public LandscapeFastScroller(Context context) {
+ super(context);
+ }
+
+ public LandscapeFastScroller(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public LandscapeFastScroller(Context context, AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ }
+
+ @Override
+ public boolean handleTouchEvent(MotionEvent ev) {
+ // We handle our own touch event, no need to handle recycler view touch delegates.
+ return false;
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent event) {
+ event.offsetLocation(0, -mRv.getPaddingTop());
+ if (super.handleTouchEvent(event)) {
+ getParent().requestDisallowInterceptTouchEvent(true);
+ }
+ event.offsetLocation(0, mRv.getPaddingTop());
+ return true;
+ }
+
+ @Override
+ public boolean shouldBlockIntercept(int x, int y) {
+ // If the user touched the scroll bar area, block swipe
+ return x >= 0 && x < getWidth() && y >= 0 && y < getHeight();
+ }
+}
diff --git a/src/com/android/launcher3/allapps/SearchUiManager.java b/src/com/android/launcher3/allapps/SearchUiManager.java
new file mode 100644
index 0000000000..c0d78508fe
--- /dev/null
+++ b/src/com/android/launcher3/allapps/SearchUiManager.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.launcher3.allapps;
+
+import android.view.KeyEvent;
+
+/**
+ * Interface for controlling the Apps search UI.
+ */
+public interface SearchUiManager {
+
+ /**
+ * Initializes the search manager.
+ */
+ void initialize(AlphabeticalAppsList appsList, AllAppsRecyclerView recyclerView);
+
+ /**
+ * Notifies the search manager that the apps-list has changed and the search UI should be
+ * updated accordingly.
+ */
+ void refreshSearchResult();
+
+ /**
+ * Notifies the search manager to close any active search session.
+ */
+ void reset();
+
+ /**
+ * Called before dispatching a key event, in case the search manager wants to initialize
+ * some UI beforehand.
+ */
+ void preDispatchKeyEvent(KeyEvent keyEvent);
+
+ void addOnScrollRangeChangeListener(OnScrollRangeChangeListener listener);
+
+ /**
+ * Callback for listening to changes in the vertical scroll range when opening all-apps.
+ */
+ interface OnScrollRangeChangeListener {
+
+ void onScrollRangeChanged(int scrollRange);
+ }
+}
diff --git a/src/com/android/launcher3/allapps/VerticalPullDetector.java b/src/com/android/launcher3/allapps/VerticalPullDetector.java
index 7800c01371..13c4f63f03 100644
--- a/src/com/android/launcher3/allapps/VerticalPullDetector.java
+++ b/src/com/android/launcher3/allapps/VerticalPullDetector.java
@@ -17,7 +17,7 @@ public class VerticalPullDetector {
private static final boolean DBG = false;
private static final String TAG = "VerticalPullDetector";
- private float mTouchSlop;
+ private final float mTouchSlop;
private int mScrollConditions;
public static final int DIRECTION_UP = 1 << 0;
@@ -47,8 +47,6 @@ public class VerticalPullDetector {
SETTLING // onDragEnd
}
- ;
-
//------------------- ScrollState transition diagram -----------------------------------
//
// IDLE -> (mDisplacement > mTouchSlop) -> DRAGGING
@@ -110,7 +108,7 @@ public class VerticalPullDetector {
private boolean mIgnoreSlopWhenSettling;
/* Client of this gesture detector can register a callback. */
- Listener mListener;
+ private Listener mListener;
public void setListener(Listener l) {
mListener = l;
diff --git a/src/com/android/launcher3/allapps/AllAppsSearchBarController.java b/src/com/android/launcher3/allapps/search/AllAppsSearchBarController.java
similarity index 79%
rename from src/com/android/launcher3/allapps/AllAppsSearchBarController.java
rename to src/com/android/launcher3/allapps/search/AllAppsSearchBarController.java
index c7ba3abc6c..63aa7be3a6 100644
--- a/src/com/android/launcher3/allapps/AllAppsSearchBarController.java
+++ b/src/com/android/launcher3/allapps/search/AllAppsSearchBarController.java
@@ -13,12 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.launcher3.allapps;
+package com.android.launcher3.allapps.search;
import android.content.Context;
-import android.content.Intent;
-import android.graphics.Rect;
-import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
@@ -37,22 +34,22 @@ import com.android.launcher3.Utilities;
import com.android.launcher3.discovery.AppDiscoveryItem;
import com.android.launcher3.discovery.AppDiscoveryUpdateState;
import com.android.launcher3.util.ComponentKey;
+import com.android.launcher3.util.PackageManagerHelper;
import java.util.ArrayList;
/**
* An interface to a search box that AllApps can command.
*/
-public abstract class AllAppsSearchBarController
+public class AllAppsSearchBarController
implements TextWatcher, OnEditorActionListener, ExtendedEditText.OnBackKeyListener {
protected Launcher mLauncher;
- protected AlphabeticalAppsList mApps;
protected Callbacks mCb;
protected ExtendedEditText mInput;
protected String mQuery;
- protected DefaultAppSearchAlgorithm mSearchAlgorithm;
+ protected SearchAlgorithm mSearchAlgorithm;
protected InputMethodManager mInputMethodManager;
public void setVisibility(int visibility) {
@@ -62,9 +59,8 @@ public abstract class AllAppsSearchBarController
* Sets the references to the apps model and the search result callback.
*/
public final void initialize(
- AlphabeticalAppsList apps, ExtendedEditText input,
+ SearchAlgorithm searchAlgorithm, ExtendedEditText input,
Launcher launcher, Callbacks cb) {
- mApps = apps;
mCb = cb;
mLauncher = launcher;
@@ -76,22 +72,9 @@ public abstract class AllAppsSearchBarController
mInputMethodManager = (InputMethodManager)
mInput.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
- mSearchAlgorithm = onInitializeSearch();
-
- onInitialized();
+ mSearchAlgorithm = searchAlgorithm;
}
- /**
- * You can override this method to perform custom initialization.
- */
- protected void onInitialized() {
- }
-
- /**
- * To be implemented by subclasses. This method will get called when the controller is set.
- */
- protected abstract DefaultAppSearchAlgorithm onInitializeSearch();
-
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do nothing
@@ -114,7 +97,7 @@ public abstract class AllAppsSearchBarController
}
}
- protected void refreshSearchResult() {
+ public void refreshSearchResult() {
if (TextUtils.isEmpty(mQuery)) {
return;
}
@@ -135,7 +118,8 @@ public abstract class AllAppsSearchBarController
if (query.isEmpty()) {
return false;
}
- return mLauncher.startActivitySafely(v, createMarketSearchIntent(query), null);
+ return mLauncher.startActivitySafely(v,
+ PackageManagerHelper.getMarketSearchIntent(mLauncher, query), null);
}
@Override
@@ -185,29 +169,11 @@ public abstract class AllAppsSearchBarController
return mInput.isFocused();
}
- /**
- * Creates a new market search intent.
- */
- public Intent createMarketSearchIntent(String query) {
- Uri marketSearchUri = Uri.parse("market://search")
- .buildUpon()
- .appendQueryParameter("c", "apps")
- .appendQueryParameter("q", query)
- .build();
- return new Intent(Intent.ACTION_VIEW).setData(marketSearchUri);
- }
-
/**
* Callback for getting search results.
*/
public interface Callbacks {
- /**
- * Called when the bounds of the search bar has changed.
- */
- @Deprecated
- void onBoundsChanged(Rect newBounds);
-
/**
* Called when the search is complete.
*
@@ -220,7 +186,6 @@ public abstract class AllAppsSearchBarController
*/
void clearSearchResult();
-
/**
* Called when the app discovery is providing an update of search, which can either be
* START for starting a new discovery,
diff --git a/src/com/android/launcher3/allapps/search/AppsSearchContainerLayout.java b/src/com/android/launcher3/allapps/search/AppsSearchContainerLayout.java
new file mode 100644
index 0000000000..5cb12d5924
--- /dev/null
+++ b/src/com/android/launcher3/allapps/search/AppsSearchContainerLayout.java
@@ -0,0 +1,213 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.launcher3.allapps.search;
+
+import android.content.Context;
+import android.graphics.Rect;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.text.Selection;
+import android.text.Spannable;
+import android.text.SpannableString;
+import android.text.SpannableStringBuilder;
+import android.text.method.TextKeyListener;
+import android.util.AttributeSet;
+import android.view.KeyEvent;
+import android.view.View;
+import android.widget.FrameLayout;
+import com.android.launcher3.DeviceProfile;
+import com.android.launcher3.ExtendedEditText;
+import com.android.launcher3.Launcher;
+import com.android.launcher3.R;
+import com.android.launcher3.allapps.AllAppsGridAdapter;
+import com.android.launcher3.allapps.AllAppsRecyclerView;
+import com.android.launcher3.allapps.AlphabeticalAppsList;
+import com.android.launcher3.allapps.SearchUiManager;
+import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.discovery.AppDiscoveryItem;
+import com.android.launcher3.discovery.AppDiscoveryUpdateState;
+import com.android.launcher3.graphics.TintedDrawableSpan;
+import com.android.launcher3.util.ComponentKey;
+import java.util.ArrayList;
+
+/**
+ * Layout to contain the All-apps search UI.
+ */
+public class AppsSearchContainerLayout extends FrameLayout
+ implements SearchUiManager, AllAppsSearchBarController.Callbacks {
+
+ private final Launcher mLauncher;
+ private final int mMinHeight;
+ private final int mSearchBoxHeight;
+ private final AllAppsSearchBarController mSearchBarController;
+ private final SpannableStringBuilder mSearchQueryBuilder;
+
+ private ExtendedEditText mSearchInput;
+ private AlphabeticalAppsList mApps;
+ private AllAppsRecyclerView mAppsRecyclerView;
+ private AllAppsGridAdapter mAdapter;
+ private View mDivider;
+ private HeaderElevationController mElevationController;
+
+ public AppsSearchContainerLayout(Context context) {
+ this(context, null);
+ }
+
+ public AppsSearchContainerLayout(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ public AppsSearchContainerLayout(Context context, AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+
+ mLauncher = Launcher.getLauncher(context);
+ mMinHeight = getResources().getDimensionPixelSize(R.dimen.all_apps_search_bar_height);
+ mSearchBoxHeight = getResources()
+ .getDimensionPixelSize(R.dimen.all_apps_search_bar_field_height);
+ mSearchBarController = new AllAppsSearchBarController();
+
+ mSearchQueryBuilder = new SpannableStringBuilder();
+ Selection.setSelection(mSearchQueryBuilder, 0);
+ }
+
+ @Override
+ protected void onFinishInflate() {
+ super.onFinishInflate();
+ mSearchInput = findViewById(R.id.search_box_input);
+ mDivider = findViewById(R.id.search_divider);
+ mElevationController = new HeaderElevationController(mDivider);
+
+ // Update the hint to contain the icon.
+ // Prefix the original hint with two spaces. The first space gets replaced by the icon
+ // using span. The second space is used for a singe space character between the hint
+ // and the icon.
+ SpannableString spanned = new SpannableString(" " + mSearchInput.getHint());
+ spanned.setSpan(new TintedDrawableSpan(getContext(), R.drawable.ic_allapps_search),
+ 0, 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
+ mSearchInput.setHint(spanned);
+
+ DeviceProfile dp = mLauncher.getDeviceProfile();
+ if (!dp.isVerticalBarLayout()) {
+ LayoutParams lp = (LayoutParams) mDivider.getLayoutParams();
+ lp.leftMargin = lp.rightMargin = dp.edgeMarginPx;
+ }
+ }
+
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ if (FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP &&
+ !mLauncher.getDeviceProfile().isVerticalBarLayout()) {
+ getLayoutParams().height = mLauncher.getDragLayer().getInsets().top + mMinHeight;
+ }
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+ }
+
+
+ @Override
+ public void initialize(
+ AlphabeticalAppsList appsList, AllAppsRecyclerView recyclerView) {
+ mApps = appsList;
+ mAppsRecyclerView = recyclerView;
+ mAppsRecyclerView.addOnScrollListener(mElevationController);
+ mAdapter = (AllAppsGridAdapter) mAppsRecyclerView.getAdapter();
+ mSearchBarController.initialize(
+ new DefaultAppSearchAlgorithm(appsList.getApps()), mSearchInput, mLauncher, this);
+ }
+
+ @Override
+ public void refreshSearchResult() {
+ mSearchBarController.refreshSearchResult();
+ }
+
+ @Override
+ public void reset() {
+ mElevationController.reset();
+ mSearchBarController.reset();
+ }
+
+ @Override
+ public void preDispatchKeyEvent(KeyEvent event) {
+ // Determine if the key event was actual text, if so, focus the search bar and then dispatch
+ // the key normally so that it can process this key event
+ if (!mSearchBarController.isSearchFieldFocused() &&
+ event.getAction() == KeyEvent.ACTION_DOWN) {
+ final int unicodeChar = event.getUnicodeChar();
+ final boolean isKeyNotWhitespace = unicodeChar > 0 &&
+ !Character.isWhitespace(unicodeChar) && !Character.isSpaceChar(unicodeChar);
+ if (isKeyNotWhitespace) {
+ boolean gotKey = TextKeyListener.getInstance().onKeyDown(this, mSearchQueryBuilder,
+ event.getKeyCode(), event);
+ if (gotKey && mSearchQueryBuilder.length() > 0) {
+ mSearchBarController.focusSearchField();
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onSearchResult(String query, ArrayList apps) {
+ if (apps != null) {
+ mApps.setOrderedFilter(apps);
+ notifyResultChanged();
+ mAdapter.setLastSearchQuery(query);
+ }
+ }
+
+ @Override
+ public void clearSearchResult() {
+ if (mApps.setOrderedFilter(null)) {
+ notifyResultChanged();
+ }
+
+ // Clear the search query
+ mSearchQueryBuilder.clear();
+ mSearchQueryBuilder.clearSpans();
+ Selection.setSelection(mSearchQueryBuilder, 0);
+ }
+
+ @Override
+ public void onAppDiscoverySearchUpdate(
+ @Nullable AppDiscoveryItem app, @NonNull AppDiscoveryUpdateState state) {
+ if (!mLauncher.isDestroyed()) {
+ mApps.onAppDiscoverySearchUpdate(app, state);
+ notifyResultChanged();
+ }
+ }
+
+ private void notifyResultChanged() {
+ mElevationController.reset();
+ mAppsRecyclerView.onSearchResultsChanged();
+ }
+
+ @Override
+ public void addOnScrollRangeChangeListener(final OnScrollRangeChangeListener listener) {
+ mLauncher.getHotseat().addOnLayoutChangeListener(new OnLayoutChangeListener() {
+ @Override
+ public void onLayoutChange(View v, int left, int top, int right, int bottom,
+ int oldLeft, int oldTop, int oldRight, int oldBottom) {
+ DeviceProfile dp = mLauncher.getDeviceProfile();
+ if (!dp.isVerticalBarLayout()) {
+ Rect insets = mLauncher.getDragLayer().getInsets();
+ int hotseatBottom = bottom - dp.hotseatBarBottomPaddingPx - insets.bottom;
+ int searchTopMargin = insets.top + (mMinHeight - mSearchBoxHeight);
+ listener.onScrollRangeChanged(hotseatBottom - searchTopMargin);
+ } else {
+ listener.onScrollRangeChanged(bottom);
+ }
+ }
+ });
+ }
+}
diff --git a/src/com/android/launcher3/allapps/DefaultAppSearchAlgorithm.java b/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithm.java
similarity index 92%
rename from src/com/android/launcher3/allapps/DefaultAppSearchAlgorithm.java
rename to src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithm.java
index 06cf9aa71d..8a0fd46f7c 100644
--- a/src/com/android/launcher3/allapps/DefaultAppSearchAlgorithm.java
+++ b/src/com/android/launcher3/allapps/search/DefaultAppSearchAlgorithm.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.launcher3.allapps;
+package com.android.launcher3.allapps.search;
import android.os.Handler;
@@ -26,7 +26,7 @@ import java.util.List;
/**
* The default search implementation.
*/
-public class DefaultAppSearchAlgorithm {
+public class DefaultAppSearchAlgorithm implements SearchAlgorithm {
private final List mApps;
protected final Handler mResultHandler;
@@ -36,12 +36,14 @@ public class DefaultAppSearchAlgorithm {
mResultHandler = new Handler();
}
+ @Override
public void cancel(boolean interruptActiveRequests) {
if (interruptActiveRequests) {
mResultHandler.removeCallbacksAndMessages(null);
}
}
+ @Override
public void doSearch(final String query,
final AllAppsSearchBarController.Callbacks callback) {
final ArrayList result = getTitleMatchResult(query);
@@ -54,7 +56,7 @@ public class DefaultAppSearchAlgorithm {
});
}
- protected ArrayList getTitleMatchResult(String query) {
+ private ArrayList getTitleMatchResult(String query) {
// Do an intersection of the words in the query and each title, and filter out all the
// apps that don't match all of the words in the query.
final String queryTextLower = query.toLowerCase();
@@ -67,7 +69,7 @@ public class DefaultAppSearchAlgorithm {
return result;
}
- protected boolean matches(AppInfo info, String query) {
+ public static boolean matches(AppInfo info, String query) {
int queryLength = query.length();
String title = info.title.toString();
@@ -103,7 +105,7 @@ public class DefaultAppSearchAlgorithm {
* 3) Any capital character after a digit or small character
* 4) Any capital character before a small character
*/
- protected boolean isBreak(int thisType, int prevType, int nextType) {
+ private static boolean isBreak(int thisType, int prevType, int nextType) {
switch (thisType) {
case Character.UPPERCASE_LETTER:
if (nextType == Character.UPPERCASE_LETTER) {
diff --git a/src/com/android/launcher3/allapps/HeaderElevationController.java b/src/com/android/launcher3/allapps/search/HeaderElevationController.java
similarity index 58%
rename from src/com/android/launcher3/allapps/HeaderElevationController.java
rename to src/com/android/launcher3/allapps/search/HeaderElevationController.java
index b167fed335..7cd32b26e5 100644
--- a/src/com/android/launcher3/allapps/HeaderElevationController.java
+++ b/src/com/android/launcher3/allapps/search/HeaderElevationController.java
@@ -1,14 +1,14 @@
-package com.android.launcher3.allapps;
+package com.android.launcher3.allapps.search;
import android.content.res.Resources;
import android.graphics.Outline;
import android.support.v7.widget.RecyclerView;
import android.view.View;
+import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import com.android.launcher3.BaseRecyclerView;
import com.android.launcher3.R;
-import com.android.launcher3.Utilities;
/**
* Helper class for controlling the header elevation in response to RecyclerView scroll.
@@ -16,6 +16,7 @@ import com.android.launcher3.Utilities;
public class HeaderElevationController extends RecyclerView.OnScrollListener {
private final View mHeader;
+ private final View mHeaderChild;
private final float mMaxElevation;
private final float mScrollToElevation;
@@ -28,23 +29,27 @@ public class HeaderElevationController extends RecyclerView.OnScrollListener {
mScrollToElevation = res.getDimension(R.dimen.all_apps_header_scroll_to_elevation);
// We need to provide a custom outline so the shadow only appears on the bottom edge.
- // The top, left and right edges are all extended out, and the shadow is clipped
- // by the parent.
+ // The top, left and right edges are all extended out to match parent's edge, so that
+ // the shadow is clipped by the parent.
final ViewOutlineProvider vop = new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
- final View parent = (View) mHeader.getParent();
+ // Set the left and top to be at the parents edge. Since the coordinates are
+ // relative to this view,
+ // (x = -view.getLeft()) for this view => (x = 0) for parent
+ final int left = -view.getLeft();
+ final int top = -view.getTop();
- final int left = parent.getLeft(); // Use the parent to account for offsets
- final int top = view.getTop();
- final int right = left + view.getWidth();
- final int bottom = view.getBottom();
-
- final int offset = Utilities.pxFromDp(mMaxElevation, res.getDisplayMetrics());
+ // Since the view is centered align, the spacing on left and right are same.
+ // Add same spacing on the right to reach parent's edge.
+ final int right = view.getWidth() - left;
+ final int bottom = view.getHeight();
+ final int offset = (int) mMaxElevation;
outline.setRect(left - offset, top - offset, right + offset, bottom);
}
};
mHeader.setOutlineProvider(vop);
+ mHeaderChild = ((ViewGroup) mHeader).getChildAt(0);
}
public void reset() {
@@ -63,6 +68,13 @@ public class HeaderElevationController extends RecyclerView.OnScrollListener {
float newElevation = mMaxElevation * elevationPct;
if (Float.compare(mHeader.getElevation(), newElevation) != 0) {
mHeader.setElevation(newElevation);
+
+ // To simulate a scrolling effect for the header, we translate the header down, and
+ // its content up by the same amount, so that it gets clipped by the parent, making it
+ // look like the content was scrolled out of the view.
+ int shift = Math.min(mHeader.getHeight(), scrollY);
+ mHeader.setTranslationY(-shift);
+ mHeaderChild.setTranslationY(shift);
}
}
diff --git a/src/com/android/launcher3/allapps/DefaultAppSearchController.java b/src/com/android/launcher3/allapps/search/SearchAlgorithm.java
similarity index 57%
rename from src/com/android/launcher3/allapps/DefaultAppSearchController.java
rename to src/com/android/launcher3/allapps/search/SearchAlgorithm.java
index 57747e3672..c409b1ce85 100644
--- a/src/com/android/launcher3/allapps/DefaultAppSearchController.java
+++ b/src/com/android/launcher3/allapps/search/SearchAlgorithm.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2015 The Android Open Source Project
+ * Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,14 +13,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.launcher3.allapps;
+package com.android.launcher3.allapps.search;
/**
- * The default search controller.
+ * An interface for handling search.
*/
-public class DefaultAppSearchController extends AllAppsSearchBarController {
+public interface SearchAlgorithm {
- public DefaultAppSearchAlgorithm onInitializeSearch() {
- return new DefaultAppSearchAlgorithm(mApps.getApps());
- }
+ /**
+ * Performs search and sends the result to the callback.
+ */
+ void doSearch(String query, AllAppsSearchBarController.Callbacks callback);
+
+ /**
+ * Cancels any active request.
+ */
+ void cancel(boolean interruptActiveRequests);
}
diff --git a/src/com/android/launcher3/anim/AnimationLayerSet.java b/src/com/android/launcher3/anim/AnimationLayerSet.java
index 14bcd17183..f0b34587a2 100644
--- a/src/com/android/launcher3/anim/AnimationLayerSet.java
+++ b/src/com/android/launcher3/anim/AnimationLayerSet.java
@@ -18,9 +18,8 @@ package com.android.launcher3.anim;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
+import android.util.ArrayMap;
import android.view.View;
-
-import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@@ -29,14 +28,14 @@ import java.util.Map;
*/
public class AnimationLayerSet extends AnimatorListenerAdapter {
- private final HashMap mViewsToLayerTypeMap;
+ private final ArrayMap mViewsToLayerTypeMap;
public AnimationLayerSet() {
- mViewsToLayerTypeMap = new HashMap<>();
+ mViewsToLayerTypeMap = new ArrayMap<>();
}
public AnimationLayerSet(View v) {
- mViewsToLayerTypeMap = new HashMap<>(1);
+ mViewsToLayerTypeMap = new ArrayMap<>(1);
addView(v);
}
diff --git a/src/com/android/launcher3/util/CircleRevealOutlineProvider.java b/src/com/android/launcher3/anim/CircleRevealOutlineProvider.java
similarity index 97%
rename from src/com/android/launcher3/util/CircleRevealOutlineProvider.java
rename to src/com/android/launcher3/anim/CircleRevealOutlineProvider.java
index 9fe51476da..9fb6b498bb 100644
--- a/src/com/android/launcher3/util/CircleRevealOutlineProvider.java
+++ b/src/com/android/launcher3/anim/CircleRevealOutlineProvider.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.launcher3.util;
+package com.android.launcher3.anim;
public class CircleRevealOutlineProvider extends RevealOutlineAnimation {
diff --git a/src/com/android/launcher3/anim/PillHeightRevealOutlineProvider.java b/src/com/android/launcher3/anim/PillHeightRevealOutlineProvider.java
deleted file mode 100644
index be1e2d644b..0000000000
--- a/src/com/android/launcher3/anim/PillHeightRevealOutlineProvider.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.launcher3.anim;
-
-import android.graphics.Rect;
-
-import com.android.launcher3.util.PillRevealOutlineProvider;
-
-/**
- * Extension of {@link PillRevealOutlineProvider} which only changes the height of the pill.
- * For now, we assume the height is added/removed from the bottom.
- */
-public class PillHeightRevealOutlineProvider extends PillRevealOutlineProvider {
-
- private final int mNewHeight;
-
- public PillHeightRevealOutlineProvider(Rect pillRect, float radius, int newHeight) {
- super(0, 0, pillRect, radius);
- mOutline.set(pillRect);
- mNewHeight = newHeight;
- }
-
- @Override
- public void setProgress(float progress) {
- mOutline.top = 0;
- int heightDifference = mPillRect.height() - mNewHeight;
- mOutline.bottom = (int) (mPillRect.bottom - heightDifference * (1 - progress));
- }
-}
diff --git a/src/com/android/launcher3/util/RevealOutlineAnimation.java b/src/com/android/launcher3/anim/RevealOutlineAnimation.java
similarity index 96%
rename from src/com/android/launcher3/util/RevealOutlineAnimation.java
rename to src/com/android/launcher3/anim/RevealOutlineAnimation.java
index 4560477753..51d00d9477 100644
--- a/src/com/android/launcher3/util/RevealOutlineAnimation.java
+++ b/src/com/android/launcher3/anim/RevealOutlineAnimation.java
@@ -1,4 +1,4 @@
-package com.android.launcher3.util;
+package com.android.launcher3.anim;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
@@ -83,4 +83,8 @@ public abstract class RevealOutlineAnimation extends ViewOutlineProvider {
public void getOutline(View v, Outline outline) {
outline.setRoundRect(mOutline, mOutlineRadius);
}
+
+ public float getRadius() {
+ return mOutlineRadius;
+ }
}
diff --git a/src/com/android/launcher3/anim/RoundedRectRevealOutlineProvider.java b/src/com/android/launcher3/anim/RoundedRectRevealOutlineProvider.java
new file mode 100644
index 0000000000..7c5fa1ced0
--- /dev/null
+++ b/src/com/android/launcher3/anim/RoundedRectRevealOutlineProvider.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.launcher3.anim;
+
+import android.graphics.Rect;
+
+import com.android.launcher3.popup.PopupContainerWithArrow;
+
+import static com.android.launcher3.popup.PopupContainerWithArrow.ROUNDED_BOTTOM_CORNERS;
+import static com.android.launcher3.popup.PopupContainerWithArrow.ROUNDED_TOP_CORNERS;
+
+/**
+ * A {@link RevealOutlineAnimation} that provides an outline that interpolates between two radii
+ * and two {@link Rect}s.
+ *
+ * An example usage of this provider is an outline that starts out as a circle and ends
+ * as a rounded rectangle.
+ */
+public class RoundedRectRevealOutlineProvider extends RevealOutlineAnimation {
+ private final float mStartRadius;
+ private final float mEndRadius;
+
+ private final Rect mStartRect;
+ private final Rect mEndRect;
+
+ private final @PopupContainerWithArrow.RoundedCornerFlags int mRoundedCorners;
+
+ public RoundedRectRevealOutlineProvider(float startRadius, float endRadius, Rect startRect,
+ Rect endRect) {
+ this(startRadius, endRadius, startRect, endRect,
+ ROUNDED_TOP_CORNERS | ROUNDED_BOTTOM_CORNERS);
+ }
+
+ public RoundedRectRevealOutlineProvider(float startRadius, float endRadius, Rect startRect,
+ Rect endRect, int roundedCorners) {
+ mStartRadius = startRadius;
+ mEndRadius = endRadius;
+ mStartRect = startRect;
+ mEndRect = endRect;
+ mRoundedCorners = roundedCorners;
+ }
+
+ @Override
+ public boolean shouldRemoveElevationDuringAnimation() {
+ return true;
+ }
+
+ @Override
+ public void setProgress(float progress) {
+ mOutlineRadius = (1 - progress) * mStartRadius + progress * mEndRadius;
+
+ mOutline.left = (int) ((1 - progress) * mStartRect.left + progress * mEndRect.left);
+ mOutline.top = (int) ((1 - progress) * mStartRect.top + progress * mEndRect.top);
+ if ((mRoundedCorners & ROUNDED_TOP_CORNERS) == 0) {
+ mOutline.top -= mOutlineRadius;
+ }
+ mOutline.right = (int) ((1 - progress) * mStartRect.right + progress * mEndRect.right);
+ mOutline.bottom = (int) ((1 - progress) * mStartRect.bottom + progress * mEndRect.bottom);
+ if ((mRoundedCorners & ROUNDED_BOTTOM_CORNERS) == 0) {
+ mOutline.bottom += mOutlineRadius;
+ }
+ }
+}
diff --git a/src/com/android/launcher3/anim/SpringAnimationHandler.java b/src/com/android/launcher3/anim/SpringAnimationHandler.java
new file mode 100644
index 0000000000..038f82682c
--- /dev/null
+++ b/src/com/android/launcher3/anim/SpringAnimationHandler.java
@@ -0,0 +1,214 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.launcher3.anim;
+
+import android.support.animation.FloatPropertyCompat;
+import android.support.animation.SpringAnimation;
+import android.support.animation.SpringForce;
+import android.support.annotation.IntDef;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.VelocityTracker;
+import android.view.View;
+
+import com.android.launcher3.R;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.ArrayList;
+
+/**
+ * Handler class that manages springs for a set of views that should all move based on the same
+ * {@link MotionEvent}s.
+ *
+ * Supports setting either X or Y velocity on the list of springs added to this handler.
+ */
+public class SpringAnimationHandler {
+
+ private static final String TAG = "SpringAnimationHandler";
+ private static final boolean DEBUG = false;
+
+ private static final float VELOCITY_DAMPING_FACTOR = 0.175f;
+
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({Y_DIRECTION, X_DIRECTION})
+ public @interface Direction {}
+ public static final int Y_DIRECTION = 0;
+ public static final int X_DIRECTION = 1;
+ private int mVelocityDirection;
+
+ private VelocityTracker mVelocityTracker;
+ private float mCurrentVelocity = 0;
+ private boolean mShouldComputeVelocity = false;
+
+ private AnimationFactory mAnimationFactory;
+
+ private ArrayList mAnimations = new ArrayList<>();
+
+ /**
+ * @param direction Either {@link #X_DIRECTION} or {@link #Y_DIRECTION}.
+ * Determines which direction we use to calculate and set the velocity.
+ * @param factory The AnimationFactory is responsible for initializing and updating the
+ * SpringAnimations added to this class.
+ */
+ public SpringAnimationHandler(@Direction int direction, AnimationFactory factory) {
+ mVelocityDirection = direction;
+ mAnimationFactory = factory;
+ }
+
+ /**
+ * Adds a new or recycled animation to the list of springs handled by this class.
+ *
+ * @param view The view the spring is attached to.
+ * @param object Used to initialize and update the spring.
+ */
+ public void add(View view, T object) {
+ SpringAnimation spring = (SpringAnimation) view.getTag(R.id.spring_animation_tag);
+ if (spring == null) {
+ spring = mAnimationFactory.initialize(object);
+ view.setTag(R.id.spring_animation_tag, spring);
+ }
+ mAnimationFactory.update(spring, object);
+ spring.setStartVelocity(mCurrentVelocity);
+ mAnimations.add(spring);
+ }
+
+ /**
+ * Stops and removes the spring attached to {@param view}.
+ */
+ public void remove(View view) {
+ SpringAnimation animation = (SpringAnimation) view.getTag(R.id.spring_animation_tag);
+ if (animation.canSkipToEnd()) {
+ animation.skipToEnd();
+ }
+ mAnimations.remove(animation);
+ }
+
+ public void addMovement(MotionEvent event) {
+ int action = event.getActionMasked();
+ if (DEBUG) Log.d(TAG, "addMovement#action=" + action);
+ switch (action) {
+ case MotionEvent.ACTION_CANCEL:
+ case MotionEvent.ACTION_DOWN:
+ reset();
+ break;
+ }
+
+ getVelocityTracker().addMovement(event);
+ mShouldComputeVelocity = true;
+ }
+
+ public void animateToFinalPosition(float position) {
+ if (DEBUG) Log.d(TAG, "animateToFinalPosition#computeVelocity=" + mShouldComputeVelocity);
+
+ if (mShouldComputeVelocity) {
+ computeVelocity();
+ setStartVelocity(mCurrentVelocity);
+ }
+
+ int size = mAnimations.size();
+ for (int i = 0; i < size; ++i) {
+ mAnimations.get(i).animateToFinalPosition(position);
+ }
+
+ reset();
+ }
+
+ public boolean isRunning() {
+ // All the animations run at the same time so we can just check the first one.
+ return !mAnimations.isEmpty() && mAnimations.get(0).isRunning();
+ }
+
+ public void skipToEnd() {
+ if (DEBUG) Log.d(TAG, "setStartVelocity#skipToEnd");
+ if (DEBUG) Log.v(TAG, "setStartVelocity#skipToEnd", new Exception());
+
+ int size = mAnimations.size();
+ for (int i = 0; i < size; ++i) {
+ if (mAnimations.get(i).canSkipToEnd()) {
+ mAnimations.get(i).skipToEnd();
+ }
+ }
+ }
+
+ public void reset() {
+ if (mVelocityTracker != null) {
+ mVelocityTracker.recycle();
+ mVelocityTracker = null;
+ }
+ mCurrentVelocity = 0;
+ }
+
+ private void setStartVelocity(float velocity) {
+ int size = mAnimations.size();
+ for (int i = 0; i < size; ++i) {
+ mAnimations.get(i).setStartVelocity(velocity);
+ }
+ }
+
+ private void computeVelocity() {
+ getVelocityTracker().computeCurrentVelocity(1000 /* millis */);
+
+ mCurrentVelocity = isVerticalDirection()
+ ? getVelocityTracker().getYVelocity()
+ : getVelocityTracker().getXVelocity();
+ mCurrentVelocity *= VELOCITY_DAMPING_FACTOR;
+ mShouldComputeVelocity = false;
+
+ if (DEBUG) Log.d(TAG, "computeVelocity=" + mCurrentVelocity);
+ }
+
+ private boolean isVerticalDirection() {
+ return mVelocityDirection == Y_DIRECTION;
+ }
+
+ private VelocityTracker getVelocityTracker() {
+ if (mVelocityTracker == null) {
+ mVelocityTracker = VelocityTracker.obtain();
+ }
+ return mVelocityTracker;
+ }
+
+ /**
+ * This interface is used to initialize and update the SpringAnimations added to the
+ * {@link SpringAnimationHandler}.
+ *
+ * @param The object that each SpringAnimation is attached to.
+ */
+ public interface AnimationFactory {
+
+ /**
+ * Initializes a new Spring for {@param object}.
+ */
+ SpringAnimation initialize(T object);
+
+ /**
+ * Updates the value of {@param spring} based on {@param object}.
+ */
+ void update(SpringAnimation spring, T object);
+ }
+
+ /**
+ * Helper method to create a new SpringAnimation for {@param view}.
+ */
+ public static SpringAnimation forView(View view, FloatPropertyCompat property, float finalPos) {
+ SpringAnimation spring = new SpringAnimation(view, property, finalPos);
+ spring.setStartValue(1f);
+ spring.setSpring(new SpringForce(finalPos));
+ return spring;
+ }
+
+}
diff --git a/src/com/android/launcher3/badge/BadgeRenderer.java b/src/com/android/launcher3/badge/BadgeRenderer.java
index ba1977af44..c2cc215ce5 100644
--- a/src/com/android/launcher3/badge/BadgeRenderer.java
+++ b/src/com/android/launcher3/badge/BadgeRenderer.java
@@ -107,7 +107,8 @@ public class BadgeRenderer {
// Lazily load the background with shadow.
Bitmap backgroundWithShadow = mBackgroundsWithShadow.get(numChars);
if (backgroundWithShadow == null) {
- backgroundWithShadow = ShadowGenerator.createPillWithShadow(Color.WHITE, width, mSize);
+ backgroundWithShadow = new ShadowGenerator.Builder(Color.WHITE)
+ .setupBlurForSize(mSize).createPill(width, mSize);
mBackgroundsWithShadow.put(numChars, backgroundWithShadow);
}
canvas.save(Canvas.MATRIX_SAVE_FLAG);
diff --git a/src/com/android/launcher3/compat/LauncherAppsCompat.java b/src/com/android/launcher3/compat/LauncherAppsCompat.java
index e997a99936..75a2a5d18d 100644
--- a/src/com/android/launcher3/compat/LauncherAppsCompat.java
+++ b/src/com/android/launcher3/compat/LauncherAppsCompat.java
@@ -25,16 +25,9 @@ import android.graphics.Rect;
import android.os.Bundle;
import android.os.UserHandle;
import android.support.annotation.Nullable;
-
-import com.android.launcher3.LauncherAppState;
-import com.android.launcher3.LauncherModel;
-import com.android.launcher3.ShortcutInfo;
import com.android.launcher3.Utilities;
-import com.android.launcher3.graphics.LauncherIcons;
import com.android.launcher3.shortcuts.ShortcutInfoCompat;
-import com.android.launcher3.util.LooperExecuter;
import com.android.launcher3.util.PackageUserKey;
-
import java.util.List;
public abstract class LauncherAppsCompat {
@@ -55,7 +48,7 @@ public abstract class LauncherAppsCompat {
}
private static LauncherAppsCompat sInstance;
- private static Object sInstanceLock = new Object();
+ private static final Object sInstanceLock = new Object();
public static LauncherAppsCompat getInstance(Context context) {
synchronized (sInstanceLock) {
@@ -88,62 +81,6 @@ public abstract class LauncherAppsCompat {
public abstract List getCustomShortcutActivityList(
@Nullable PackageUserKey packageUser);
- /**
- * request.accept() will initiate the following flow:
- * -> go-to-system-process for actual processing (a)
- * -> callback-to-launcher on UI thread (b)
- * -> post callback on the worker thread (c)
- * -> Update model and unpin (in system) any shortcut not in out model. (d)
- *
- * Note that (b) will take at-least one frame as it involves posting callback from binder
- * thread to UI thread.
- * If (d) happens before we add this shortcut to our model, we will end up unpinning
- * the shortcut in the system.
- * Here its the caller's responsibility to add the newly created ShortcutInfo immediately
- * to the model (which may involves a single post-to-worker-thread). That will guarantee
- * that (d) happens after model is updated.
- */
- @Nullable
- public static ShortcutInfo createShortcutInfoFromPinItemRequest(
- Context context, final PinItemRequestCompat request, final long acceptDelay) {
- if (request != null &&
- request.getRequestType() == PinItemRequestCompat.REQUEST_TYPE_SHORTCUT &&
- request.isValid()) {
-
- if (acceptDelay <= 0) {
- if (!request.accept()) {
- return null;
- }
- } else {
- // Block the worker thread until the accept() is called.
- new LooperExecuter(LauncherModel.getWorkerLooper()).execute(new Runnable() {
- @Override
- public void run() {
- try {
- Thread.sleep(acceptDelay);
- } catch (InterruptedException e) {
- // Ignore
- }
- if (request.isValid()) {
- request.accept();
- }
- }
- });
- }
-
- ShortcutInfoCompat compat = new ShortcutInfoCompat(request.getShortcutInfo());
- ShortcutInfo info = new ShortcutInfo(compat, context);
- // Apply the unbadged icon and fetch the actual icon asynchronously.
- info.iconBitmap = LauncherIcons
- .createShortcutIcon(compat, context, false /* badged */);
- LauncherAppState.getInstance(context).getModel()
- .updateAndBindShortcutInfo(info, compat);
- return info;
- } else {
- return null;
- }
- }
-
public void showAppDetailsForProfile(ComponentName component, UserHandle user) {
showAppDetailsForProfile(component, user, null, null);
}
diff --git a/src/com/android/launcher3/compat/LauncherAppsCompatVL.java b/src/com/android/launcher3/compat/LauncherAppsCompatVL.java
index 647c31593b..cc3e5a7277 100644
--- a/src/com/android/launcher3/compat/LauncherAppsCompatVL.java
+++ b/src/com/android/launcher3/compat/LauncherAppsCompatVL.java
@@ -29,23 +29,22 @@ import android.graphics.Rect;
import android.os.Bundle;
import android.os.Process;
import android.os.UserHandle;
+import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
-
+import android.util.ArrayMap;
import com.android.launcher3.compat.ShortcutConfigActivityInfo.ShortcutConfigActivityInfoVL;
import com.android.launcher3.shortcuts.ShortcutInfoCompat;
import com.android.launcher3.util.PackageUserKey;
-
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
public class LauncherAppsCompatVL extends LauncherAppsCompat {
protected final LauncherApps mLauncherApps;
protected final Context mContext;
- private Map mCallbacks = new HashMap<>();
+ private final ArrayMap mCallbacks =
+ new ArrayMap<>();
LauncherAppsCompatVL(Context context) {
mContext = context;
@@ -131,43 +130,52 @@ public class LauncherAppsCompatVL extends LauncherAppsCompat {
}
private static class WrappedCallback extends LauncherApps.Callback {
- private LauncherAppsCompat.OnAppsChangedCallbackCompat mCallback;
+ private final LauncherAppsCompat.OnAppsChangedCallbackCompat mCallback;
public WrappedCallback(LauncherAppsCompat.OnAppsChangedCallbackCompat callback) {
mCallback = callback;
}
+ @Override
public void onPackageRemoved(String packageName, UserHandle user) {
mCallback.onPackageRemoved(packageName, user);
}
+ @Override
public void onPackageAdded(String packageName, UserHandle user) {
mCallback.onPackageAdded(packageName, user);
}
+ @Override
public void onPackageChanged(String packageName, UserHandle user) {
mCallback.onPackageChanged(packageName, user);
}
+ @Override
public void onPackagesAvailable(String[] packageNames, UserHandle user, boolean replacing) {
mCallback.onPackagesAvailable(packageNames, user, replacing);
}
+ @Override
public void onPackagesUnavailable(String[] packageNames, UserHandle user,
boolean replacing) {
mCallback.onPackagesUnavailable(packageNames, user, replacing);
}
+ @Override
public void onPackagesSuspended(String[] packageNames, UserHandle user) {
mCallback.onPackagesSuspended(packageNames, user);
}
+ @Override
public void onPackagesUnsuspended(String[] packageNames, UserHandle user) {
mCallback.onPackagesUnsuspended(packageNames, user);
}
- public void onShortcutsChanged(String packageName, List shortcuts,
- UserHandle user) {
+ @Override
+ public void onShortcutsChanged(@NonNull String packageName,
+ @NonNull List shortcuts,
+ @NonNull UserHandle user) {
List shortcutInfoCompats = new ArrayList<>(shortcuts.size());
for (ShortcutInfo shortcutInfo : shortcuts) {
shortcutInfoCompats.add(new ShortcutInfoCompat(shortcutInfo));
diff --git a/src/com/android/launcher3/compat/LauncherAppsCompatVO.java b/src/com/android/launcher3/compat/LauncherAppsCompatVO.java
index d145539c7a..3214b4672c 100644
--- a/src/com/android/launcher3/compat/LauncherAppsCompatVO.java
+++ b/src/com/android/launcher3/compat/LauncherAppsCompatVO.java
@@ -18,20 +18,27 @@ package com.android.launcher3.compat;
import android.annotation.TargetApi;
import android.content.Context;
+import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
+import android.content.pm.LauncherApps.PinItemRequest;
import android.content.pm.PackageManager;
import android.os.Build;
+import android.os.Parcelable;
import android.os.Process;
import android.os.UserHandle;
import android.support.annotation.Nullable;
-import android.util.Log;
+import com.android.launcher3.LauncherAppState;
+import com.android.launcher3.LauncherModel;
+import com.android.launcher3.ShortcutInfo;
import com.android.launcher3.compat.ShortcutConfigActivityInfo.ShortcutConfigActivityInfoVO;
+import com.android.launcher3.graphics.LauncherIcons;
+import com.android.launcher3.shortcuts.ShortcutInfoCompat;
+import com.android.launcher3.util.LooperExecutor;
import com.android.launcher3.util.PackageUserKey;
-import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@@ -45,11 +52,6 @@ public class LauncherAppsCompatVO extends LauncherAppsCompatVL {
@Override
public ApplicationInfo getApplicationInfo(String packageName, int flags, UserHandle user) {
try {
- // TODO: Temporary workaround until the API signature is updated
- if (false) {
- throw new PackageManager.NameNotFoundException();
- }
-
ApplicationInfo info = mLauncherApps.getApplicationInfo(packageName, flags, user);
return (info.flags & ApplicationInfo.FLAG_INSTALLED) == 0 || !info.enabled
? null : info;
@@ -64,34 +66,89 @@ public class LauncherAppsCompatVO extends LauncherAppsCompatVL {
List