screenIds)
throws XmlPullParserException, IOException {
+
+ if (TAG_INCLUDE.equals(parser.getName())) {
+ final int resId = getAttributeResourceValue(parser, ATTR_WORKSPACE, 0);
+ if (resId != 0) {
+ // recursively load some more favorites, why not?
+ return parseLayout(resId, screenIds);
+ } else {
+ return 0;
+ }
+ }
+
mValues.clear();
parseContainerAndScreen(parser, mTemp);
final long container = mTemp[0];
@@ -528,6 +580,7 @@ public class AutoInstallsLayout {
int type;
int folderDepth = parser.getDepth();
+ int rank = 0;
while ((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > folderDepth) {
if (type != XmlPullParser.START_TAG) {
@@ -535,12 +588,14 @@ public class AutoInstallsLayout {
}
mValues.clear();
mValues.put(Favorites.CONTAINER, folderId);
+ mValues.put(Favorites.RANK, rank);
TagParser tagParser = mFolderElements.get(parser.getName());
if (tagParser != null) {
final long id = tagParser.parseAndAdd(parser);
if (id >= 0) {
folderItems.add(id);
+ rank++;
}
} else {
throw new RuntimeException("Invalid folder item " + parser.getName());
@@ -554,7 +609,7 @@ public class AutoInstallsLayout {
// failed to add, and less than 2 were actually added
if (folderItems.size() < 2) {
// Delete the folder
- Uri uri = Favorites.getContentUri(folderId, false);
+ Uri uri = Favorites.getContentUri(folderId);
SqlArguments args = new SqlArguments(uri, null, null);
mDb.delete(args.table, args.where, args.args);
addedId = -1;
@@ -627,7 +682,7 @@ public class AutoInstallsLayout {
long insertAndCheck(SQLiteDatabase db, ContentValues values);
}
- private static void copyInteger(ContentValues from, ContentValues to, String key) {
+ @Thunk static void copyInteger(ContentValues from, ContentValues to, String key) {
to.put(key, from.getAsInteger(key));
}
}
diff --git a/src/com/android/launcher3/BaseContainerView.java b/src/com/android/launcher3/BaseContainerView.java
new file mode 100644
index 0000000000..c8de9df10d
--- /dev/null
+++ b/src/com/android/launcher3/BaseContainerView.java
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2015 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.Context;
+import android.graphics.Rect;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.widget.LinearLayout;
+
+/**
+ * A base container view, which supports resizing.
+ */
+public abstract class BaseContainerView extends LinearLayout implements Insettable {
+
+ private final static String TAG = "BaseContainerView";
+
+ // The window insets
+ private Rect mInsets = new Rect();
+ // The bounds of the search bar. Only the left, top, right are used to inset the
+ // search bar and the height is determined by the measurement of the layout
+ private Rect mFixedSearchBarBounds = new Rect();
+ // The bounds of the container
+ protected Rect mContentBounds = new Rect();
+ // The padding to apply to the container to achieve the bounds
+ protected Rect mContentPadding = new Rect();
+ // The inset to apply to the edges and between the search bar and the container
+ private int mContainerBoundsInset;
+ private boolean mHasSearchBar;
+
+ public BaseContainerView(Context context) {
+ this(context, null);
+ }
+
+ public BaseContainerView(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ public BaseContainerView(Context context, AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ mContainerBoundsInset = getResources().getDimensionPixelSize(R.dimen.container_bounds_inset);
+ }
+
+ @Override
+ final public void setInsets(Rect insets) {
+ mInsets.set(insets);
+ updateBackgroundAndPaddings();
+ }
+
+ protected void setHasSearchBar() {
+ mHasSearchBar = true;
+ }
+
+ /**
+ * Sets the search bar bounds for this container view to match.
+ */
+ final public void setSearchBarBounds(Rect bounds) {
+ if (LauncherAppState.isDogfoodBuild() && !isValidSearchBarBounds(bounds)) {
+ Log.e(TAG, "Invalid search bar bounds: " + bounds);
+ }
+
+ mFixedSearchBarBounds.set(bounds);
+
+ // Post the updates since they can trigger a relayout, and this call can be triggered from
+ // a layout pass itself.
+ post(new Runnable() {
+ @Override
+ public void run() {
+ updateBackgroundAndPaddings();
+ }
+ });
+ }
+
+ /**
+ * Update the backgrounds and padding in response to a change in the bounds or insets.
+ */
+ protected void updateBackgroundAndPaddings() {
+ Rect padding;
+ Rect searchBarBounds = new Rect(mFixedSearchBarBounds);
+ if (!isValidSearchBarBounds(mFixedSearchBarBounds)) {
+ // Use the default bounds
+ padding = new Rect(mInsets.left + mContainerBoundsInset,
+ (mHasSearchBar ? 0 : (mInsets.top + mContainerBoundsInset)),
+ mInsets.right + mContainerBoundsInset,
+ mInsets.bottom + mContainerBoundsInset);
+
+ // Special case -- we have the search bar, but no specific bounds, so just give it
+ // the inset bounds without a height.
+ searchBarBounds.set(mInsets.left + mContainerBoundsInset,
+ mInsets.top + mContainerBoundsInset,
+ getMeasuredWidth() - (mInsets.right + mContainerBoundsInset), 0);
+ } else {
+ // Use the search bounds, if there is a search bar, the bounds will contain
+ // the offsets for the insets so we can ignore that
+ padding = new Rect(mFixedSearchBarBounds.left,
+ (mHasSearchBar ? 0 : (mInsets.top + mContainerBoundsInset)),
+ getMeasuredWidth() - mFixedSearchBarBounds.right,
+ mInsets.bottom + mContainerBoundsInset);
+ }
+ if (!padding.equals(mContentPadding) || !searchBarBounds.equals(mFixedSearchBarBounds)) {
+ mContentPadding.set(padding);
+ mContentBounds.set(padding.left, padding.top,
+ getMeasuredWidth() - padding.right,
+ getMeasuredHeight() - padding.bottom);
+ mFixedSearchBarBounds.set(searchBarBounds);
+ onUpdateBackgroundAndPaddings(mFixedSearchBarBounds, padding);
+ }
+ }
+
+ /**
+ * To be implemented by container views to update themselves when the bounds changes.
+ */
+ protected abstract void onUpdateBackgroundAndPaddings(Rect searchBarBounds, Rect padding);
+
+ /**
+ * Returns whether the search bar bounds we got are considered valid.
+ */
+ private boolean isValidSearchBarBounds(Rect searchBarBounds) {
+ return !searchBarBounds.isEmpty() &&
+ searchBarBounds.right <= getMeasuredWidth() &&
+ searchBarBounds.bottom <= getMeasuredHeight();
+ }
+}
\ No newline at end of file
diff --git a/src/com/android/launcher3/BaseRecyclerView.java b/src/com/android/launcher3/BaseRecyclerView.java
new file mode 100644
index 0000000000..0fae427e86
--- /dev/null
+++ b/src/com/android/launcher3/BaseRecyclerView.java
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2015 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.Context;
+import android.graphics.Canvas;
+import android.graphics.Rect;
+import android.support.v7.widget.RecyclerView;
+import android.util.AttributeSet;
+import android.view.MotionEvent;
+import com.android.launcher3.util.Thunk;
+
+
+/**
+ * A base {@link RecyclerView}, which does the following:
+ *
+ * - NOT intercept a touch unless the scrolling velocity is below a predefined threshold.
+ *
- Enable fast scroller.
+ *
+ */
+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;
+
+ /**
+ * The current scroll state of the recycler view. We use this in onUpdateScrollbar()
+ * and scrollToPositionAtProgress() to determine the scroll position of the recycler view so
+ * that we can calculate what the scroll bar looks like, and where to jump to from the fast
+ * scroller.
+ */
+ public static class ScrollPositionState {
+ // The index of the first visible row
+ public int rowIndex;
+ // The offset of the first visible row
+ public int rowTopOffset;
+ // The height of a given row (they are currently all the same height)
+ public int rowHeight;
+ }
+
+ protected BaseRecyclerViewFastScrollBar mScrollbar;
+
+ private int mDownX;
+ private int mDownY;
+ private int mLastY;
+ protected Rect mBackgroundPadding = new Rect();
+
+ public BaseRecyclerView(Context context) {
+ this(context, null);
+ }
+
+ public BaseRecyclerView(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ 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.
+ }
+ }
+
+ @Override
+ protected void onFinishInflate() {
+ super.onFinishInflate();
+ addOnItemTouchListener(this);
+ }
+
+ /**
+ * We intercept the touch handling only to support fast scrolling when initiated from the
+ * scroll bar. Otherwise, we fall back to the default RecyclerView touch handling.
+ */
+ @Override
+ public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent ev) {
+ return handleTouchEvent(ev);
+ }
+
+ @Override
+ public void onTouchEvent(RecyclerView rv, MotionEvent ev) {
+ handleTouchEvent(ev);
+ }
+
+ /**
+ * Handles the touch event and determines whether to show the fast scroller (or updates it if
+ * 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;
+ }
+ return mScrollbar.isDragging();
+ }
+
+ 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;
+ }
+
+ public void updateBackgroundPadding(Rect padding) {
+ mBackgroundPadding.set(padding);
+ }
+
+ public Rect getBackgroundPadding() {
+ return mBackgroundPadding;
+ }
+
+ /**
+ * Returns the scroll bar width when the user is scrolling.
+ */
+ public int getMaxScrollbarWidth() {
+ return mScrollbar.getThumbMaxWidth();
+ }
+
+ /**
+ * Returns the available scroll height:
+ * AvailableScrollHeight = Total height of the all items - last page height
+ *
+ * This assumes that all rows are the same height.
+ *
+ * @param yOffset the offset from the top of the recycler view to start tracking.
+ */
+ protected int getAvailableScrollHeight(int rowCount, int rowHeight, int yOffset) {
+ int visibleHeight = getHeight() - mBackgroundPadding.top - mBackgroundPadding.bottom;
+ int scrollHeight = getPaddingTop() + yOffset + rowCount * rowHeight + getPaddingBottom();
+ int availableScrollHeight = scrollHeight - visibleHeight;
+ return availableScrollHeight;
+ }
+
+ /**
+ * Returns the available scroll bar height:
+ * AvailableScrollBarHeight = Total height of the visible view - thumb height
+ */
+ protected int getAvailableScrollBarHeight() {
+ int visibleHeight = getHeight() - mBackgroundPadding.top - mBackgroundPadding.bottom;
+ int availableScrollBarHeight = visibleHeight - mScrollbar.getThumbHeight();
+ return availableScrollBarHeight;
+ }
+
+ /**
+ * Returns the track color (ignoring alpha), can be overridden by each subclass.
+ */
+ public int getFastScrollerTrackColor(int defaultTrackColor) {
+ return defaultTrackColor;
+ }
+
+ /**
+ * Returns the inactive thumb color, can be overridden by each subclass.
+ */
+ public int getFastScrollerThumbInactiveColor(int defaultInactiveThumbColor) {
+ return defaultInactiveThumbColor;
+ }
+
+ @Override
+ protected void dispatchDraw(Canvas canvas) {
+ super.dispatchDraw(canvas);
+ onUpdateScrollbar();
+ mScrollbar.draw(canvas);
+ }
+
+ /**
+ * Updates the scrollbar thumb offset to match the visible scroll of the recycler view. It does
+ * this by mapping the available scroll area of the recycler view to the available space for the
+ * scroll bar.
+ *
+ * @param scrollPosState the current scroll position
+ * @param rowCount the number of rows, used to calculate the total scroll height (assumes that
+ * all rows are the same height)
+ * @param yOffset the offset to start tracking in the recycler view (only used for all apps)
+ */
+ protected void synchronizeScrollBarThumbOffsetToViewScroll(ScrollPositionState scrollPosState,
+ int rowCount, int yOffset) {
+ int availableScrollHeight = getAvailableScrollHeight(rowCount, scrollPosState.rowHeight,
+ yOffset);
+ int availableScrollBarHeight = getAvailableScrollBarHeight();
+
+ // Only show the scrollbar if there is height to be scrolled
+ if (availableScrollHeight <= 0) {
+ mScrollbar.setScrollbarThumbOffset(-1, -1);
+ return;
+ }
+
+ // Calculate the current scroll position, the scrollY of the recycler view accounts for the
+ // view padding, while the scrollBarY is drawn right up to the background padding (ignoring
+ // padding)
+ int scrollY = getPaddingTop() + yOffset +
+ (scrollPosState.rowIndex * scrollPosState.rowHeight) - scrollPosState.rowTopOffset;
+ int scrollBarY = mBackgroundPadding.top +
+ (int) (((float) scrollY / availableScrollHeight) * availableScrollBarHeight);
+
+ // Calculate the position and size of the scroll bar
+ int scrollBarX;
+ if (Utilities.isRtl(getResources())) {
+ scrollBarX = mBackgroundPadding.left;
+ } else {
+ scrollBarX = getWidth() - mBackgroundPadding.right - mScrollbar.getWidth();
+ }
+ mScrollbar.setScrollbarThumbOffset(scrollBarX, scrollBarY);
+ }
+
+ /**
+ * Maps the touch (from 0..1) to the adapter position that should be visible.
+ * Override in each subclass of this base class.
+ */
+ public abstract String scrollToPositionAtProgress(float touchFraction);
+
+ /**
+ * Updates the bounds for the scrollbar.
+ *
Override in each subclass of this base class.
+ */
+ public abstract void onUpdateScrollbar();
+
+ /**
+ *
Override in each subclass of this base class.
+ */
+ public void onFastScrollCompleted() {}
+}
\ No newline at end of file
diff --git a/src/com/android/launcher3/BaseRecyclerViewFastScrollBar.java b/src/com/android/launcher3/BaseRecyclerViewFastScrollBar.java
new file mode 100644
index 0000000000..2c4184dc48
--- /dev/null
+++ b/src/com/android/launcher3/BaseRecyclerViewFastScrollBar.java
@@ -0,0 +1,235 @@
+/*
+ * Copyright (C) 2015 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.animation.AnimatorSet;
+import android.animation.ArgbEvaluator;
+import android.animation.ObjectAnimator;
+import android.animation.ValueAnimator;
+import android.content.res.Resources;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.view.MotionEvent;
+import android.view.ViewConfiguration;
+
+import com.android.launcher3.util.Thunk;
+
+/**
+ * The track and scrollbar that shows when you scroll the list.
+ */
+public class BaseRecyclerViewFastScrollBar {
+
+ public interface FastScrollFocusableView {
+ void setFastScrollFocused(boolean focused, boolean animated);
+ }
+
+ private final static int MAX_TRACK_ALPHA = 30;
+ private final static int SCROLL_BAR_VIS_DURATION = 150;
+
+ @Thunk BaseRecyclerView mRv;
+ private BaseRecyclerViewFastScrollPopup mPopup;
+
+ private AnimatorSet mScrollbarAnimator;
+
+ private int mThumbInactiveColor;
+ private int mThumbActiveColor;
+ @Thunk Point mThumbOffset = new Point(-1, -1);
+ @Thunk Paint mThumbPaint;
+ private Paint mTrackPaint;
+ private int mThumbMinWidth;
+ private int mThumbMaxWidth;
+ @Thunk int mThumbWidth;
+ @Thunk int mThumbHeight;
+ // The inset is the buffer around which a point will still register as a click on the scrollbar
+ private int mTouchInset;
+ private boolean mIsDragging;
+
+ // This is the offset from the top of the scrollbar when the user first starts touching. To
+ // prevent jumping, this offset is applied as the user scrolls.
+ private int mTouchOffset;
+
+ private Rect mInvalidateRect = new Rect();
+ private Rect mTmpRect = new Rect();
+
+ public BaseRecyclerViewFastScrollBar(BaseRecyclerView rv, Resources res) {
+ mRv = rv;
+ mPopup = new BaseRecyclerViewFastScrollPopup(rv, res);
+ mTrackPaint = new Paint();
+ mTrackPaint.setColor(rv.getFastScrollerTrackColor(Color.BLACK));
+ mTrackPaint.setAlpha(0);
+ mThumbInactiveColor = rv.getFastScrollerThumbInactiveColor(
+ res.getColor(R.color.container_fastscroll_thumb_inactive_color));
+ mThumbActiveColor = res.getColor(R.color.container_fastscroll_thumb_active_color);
+ mThumbPaint = new Paint();
+ mThumbPaint.setColor(mThumbInactiveColor);
+ mThumbWidth = mThumbMinWidth = res.getDimensionPixelSize(R.dimen.container_fastscroll_thumb_min_width);
+ mThumbMaxWidth = res.getDimensionPixelSize(R.dimen.container_fastscroll_thumb_max_width);
+ mThumbHeight = res.getDimensionPixelSize(R.dimen.container_fastscroll_thumb_height);
+ mTouchInset = res.getDimensionPixelSize(R.dimen.container_fastscroll_thumb_touch_inset);
+ }
+
+ public void setScrollbarThumbOffset(int x, int y) {
+ if (mThumbOffset.x == x && mThumbOffset.y == y) {
+ return;
+ }
+ mInvalidateRect.set(mThumbOffset.x, 0, mThumbOffset.x + mThumbWidth, mRv.getHeight());
+ mThumbOffset.set(x, y);
+ mInvalidateRect.union(new Rect(mThumbOffset.x, 0, mThumbOffset.x + mThumbWidth,
+ mRv.getHeight()));
+ mRv.invalidate(mInvalidateRect);
+ }
+
+ // Setter/getter for the search bar width for animations
+ public void setWidth(int width) {
+ mInvalidateRect.set(mThumbOffset.x, 0, mThumbOffset.x + mThumbWidth, mRv.getHeight());
+ mThumbWidth = width;
+ mInvalidateRect.union(new Rect(mThumbOffset.x, 0, mThumbOffset.x + mThumbWidth,
+ mRv.getHeight()));
+ mRv.invalidate(mInvalidateRect);
+ }
+
+ public int getWidth() {
+ return mThumbWidth;
+ }
+
+ // Setter/getter for the track background alpha for animations
+ public void setTrackAlpha(int alpha) {
+ mTrackPaint.setAlpha(alpha);
+ mInvalidateRect.set(mThumbOffset.x, 0, mThumbOffset.x + mThumbWidth, mRv.getHeight());
+ mRv.invalidate(mInvalidateRect);
+ }
+
+ public int getTrackAlpha() {
+ return mTrackPaint.getAlpha();
+ }
+
+ public int getThumbHeight() {
+ return mThumbHeight;
+ }
+
+ public int getThumbMaxWidth() {
+ return mThumbMaxWidth;
+ }
+
+ public boolean isDragging() {
+ return mIsDragging;
+ }
+
+ /**
+ * Handles the touch event and determines whether to show the fast scroller (or updates it if
+ * it is already showing).
+ */
+ public void handleTouchEvent(MotionEvent ev, int downX, int downY, int lastY) {
+ ViewConfiguration config = ViewConfiguration.get(mRv.getContext());
+
+ int action = ev.getAction();
+ int y = (int) ev.getY();
+ switch (action) {
+ case MotionEvent.ACTION_DOWN:
+ if (isNearPoint(downX, downY)) {
+ mTouchOffset = downY - mThumbOffset.y;
+ }
+ break;
+ case MotionEvent.ACTION_MOVE:
+ // Check if we should start scrolling
+ if (!mIsDragging && isNearPoint(downX, downY) &&
+ Math.abs(y - downY) > config.getScaledTouchSlop()) {
+ mRv.getParent().requestDisallowInterceptTouchEvent(true);
+ mIsDragging = true;
+ mTouchOffset += (lastY - downY);
+ mPopup.animateVisibility(true);
+ animateScrollbar(true);
+ }
+ if (mIsDragging) {
+ // Update the fastscroller section name at this touch position
+ int top = mRv.getBackgroundPadding().top;
+ int bottom = mRv.getHeight() - mRv.getBackgroundPadding().bottom - mThumbHeight;
+ float boundedY = (float) Math.max(top, Math.min(bottom, y - mTouchOffset));
+ String sectionName = mRv.scrollToPositionAtProgress((boundedY - top) /
+ (bottom - top));
+ mPopup.setSectionName(sectionName);
+ mPopup.animateVisibility(!sectionName.isEmpty());
+ mRv.invalidate(mPopup.updateFastScrollerBounds(mRv, lastY));
+ }
+ break;
+ case MotionEvent.ACTION_UP:
+ case MotionEvent.ACTION_CANCEL:
+ mTouchOffset = 0;
+ if (mIsDragging) {
+ mIsDragging = false;
+ mPopup.animateVisibility(false);
+ animateScrollbar(false);
+ }
+ break;
+ }
+ }
+
+ public void draw(Canvas canvas) {
+ if (mThumbOffset.x < 0 || mThumbOffset.y < 0) {
+ return;
+ }
+
+ // Draw the scroll bar track and thumb
+ if (mTrackPaint.getAlpha() > 0) {
+ canvas.drawRect(mThumbOffset.x, 0, mThumbOffset.x + mThumbWidth, mRv.getHeight(), mTrackPaint);
+ }
+ canvas.drawRect(mThumbOffset.x, mThumbOffset.y, mThumbOffset.x + mThumbWidth,
+ mThumbOffset.y + mThumbHeight, mThumbPaint);
+
+ // Draw the popup
+ mPopup.draw(canvas);
+ }
+
+ /**
+ * Animates the width and color of the scrollbar.
+ */
+ private void animateScrollbar(boolean isScrolling) {
+ if (mScrollbarAnimator != null) {
+ mScrollbarAnimator.cancel();
+ }
+ ObjectAnimator trackAlphaAnim = ObjectAnimator.ofInt(this, "trackAlpha",
+ isScrolling ? MAX_TRACK_ALPHA : 0);
+ ObjectAnimator thumbWidthAnim = ObjectAnimator.ofInt(this, "width",
+ isScrolling ? mThumbMaxWidth : mThumbMinWidth);
+ ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(),
+ mThumbPaint.getColor(), isScrolling ? mThumbActiveColor : mThumbInactiveColor);
+ colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
+ @Override
+ public void onAnimationUpdate(ValueAnimator animator) {
+ mThumbPaint.setColor((Integer) animator.getAnimatedValue());
+ mRv.invalidate(mThumbOffset.x, mThumbOffset.y, mThumbOffset.x + mThumbWidth,
+ mThumbOffset.y + mThumbHeight);
+ }
+ });
+ mScrollbarAnimator = new AnimatorSet();
+ mScrollbarAnimator.playTogether(trackAlphaAnim, thumbWidthAnim, colorAnimation);
+ mScrollbarAnimator.setDuration(SCROLL_BAR_VIS_DURATION);
+ mScrollbarAnimator.start();
+ }
+
+ /**
+ * Returns whether the specified points are near the scroll bar bounds.
+ */
+ private boolean isNearPoint(int x, int y) {
+ mTmpRect.set(mThumbOffset.x, mThumbOffset.y, mThumbOffset.x + mThumbWidth,
+ mThumbOffset.y + mThumbHeight);
+ mTmpRect.inset(mTouchInset, mTouchInset);
+ return mTmpRect.contains(x, y);
+ }
+}
diff --git a/src/com/android/launcher3/BaseRecyclerViewFastScrollPopup.java b/src/com/android/launcher3/BaseRecyclerViewFastScrollPopup.java
new file mode 100644
index 0000000000..aeeb5156da
--- /dev/null
+++ b/src/com/android/launcher3/BaseRecyclerViewFastScrollPopup.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright (C) 2015 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.animation.Animator;
+import android.animation.ObjectAnimator;
+import android.content.res.Resources;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.drawable.Drawable;
+
+/**
+ * The fast scroller popup that shows the section name the list will jump to.
+ */
+public class BaseRecyclerViewFastScrollPopup {
+
+ private static final float FAST_SCROLL_OVERLAY_Y_OFFSET_FACTOR = 1.5f;
+
+ private Resources mRes;
+ private BaseRecyclerView mRv;
+
+ private Drawable mBg;
+ // The absolute bounds of the fast scroller bg
+ private Rect mBgBounds = new Rect();
+ private int mBgOriginalSize;
+ private Rect mInvalidateRect = new Rect();
+ private Rect mTmpRect = new Rect();
+
+ private String mSectionName;
+ private Paint mTextPaint;
+ private Rect mTextBounds = new Rect();
+ private float mAlpha;
+
+ private Animator mAlphaAnimator;
+ private boolean mVisible;
+
+ public BaseRecyclerViewFastScrollPopup(BaseRecyclerView rv, Resources res) {
+ mRes = res;
+ mRv = rv;
+ mBgOriginalSize = res.getDimensionPixelSize(R.dimen.container_fastscroll_popup_size);
+ mBg = res.getDrawable(R.drawable.container_fastscroll_popup_bg);
+ mBg.setBounds(0, 0, mBgOriginalSize, mBgOriginalSize);
+ mTextPaint = new Paint();
+ mTextPaint.setColor(Color.WHITE);
+ mTextPaint.setAntiAlias(true);
+ mTextPaint.setTextSize(res.getDimensionPixelSize(R.dimen.container_fastscroll_popup_text_size));
+ }
+
+ /**
+ * Sets the section name.
+ */
+ public void setSectionName(String sectionName) {
+ if (!sectionName.equals(mSectionName)) {
+ mSectionName = sectionName;
+ mTextPaint.getTextBounds(sectionName, 0, sectionName.length(), mTextBounds);
+ // Update the width to use measureText since that is more accurate
+ mTextBounds.right = (int) (mTextBounds.left + mTextPaint.measureText(sectionName));
+ }
+ }
+
+ /**
+ * Updates the bounds for the fast scroller.
+ * @return the invalidation rect for this update.
+ */
+ public Rect updateFastScrollerBounds(BaseRecyclerView rv, int lastTouchY) {
+ mInvalidateRect.set(mBgBounds);
+
+ if (isVisible()) {
+ // Calculate the dimensions and position of the fast scroller popup
+ int edgePadding = rv.getMaxScrollbarWidth();
+ int bgPadding = (mBgOriginalSize - mTextBounds.height()) / 2;
+ int bgHeight = mBgOriginalSize;
+ int bgWidth = Math.max(mBgOriginalSize, mTextBounds.width() + (2 * bgPadding));
+ if (Utilities.isRtl(mRes)) {
+ mBgBounds.left = rv.getBackgroundPadding().left + (2 * rv.getMaxScrollbarWidth());
+ mBgBounds.right = mBgBounds.left + bgWidth;
+ } else {
+ mBgBounds.right = rv.getWidth() - rv.getBackgroundPadding().right -
+ (2 * rv.getMaxScrollbarWidth());
+ mBgBounds.left = mBgBounds.right - bgWidth;
+ }
+ mBgBounds.top = lastTouchY - (int) (FAST_SCROLL_OVERLAY_Y_OFFSET_FACTOR * bgHeight);
+ mBgBounds.top = Math.max(edgePadding,
+ Math.min(mBgBounds.top, rv.getHeight() - edgePadding - bgHeight));
+ mBgBounds.bottom = mBgBounds.top + bgHeight;
+ } else {
+ mBgBounds.setEmpty();
+ }
+
+ // Combine the old and new fast scroller bounds to create the full invalidate rect
+ mInvalidateRect.union(mBgBounds);
+ return mInvalidateRect;
+ }
+
+ /**
+ * Animates the visibility of the fast scroller popup.
+ */
+ public void animateVisibility(boolean visible) {
+ if (mVisible != visible) {
+ mVisible = visible;
+ if (mAlphaAnimator != null) {
+ mAlphaAnimator.cancel();
+ }
+ mAlphaAnimator = ObjectAnimator.ofFloat(this, "alpha", visible ? 1f : 0f);
+ mAlphaAnimator.setDuration(visible ? 200 : 150);
+ mAlphaAnimator.start();
+ }
+ }
+
+ // Setter/getter for the popup alpha for animations
+ public void setAlpha(float alpha) {
+ mAlpha = alpha;
+ mRv.invalidate(mBgBounds);
+ }
+
+ public float getAlpha() {
+ return mAlpha;
+ }
+
+ public int getHeight() {
+ return mBgOriginalSize;
+ }
+
+ public void draw(Canvas c) {
+ if (isVisible()) {
+ // Draw the fast scroller popup
+ int restoreCount = c.save(Canvas.MATRIX_SAVE_FLAG);
+ c.translate(mBgBounds.left, mBgBounds.top);
+ mTmpRect.set(mBgBounds);
+ mTmpRect.offsetTo(0, 0);
+ mBg.setBounds(mTmpRect);
+ mBg.setAlpha((int) (mAlpha * 255));
+ mBg.draw(c);
+ mTextPaint.setAlpha((int) (mAlpha * 255));
+ c.drawText(mSectionName, (mBgBounds.width() - mTextBounds.width()) / 2,
+ mBgBounds.height() - (mBgBounds.height() - mTextBounds.height()) / 2,
+ mTextPaint);
+ c.restoreToCount(restoreCount);
+ }
+ }
+
+ public boolean isVisible() {
+ return (mAlpha > 0f) && (mSectionName != null);
+ }
+}
diff --git a/src/com/android/launcher3/BubbleTextView.java b/src/com/android/launcher3/BubbleTextView.java
index 07f3045a5b..a0be8ea2b2 100644
--- a/src/com/android/launcher3/BubbleTextView.java
+++ b/src/com/android/launcher3/BubbleTextView.java
@@ -16,6 +16,8 @@
package com.android.launcher3;
+import android.animation.ObjectAnimator;
+import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
@@ -23,22 +25,30 @@ import android.content.res.Resources.Theme;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
+import android.graphics.Paint;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
+import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
+import android.view.ViewParent;
+import android.view.animation.AccelerateInterpolator;
+import android.view.animation.DecelerateInterpolator;
import android.widget.TextView;
+import com.android.launcher3.IconCache.IconLoadRequest;
+import com.android.launcher3.model.PackageItemInfo;
/**
* TextView that draws a bubble behind the text. We cannot use a LineBackgroundSpan
* because we want to make the bubble taller than the text and TextView's clip is
* too aggressive.
*/
-public class BubbleTextView extends TextView {
+public class BubbleTextView extends TextView
+ implements BaseRecyclerViewFastScrollBar.FastScrollFocusableView {
private static SparseArray sPreloaderThemes = new SparseArray(2);
@@ -47,25 +57,47 @@ public class BubbleTextView extends TextView {
private static final float SHADOW_Y_OFFSET = 2.0f;
private static final int SHADOW_LARGE_COLOUR = 0xDD000000;
private static final int SHADOW_SMALL_COLOUR = 0xCC000000;
- static final float PADDING_V = 3.0f;
- private HolographicOutlineHelper mOutlineHelper;
+ private static final int DISPLAY_WORKSPACE = 0;
+ private static final int DISPLAY_ALL_APPS = 1;
+
+ private static final float FAST_SCROLL_FOCUS_MAX_SCALE = 1.15f;
+ private static final int FAST_SCROLL_FOCUS_MODE_NONE = 0;
+ private static final int FAST_SCROLL_FOCUS_MODE_SCALE_ICON = 1;
+ private static final int FAST_SCROLL_FOCUS_MODE_DRAW_CIRCLE_BG = 2;
+ private static final int FAST_SCROLL_FOCUS_FADE_IN_DURATION = 175;
+ private static final int FAST_SCROLL_FOCUS_FADE_OUT_DURATION = 125;
+
+ private final Launcher mLauncher;
+ private Drawable mIcon;
+ private final Drawable mBackground;
+ private final CheckLongPressHelper mLongPressHelper;
+ private final HolographicOutlineHelper mOutlineHelper;
+ private final StylusEventHelper mStylusEventHelper;
+
+ private boolean mBackgroundSizeChanged;
+
private Bitmap mPressedBackground;
private float mSlop;
- private int mTextColor;
+ private final boolean mDeferShadowGenerationOnTouch;
private final boolean mCustomShadowsEnabled;
- private boolean mIsTextVisible;
-
- // TODO: Remove custom background handling code, as no instance of BubbleTextView use any
- // background.
- private boolean mBackgroundSizeChanged;
- private final Drawable mBackground;
+ private final boolean mLayoutHorizontal;
+ private final int mIconSize;
+ private int mTextColor;
private boolean mStayPressed;
private boolean mIgnorePressedStateChange;
- private CheckLongPressHelper mLongPressHelper;
+ private boolean mDisableRelayout = false;
+
+ private ObjectAnimator mFastScrollFocusAnimator;
+ private Paint mFastScrollFocusBgPaint;
+ private float mFastScrollFocusFraction;
+ private boolean mFastScrollFocused;
+ private final int mFastScrollMode = FAST_SCROLL_FOCUS_MODE_SCALE_ICON;
+
+ private IconLoadRequest mIconLoadRequest;
public BubbleTextView(Context context) {
this(context, null, 0);
@@ -77,10 +109,28 @@ public class BubbleTextView extends TextView {
public BubbleTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
+ mLauncher = (Launcher) context;
+ DeviceProfile grid = mLauncher.getDeviceProfile();
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.BubbleTextView, defStyle, 0);
mCustomShadowsEnabled = a.getBoolean(R.styleable.BubbleTextView_customShadows, true);
+ mLayoutHorizontal = a.getBoolean(R.styleable.BubbleTextView_layoutHorizontal, false);
+ mDeferShadowGenerationOnTouch =
+ a.getBoolean(R.styleable.BubbleTextView_deferShadowGeneration, false);
+
+ int display = a.getInteger(R.styleable.BubbleTextView_iconDisplay, DISPLAY_WORKSPACE);
+ int defaultIconSize = grid.iconSizePx;
+ if (display == DISPLAY_WORKSPACE) {
+ setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.iconTextSizePx);
+ } else if (display == DISPLAY_ALL_APPS) {
+ setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.allAppsIconTextSizePx);
+ defaultIconSize = grid.allAppsIconSizePx;
+ }
+
+ mIconSize = a.getDimensionPixelSize(R.styleable.BubbleTextView_iconSizeOverride,
+ defaultIconSize);
+
a.recycle();
if (mCustomShadowsEnabled) {
@@ -90,45 +140,37 @@ public class BubbleTextView extends TextView {
} else {
mBackground = null;
}
- init();
- }
- public void onFinishInflate() {
- super.onFinishInflate();
-
- // Ensure we are using the right text size
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
- setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.iconTextSizePx);
- }
-
- private void init() {
mLongPressHelper = new CheckLongPressHelper(this);
+ mStylusEventHelper = new StylusEventHelper(this);
mOutlineHelper = HolographicOutlineHelper.obtain(getContext());
if (mCustomShadowsEnabled) {
setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
}
+
+ if (mFastScrollMode == FAST_SCROLL_FOCUS_MODE_DRAW_CIRCLE_BG) {
+ mFastScrollFocusBgPaint = new Paint();
+ mFastScrollFocusBgPaint.setAntiAlias(true);
+ mFastScrollFocusBgPaint.setColor(
+ getResources().getColor(R.color.container_fastscroll_thumb_active_color));
+ }
+
+ setAccessibilityDelegate(LauncherAppState.getInstance().getAccessibilityDelegate());
+ }
+
+ public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache) {
+ applyFromShortcutInfo(info, iconCache, false);
}
public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache,
- boolean setDefaultPadding) {
- applyFromShortcutInfo(info, iconCache, setDefaultPadding, false);
- }
-
- public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache,
- boolean setDefaultPadding, boolean promiseStateChanged) {
+ boolean promiseStateChanged) {
Bitmap b = info.getIcon(iconCache);
- LauncherAppState app = LauncherAppState.getInstance();
- FastBitmapDrawable iconDrawable = Utilities.createIconDrawable(b);
+ FastBitmapDrawable iconDrawable = mLauncher.createIconDrawable(b);
iconDrawable.setGhostModeEnabled(info.isDisabled != 0);
- setCompoundDrawables(null, iconDrawable, null, null);
- if (setDefaultPadding) {
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
- setCompoundDrawablePadding(grid.iconDrawablePaddingPx);
- }
+ setIcon(iconDrawable, mIconSize);
if (info.contentDescription != null) {
setContentDescription(info.contentDescription);
}
@@ -141,20 +183,37 @@ public class BubbleTextView extends TextView {
}
public void applyFromApplicationInfo(AppInfo info) {
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
-
- Drawable topDrawable = Utilities.createIconDrawable(info.iconBitmap);
- topDrawable.setBounds(0, 0, grid.allAppsIconSizePx, grid.allAppsIconSizePx);
- setCompoundDrawables(null, topDrawable, null, null);
- setCompoundDrawablePadding(grid.iconDrawablePaddingPx);
+ setIcon(mLauncher.createIconDrawable(info.iconBitmap), mIconSize);
setText(info.title);
if (info.contentDescription != null) {
setContentDescription(info.contentDescription);
}
- setTag(info);
+ // We don't need to check the info since it's not a ShortcutInfo
+ super.setTag(info);
+
+ // Verify high res immediately
+ verifyHighRes();
}
+ public void applyFromPackageItemInfo(PackageItemInfo info) {
+ setIcon(mLauncher.createIconDrawable(info.iconBitmap), mIconSize);
+ setText(info.title);
+ if (info.contentDescription != null) {
+ setContentDescription(info.contentDescription);
+ }
+ // We don't need to check the info since it's not a ShortcutInfo
+ super.setTag(info);
+
+ // Verify high res immediately
+ verifyHighRes();
+ }
+
+ /**
+ * Overrides the default long press timeout.
+ */
+ public void setLongPressTimeout(int longPressTimeout) {
+ mLongPressHelper.setLongPressTimeout(longPressTimeout);
+ }
@Override
protected boolean setFrame(int left, int top, int right, int bottom) {
@@ -186,10 +245,19 @@ public class BubbleTextView extends TextView {
}
}
+ /** Returns the icon for this view. */
+ public Drawable getIcon() {
+ return mIcon;
+ }
+
+ /** Returns whether the layout is horizontal. */
+ public boolean isLayoutHorizontal() {
+ return mLayoutHorizontal;
+ }
+
private void updateIconState() {
- Drawable top = getCompoundDrawables()[1];
- if (top instanceof FastBitmapDrawable) {
- ((FastBitmapDrawable) top).setPressed(isPressed() || mStayPressed);
+ if (mIcon instanceof FastBitmapDrawable) {
+ ((FastBitmapDrawable) mIcon).setPressed(isPressed() || mStayPressed);
}
}
@@ -199,16 +267,25 @@ public class BubbleTextView extends TextView {
// isPressed() on an ACTION_UP
boolean result = super.onTouchEvent(event);
+ // Check for a stylus button press, if it occurs cancel any long press checks.
+ if (mStylusEventHelper.checkAndPerformStylusEvent(event)) {
+ mLongPressHelper.cancelLongPress();
+ result = true;
+ }
+
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// So that the pressed outline is visible immediately on setStayPressed(),
// we pre-create it on ACTION_DOWN (it takes a small but perceptible amount of time
// to create it)
- if (mPressedBackground == null) {
+ if (!mDeferShadowGenerationOnTouch && mPressedBackground == null) {
mPressedBackground = mOutlineHelper.createMediumDropShadow(this);
}
- mLongPressHelper.postCheckForLongPress();
+ // If we're in a stylus button press, don't check for long press.
+ if (!mStylusEventHelper.inStylusButtonPressed()) {
+ mLongPressHelper.postCheckForLongPress();
+ }
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
@@ -233,12 +310,17 @@ public class BubbleTextView extends TextView {
mStayPressed = stayPressed;
if (!stayPressed) {
mPressedBackground = null;
+ } else {
+ if (mPressedBackground == null) {
+ mPressedBackground = mOutlineHelper.createMediumDropShadow(this);
+ }
}
// Only show the shadow effect when persistent pressed state is set.
- if (getParent() instanceof ShortcutAndWidgetContainer) {
- CellLayout layout = (CellLayout) getParent().getParent();
- layout.setPressedIcon(this, mPressedBackground, mOutlineHelper.shadowBitmapPadding);
+ ViewParent parent = getParent();
+ if (parent != null && parent.getParent() instanceof BubbleTextShadowHandler) {
+ ((BubbleTextShadowHandler) parent.getParent()).setPressedIcon(
+ this, mPressedBackground);
}
updateIconState();
@@ -278,7 +360,18 @@ public class BubbleTextView extends TextView {
@Override
public void draw(Canvas canvas) {
if (!mCustomShadowsEnabled) {
+ // Draw the fast scroll focus bg if we have one
+ if (mFastScrollMode == FAST_SCROLL_FOCUS_MODE_DRAW_CIRCLE_BG &&
+ mFastScrollFocusFraction > 0f) {
+ DeviceProfile grid = mLauncher.getDeviceProfile();
+ int iconCenterX = getScrollX() + (getWidth() / 2);
+ int iconCenterY = getScrollY() + getPaddingTop() + (grid.iconSizePx / 2);
+ canvas.drawCircle(iconCenterX, iconCenterY,
+ mFastScrollFocusFraction * (getWidth() / 2), mFastScrollFocusBgPaint);
+ }
+
super.draw(canvas);
+
return;
}
@@ -325,10 +418,9 @@ public class BubbleTextView extends TextView {
super.onAttachedToWindow();
if (mBackground != null) mBackground.setCallback(this);
- Drawable top = getCompoundDrawables()[1];
- if (top instanceof PreloadIconDrawable) {
- ((PreloadIconDrawable) top).applyTheme(getPreloaderTheme());
+ if (mIcon instanceof PreloadIconDrawable) {
+ ((PreloadIconDrawable) mIcon).applyPreloaderTheme(getPreloaderTheme());
}
mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
}
@@ -358,16 +450,6 @@ public class BubbleTextView extends TextView {
} else {
super.setTextColor(res.getColor(android.R.color.transparent));
}
- mIsTextVisible = visible;
- }
-
- public boolean isTextVisible() {
- return mIsTextVisible;
- }
-
- @Override
- protected boolean onSetAlpha(int alpha) {
- return true;
}
@Override
@@ -385,15 +467,13 @@ public class BubbleTextView extends TextView {
((info.hasStatusFlag(ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE) ?
info.getInstallProgress() : 0)) : 100;
- Drawable[] drawables = getCompoundDrawables();
- Drawable top = drawables[1];
- if (top != null) {
+ if (mIcon != null) {
final PreloadIconDrawable preloadDrawable;
- if (top instanceof PreloadIconDrawable) {
- preloadDrawable = (PreloadIconDrawable) top;
+ if (mIcon instanceof PreloadIconDrawable) {
+ preloadDrawable = (PreloadIconDrawable) mIcon;
} else {
- preloadDrawable = new PreloadIconDrawable(top, getPreloaderTheme());
- setCompoundDrawables(drawables[0], preloadDrawable, drawables[2], drawables[3]);
+ preloadDrawable = new PreloadIconDrawable(mIcon, getPreloaderTheme());
+ setIcon(preloadDrawable, mIconSize);
}
preloadDrawable.setLevel(progressLevel);
@@ -417,4 +497,132 @@ public class BubbleTextView extends TextView {
}
return theme;
}
+
+ /**
+ * Sets the icon for this view based on the layout direction.
+ */
+ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
+ private Drawable setIcon(Drawable icon, int iconSize) {
+ mIcon = icon;
+ if (iconSize != -1) {
+ mIcon.setBounds(0, 0, iconSize, iconSize);
+ }
+ if (mLayoutHorizontal) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
+ setCompoundDrawablesRelative(mIcon, null, null, null);
+ } else {
+ setCompoundDrawables(mIcon, null, null, null);
+ }
+ } else {
+ setCompoundDrawables(null, mIcon, null, null);
+ }
+ return icon;
+ }
+
+ @Override
+ public void requestLayout() {
+ if (!mDisableRelayout) {
+ super.requestLayout();
+ }
+ }
+
+ /**
+ * Applies the item info if it is same as what the view is pointing to currently.
+ */
+ public void reapplyItemInfo(final ItemInfo info) {
+ if (getTag() == info) {
+ mIconLoadRequest = null;
+ mDisableRelayout = true;
+ if (info instanceof AppInfo) {
+ applyFromApplicationInfo((AppInfo) info);
+ } else if (info instanceof ShortcutInfo) {
+ applyFromShortcutInfo((ShortcutInfo) info,
+ LauncherAppState.getInstance().getIconCache());
+ } else if (info instanceof PackageItemInfo) {
+ applyFromPackageItemInfo((PackageItemInfo) info);
+ }
+ mDisableRelayout = false;
+ }
+ }
+
+ /**
+ * Verifies that the current icon is high-res otherwise posts a request to load the icon.
+ */
+ public void verifyHighRes() {
+ if (mIconLoadRequest != null) {
+ mIconLoadRequest.cancel();
+ mIconLoadRequest = null;
+ }
+ if (getTag() instanceof AppInfo) {
+ AppInfo info = (AppInfo) getTag();
+ if (info.usingLowResIcon) {
+ mIconLoadRequest = LauncherAppState.getInstance().getIconCache()
+ .updateIconInBackground(BubbleTextView.this, info);
+ }
+ } else if (getTag() instanceof ShortcutInfo) {
+ ShortcutInfo info = (ShortcutInfo) getTag();
+ if (info.usingLowResIcon) {
+ mIconLoadRequest = LauncherAppState.getInstance().getIconCache()
+ .updateIconInBackground(BubbleTextView.this, info);
+ }
+ } else if (getTag() instanceof PackageItemInfo) {
+ PackageItemInfo info = (PackageItemInfo) getTag();
+ if (info.usingLowResIcon) {
+ mIconLoadRequest = LauncherAppState.getInstance().getIconCache()
+ .updateIconInBackground(BubbleTextView.this, info);
+ }
+ }
+ }
+
+ // Setters & getters for the animation
+ public void setFastScrollFocus(float fraction) {
+ mFastScrollFocusFraction = fraction;
+ if (mFastScrollMode == FAST_SCROLL_FOCUS_MODE_SCALE_ICON) {
+ setScaleX(1f + fraction * (FAST_SCROLL_FOCUS_MAX_SCALE - 1f));
+ setScaleY(1f + fraction * (FAST_SCROLL_FOCUS_MAX_SCALE - 1f));
+ } else {
+ invalidate();
+ }
+ }
+
+ public float getFastScrollFocus() {
+ return mFastScrollFocusFraction;
+ }
+
+ @Override
+ public void setFastScrollFocused(final boolean focused, boolean animated) {
+ if (mFastScrollMode == FAST_SCROLL_FOCUS_MODE_NONE) {
+ return;
+ }
+
+ if (mFastScrollFocused != focused) {
+ mFastScrollFocused = focused;
+
+ if (animated) {
+ // Clean up the previous focus animator
+ if (mFastScrollFocusAnimator != null) {
+ mFastScrollFocusAnimator.cancel();
+ }
+ mFastScrollFocusAnimator = ObjectAnimator.ofFloat(this, "fastScrollFocus",
+ focused ? 1f : 0f);
+ if (focused) {
+ mFastScrollFocusAnimator.setInterpolator(new DecelerateInterpolator());
+ } else {
+ mFastScrollFocusAnimator.setInterpolator(new AccelerateInterpolator());
+ }
+ mFastScrollFocusAnimator.setDuration(focused ?
+ FAST_SCROLL_FOCUS_FADE_IN_DURATION : FAST_SCROLL_FOCUS_FADE_OUT_DURATION);
+ mFastScrollFocusAnimator.start();
+ } else {
+ mFastScrollFocusFraction = focused ? 1f : 0f;
+ }
+ }
+ }
+
+ /**
+ * Interface to be implemented by the grand parent to allow click shadow effect.
+ */
+ public static interface BubbleTextShadowHandler {
+ void setPressedIcon(BubbleTextView icon, Bitmap background);
+ }
}
diff --git a/src/com/android/launcher3/ButtonDropTarget.java b/src/com/android/launcher3/ButtonDropTarget.java
index 019f86c217..b7f89d02a8 100644
--- a/src/com/android/launcher3/ButtonDropTarget.java
+++ b/src/com/android/launcher3/ButtonDropTarget.java
@@ -16,26 +16,41 @@
package com.android.launcher3;
+import android.animation.AnimatorSet;
+import android.animation.FloatArrayEvaluator;
+import android.animation.ObjectAnimator;
+import android.animation.ValueAnimator;
+import android.animation.ValueAnimator.AnimatorUpdateListener;
+import android.annotation.TargetApi;
import android.content.Context;
-import android.content.res.Resources;
+import android.content.res.ColorStateList;
+import android.content.res.Configuration;
+import android.graphics.ColorMatrix;
+import android.graphics.ColorMatrixColorFilter;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
+import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
+import android.view.View.OnClickListener;
+import android.view.ViewGroup;
+import android.view.animation.DecelerateInterpolator;
+import android.view.animation.LinearInterpolator;
import android.widget.TextView;
+import com.android.launcher3.util.Thunk;
/**
* Implements a DropTarget.
*/
-public class ButtonDropTarget extends TextView implements DropTarget, DragController.DragListener {
+public abstract class ButtonDropTarget extends TextView
+ implements DropTarget, DragController.DragListener, OnClickListener {
- protected final int mTransitionDuration;
+ private static int DRAG_VIEW_DROP_DURATION = 285;
protected Launcher mLauncher;
private int mBottomDragPadding;
- protected TextView mText;
protected SearchDropTargetBar mSearchDropTargetBar;
/** Whether this drop target is active for the current drag */
@@ -44,71 +59,196 @@ public class ButtonDropTarget extends TextView implements DropTarget, DragContro
/** The paint applied to the drag view on hover */
protected int mHoverColor = 0;
+ protected ColorStateList mOriginalTextColor;
+ protected Drawable mDrawable;
+
+ private AnimatorSet mCurrentColorAnim;
+ @Thunk ColorMatrix mSrcFilter, mDstFilter, mCurrentFilter;
+
+
public ButtonDropTarget(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ButtonDropTarget(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
-
- Resources r = getResources();
- mTransitionDuration = r.getInteger(R.integer.config_dropTargetBgTransitionDuration);
- mBottomDragPadding = r.getDimensionPixelSize(R.dimen.drop_target_drag_padding);
+ mBottomDragPadding = getResources().getDimensionPixelSize(R.dimen.drop_target_drag_padding);
}
- void setLauncher(Launcher launcher) {
+ @Override
+ protected void onFinishInflate() {
+ super.onFinishInflate();
+ mOriginalTextColor = getTextColors();
+
+ // Remove the text in the Phone UI in landscape
+ DeviceProfile grid = ((Launcher) getContext()).getDeviceProfile();
+ if (grid.isVerticalBarLayout()) {
+ setText("");
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
+ 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);
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
+ setCompoundDrawablesRelativeWithIntrinsicBounds(mDrawable, null, null, null);
+ } else {
+ setCompoundDrawablesWithIntrinsicBounds(mDrawable, null, null, null);
+ }
+ }
+
+ public void setLauncher(Launcher launcher) {
mLauncher = launcher;
}
- public boolean acceptDrop(DragObject d) {
- return false;
- }
-
public void setSearchDropTargetBar(SearchDropTargetBar searchDropTargetBar) {
mSearchDropTargetBar = searchDropTargetBar;
}
- protected Drawable getCurrentDrawable() {
- Drawable[] drawables = getCompoundDrawablesRelative();
- for (int i = 0; i < drawables.length; ++i) {
- if (drawables[i] != null) {
- return drawables[i];
- }
- }
- return null;
- }
+ @Override
+ public void onFlingToDelete(DragObject d, PointF vec) { }
- public void onDrop(DragObject d) {
- }
-
- public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
- // Do nothing
- }
-
- public void onDragEnter(DragObject d) {
+ @Override
+ public final void onDragEnter(DragObject d) {
d.dragView.setColor(mHoverColor);
+ if (Utilities.isLmpOrAbove()) {
+ animateTextColor(mHoverColor);
+ } else {
+ if (mCurrentFilter == null) {
+ mCurrentFilter = new ColorMatrix();
+ }
+ DragView.setColorScale(mHoverColor, mCurrentFilter);
+ mDrawable.setColorFilter(new ColorMatrixColorFilter(mCurrentFilter));
+ setTextColor(mHoverColor);
+ }
}
+ @Override
public void onDragOver(DragObject d) {
// Do nothing
}
- public void onDragExit(DragObject d) {
- d.dragView.setColor(0);
+ protected void resetHoverColor() {
+ if (Utilities.isLmpOrAbove()) {
+ animateTextColor(mOriginalTextColor.getDefaultColor());
+ } else {
+ mDrawable.setColorFilter(null);
+ setTextColor(mOriginalTextColor);
+ }
}
- public void onDragStart(DragSource source, Object info, int dragAction) {
- // Do nothing
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+ private void animateTextColor(int targetColor) {
+ if (mCurrentColorAnim != null) {
+ mCurrentColorAnim.cancel();
+ }
+
+ mCurrentColorAnim = new AnimatorSet();
+ mCurrentColorAnim.setDuration(DragView.COLOR_CHANGE_DURATION);
+
+ if (mSrcFilter == null) {
+ mSrcFilter = new ColorMatrix();
+ mDstFilter = new ColorMatrix();
+ mCurrentFilter = new ColorMatrix();
+ }
+
+ DragView.setColorScale(getTextColor(), mSrcFilter);
+ DragView.setColorScale(targetColor, mDstFilter);
+ ValueAnimator anim1 = ValueAnimator.ofObject(
+ new FloatArrayEvaluator(mCurrentFilter.getArray()),
+ mSrcFilter.getArray(), mDstFilter.getArray());
+ anim1.addUpdateListener(new AnimatorUpdateListener() {
+
+ @Override
+ public void onAnimationUpdate(ValueAnimator animation) {
+ mDrawable.setColorFilter(new ColorMatrixColorFilter(mCurrentFilter));
+ invalidate();
+ }
+ });
+
+ mCurrentColorAnim.play(anim1);
+ mCurrentColorAnim.play(ObjectAnimator.ofArgb(this, "textColor", targetColor));
+ mCurrentColorAnim.start();
}
+ @Override
+ public final void onDragExit(DragObject d) {
+ if (!d.dragComplete) {
+ d.dragView.setColor(0);
+ resetHoverColor();
+ } else {
+ // Restore the hover color
+ d.dragView.setColor(mHoverColor);
+ }
+ }
+
+ @Override
+ public final void onDragStart(DragSource source, Object info, int dragAction) {
+ mActive = supportsDrop(source, info);
+ mDrawable.setColorFilter(null);
+ if (mCurrentColorAnim != null) {
+ mCurrentColorAnim.cancel();
+ mCurrentColorAnim = null;
+ }
+ setTextColor(mOriginalTextColor);
+ ((ViewGroup) getParent()).setVisibility(mActive ? View.VISIBLE : View.GONE);
+ }
+
+ @Override
+ public final boolean acceptDrop(DragObject dragObject) {
+ return supportsDrop(dragObject.dragSource, dragObject.dragInfo);
+ }
+
+ protected abstract boolean supportsDrop(DragSource source, Object info);
+
+ @Override
public boolean isDropEnabled() {
return mActive;
}
+ @Override
public void onDragEnd() {
- // Do nothing
+ mActive = false;
}
+ /**
+ * On drop animate the dropView to the icon.
+ */
+ @Override
+ public void onDrop(final DragObject d) {
+ final DragLayer dragLayer = mLauncher.getDragLayer();
+ final Rect from = new Rect();
+ dragLayer.getViewRectRelativeToSelf(d.dragView, from);
+
+ int width = mDrawable.getIntrinsicWidth();
+ int height = mDrawable.getIntrinsicHeight();
+ final Rect to = getIconRect(d.dragView.getMeasuredWidth(), d.dragView.getMeasuredHeight(),
+ width, height);
+ final float scale = (float) to.width() / from.width();
+ mSearchDropTargetBar.deferOnDragEnd();
+
+ Runnable onAnimationEndRunnable = new Runnable() {
+ @Override
+ public void run() {
+ completeDrop(d);
+ mSearchDropTargetBar.onDragEnd();
+ mLauncher.exitSpringLoadedDragModeDelayed(true, 0, null);
+ }
+ };
+ dragLayer.animateView(d.dragView, from, to, scale, 1f, 1f, 0.1f, 0.1f,
+ DRAG_VIEW_DROP_DURATION, new DecelerateInterpolator(2),
+ new LinearInterpolator(), onAnimationEndRunnable,
+ DragLayer.ANIMATION_END_DISAPPEAR, null);
+ }
+
+ @Override
+ public void prepareAccessibilityDrop() { }
+
+ @Thunk abstract void completeDrop(DragObject d);
+
@Override
public void getHitRectRelativeToDragLayer(android.graphics.Rect outRect) {
super.getHitRect(outRect);
@@ -119,11 +259,7 @@ public class ButtonDropTarget extends TextView implements DropTarget, DragContro
outRect.offsetTo(coords[0], coords[1]);
}
- private boolean isRtl() {
- return (getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
- }
-
- Rect getIconRect(int viewWidth, int viewHeight, int drawableWidth, int drawableHeight) {
+ protected Rect getIconRect(int viewWidth, int viewHeight, int drawableWidth, int drawableHeight) {
DragLayer dragLayer = mLauncher.getDragLayer();
// Find the rect to animate to (the view is center aligned)
@@ -136,7 +272,7 @@ public class ButtonDropTarget extends TextView implements DropTarget, DragContro
final int left;
final int right;
- if (isRtl()) {
+ if (Utilities.isRtl(getResources())) {
right = to.right - getPaddingRight();
left = right - width;
} else {
@@ -157,7 +293,26 @@ public class ButtonDropTarget extends TextView implements DropTarget, DragContro
return to;
}
+ @Override
public void getLocationInDragLayer(int[] loc) {
mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
}
+
+ public void enableAccessibleDrag(boolean enable) {
+ setOnClickListener(enable ? this : null);
+ }
+
+ protected String getAccessibilityDropConfirmation() {
+ return null;
+ }
+
+ @Override
+ public void onClick(View v) {
+ LauncherAppState.getInstance().getAccessibilityDelegate()
+ .handleAccessibleDrop(this, null, getAccessibilityDropConfirmation());
+ }
+
+ public int getTextColor() {
+ return getTextColors().getDefaultColor();
+ }
}
diff --git a/src/com/android/launcher3/CellLayout.java b/src/com/android/launcher3/CellLayout.java
index 0ff1ef4adf..8096887128 100644
--- a/src/com/android/launcher3/CellLayout.java
+++ b/src/com/android/launcher3/CellLayout.java
@@ -22,6 +22,7 @@ import android.animation.AnimatorSet;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
+import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
@@ -33,7 +34,10 @@ import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
+import android.graphics.drawable.TransitionDrawable;
+import android.os.Build;
import android.os.Parcelable;
+import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
@@ -41,11 +45,16 @@ import android.view.MotionEvent;
import android.view.View;
import android.view.ViewDebug;
import android.view.ViewGroup;
-import android.view.animation.Animation;
+import android.view.accessibility.AccessibilityEvent;
import android.view.animation.DecelerateInterpolator;
-import android.view.animation.LayoutAnimationController;
+import com.android.launcher3.BubbleTextView.BubbleTextShadowHandler;
import com.android.launcher3.FolderIcon.FolderRingAnimator;
+import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
+import com.android.launcher3.accessibility.FolderAccessibilityHelper;
+import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
+import com.android.launcher3.util.Thunk;
+import com.android.launcher3.widget.PendingAddWidgetInfo;
import java.util.ArrayList;
import java.util.Arrays;
@@ -54,55 +63,47 @@ import java.util.Comparator;
import java.util.HashMap;
import java.util.Stack;
-public class CellLayout extends ViewGroup {
+public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
+ public static final int WORKSPACE_ACCESSIBILITY_DRAG = 2;
+ public static final int FOLDER_ACCESSIBILITY_DRAG = 1;
+
static final String TAG = "CellLayout";
private Launcher mLauncher;
- private int mCellWidth;
- private int mCellHeight;
+ @Thunk int mCellWidth;
+ @Thunk int mCellHeight;
private int mFixedCellWidth;
private int mFixedCellHeight;
- private int mCountX;
- private int mCountY;
+ @Thunk int mCountX;
+ @Thunk int mCountY;
private int mOriginalWidthGap;
private int mOriginalHeightGap;
- private int mWidthGap;
- private int mHeightGap;
+ @Thunk int mWidthGap;
+ @Thunk int mHeightGap;
private int mMaxGap;
private boolean mDropPending = false;
private boolean mIsDragTarget = true;
// These are temporary variables to prevent having to allocate a new object just to
// return an (x, y) value from helper functions. Do NOT use them to maintain other state.
- private final int[] mTmpXY = new int[2];
- private final int[] mTmpPoint = new int[2];
- int[] mTempLocation = new int[2];
+ @Thunk final int[] mTmpPoint = new int[2];
+ @Thunk final int[] mTempLocation = new int[2];
boolean[][] mOccupied;
boolean[][] mTmpOccupied;
- private boolean mLastDownOnOccupiedCell = false;
private OnTouchListener mInterceptTouchListener;
+ private StylusEventHelper mStylusEventHelper;
private ArrayList mFolderOuterRings = new ArrayList();
private int[] mFolderLeaveBehindCell = {-1, -1};
- private float FOREGROUND_ALPHA_DAMPER = 0.65f;
- private int mForegroundAlpha = 0;
private float mBackgroundAlpha;
- private float mBackgroundAlphaMultiplier = 1.0f;
- private boolean mDrawBackground = true;
- private Drawable mNormalBackground;
- private Drawable mActiveGlowBackground;
- private Drawable mOverScrollForegroundDrawable;
- private Drawable mOverScrollLeft;
- private Drawable mOverScrollRight;
- private Rect mBackgroundRect;
- private Rect mForegroundRect;
- private int mForegroundPadding;
+ private static final int BACKGROUND_ACTIVATE_DURATION = 120;
+ private final TransitionDrawable mBackground;
// These values allow a fixed measurement to be set on the CellLayout.
private int mFixedWidth = -1;
@@ -110,12 +111,11 @@ public class CellLayout extends ViewGroup {
// If we're actively dragging something over this screen, mIsDragOverlapping is true
private boolean mIsDragOverlapping = false;
- boolean mUseActiveGlowBackground = false;
// These arrays are used to implement the drag visualization on x-large screens.
// They are used as circular arrays, indexed by mDragOutlineCurrent.
- private Rect[] mDragOutlines = new Rect[4];
- private float[] mDragOutlineAlphas = new float[mDragOutlines.length];
+ @Thunk Rect[] mDragOutlines = new Rect[4];
+ @Thunk float[] mDragOutlineAlphas = new float[mDragOutlines.length];
private InterruptibleInOutAnimator[] mDragOutlineAnims =
new InterruptibleInOutAnimator[mDragOutlines.length];
@@ -123,12 +123,10 @@ public class CellLayout extends ViewGroup {
private int mDragOutlineCurrent = 0;
private final Paint mDragOutlinePaint = new Paint();
- private final FastBitmapView mTouchFeedbackView;
+ private final ClickShadowView mTouchFeedbackView;
- private HashMap mReorderAnimators = new
- HashMap();
- private HashMap
- mShakeAnimators = new HashMap();
+ @Thunk HashMap mReorderAnimators = new HashMap<>();
+ @Thunk HashMap mShakeAnimators = new HashMap<>();
private boolean mItemPlacementDirty = false;
@@ -156,19 +154,22 @@ public class CellLayout extends ViewGroup {
private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
private static final int REORDER_ANIMATION_DURATION = 150;
- private float mReorderPreviewAnimationMagnitude;
+ @Thunk float mReorderPreviewAnimationMagnitude;
private ArrayList mIntersectingViews = new ArrayList();
private Rect mOccupiedRect = new Rect();
private int[] mDirectionVector = new int[2];
int[] mPreviousReorderDirection = new int[2];
private static final int INVALID_DIRECTION = -100;
- private DropTarget.DragEnforcer mDragEnforcer;
- private Rect mTempRect = new Rect();
+ private final Rect mTempRect = new Rect();
private final static Paint sPaint = new Paint();
+ // Related to accessible drag and drop
+ private DragAndDropAccessibilityDelegate mTouchHelper;
+ private boolean mUseTouchHelper = false;
+
public CellLayout(Context context) {
this(context, null);
}
@@ -179,7 +180,6 @@ public class CellLayout extends ViewGroup {
public CellLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
- mDragEnforcer = new DropTarget.DragEnforcer(context);
// A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
// the user where a dragged item will land when dropped.
@@ -187,8 +187,7 @@ public class CellLayout extends ViewGroup {
setClipToPadding(false);
mLauncher = (Launcher) context;
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
+ DeviceProfile grid = mLauncher.getDeviceProfile();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
mCellWidth = mCellHeight = -1;
@@ -196,8 +195,8 @@ public class CellLayout extends ViewGroup {
mWidthGap = mOriginalWidthGap = 0;
mHeightGap = mOriginalHeightGap = 0;
mMaxGap = Integer.MAX_VALUE;
- mCountX = (int) grid.numColumns;
- mCountY = (int) grid.numRows;
+ mCountX = (int) grid.inv.numColumns;
+ mCountY = (int) grid.inv.numRows;
mOccupied = new boolean[mCountX][mCountY];
mTmpOccupied = new boolean[mCountX][mCountY];
mPreviousReorderDirection[0] = INVALID_DIRECTION;
@@ -210,20 +209,12 @@ public class CellLayout extends ViewGroup {
final Resources res = getResources();
mHotseatScale = (float) grid.hotseatIconSizePx / grid.iconSizePx;
- mNormalBackground = res.getDrawable(R.drawable.screenpanel);
- mActiveGlowBackground = res.getDrawable(R.drawable.screenpanel_hover);
-
- mOverScrollLeft = res.getDrawable(R.drawable.overscroll_glow_left);
- mOverScrollRight = res.getDrawable(R.drawable.overscroll_glow_right);
- mForegroundPadding =
- res.getDimensionPixelSize(R.dimen.workspace_overscroll_drawable_padding);
+ mBackground = (TransitionDrawable) res.getDrawable(R.drawable.bg_screenpanel);
+ mBackground.setCallback(this);
mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE *
grid.iconSizePx);
- mNormalBackground.setFilterBitmap(true);
- mActiveGlowBackground.setFilterBitmap(true);
-
// Initialize the data structures used for the drag visualization.
mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
mDragCell[0] = mDragCell[1] = -1;
@@ -281,19 +272,78 @@ public class CellLayout extends ViewGroup {
mDragOutlineAnims[i] = anim;
}
- mBackgroundRect = new Rect();
- mForegroundRect = new Rect();
-
mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
mCountX, mCountY);
- mTouchFeedbackView = new FastBitmapView(context);
- // Make the feedback view large enough to hold the blur bitmap.
- addView(mTouchFeedbackView, (int) (grid.cellWidthPx * 1.5), (int) (grid.cellHeightPx * 1.5));
+ mStylusEventHelper = new StylusEventHelper(this);
+
+ mTouchFeedbackView = new ClickShadowView(context);
+ addView(mTouchFeedbackView);
addView(mShortcutsAndWidgets);
}
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+ public void enableAccessibleDrag(boolean enable, int dragType) {
+ mUseTouchHelper = enable;
+ if (!enable) {
+ ViewCompat.setAccessibilityDelegate(this, null);
+ setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
+ getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
+ setOnClickListener(mLauncher);
+ } else {
+ if (dragType == WORKSPACE_ACCESSIBILITY_DRAG &&
+ !(mTouchHelper instanceof WorkspaceAccessibilityHelper)) {
+ mTouchHelper = new WorkspaceAccessibilityHelper(this);
+ } else if (dragType == FOLDER_ACCESSIBILITY_DRAG &&
+ !(mTouchHelper instanceof FolderAccessibilityHelper)) {
+ mTouchHelper = new FolderAccessibilityHelper(this);
+ }
+ ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
+ setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
+ getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
+ setOnClickListener(mTouchHelper);
+ }
+
+ // Invalidate the accessibility hierarchy
+ if (getParent() != null) {
+ getParent().notifySubtreeAccessibilityStateChanged(
+ this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
+ }
+ }
+
+ @Override
+ public boolean dispatchHoverEvent(MotionEvent event) {
+ // Always attempt to dispatch hover events to accessibility first.
+ if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
+ return true;
+ }
+ return super.dispatchHoverEvent(event);
+ }
+
+ @Override
+ public boolean onInterceptTouchEvent(MotionEvent ev) {
+ if (mUseTouchHelper ||
+ (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent ev) {
+ boolean handled = super.onTouchEvent(ev);
+ // Stylus button press on a home screen should not switch between overview mode and
+ // the home screen mode, however, once in overview mode stylus button press should be
+ // enabled to allow rearranging the different home screens. So check what mode
+ // the workspace is in, and only perform stylus button presses while in overview mode.
+ if (mLauncher.mWorkspace.isInOverviewMode()
+ && mStylusEventHelper.checkAndPerformStylusEvent(ev)) {
+ return true;
+ }
+ return handled;
+ }
+
public void enableHardwareLayer(boolean hasLayer) {
mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
}
@@ -337,47 +387,19 @@ public class CellLayout extends ViewGroup {
return mDropPending;
}
- void setOverScrollAmount(float r, boolean left) {
- if (left && mOverScrollForegroundDrawable != mOverScrollLeft) {
- mOverScrollForegroundDrawable = mOverScrollLeft;
- } else if (!left && mOverScrollForegroundDrawable != mOverScrollRight) {
- mOverScrollForegroundDrawable = mOverScrollRight;
- }
-
- r *= FOREGROUND_ALPHA_DAMPER;
- mForegroundAlpha = (int) Math.round((r * 255));
- mOverScrollForegroundDrawable.setAlpha(mForegroundAlpha);
- invalidate();
- }
-
- void setPressedIcon(BubbleTextView icon, Bitmap background, int padding) {
+ @Override
+ public void setPressedIcon(BubbleTextView icon, Bitmap background) {
if (icon == null || background == null) {
mTouchFeedbackView.setBitmap(null);
mTouchFeedbackView.animate().cancel();
} else {
- int offset = getMeasuredWidth() - getPaddingLeft() - getPaddingRight()
- - (mCountX * mCellWidth);
- mTouchFeedbackView.setTranslationX(icon.getLeft() + (int) Math.ceil(offset / 2f)
- - padding);
- mTouchFeedbackView.setTranslationY(icon.getTop() - padding);
if (mTouchFeedbackView.setBitmap(background)) {
- mTouchFeedbackView.setAlpha(0);
- mTouchFeedbackView.animate().alpha(1)
- .setDuration(FastBitmapDrawable.CLICK_FEEDBACK_DURATION)
- .setInterpolator(FastBitmapDrawable.CLICK_FEEDBACK_INTERPOLATOR)
- .start();
+ mTouchFeedbackView.alignWithIconView(icon, mShortcutsAndWidgets);
+ mTouchFeedbackView.animateShadow();
}
}
}
- void setUseActiveGlowBackground(boolean use) {
- mUseActiveGlowBackground = use;
- }
-
- void disableBackground() {
- mDrawBackground = false;
- }
-
void disableDragTarget() {
mIsDragTarget = false;
}
@@ -389,7 +411,11 @@ public class CellLayout extends ViewGroup {
void setIsDragOverlapping(boolean isDragOverlapping) {
if (mIsDragOverlapping != isDragOverlapping) {
mIsDragOverlapping = isDragOverlapping;
- setUseActiveGlowBackground(mIsDragOverlapping);
+ if (mIsDragOverlapping) {
+ mBackground.startTransition(BACKGROUND_ACTIVATE_DURATION);
+ } else {
+ mBackground.reverseTransition(BACKGROUND_ACTIVATE_DURATION);
+ }
invalidate();
}
}
@@ -400,24 +426,17 @@ public class CellLayout extends ViewGroup {
@Override
protected void onDraw(Canvas canvas) {
+ if (!mIsDragTarget) {
+ return;
+ }
+
// When we're large, we are either drawn in a "hover" state (ie when dragging an item to
// a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
// When we're small, we are either drawn normally or in the "accepts drops" state (during
// a drag). However, we also drag the mini hover background *over* one of those two
// backgrounds
- if (mDrawBackground && mBackgroundAlpha > 0.0f) {
- Drawable bg;
-
- if (mUseActiveGlowBackground) {
- // In the mini case, we draw the active_glow bg *over* the active background
- bg = mActiveGlowBackground;
- } else {
- bg = mNormalBackground;
- }
-
- bg.setAlpha((int) (mBackgroundAlpha * mBackgroundAlphaMultiplier * 255));
- bg.setBounds(mBackgroundRect);
- bg.draw(canvas);
+ if (mBackgroundAlpha > 0.0f) {
+ mBackground.draw(canvas);
}
final Paint paint = mDragOutlinePaint;
@@ -453,8 +472,7 @@ public class CellLayout extends ViewGroup {
int previewOffset = FolderRingAnimator.sPreviewSize;
// The folder outer / inner ring image(s)
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
+ DeviceProfile grid = mLauncher.getDeviceProfile();
for (int i = 0; i < mFolderOuterRings.size(); i++) {
FolderRingAnimator fra = mFolderOuterRings.get(i);
@@ -513,15 +531,6 @@ public class CellLayout extends ViewGroup {
}
}
- @Override
- protected void dispatchDraw(Canvas canvas) {
- super.dispatchDraw(canvas);
- if (mForegroundAlpha > 0) {
- mOverScrollForegroundDrawable.setBounds(mForegroundRect);
- mOverScrollForegroundDrawable.draw(canvas);
- }
- }
-
public void showFolderAccept(FolderRingAnimator fra) {
mFolderOuterRings.add(fra);
}
@@ -578,11 +587,11 @@ public class CellLayout extends ViewGroup {
mInterceptTouchListener = listener;
}
- int getCountX() {
+ public int getCountX() {
return mCountX;
}
- int getCountY() {
+ public int getCountY() {
return mCountY;
}
@@ -591,6 +600,10 @@ public class CellLayout extends ViewGroup {
mShortcutsAndWidgets.setIsHotseat(isHotseat);
}
+ public boolean isHotseat() {
+ return mIsHotseat;
+ }
+
public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
boolean markCells) {
final LayoutParams lp = params;
@@ -613,7 +626,6 @@ public class CellLayout extends ViewGroup {
if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
child.setId(childId);
-
mShortcutsAndWidgets.addView(child, index, lp);
if (markCells) markCellsAsOccupiedForView(child);
@@ -637,10 +649,6 @@ public class CellLayout extends ViewGroup {
}
}
- public void removeViewWithoutMarkingCells(View view) {
- mShortcutsAndWidgets.removeView(view);
- }
-
@Override
public void removeView(View view) {
markCellsAsUnoccupiedForView(view);
@@ -675,25 +683,13 @@ public class CellLayout extends ViewGroup {
mShortcutsAndWidgets.removeViewsInLayout(start, count);
}
- @Override
- public boolean onInterceptTouchEvent(MotionEvent ev) {
- // First we clear the tag to ensure that on every touch down we start with a fresh slate,
- // even in the case where we return early. Not clearing here was causing bugs whereby on
- // long-press we'd end up picking up an item from a previous drag operation.
- if (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev)) {
- return true;
- }
-
- return false;
- }
-
/**
* Given a point, return the cell that strictly encloses that point
* @param x X coordinate of the point
* @param y Y coordinate of the point
* @param result Array of 2 ints to hold the x and y coordinate of the cell
*/
- void pointToCellExact(int x, int y, int[] result) {
+ public void pointToCellExact(int x, int y, int[] result) {
final int hStartPadding = getPaddingLeft();
final int vStartPadding = getPaddingTop();
@@ -782,9 +778,7 @@ public class CellLayout extends ViewGroup {
public float getDistanceFromCell(float x, float y, int[] cell) {
cellToCenterPoint(cell[0], cell[1], mTmpPoint);
- float distance = (float) Math.sqrt( Math.pow(x - mTmpPoint[0], 2) +
- Math.pow(y - mTmpPoint[1], 2));
- return distance;
+ return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
}
int getCellWidth() {
@@ -803,28 +797,6 @@ public class CellLayout extends ViewGroup {
return mHeightGap;
}
- Rect getContentRect(Rect r) {
- if (r == null) {
- r = new Rect();
- }
- int left = getPaddingLeft();
- int top = getPaddingTop();
- int right = left + getWidth() - getPaddingLeft() - getPaddingRight();
- int bottom = top + getHeight() - getPaddingTop() - getPaddingBottom();
- r.set(left, top, right, bottom);
- return r;
- }
-
- /** Return a rect that has the cellWidth/cellHeight (left, top), and
- * widthGap/heightGap (right, bottom) */
- static void getMetrics(Rect metrics, int paddedMeasureWidth,
- int paddedMeasureHeight, int countX, int countY) {
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
- metrics.set(grid.calculateCellWidth(paddedMeasureWidth, countX),
- grid.calculateCellHeight(paddedMeasureHeight, countY), 0, 0);
- }
-
public void setFixedSize(int width, int height) {
mFixedWidth = width;
mFixedHeight = height;
@@ -832,9 +804,6 @@ public class CellLayout extends ViewGroup {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
-
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
@@ -842,8 +811,8 @@ public class CellLayout extends ViewGroup {
int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
- int cw = grid.calculateCellWidth(childWidthSize, mCountX);
- int ch = grid.calculateCellHeight(childHeightSize, mCountY);
+ int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
+ int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
if (cw != mCellWidth || ch != mCellHeight) {
mCellWidth = cw;
mCellHeight = ch;
@@ -877,19 +846,20 @@ public class CellLayout extends ViewGroup {
mWidthGap = mOriginalWidthGap;
mHeightGap = mOriginalHeightGap;
}
- int count = getChildCount();
- int maxWidth = 0;
- int maxHeight = 0;
- for (int i = 0; i < count; i++) {
- View child = getChildAt(i);
- int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth,
- MeasureSpec.EXACTLY);
- int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight,
- MeasureSpec.EXACTLY);
- child.measure(childWidthMeasureSpec, childheightMeasureSpec);
- maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
- maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
- }
+
+ // Make the feedback view large enough to hold the blur bitmap.
+ mTouchFeedbackView.measure(
+ MeasureSpec.makeMeasureSpec(mCellWidth + mTouchFeedbackView.getExtraSize(),
+ MeasureSpec.EXACTLY),
+ MeasureSpec.makeMeasureSpec(mCellHeight + mTouchFeedbackView.getExtraSize(),
+ MeasureSpec.EXACTLY));
+
+ mShortcutsAndWidgets.measure(
+ MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
+ MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
+
+ int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
+ int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
if (mFixedWidth > 0 && mFixedHeight > 0) {
setMeasuredDimension(maxWidth, maxHeight);
} else {
@@ -903,13 +873,13 @@ public class CellLayout extends ViewGroup {
(mCountX * mCellWidth);
int left = getPaddingLeft() + (int) Math.ceil(offset / 2f);
int top = getPaddingTop();
- int count = getChildCount();
- for (int i = 0; i < count; i++) {
- View child = getChildAt(i);
- child.layout(left, top,
- left + r - l,
- top + b - t);
- }
+
+ mTouchFeedbackView.layout(left, top,
+ left + mTouchFeedbackView.getMeasuredWidth(),
+ top + mTouchFeedbackView.getMeasuredHeight());
+ mShortcutsAndWidgets.layout(left, top,
+ left + r - l,
+ top + b - t);
}
@Override
@@ -917,12 +887,9 @@ public class CellLayout extends ViewGroup {
super.onSizeChanged(w, h, oldw, oldh);
// Expand the background drawing bounds by the padding baked into the background drawable
- Rect padding = new Rect();
- mNormalBackground.getPadding(padding);
- mBackgroundRect.set(-padding.left, -padding.top, w + padding.right, h + padding.bottom);
-
- mForegroundRect.set(mForegroundPadding, mForegroundPadding,
- w - mForegroundPadding, h - mForegroundPadding);
+ mBackground.getPadding(mTempRect);
+ mBackground.setBounds(-mTempRect.left, -mTempRect.top,
+ w + mTempRect.right, h + mTempRect.bottom);
}
@Override
@@ -939,25 +906,18 @@ public class CellLayout extends ViewGroup {
return mBackgroundAlpha;
}
- public void setBackgroundAlphaMultiplier(float multiplier) {
-
- if (mBackgroundAlphaMultiplier != multiplier) {
- mBackgroundAlphaMultiplier = multiplier;
- invalidate();
- }
- }
-
- public float getBackgroundAlphaMultiplier() {
- return mBackgroundAlphaMultiplier;
- }
-
public void setBackgroundAlpha(float alpha) {
if (mBackgroundAlpha != alpha) {
mBackgroundAlpha = alpha;
- invalidate();
+ mBackground.setAlpha((int) (mBackgroundAlpha * 255));
}
}
+ @Override
+ protected boolean verifyDrawable(Drawable who) {
+ return super.verifyDrawable(who) || (mIsDragTarget && who == mBackground);
+ }
+
public void setShortcutAndWidgetAlpha(float alpha) {
mShortcutsAndWidgets.setAlpha(alpha);
}
@@ -1054,36 +1014,6 @@ public class CellLayout extends ViewGroup {
return false;
}
- /**
- * Estimate where the top left cell of the dragged item will land if it is dropped.
- *
- * @param originX The X value of the top left corner of the item
- * @param originY The Y value of the top left corner of the item
- * @param spanX The number of horizontal cells that the item spans
- * @param spanY The number of vertical cells that the item spans
- * @param result The estimated drop cell X and Y.
- */
- void estimateDropCell(int originX, int originY, int spanX, int spanY, int[] result) {
- final int countX = mCountX;
- final int countY = mCountY;
-
- // pointToCellRounded takes the top left of a cell but will pad that with
- // cellWidth/2 and cellHeight/2 when finding the matching cell
- pointToCellRounded(originX, originY, result);
-
- // If the item isn't fully on this screen, snap to the edges
- int rightOverhang = result[0] + spanX - countX;
- if (rightOverhang > 0) {
- result[0] -= rightOverhang; // Snap to right
- }
- result[0] = Math.max(0, result[0]); // Snap to left
- int bottomOverhang = result[1] + spanY - countY;
- if (bottomOverhang > 0) {
- result[1] -= bottomOverhang; // Snap to bottom
- }
- result[1] = Math.max(0, result[1]); // Snap to top
- }
-
void visualizeDropLocation(View v, Bitmap dragOutline, int originX, int originY, int cellX,
int cellY, int spanX, int spanY, boolean resize, Point dragOffset, Rect dragRegion) {
final int oldDragCellX = mDragCell[0];
@@ -1167,9 +1097,8 @@ public class CellLayout extends ViewGroup {
* @return The X, Y cell of a vacant area that can contain this object,
* nearest the requested location.
*/
- int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY,
- int[] result) {
- return findNearestVacantArea(pixelX, pixelY, spanX, spanY, null, result);
+ int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
+ return findNearestVacantArea(pixelX, pixelY, spanX, spanY, spanX, spanY, result, null);
}
/**
@@ -1189,30 +1118,10 @@ public class CellLayout extends ViewGroup {
*/
int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
int spanY, int[] result, int[] resultSpan) {
- return findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null,
+ return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
result, resultSpan);
}
- /**
- * Find a vacant area that will fit the given bounds nearest the requested
- * cell location. Uses Euclidean distance to score multiple vacant areas.
- *
- * @param pixelX The X location at which you want to search for a vacant area.
- * @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 ignoreOccupied If true, the result can be an occupied cell
- * @param result Array in which to place the result, or null (in which case a new array will
- * be allocated)
- * @return The X, Y cell of a vacant area that can contain this object,
- * nearest the requested location.
- */
- int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, View ignoreView,
- boolean ignoreOccupied, int[] result) {
- return findNearestArea(pixelX, pixelY, spanX, spanY,
- spanX, spanY, ignoreView, ignoreOccupied, result, null, mOccupied);
- }
-
private final Stack mTempRectStack = new Stack();
private void lazyInitTempRectStack() {
if (mTempRectStack.isEmpty()) {
@@ -1244,12 +1153,9 @@ public class CellLayout extends ViewGroup {
* @return The X, Y cell of a vacant area that can contain this object,
* nearest the requested location.
*/
- int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
- View ignoreView, boolean ignoreOccupied, int[] result, int[] resultSpan,
- boolean[][] occupied) {
+ private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
+ int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
lazyInitTempRectStack();
- // mark space take by ignoreView as available (method checks if ignoreView is null)
- markCellsAsUnoccupiedForView(ignoreView, occupied);
// For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
// to the center of the item, but we are searching based on the top-left cell, so
@@ -1280,7 +1186,7 @@ public class CellLayout extends ViewGroup {
// First, let's see if this thing fits anywhere
for (int i = 0; i < minSpanX; i++) {
for (int j = 0; j < minSpanY; j++) {
- if (occupied[x + i][y + j]) {
+ if (mOccupied[x + i][y + j]) {
continue inner;
}
}
@@ -1297,7 +1203,7 @@ public class CellLayout extends ViewGroup {
while (!(hitMaxX && hitMaxY)) {
if (incX && !hitMaxX) {
for (int j = 0; j < ySize; j++) {
- if (x + xSize > countX -1 || occupied[x + xSize][y + j]) {
+ if (x + xSize > countX -1 || mOccupied[x + xSize][y + j]) {
// We can't move out horizontally
hitMaxX = true;
}
@@ -1307,7 +1213,7 @@ public class CellLayout extends ViewGroup {
}
} else if (!hitMaxY) {
for (int i = 0; i < xSize; i++) {
- if (y + ySize > countY - 1 || occupied[x + i][y + ySize]) {
+ if (y + ySize > countY - 1 || mOccupied[x + i][y + ySize]) {
// We can't move out vertically
hitMaxY = true;
}
@@ -1324,7 +1230,7 @@ public class CellLayout extends ViewGroup {
hitMaxX = xSize >= spanX;
hitMaxY = ySize >= spanY;
}
- final int[] cellXY = mTmpXY;
+ final int[] cellXY = mTmpPoint;
cellToCenterPoint(x, y, cellXY);
// We verify that the current rect is not a sub-rect of any of our previous
@@ -1340,8 +1246,7 @@ public class CellLayout extends ViewGroup {
}
}
validRegions.push(currentRect);
- double distance = Math.sqrt(Math.pow(cellXY[0] - pixelX, 2)
- + Math.pow(cellXY[1] - pixelY, 2));
+ double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
if ((distance <= bestDistance && !contained) ||
currentRect.contains(bestRect)) {
@@ -1356,8 +1261,6 @@ public class CellLayout extends ViewGroup {
}
}
}
- // re-mark space taken by ignoreView as occupied
- markCellsAsOccupiedForView(ignoreView, occupied);
// Return -1, -1 if no suitable location found
if (bestDistance == Double.MAX_VALUE) {
@@ -1411,8 +1314,7 @@ public class CellLayout extends ViewGroup {
}
}
- float distance = (float)
- Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
+ float distance = (float) Math.hypot(x - cellX, y - cellY);
int[] curDirection = mTmpPoint;
computeDirectionVector(x - cellX, y - cellY, curDirection);
// The direction score is just the dot product of the two candidate direction
@@ -2028,7 +1930,7 @@ public class CellLayout extends ViewGroup {
}
}
- ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
+ private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
int spanX, int spanY, int[] direction, View dragView, boolean decX,
ItemConfiguration solution) {
// Copy the current state into the solution. This solution will be manipulated as necessary.
@@ -2264,7 +2166,7 @@ public class CellLayout extends ViewGroup {
}
}
- private void completeAnimationImmediately() {
+ @Thunk void completeAnimationImmediately() {
if (a != null) {
a.cancel();
}
@@ -2317,7 +2219,7 @@ public class CellLayout extends ViewGroup {
mLauncher.getWorkspace().updateItemLocationsInDatabase(this);
}
- public void setUseTempCoords(boolean useTempCoords) {
+ private void setUseTempCoords(boolean useTempCoords) {
int childCount = mShortcutsAndWidgets.getChildCount();
for (int i = 0; i < childCount; i++) {
LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
@@ -2325,11 +2227,11 @@ public class CellLayout extends ViewGroup {
}
}
- ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
+ private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
int spanX, int spanY, View dragView, ItemConfiguration solution) {
int[] result = new int[2];
int[] resultSpan = new int[2];
- findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null, result,
+ findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
resultSpan);
if (result[0] >= 0 && result[1] >= 0) {
copyCurrentStateToSolution(solution, false);
@@ -2585,7 +2487,7 @@ public class CellLayout extends ViewGroup {
return mItemPlacementDirty;
}
- private class ItemConfiguration {
+ @Thunk class ItemConfiguration {
HashMap map = new HashMap();
private HashMap savedMap = new HashMap();
ArrayList sortedViews = new ArrayList();
@@ -2645,45 +2547,6 @@ public class CellLayout extends ViewGroup {
}
- /**
- * Find a vacant area that will fit the given bounds nearest the requested
- * cell location. Uses Euclidean distance to score multiple vacant areas.
- *
- * @param pixelX The X location at which you want to search for a vacant area.
- * @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.
- */
- int[] findNearestVacantArea(
- int pixelX, int pixelY, int spanX, int spanY, View ignoreView, int[] result) {
- return findNearestArea(pixelX, pixelY, spanX, spanY, ignoreView, true, result);
- }
-
- /**
- * Find a vacant area that will fit the given bounds nearest the requested
- * cell location. Uses Euclidean distance to score multiple vacant areas.
- *
- * @param pixelX The X location at which you want to search for a vacant area.
- * @param pixelY The Y location at which you want to search for a vacant area.
- * @param minSpanX The minimum horizontal span required
- * @param minSpanY The minimum vertical span required
- * @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.
- */
- int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
- int spanX, int spanY, View ignoreView, int[] result, int[] resultSpan) {
- return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, true,
- result, resultSpan, mOccupied);
- }
-
/**
* Find a starting cell position that will fit the given bounds nearest the requested
* cell location. Uses Euclidean distance to score multiple vacant areas.
@@ -2697,9 +2560,8 @@ public class CellLayout extends ViewGroup {
* @return The X, Y cell of a vacant area that can contain this object,
* nearest the requested location.
*/
- int[] findNearestArea(
- int pixelX, int pixelY, int spanX, int spanY, int[] result) {
- return findNearestArea(pixelX, pixelY, spanX, spanY, null, false, result);
+ int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
+ return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
}
boolean existsEmptyCell() {
@@ -2719,104 +2581,33 @@ public class CellLayout extends ViewGroup {
*
* @return True if a vacant cell of the specified dimension was found, false otherwise.
*/
- boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
- return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1, null, mOccupied);
- }
-
- /**
- * Like above, but ignores any cells occupied by the item "ignoreView"
- *
- * @param cellXY The array that will contain the position of a vacant cell if such a cell
- * can be found.
- * @param spanX The horizontal span of the cell we want to find.
- * @param spanY The vertical span of the cell we want to find.
- * @param ignoreView The home screen item we should treat as not occupying any space
- * @return
- */
- boolean findCellForSpanIgnoring(int[] cellXY, int spanX, int spanY, View ignoreView) {
- return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1,
- ignoreView, mOccupied);
- }
-
- /**
- * Like above, but if intersectX and intersectY are not -1, then this method will try to
- * return coordinates for rectangles that contain the cell [intersectX, intersectY]
- *
- * @param spanX The horizontal span of the cell we want to find.
- * @param spanY The vertical span of the cell we want to find.
- * @param ignoreView The home screen item we should treat as not occupying any space
- * @param intersectX The X coordinate of the cell that we should try to overlap
- * @param intersectX The Y coordinate of the cell that we should try to overlap
- *
- * @return True if a vacant cell of the specified dimension was found, false otherwise.
- */
- boolean findCellForSpanThatIntersects(int[] cellXY, int spanX, int spanY,
- int intersectX, int intersectY) {
- return findCellForSpanThatIntersectsIgnoring(
- cellXY, spanX, spanY, intersectX, intersectY, null, mOccupied);
- }
-
- /**
- * The superset of the above two methods
- */
- boolean findCellForSpanThatIntersectsIgnoring(int[] cellXY, int spanX, int spanY,
- int intersectX, int intersectY, View ignoreView, boolean occupied[][]) {
- // mark space take by ignoreView as available (method checks if ignoreView is null)
- markCellsAsUnoccupiedForView(ignoreView, occupied);
-
+ public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
boolean foundCell = false;
- while (true) {
- int startX = 0;
- if (intersectX >= 0) {
- startX = Math.max(startX, intersectX - (spanX - 1));
- }
- int endX = mCountX - (spanX - 1);
- if (intersectX >= 0) {
- endX = Math.min(endX, intersectX + (spanX - 1) + (spanX == 1 ? 1 : 0));
- }
- int startY = 0;
- if (intersectY >= 0) {
- startY = Math.max(startY, intersectY - (spanY - 1));
- }
- int endY = mCountY - (spanY - 1);
- if (intersectY >= 0) {
- endY = Math.min(endY, intersectY + (spanY - 1) + (spanY == 1 ? 1 : 0));
- }
+ final int endX = mCountX - (spanX - 1);
+ final int endY = mCountY - (spanY - 1);
- for (int y = startY; y < endY && !foundCell; y++) {
- inner:
- for (int x = startX; x < endX; x++) {
- for (int i = 0; i < spanX; i++) {
- for (int j = 0; j < spanY; j++) {
- if (occupied[x + i][y + j]) {
- // small optimization: we can skip to after the column we just found
- // an occupied cell
- x += i;
- continue inner;
- }
+ for (int y = 0; y < endY && !foundCell; y++) {
+ inner:
+ for (int x = 0; x < endX; x++) {
+ for (int i = 0; i < spanX; i++) {
+ for (int j = 0; j < spanY; j++) {
+ if (mOccupied[x + i][y + j]) {
+ // small optimization: we can skip to after the column we just found
+ // an occupied cell
+ x += i;
+ continue inner;
}
}
- if (cellXY != null) {
- cellXY[0] = x;
- cellXY[1] = y;
- }
- foundCell = true;
- break;
}
- }
- if (intersectX == -1 && intersectY == -1) {
+ if (cellXY != null) {
+ cellXY[0] = x;
+ cellXY[1] = y;
+ }
+ foundCell = true;
break;
- } else {
- // if we failed to find anything, try again but without any requirements of
- // intersecting
- intersectX = -1;
- intersectY = -1;
- continue;
}
}
- // re-mark space taken by ignoreView as occupied
- markCellsAsOccupiedForView(ignoreView, occupied);
return foundCell;
}
@@ -2826,7 +2617,6 @@ public class CellLayout extends ViewGroup {
* or it may have begun on another layout.
*/
void onDragEnter() {
- mDragEnforcer.onDragEnter();
mDragging = true;
}
@@ -2834,7 +2624,6 @@ public class CellLayout extends ViewGroup {
* Called when drag has left this CellLayout or has been completed (successfully or not)
*/
void onDragExit() {
- mDragEnforcer.onDragExit();
// This can actually be called when we aren't in a drag, e.g. when adding a new
// item to this layout via the customize drawer.
// Guard against that case.
@@ -2900,18 +2689,20 @@ public class CellLayout extends ViewGroup {
* @param height Height in pixels
* @param result An array of length 2 in which to store the result (may be null).
*/
- public static int[] rectToCell(int width, int height, int[] result) {
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
- Rect padding = grid.getWorkspacePadding(grid.isLandscape ?
- CellLayout.LANDSCAPE : CellLayout.PORTRAIT);
+ public static int[] rectToCell(Launcher launcher, int width, int height, int[] result) {
+ return rectToCell(launcher.getDeviceProfile(), launcher, width, height, result);
+ }
+
+ public static int[] rectToCell(DeviceProfile grid, Context context, int width, int height,
+ int[] result) {
+ Rect padding = grid.getWorkspacePadding(Utilities.isRtl(context.getResources()));
// Always assume we're working with the smallest span to make sure we
// reserve enough space in both orientations.
- int parentWidth = grid.calculateCellWidth(grid.widthPx
- - padding.left - padding.right, (int) grid.numColumns);
- int parentHeight = grid.calculateCellHeight(grid.heightPx
- - padding.top - padding.bottom, (int) grid.numRows);
+ int parentWidth = DeviceProfile.calculateCellWidth(grid.widthPx
+ - padding.left - padding.right, (int) grid.inv.numColumns);
+ int parentHeight = DeviceProfile.calculateCellHeight(grid.heightPx
+ - padding.top - padding.bottom, (int) grid.inv.numRows);
int smallerSize = Math.min(parentWidth, parentHeight);
// Always round up to next largest cell
@@ -2926,13 +2717,6 @@ public class CellLayout extends ViewGroup {
return result;
}
- public int[] cellSpansToSize(int hSpans, int vSpans) {
- int[] size = new int[2];
- size[0] = hSpans * mCellWidth + (hSpans - 1) * mWidthGap;
- size[1] = vSpans * mCellHeight + (vSpans - 1) * mHeightGap;
- return size;
- }
-
/**
* Calculate the grid spans needed to fit given item
*/
@@ -2951,49 +2735,11 @@ public class CellLayout extends ViewGroup {
info.spanX = info.spanY = 1;
return;
}
- int[] spans = rectToCell(minWidth, minHeight, null);
+ int[] spans = rectToCell(mLauncher, minWidth, minHeight, null);
info.spanX = spans[0];
info.spanY = spans[1];
}
- /**
- * Find the first vacant cell, if there is one.
- *
- * @param vacant Holds the x and y coordinate of the vacant cell
- * @param spanX Horizontal cell span.
- * @param spanY Vertical cell span.
- *
- * @return True if a vacant cell was found
- */
- public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
-
- return findVacantCell(vacant, spanX, spanY, mCountX, mCountY, mOccupied);
- }
-
- static boolean findVacantCell(int[] vacant, int spanX, int spanY,
- int xCount, int yCount, boolean[][] occupied) {
-
- for (int y = 0; y < yCount; y++) {
- for (int x = 0; x < xCount; x++) {
- boolean available = !occupied[x][y];
-out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
- for (int j = y; j < y + spanY - 1 && y < yCount; j++) {
- available = available && !occupied[i][j];
- if (!available) break out;
- }
- }
-
- if (available) {
- vacant[0] = x;
- vacant[1] = y;
- return true;
- }
- }
- }
-
- return false;
- }
-
private void clearOccupiedCells() {
for (int x = 0; x < mCountX; x++) {
for (int y = 0; y < mCountY; y++) {
@@ -3002,27 +2748,16 @@ out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
}
}
- public void onMove(View view, int newCellX, int newCellY, int newSpanX, int newSpanY) {
- markCellsAsUnoccupiedForView(view);
- markCellsForView(newCellX, newCellY, newSpanX, newSpanY, mOccupied, true);
- }
-
public void markCellsAsOccupiedForView(View view) {
- markCellsAsOccupiedForView(view, mOccupied);
- }
- public void markCellsAsOccupiedForView(View view, boolean[][] occupied) {
if (view == null || view.getParent() != mShortcutsAndWidgets) return;
LayoutParams lp = (LayoutParams) view.getLayoutParams();
- markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, true);
+ markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, true);
}
public void markCellsAsUnoccupiedForView(View view) {
- markCellsAsUnoccupiedForView(view, mOccupied);
- }
- public void markCellsAsUnoccupiedForView(View view, boolean occupied[][]) {
if (view == null || view.getParent() != mShortcutsAndWidgets) return;
LayoutParams lp = (LayoutParams) view.getLayoutParams();
- markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, false);
+ markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, false);
}
private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
@@ -3068,17 +2803,6 @@ out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
return new CellLayout.LayoutParams(p);
}
- public static class CellLayoutAnimationController extends LayoutAnimationController {
- public CellLayoutAnimationController(Animation animation, float delay) {
- super(animation, delay);
- }
-
- @Override
- protected long getDelayForView(View view) {
- return (int) (Math.random() * 150);
- }
- }
-
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
/**
* Horizontal location of the item in the grid.
@@ -3237,7 +2961,7 @@ out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
// 2. When long clicking on an empty cell in a CellLayout, we save information about the
// cellX and cellY coordinates and which page was clicked. We then set this as a tag on
// the CellLayout that was long clicked
- static final class CellInfo {
+ public static final class CellInfo {
View cell;
int cellX = -1;
int cellY = -1;
@@ -3246,7 +2970,7 @@ out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
long screenId;
long container;
- CellInfo(View v, ItemInfo info) {
+ public CellInfo(View v, ItemInfo info) {
cell = v;
cellX = info.cellX;
cellY = info.cellY;
@@ -3263,7 +2987,24 @@ out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
}
}
- public boolean lastDownOnOccupiedCell() {
- return mLastDownOnOccupiedCell;
+ public boolean findVacantCell(int spanX, int spanY, int[] outXY) {
+ return Utilities.findVacantCell(outXY, spanX, spanY, mCountX, mCountY, mOccupied);
+ }
+
+ public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
+ int x2 = x + spanX - 1;
+ int y2 = y + spanY - 1;
+ if (x < 0 || y < 0 || x2 >= mCountX || y2 >= mCountY) {
+ return false;
+ }
+ for (int i = x; i <= x2; i++) {
+ for (int j = y; j <= y2; j++) {
+ if (mOccupied[i][j]) {
+ return false;
+ }
+ }
+ }
+
+ return true;
}
}
diff --git a/src/com/android/launcher3/CheckLongPressHelper.java b/src/com/android/launcher3/CheckLongPressHelper.java
index 81149793df..483c62249e 100644
--- a/src/com/android/launcher3/CheckLongPressHelper.java
+++ b/src/com/android/launcher3/CheckLongPressHelper.java
@@ -18,16 +18,27 @@ package com.android.launcher3;
import android.view.View;
+import com.android.launcher3.util.Thunk;
+
public class CheckLongPressHelper {
- private View mView;
- private boolean mHasPerformedLongPress;
+
+ @Thunk View mView;
+ @Thunk View.OnLongClickListener mListener;
+ @Thunk boolean mHasPerformedLongPress;
+ private int mLongPressTimeout = 300;
private CheckForLongPress mPendingCheckForLongPress;
class CheckForLongPress implements Runnable {
public void run() {
if ((mView.getParent() != null) && mView.hasWindowFocus()
&& !mHasPerformedLongPress) {
- if (mView.performLongClick()) {
+ boolean handled;
+ if (mListener != null) {
+ handled = mListener.onLongClick(mView);
+ } else {
+ handled = mView.performLongClick();
+ }
+ if (handled) {
mView.setPressed(false);
mHasPerformedLongPress = true;
}
@@ -39,14 +50,25 @@ public class CheckLongPressHelper {
mView = v;
}
+ public CheckLongPressHelper(View v, View.OnLongClickListener listener) {
+ mView = v;
+ mListener = listener;
+ }
+
+ /**
+ * Overrides the default long press timeout.
+ */
+ public void setLongPressTimeout(int longPressTimeout) {
+ mLongPressTimeout = longPressTimeout;
+ }
+
public void postCheckForLongPress() {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
- mView.postDelayed(mPendingCheckForLongPress,
- LauncherAppState.getInstance().getLongPressTimeout());
+ mView.postDelayed(mPendingCheckForLongPress, mLongPressTimeout);
}
public void cancelLongPress() {
diff --git a/src/com/android/launcher3/ClickShadowView.java b/src/com/android/launcher3/ClickShadowView.java
new file mode 100644
index 0000000000..e31d7f7f63
--- /dev/null
+++ b/src/com/android/launcher3/ClickShadowView.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2014 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.Context;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.view.View;
+import android.view.ViewGroup;
+
+public class ClickShadowView extends View {
+
+ private static final int SHADOW_SIZE_FACTOR = 3;
+ private static final int SHADOW_LOW_ALPHA = 30;
+ private static final int SHADOW_HIGH_ALPHA = 60;
+
+ private final Paint mPaint;
+
+ private final float mShadowOffset;
+ private final float mShadowPadding;
+
+ private Bitmap mBitmap;
+
+ public ClickShadowView(Context context) {
+ super(context);
+ mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
+ mPaint.setColor(Color.BLACK);
+
+ mShadowPadding = getResources().getDimension(R.dimen.blur_size_click_shadow);
+ mShadowOffset = getResources().getDimension(R.dimen.click_shadow_high_shift);
+ }
+
+ /**
+ * @return extra space required by the view to show the shadow.
+ */
+ public int getExtraSize() {
+ return (int) (SHADOW_SIZE_FACTOR * mShadowPadding);
+ }
+
+ /**
+ * Applies the new bitmap.
+ * @return true if the view was invalidated.
+ */
+ public boolean setBitmap(Bitmap b) {
+ if (b != mBitmap){
+ mBitmap = b;
+ invalidate();
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+ if (mBitmap != null) {
+ mPaint.setAlpha(SHADOW_LOW_ALPHA);
+ canvas.drawBitmap(mBitmap, 0, 0, mPaint);
+ mPaint.setAlpha(SHADOW_HIGH_ALPHA);
+ canvas.drawBitmap(mBitmap, 0, mShadowOffset, mPaint);
+ }
+ }
+
+ public void animateShadow() {
+ setAlpha(0);
+ animate().alpha(1)
+ .setDuration(FastBitmapDrawable.CLICK_FEEDBACK_DURATION)
+ .setInterpolator(FastBitmapDrawable.CLICK_FEEDBACK_INTERPOLATOR)
+ .start();
+ }
+
+ /**
+ * Aligns the shadow with {@param view}
+ * @param viewParent immediate parent of {@param view}. It must be a sibling of this view.
+ */
+ public void alignWithIconView(BubbleTextView view, ViewGroup viewParent) {
+ float leftShift = view.getLeft() + viewParent.getLeft() - getLeft();
+ float topShift = view.getTop() + viewParent.getTop() - getTop();
+ int iconWidth = view.getRight() - view.getLeft();
+ int iconHSpace = iconWidth - view.getCompoundPaddingRight() - view.getCompoundPaddingLeft();
+ float drawableWidth = view.getIcon().getBounds().width();
+
+ setTranslationX(leftShift
+ + viewParent.getTranslationX()
+ + view.getCompoundPaddingLeft() * view.getScaleX()
+ + (iconHSpace - drawableWidth) * view.getScaleX() / 2 /* drawable gap */
+ + iconWidth * (1 - view.getScaleX()) / 2 /* gap due to scale */
+ - mShadowPadding /* extra shadow size */
+ );
+ setTranslationY(topShift
+ + viewParent.getTranslationY()
+ + view.getPaddingTop() * view.getScaleY() /* drawable gap */
+ + view.getHeight() * (1 - view.getScaleY()) / 2 /* gap due to scale */
+ - mShadowPadding /* extra shadow size */
+ );
+ }
+}
diff --git a/src/com/android/launcher3/CommonAppTypeParser.java b/src/com/android/launcher3/CommonAppTypeParser.java
new file mode 100644
index 0000000000..5314ecff17
--- /dev/null
+++ b/src/com/android/launcher3/CommonAppTypeParser.java
@@ -0,0 +1,153 @@
+/*
+ * 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.content.ContentValues;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.XmlResourceParser;
+import android.database.sqlite.SQLiteDatabase;
+import android.util.Log;
+
+import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
+import com.android.launcher3.LauncherSettings.Favorites;
+import com.android.launcher3.backup.BackupProtos.Favorite;
+import com.android.launcher3.util.Thunk;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+
+/**
+ * A class that parses content values corresponding to some common app types.
+ */
+public class CommonAppTypeParser implements LayoutParserCallback {
+ private static final String TAG = "CommonAppTypeParser";
+
+ // Including TARGET_NONE
+ public static final int SUPPORTED_TYPE_COUNT = 7;
+
+ private static final int RESTORE_FLAG_BIT_SHIFT = 4;
+
+
+ private final long mItemId;
+ @Thunk final int mResId;
+ @Thunk final Context mContext;
+
+ ContentValues parsedValues;
+ Intent parsedIntent;
+ String parsedTitle;
+
+ public CommonAppTypeParser(long itemId, int itemType, Context context) {
+ mItemId = itemId;
+ mContext = context;
+ mResId = getResourceForItemType(itemType);
+ }
+
+ @Override
+ public long generateNewItemId() {
+ return mItemId;
+ }
+
+ @Override
+ public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
+ parsedValues = values;
+
+ // Remove unwanted values
+ values.put(Favorites.ICON_TYPE, (Integer) null);
+ values.put(Favorites.ICON_PACKAGE, (String) null);
+ values.put(Favorites.ICON_RESOURCE, (String) null);
+ values.put(Favorites.ICON, (byte[]) null);
+ return 1;
+ }
+
+ /**
+ * Tries to find a suitable app to the provided app type.
+ */
+ public boolean findDefaultApp() {
+ if (mResId == 0) {
+ return false;
+ }
+
+ parsedIntent = null;
+ parsedValues = null;
+ new MyLayoutParser().parseValues();
+ return (parsedValues != null) && (parsedIntent != null);
+ }
+
+ private class MyLayoutParser extends DefaultLayoutParser {
+
+ public MyLayoutParser() {
+ super(CommonAppTypeParser.this.mContext, null, CommonAppTypeParser.this,
+ CommonAppTypeParser.this.mContext.getResources(), mResId, TAG_RESOLVE, 0);
+ }
+
+ @Override
+ protected long addShortcut(String title, Intent intent, int type) {
+ if (type == Favorites.ITEM_TYPE_APPLICATION) {
+ parsedIntent = intent;
+ parsedTitle = title;
+ }
+ return super.addShortcut(title, intent, type);
+ }
+
+ public void parseValues() {
+ XmlResourceParser parser = mSourceRes.getXml(mLayoutId);
+ try {
+ beginDocument(parser, mRootTag);
+ new ResolveParser().parseAndAdd(parser);
+ } catch (IOException | XmlPullParserException e) {
+ Log.e(TAG, "Unable to parse default app info", e);
+ }
+ parser.close();
+ }
+ }
+
+ public static int getResourceForItemType(int type) {
+ switch (type) {
+ case Favorite.TARGET_PHONE:
+ return R.xml.app_target_phone;
+
+ case Favorite.TARGET_MESSENGER:
+ return R.xml.app_target_messenger;
+
+ case Favorite.TARGET_EMAIL:
+ return R.xml.app_target_email;
+
+ case Favorite.TARGET_BROWSER:
+ return R.xml.app_target_browser;
+
+ case Favorite.TARGET_GALLERY:
+ return R.xml.app_target_gallery;
+
+ case Favorite.TARGET_CAMERA:
+ return R.xml.app_target_camera;
+
+ default:
+ return 0;
+ }
+ }
+
+ public static int encodeItemTypeToFlag(int itemType) {
+ return itemType << RESTORE_FLAG_BIT_SHIFT;
+ }
+
+ public static int decodeItemTypeFromFlag(int flag) {
+ return (flag & ShortcutInfo.FLAG_RESTORED_APP_TYPE) >> RESTORE_FLAG_BIT_SHIFT;
+ }
+
+}
diff --git a/src/com/android/launcher3/CustomAppWidget.java b/src/com/android/launcher3/CustomAppWidget.java
new file mode 100644
index 0000000000..1b4ed79c0b
--- /dev/null
+++ b/src/com/android/launcher3/CustomAppWidget.java
@@ -0,0 +1,14 @@
+package com.android.launcher3;
+
+public interface CustomAppWidget {
+ public String getLabel();
+ public int getPreviewImage();
+ public int getIcon();
+ public int getWidgetLayout();
+
+ public int getSpanX();
+ public int getSpanY();
+ public int getMinSpanX();
+ public int getMinSpanY();
+ public int getResizeMode();
+}
diff --git a/src/com/android/launcher3/DefaultLayoutParser.java b/src/com/android/launcher3/DefaultLayoutParser.java
index e3ea40ebb8..7b91c675be 100644
--- a/src/com/android/launcher3/DefaultLayoutParser.java
+++ b/src/com/android/launcher3/DefaultLayoutParser.java
@@ -13,13 +13,13 @@ import android.text.TextUtils;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -29,17 +29,15 @@ import java.util.List;
public class DefaultLayoutParser extends AutoInstallsLayout {
private static final String TAG = "DefaultLayoutParser";
- private static final String TAG_RESOLVE = "resolve";
+ protected static final String TAG_RESOLVE = "resolve";
private static final String TAG_FAVORITES = "favorites";
- private static final String TAG_FAVORITE = "favorite";
+ protected static final String TAG_FAVORITE = "favorite";
private static final String TAG_APPWIDGET = "appwidget";
private static final String TAG_SHORTCUT = "shortcut";
private static final String TAG_FOLDER = "folder";
private static final String TAG_PARTNER_FOLDER = "partner-folder";
- private static final String TAG_INCLUDE = "include";
- private static final String ATTR_URI = "uri";
- private static final String ATTR_WORKSPACE = "workspace";
+ protected static final String ATTR_URI = "uri";
private static final String ATTR_CONTAINER = "container";
private static final String ATTR_SCREEN = "screen";
private static final String ATTR_FOLDER_ITEMS = "folderItems";
@@ -47,7 +45,12 @@ public class DefaultLayoutParser extends AutoInstallsLayout {
public DefaultLayoutParser(Context context, AppWidgetHost appWidgetHost,
LayoutParserCallback callback, Resources sourceRes, int layoutId) {
super(context, appWidgetHost, callback, sourceRes, layoutId, TAG_FAVORITES);
- Log.e(TAG, "Default layout parser initialized");
+ }
+
+ public DefaultLayoutParser(Context context, AppWidgetHost appWidgetHost,
+ LayoutParserCallback callback, Resources sourceRes, int layoutId, String rootTag,
+ int hotseatAllAppsRank) {
+ super(context, appWidgetHost, callback, sourceRes, layoutId, rootTag, hotseatAllAppsRank);
}
@Override
@@ -55,7 +58,7 @@ public class DefaultLayoutParser extends AutoInstallsLayout {
return getFolderElementsMap(mSourceRes);
}
- private HashMap getFolderElementsMap(Resources res) {
+ @Thunk HashMap getFolderElementsMap(Resources res) {
HashMap parsers = new HashMap();
parsers.put(TAG_FAVORITE, new AppShortcutWithUriParser());
parsers.put(TAG_SHORTCUT, new UriShortcutParser(res));
@@ -84,29 +87,10 @@ public class DefaultLayoutParser extends AutoInstallsLayout {
out[1] = Long.parseLong(getAttributeValue(parser, ATTR_SCREEN));
}
- @Override
- protected int parseAndAddNode(
- XmlResourceParser parser,
- HashMap tagParserMap,
- ArrayList screenIds)
- throws XmlPullParserException, IOException {
- if (TAG_INCLUDE.equals(parser.getName())) {
- final int resId = getAttributeResourceValue(parser, ATTR_WORKSPACE, 0);
- if (resId != 0) {
- // recursively load some more favorites, why not?
- return parseLayout(resId, screenIds);
- } else {
- return 0;
- }
- } else {
- return super.parseAndAddNode(parser, tagParserMap, screenIds);
- }
- }
-
/**
* AppShortcutParser which also supports adding URI based intents
*/
- private class AppShortcutWithUriParser extends AppShortcutParser {
+ @Thunk class AppShortcutWithUriParser extends AppShortcutParser {
@Override
protected long invalidPackageOrClass(XmlResourceParser parser) {
@@ -218,7 +202,7 @@ public class DefaultLayoutParser extends AutoInstallsLayout {
/**
* Contains a list of nodes, and accepts the first successfully parsed node.
*/
- private class ResolveParser implements TagParser {
+ protected class ResolveParser implements TagParser {
private final AppShortcutWithUriParser mChildParser = new AppShortcutWithUriParser();
@@ -248,7 +232,7 @@ public class DefaultLayoutParser extends AutoInstallsLayout {
/**
* A parser which adds a folder whose contents come from partner apk.
*/
- private class PartnerFolderParser implements TagParser {
+ @Thunk class PartnerFolderParser implements TagParser {
@Override
public long parseAndAdd(XmlResourceParser parser) throws XmlPullParserException,
@@ -274,7 +258,7 @@ public class DefaultLayoutParser extends AutoInstallsLayout {
/**
* An extension of FolderParser which allows adding items from a different xml.
*/
- private class MyFolderParser extends FolderParser {
+ @Thunk class MyFolderParser extends FolderParser {
@Override
public long parseAndAdd(XmlResourceParser parser) throws XmlPullParserException,
diff --git a/src/com/android/launcher3/DeferredHandler.java b/src/com/android/launcher3/DeferredHandler.java
index a2d121d635..a43ab67239 100644
--- a/src/com/android/launcher3/DeferredHandler.java
+++ b/src/com/android/launcher3/DeferredHandler.java
@@ -20,10 +20,10 @@ import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
-import android.util.Pair;
+
+import com.android.launcher3.util.Thunk;
import java.util.LinkedList;
-import java.util.ListIterator;
/**
* Queue of things to run on a looper thread. Items posted with {@link #post} will not
@@ -33,20 +33,18 @@ import java.util.ListIterator;
* This class is fifo.
*/
public class DeferredHandler {
- private LinkedList> mQueue = new LinkedList>();
+ @Thunk LinkedList mQueue = new LinkedList<>();
private MessageQueue mMessageQueue = Looper.myQueue();
private Impl mHandler = new Impl();
- private class Impl extends Handler implements MessageQueue.IdleHandler {
+ @Thunk class Impl extends Handler implements MessageQueue.IdleHandler {
public void handleMessage(Message msg) {
- Pair p;
Runnable r;
synchronized (mQueue) {
if (mQueue.size() == 0) {
return;
}
- p = mQueue.removeFirst();
- r = p.first;
+ r = mQueue.removeFirst();
}
r.run();
synchronized (mQueue) {
@@ -77,11 +75,8 @@ public class DeferredHandler {
/** Schedule runnable to run after everything that's on the queue right now. */
public void post(Runnable runnable) {
- post(runnable, 0);
- }
- public void post(Runnable runnable, int type) {
synchronized (mQueue) {
- mQueue.add(new Pair(runnable, type));
+ mQueue.add(runnable);
if (mQueue.size() == 1) {
scheduleNextLocked();
}
@@ -90,31 +85,10 @@ public class DeferredHandler {
/** Schedule runnable to run when the queue goes idle. */
public void postIdle(final Runnable runnable) {
- postIdle(runnable, 0);
- }
- public void postIdle(final Runnable runnable, int type) {
- post(new IdleRunnable(runnable), type);
+ post(new IdleRunnable(runnable));
}
- public void cancelRunnable(Runnable runnable) {
- synchronized (mQueue) {
- while (mQueue.remove(runnable)) { }
- }
- }
- public void cancelAllRunnablesOfType(int type) {
- synchronized (mQueue) {
- ListIterator> iter = mQueue.listIterator();
- Pair p;
- while (iter.hasNext()) {
- p = iter.next();
- if (p.second == type) {
- iter.remove();
- }
- }
- }
- }
-
- public void cancel() {
+ public void cancelAll() {
synchronized (mQueue) {
mQueue.clear();
}
@@ -122,20 +96,19 @@ public class DeferredHandler {
/** Runs all queued Runnables from the calling thread. */
public void flush() {
- LinkedList> queue = new LinkedList>();
+ LinkedList queue = new LinkedList<>();
synchronized (mQueue) {
queue.addAll(mQueue);
mQueue.clear();
}
- for (Pair p : queue) {
- p.first.run();
+ for (Runnable r : queue) {
+ r.run();
}
}
void scheduleNextLocked() {
if (mQueue.size() > 0) {
- Pair p = mQueue.getFirst();
- Runnable peek = p.first;
+ Runnable peek = mQueue.getFirst();
if (peek instanceof IdleRunnable) {
mMessageQueue.addIdleHandler(mHandler);
} else {
diff --git a/src/com/android/launcher3/DeleteDropTarget.java b/src/com/android/launcher3/DeleteDropTarget.java
index ea058ea71a..9c8659c293 100644
--- a/src/com/android/launcher3/DeleteDropTarget.java
+++ b/src/com/android/launcher3/DeleteDropTarget.java
@@ -17,45 +17,17 @@
package com.android.launcher3;
import android.animation.TimeInterpolator;
-import android.animation.ValueAnimator;
-import android.animation.ValueAnimator.AnimatorUpdateListener;
-import android.content.ComponentName;
import android.content.Context;
-import android.content.res.ColorStateList;
-import android.content.res.Configuration;
-import android.content.res.Resources;
import android.graphics.PointF;
-import android.graphics.Rect;
-import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.UserManager;
import android.util.AttributeSet;
import android.view.View;
-import android.view.ViewConfiguration;
-import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
-import android.view.animation.DecelerateInterpolator;
-import android.view.animation.LinearInterpolator;
-import com.android.launcher3.compat.UserHandleCompat;
+import com.android.launcher3.util.FlingAnimation;
+import com.android.launcher3.util.Thunk;
public class DeleteDropTarget extends ButtonDropTarget {
- private static int DELETE_ANIMATION_DURATION = 285;
- private static int FLING_DELETE_ANIMATION_DURATION = 350;
- private static float FLING_TO_DELETE_FRICTION = 0.035f;
- private static int MODE_FLING_DELETE_TO_TRASH = 0;
- private static int MODE_FLING_DELETE_ALONG_VECTOR = 1;
-
- private final int mFlingDeleteMode = MODE_FLING_DELETE_ALONG_VECTOR;
-
- private ColorStateList mOriginalTextColor;
- private TransitionDrawable mUninstallDrawable;
- private TransitionDrawable mRemoveDrawable;
- private TransitionDrawable mCurrentDrawable;
-
- private boolean mWaitingForUninstall = false;
public DeleteDropTarget(Context context, AttributeSet attrs) {
this(context, attrs, 0);
@@ -68,442 +40,86 @@ public class DeleteDropTarget extends ButtonDropTarget {
@Override
protected void onFinishInflate() {
super.onFinishInflate();
-
- // Get the drawable
- mOriginalTextColor = getTextColors();
-
// Get the hover color
- Resources r = getResources();
- mHoverColor = r.getColor(R.color.delete_target_hover_tint);
- mUninstallDrawable = (TransitionDrawable)
- r.getDrawable(R.drawable.uninstall_target_selector);
- mRemoveDrawable = (TransitionDrawable) r.getDrawable(R.drawable.remove_target_selector);
+ mHoverColor = getResources().getColor(R.color.delete_target_hover_tint);
- mRemoveDrawable.setCrossFadeEnabled(true);
- mUninstallDrawable.setCrossFadeEnabled(true);
-
- // The current drawable is set to either the remove drawable or the uninstall drawable
- // and is initially set to the remove drawable, as set in the layout xml.
- mCurrentDrawable = (TransitionDrawable) getCurrentDrawable();
-
- // Remove the text in the Phone UI in landscape
- int orientation = getResources().getConfiguration().orientation;
- if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
- if (!LauncherAppState.getInstance().isScreenLarge()) {
- setText("");
- }
- }
+ setDrawable(R.drawable.ic_remove_launcher);
}
- private boolean isAllAppsApplication(DragSource source, Object info) {
- return source.supportsAppInfoDropTarget() && (info instanceof AppInfo);
- }
- private boolean isAllAppsWidget(DragSource source, Object info) {
- if (source instanceof AppsCustomizePagedView) {
- if (info instanceof PendingAddItemInfo) {
- PendingAddItemInfo addInfo = (PendingAddItemInfo) info;
- switch (addInfo.itemType) {
- case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
- case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
- return true;
- }
- }
- }
- return false;
- }
- private boolean isDragSourceWorkspaceOrFolder(DragObject d) {
- return (d.dragSource instanceof Workspace) || (d.dragSource instanceof Folder);
- }
- private boolean isWorkspaceOrFolderApplication(DragObject d) {
- return isDragSourceWorkspaceOrFolder(d) && (d.dragInfo instanceof ShortcutInfo);
- }
- private boolean isWorkspaceOrFolderWidget(DragObject d) {
- return isDragSourceWorkspaceOrFolder(d) && (d.dragInfo instanceof LauncherAppWidgetInfo);
- }
- private boolean isWorkspaceFolder(DragObject d) {
- return (d.dragSource instanceof Workspace) && (d.dragInfo instanceof FolderInfo);
- }
-
- private void setHoverColor() {
- if (mCurrentDrawable != null) {
- mCurrentDrawable.startTransition(mTransitionDuration);
- }
- setTextColor(mHoverColor);
- }
- private void resetHoverColor() {
- if (mCurrentDrawable != null) {
- mCurrentDrawable.resetTransition();
- }
- setTextColor(mOriginalTextColor);
+ public static boolean supportsDrop(Object info) {
+ return (info instanceof ShortcutInfo)
+ || (info instanceof LauncherAppWidgetInfo)
+ || (info instanceof FolderInfo);
}
@Override
- public boolean acceptDrop(DragObject d) {
- return willAcceptDrop(d.dragInfo);
- }
-
- public static boolean willAcceptDrop(Object info) {
- if (info instanceof ItemInfo) {
- ItemInfo item = (ItemInfo) info;
- if (item.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET ||
- item.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
- return true;
- }
-
- if (!LauncherAppState.isDisableAllApps() &&
- item.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
- return true;
- }
-
- if (!LauncherAppState.isDisableAllApps() &&
- item.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
- item instanceof AppInfo) {
- AppInfo appInfo = (AppInfo) info;
- return (appInfo.flags & AppInfo.DOWNLOADED_FLAG) != 0;
- }
-
- if (item.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
- item instanceof ShortcutInfo) {
- if (LauncherAppState.isDisableAllApps()) {
- ShortcutInfo shortcutInfo = (ShortcutInfo) info;
- return (shortcutInfo.flags & AppInfo.DOWNLOADED_FLAG) != 0;
- } else {
- return true;
- }
- }
- }
- return false;
+ protected boolean supportsDrop(DragSource source, Object info) {
+ return source.supportsDeleteDropTarget() && supportsDrop(info);
}
@Override
- public void onDragStart(DragSource source, Object info, int dragAction) {
- boolean isVisible = true;
- boolean useUninstallLabel = !LauncherAppState.isDisableAllApps() &&
- isAllAppsApplication(source, info);
- boolean useDeleteLabel = !useUninstallLabel && source.supportsDeleteDropTarget();
-
- // If we are dragging an application from AppsCustomize, only show the control if we can
- // delete the app (it was downloaded), and rename the string to "uninstall" in such a case.
- // Hide the delete target if it is a widget from AppsCustomize.
- if (!willAcceptDrop(info) || isAllAppsWidget(source, info)) {
- isVisible = false;
- }
- if (useUninstallLabel) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
- UserManager userManager = (UserManager)
- getContext().getSystemService(Context.USER_SERVICE);
- Bundle restrictions = userManager.getUserRestrictions();
- if (restrictions.getBoolean(UserManager.DISALLOW_APPS_CONTROL, false)
- || restrictions.getBoolean(UserManager.DISALLOW_UNINSTALL_APPS, false)) {
- isVisible = false;
- }
- }
- }
-
- if (useUninstallLabel) {
- setCompoundDrawablesRelativeWithIntrinsicBounds(mUninstallDrawable, null, null, null);
- } else if (useDeleteLabel) {
- setCompoundDrawablesRelativeWithIntrinsicBounds(mRemoveDrawable, null, null, null);
- } else {
- isVisible = false;
- }
- mCurrentDrawable = (TransitionDrawable) getCurrentDrawable();
-
- mActive = isVisible;
- resetHoverColor();
- ((ViewGroup) getParent()).setVisibility(isVisible ? View.VISIBLE : View.GONE);
- if (isVisible && getText().length() > 0) {
- setText(useUninstallLabel ? R.string.delete_target_uninstall_label
- : R.string.delete_target_label);
- }
- }
-
- @Override
- public void onDragEnd() {
- super.onDragEnd();
- mActive = false;
- }
-
- public void onDragEnter(DragObject d) {
- super.onDragEnter(d);
-
- setHoverColor();
- }
-
- public void onDragExit(DragObject d) {
- super.onDragExit(d);
-
- if (!d.dragComplete) {
- resetHoverColor();
- } else {
- // Restore the hover color if we are deleting
- d.dragView.setColor(mHoverColor);
- }
- }
-
- private void animateToTrashAndCompleteDrop(final DragObject d) {
- final DragLayer dragLayer = mLauncher.getDragLayer();
- final Rect from = new Rect();
- dragLayer.getViewRectRelativeToSelf(d.dragView, from);
-
- int width = mCurrentDrawable == null ? 0 : mCurrentDrawable.getIntrinsicWidth();
- int height = mCurrentDrawable == null ? 0 : mCurrentDrawable.getIntrinsicHeight();
- final Rect to = getIconRect(d.dragView.getMeasuredWidth(), d.dragView.getMeasuredHeight(),
- width, height);
- final float scale = (float) to.width() / from.width();
-
- mSearchDropTargetBar.deferOnDragEnd();
- deferCompleteDropIfUninstalling(d);
-
- Runnable onAnimationEndRunnable = new Runnable() {
- @Override
- public void run() {
- completeDrop(d);
- mSearchDropTargetBar.onDragEnd();
- mLauncher.exitSpringLoadedDragModeDelayed(true, 0, null);
- }
- };
- dragLayer.animateView(d.dragView, from, to, scale, 1f, 1f, 0.1f, 0.1f,
- DELETE_ANIMATION_DURATION, new DecelerateInterpolator(2),
- new LinearInterpolator(), onAnimationEndRunnable,
- DragLayer.ANIMATION_END_DISAPPEAR, null);
- }
-
- private void deferCompleteDropIfUninstalling(DragObject d) {
- mWaitingForUninstall = false;
- if (isUninstallFromWorkspace(d)) {
- if (d.dragSource instanceof Folder) {
- ((Folder) d.dragSource).deferCompleteDropAfterUninstallActivity();
- } else if (d.dragSource instanceof Workspace) {
- ((Workspace) d.dragSource).deferCompleteDropAfterUninstallActivity();
- }
- mWaitingForUninstall = true;
- }
- }
-
- private boolean isUninstallFromWorkspace(DragObject d) {
- if (LauncherAppState.isDisableAllApps() && isWorkspaceOrFolderApplication(d)) {
- ShortcutInfo shortcut = (ShortcutInfo) d.dragInfo;
- // Only allow manifest shortcuts to initiate an un-install.
- return !InstallShortcutReceiver.isValidShortcutLaunchIntent(shortcut.intent);
- }
- return false;
- }
-
- private void completeDrop(DragObject d) {
+ @Thunk void completeDrop(DragObject d) {
ItemInfo item = (ItemInfo) d.dragInfo;
- boolean wasWaitingForUninstall = mWaitingForUninstall;
- mWaitingForUninstall = false;
- if (isAllAppsApplication(d.dragSource, item)) {
- // Uninstall the application if it is being dragged from AppsCustomize
- AppInfo appInfo = (AppInfo) item;
- mLauncher.startApplicationUninstallActivity(appInfo.componentName, appInfo.flags,
- appInfo.user);
- } else if (isUninstallFromWorkspace(d)) {
- ShortcutInfo shortcut = (ShortcutInfo) item;
- if (shortcut.intent != null && shortcut.intent.getComponent() != null) {
- final ComponentName componentName = shortcut.intent.getComponent();
- final DragSource dragSource = d.dragSource;
- final UserHandleCompat user = shortcut.user;
- mWaitingForUninstall = mLauncher.startApplicationUninstallActivity(
- componentName, shortcut.flags, user);
- if (mWaitingForUninstall) {
- final Runnable checkIfUninstallWasSuccess = new Runnable() {
- @Override
- public void run() {
- mWaitingForUninstall = false;
- String packageName = componentName.getPackageName();
- boolean uninstallSuccessful = !AllAppsList.packageHasActivities(
- getContext(), packageName, user);
- if (dragSource instanceof Folder) {
- ((Folder) dragSource).
- onUninstallActivityReturned(uninstallSuccessful);
- } else if (dragSource instanceof Workspace) {
- ((Workspace) dragSource).
- onUninstallActivityReturned(uninstallSuccessful);
- }
- }
- };
- mLauncher.addOnResumeCallback(checkIfUninstallWasSuccess);
- }
- }
- } else if (isWorkspaceOrFolderApplication(d)) {
- LauncherModel.deleteItemFromDatabase(mLauncher, item);
- } else if (isWorkspaceFolder(d)) {
- // Remove the folder from the workspace and delete the contents from launcher model
- FolderInfo folderInfo = (FolderInfo) item;
- mLauncher.removeFolder(folderInfo);
- LauncherModel.deleteFolderContentsFromDatabase(mLauncher, folderInfo);
- } else if (isWorkspaceOrFolderWidget(d)) {
- // Remove the widget from the workspace
- mLauncher.removeAppWidget((LauncherAppWidgetInfo) item);
- LauncherModel.deleteItemFromDatabase(mLauncher, item);
+ if ((d.dragSource instanceof Workspace) || (d.dragSource instanceof Folder)) {
+ removeWorkspaceOrFolderItem(mLauncher, item, null);
+ }
+ }
- final LauncherAppWidgetInfo launcherAppWidgetInfo = (LauncherAppWidgetInfo) item;
- final LauncherAppWidgetHost appWidgetHost = mLauncher.getAppWidgetHost();
- if ((appWidgetHost != null) && launcherAppWidgetInfo.isWidgetIdValid()) {
+ /**
+ * Removes the item from the workspace. If the view is not null, it also removes the view.
+ * @return true if the item was removed.
+ */
+ public static boolean removeWorkspaceOrFolderItem(Launcher launcher, ItemInfo item, View view) {
+ if (item instanceof ShortcutInfo) {
+ LauncherModel.deleteItemFromDatabase(launcher, item);
+ } else if (item instanceof FolderInfo) {
+ FolderInfo folder = (FolderInfo) item;
+ launcher.removeFolder(folder);
+ LauncherModel.deleteFolderContentsFromDatabase(launcher, folder);
+ } else if (item instanceof LauncherAppWidgetInfo) {
+ final LauncherAppWidgetInfo widget = (LauncherAppWidgetInfo) item;
+
+ // Remove the widget from the workspace
+ launcher.removeAppWidget(widget);
+ LauncherModel.deleteItemFromDatabase(launcher, widget);
+
+ final LauncherAppWidgetHost appWidgetHost = launcher.getAppWidgetHost();
+
+ if (appWidgetHost != null && !widget.isCustomWidget()
+ && widget.isWidgetIdValid()) {
// Deleting an app widget ID is a void call but writes to disk before returning
// to the caller...
new AsyncTask() {
public Void doInBackground(Void ... args) {
- appWidgetHost.deleteAppWidgetId(launcherAppWidgetInfo.appWidgetId);
+ appWidgetHost.deleteAppWidgetId(widget.appWidgetId);
return null;
}
- }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
+ }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
- }
- if (wasWaitingForUninstall && !mWaitingForUninstall) {
- if (d.dragSource instanceof Folder) {
- ((Folder) d.dragSource).onUninstallActivityReturned(false);
- } else if (d.dragSource instanceof Workspace) {
- ((Workspace) d.dragSource).onUninstallActivityReturned(false);
- }
- }
- }
-
- public void onDrop(DragObject d) {
- animateToTrashAndCompleteDrop(d);
- }
-
- /**
- * Creates an animation from the current drag view to the delete trash icon.
- */
- private AnimatorUpdateListener createFlingToTrashAnimatorListener(final DragLayer dragLayer,
- DragObject d, PointF vel, ViewConfiguration config) {
-
- int width = mCurrentDrawable == null ? 0 : mCurrentDrawable.getIntrinsicWidth();
- int height = mCurrentDrawable == null ? 0 : mCurrentDrawable.getIntrinsicHeight();
- final Rect to = getIconRect(d.dragView.getMeasuredWidth(), d.dragView.getMeasuredHeight(),
- width, height);
- final Rect from = new Rect();
- dragLayer.getViewRectRelativeToSelf(d.dragView, from);
-
- // Calculate how far along the velocity vector we should put the intermediate point on
- // the bezier curve
- float velocity = Math.abs(vel.length());
- float vp = Math.min(1f, velocity / (config.getScaledMaximumFlingVelocity() / 2f));
- int offsetY = (int) (-from.top * vp);
- int offsetX = (int) (offsetY / (vel.y / vel.x));
- final float y2 = from.top + offsetY; // intermediate t/l
- final float x2 = from.left + offsetX;
- final float x1 = from.left; // drag view t/l
- final float y1 = from.top;
- final float x3 = to.left; // delete target t/l
- final float y3 = to.top;
-
- final TimeInterpolator scaleAlphaInterpolator = new TimeInterpolator() {
- @Override
- public float getInterpolation(float t) {
- return t * t * t * t * t * t * t * t;
- }
- };
- return new AnimatorUpdateListener() {
- @Override
- public void onAnimationUpdate(ValueAnimator animation) {
- final DragView dragView = (DragView) dragLayer.getAnimatedView();
- float t = ((Float) animation.getAnimatedValue()).floatValue();
- float tp = scaleAlphaInterpolator.getInterpolation(t);
- float initialScale = dragView.getInitialScale();
- float finalAlpha = 0.5f;
- float scale = dragView.getScaleX();
- float x1o = ((1f - scale) * dragView.getMeasuredWidth()) / 2f;
- float y1o = ((1f - scale) * dragView.getMeasuredHeight()) / 2f;
- float x = (1f - t) * (1f - t) * (x1 - x1o) + 2 * (1f - t) * t * (x2 - x1o) +
- (t * t) * x3;
- float y = (1f - t) * (1f - t) * (y1 - y1o) + 2 * (1f - t) * t * (y2 - x1o) +
- (t * t) * y3;
-
- dragView.setTranslationX(x);
- dragView.setTranslationY(y);
- dragView.setScaleX(initialScale * (1f - tp));
- dragView.setScaleY(initialScale * (1f - tp));
- dragView.setAlpha(finalAlpha + (1f - finalAlpha) * (1f - tp));
- }
- };
- }
-
- /**
- * Creates an animation from the current drag view along its current velocity vector.
- * For this animation, the alpha runs for a fixed duration and we update the position
- * progressively.
- */
- private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
- private DragLayer mDragLayer;
- private PointF mVelocity;
- private Rect mFrom;
- private long mPrevTime;
- private boolean mHasOffsetForScale;
- private float mFriction;
-
- private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
-
- public FlingAlongVectorAnimatorUpdateListener(DragLayer dragLayer, PointF vel, Rect from,
- long startTime, float friction) {
- mDragLayer = dragLayer;
- mVelocity = vel;
- mFrom = from;
- mPrevTime = startTime;
- mFriction = 1f - (dragLayer.getResources().getDisplayMetrics().density * friction);
+ } else {
+ return false;
}
- @Override
- public void onAnimationUpdate(ValueAnimator animation) {
- final DragView dragView = (DragView) mDragLayer.getAnimatedView();
- float t = ((Float) animation.getAnimatedValue()).floatValue();
- long curTime = AnimationUtils.currentAnimationTimeMillis();
-
- if (!mHasOffsetForScale) {
- mHasOffsetForScale = true;
- float scale = dragView.getScaleX();
- float xOffset = ((scale - 1f) * dragView.getMeasuredWidth()) / 2f;
- float yOffset = ((scale - 1f) * dragView.getMeasuredHeight()) / 2f;
-
- mFrom.left += xOffset;
- mFrom.top += yOffset;
- }
-
- mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
- mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
-
- dragView.setTranslationX(mFrom.left);
- dragView.setTranslationY(mFrom.top);
- dragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
-
- mVelocity.x *= mFriction;
- mVelocity.y *= mFriction;
- mPrevTime = curTime;
+ if (view != null) {
+ launcher.getWorkspace().removeWorkspaceItem(view);
+ launcher.getWorkspace().stripEmptyScreens();
}
- };
- private AnimatorUpdateListener createFlingAlongVectorAnimatorListener(final DragLayer dragLayer,
- DragObject d, PointF vel, final long startTime, final int duration,
- ViewConfiguration config) {
- final Rect from = new Rect();
- dragLayer.getViewRectRelativeToSelf(d.dragView, from);
-
- return new FlingAlongVectorAnimatorUpdateListener(dragLayer, vel, from, startTime,
- FLING_TO_DELETE_FRICTION);
+ return true;
}
- public void onFlingToDelete(final DragObject d, int x, int y, PointF vel) {
- final boolean isAllApps = d.dragSource instanceof AppsCustomizePagedView;
-
+ @Override
+ public void onFlingToDelete(final DragObject d, PointF vel) {
// Don't highlight the icon as it's animating
d.dragView.setColor(0);
d.dragView.updateInitialScaleToCurrentScale();
- // Don't highlight the target if we are flinging from AllApps
- if (isAllApps) {
- resetHoverColor();
- }
- if (mFlingDeleteMode == MODE_FLING_DELETE_TO_TRASH) {
- // Defer animating out the drop target if we are animating to it
- mSearchDropTargetBar.deferOnDragEnd();
- mSearchDropTargetBar.finishAnimations();
- }
-
- final ViewConfiguration config = ViewConfiguration.get(mLauncher);
final DragLayer dragLayer = mLauncher.getDragLayer();
- final int duration = FLING_DELETE_ANIMATION_DURATION;
+ FlingAnimation fling = new FlingAnimation(d, vel,
+ getIconRect(d.dragView.getMeasuredWidth(), d.dragView.getMeasuredHeight(),
+ mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()),
+ dragLayer);
+
+ final int duration = fling.getDuration();
final long startTime = AnimationUtils.currentAnimationTimeMillis();
// NOTE: Because it takes time for the first frame of animation to actually be
@@ -527,28 +143,22 @@ public class DeleteDropTarget extends ButtonDropTarget {
return Math.min(1f, mOffset + t);
}
};
- AnimatorUpdateListener updateCb = null;
- if (mFlingDeleteMode == MODE_FLING_DELETE_TO_TRASH) {
- updateCb = createFlingToTrashAnimatorListener(dragLayer, d, vel, config);
- } else if (mFlingDeleteMode == MODE_FLING_DELETE_ALONG_VECTOR) {
- updateCb = createFlingAlongVectorAnimatorListener(dragLayer, d, vel, startTime,
- duration, config);
- }
- deferCompleteDropIfUninstalling(d);
Runnable onAnimationEndRunnable = new Runnable() {
@Override
public void run() {
- // If we are dragging from AllApps, then we allow AppsCustomizePagedView to clean up
- // itself, otherwise, complete the drop to initiate the deletion process
- if (!isAllApps) {
- mLauncher.exitSpringLoadedDragMode();
- completeDrop(d);
- }
+ mLauncher.exitSpringLoadedDragMode();
+ completeDrop(d);
mLauncher.getDragController().onDeferredEndFling(d);
}
};
- dragLayer.animateView(d.dragView, updateCb, duration, tInterpolator, onAnimationEndRunnable,
+
+ dragLayer.animateView(d.dragView, fling, duration, tInterpolator, onAnimationEndRunnable,
DragLayer.ANIMATION_END_DISAPPEAR, null);
}
+
+ @Override
+ protected String getAccessibilityDropConfirmation() {
+ return getResources().getString(R.string.item_removed);
+ }
}
diff --git a/src/com/android/launcher3/DeviceProfile.java b/src/com/android/launcher3/DeviceProfile.java
index d6aadcee1e..62b05b0d65 100644
--- a/src/com/android/launcher3/DeviceProfile.java
+++ b/src/com/android/launcher3/DeviceProfile.java
@@ -19,155 +19,103 @@ 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.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Point;
-import android.graphics.PointF;
import android.graphics.Rect;
import android.util.DisplayMetrics;
-import android.view.Display;
import android.view.Gravity;
-import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
-import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-
-
-class DeviceProfileQuery {
- DeviceProfile profile;
- float widthDps;
- float heightDps;
- float value;
- PointF dimens;
-
- DeviceProfileQuery(DeviceProfile p, float v) {
- widthDps = p.minWidthDps;
- heightDps = p.minHeightDps;
- value = v;
- dimens = new PointF(widthDps, heightDps);
- profile = p;
- }
-}
-
public class DeviceProfile {
- public static interface DeviceProfileCallbacks {
- public void onAvailableSizeChanged(DeviceProfile grid);
- }
- String name;
- float minWidthDps;
- float minHeightDps;
- float numRows;
- float numColumns;
- float numHotseatIcons;
- float iconSize;
- private float iconTextSize;
- private int iconDrawablePaddingOriginalPx;
- private float hotseatIconSize;
+ public final InvariantDeviceProfile inv;
- int defaultLayoutId;
+ // Device properties
+ public final boolean isTablet;
+ public final boolean isLargeTablet;
+ public final boolean isPhone;
+ public final boolean transposeLayoutWithOrientation;
- boolean isLandscape;
- boolean isTablet;
- boolean isLargeTablet;
- boolean isLayoutRtl;
- boolean transposeLayoutWithOrientation;
+ // Device properties in current orientation
+ public final boolean isLandscape;
+ public final int widthPx;
+ public final int heightPx;
+ public final int availableWidthPx;
+ public final int availableHeightPx;
- int desiredWorkspaceLeftRightMarginPx;
- int edgeMarginPx;
- Rect defaultWidgetPadding;
+ // Overview mode
+ private final int overviewModeMinIconZoneHeightPx;
+ private final int overviewModeMaxIconZoneHeightPx;
+ private final int overviewModeBarItemWidthPx;
+ private final int overviewModeBarSpacerWidthPx;
+ private final float overviewModeIconZoneRatio;
+ private final float overviewModeScaleFactor;
- int widthPx;
- int heightPx;
- int availableWidthPx;
- int availableHeightPx;
- int defaultPageSpacingPx;
+ // Workspace
+ private int desiredWorkspaceLeftRightMarginPx;
+ public final int edgeMarginPx;
+ public final Rect defaultWidgetPadding;
+ private final int pageIndicatorHeightPx;
+ private final int defaultPageSpacingPx;
+ private float dragViewScale;
- int overviewModeMinIconZoneHeightPx;
- int overviewModeMaxIconZoneHeightPx;
- int overviewModeBarItemWidthPx;
- int overviewModeBarSpacerWidthPx;
- float overviewModeIconZoneRatio;
- float overviewModeScaleFactor;
+ // Workspace icons
+ public int iconSizePx;
+ public int iconTextSizePx;
+ public int iconDrawablePaddingPx;
+ public int iconDrawablePaddingOriginalPx;
- int iconSizePx;
- int iconTextSizePx;
- int iconDrawablePaddingPx;
- int cellWidthPx;
- int cellHeightPx;
- int allAppsIconSizePx;
- int allAppsIconTextSizePx;
- int allAppsCellWidthPx;
- int allAppsCellHeightPx;
- int allAppsCellPaddingPx;
- int folderBackgroundOffset;
- int folderIconSizePx;
- int folderCellWidthPx;
- int folderCellHeightPx;
- int hotseatCellWidthPx;
- int hotseatCellHeightPx;
- int hotseatIconSizePx;
- int hotseatBarHeightPx;
- int hotseatAllAppsRank;
- int allAppsNumRows;
- int allAppsNumCols;
- int searchBarSpaceWidthPx;
- int searchBarSpaceHeightPx;
- int pageIndicatorHeightPx;
- int allAppsButtonVisualSize;
+ public int cellWidthPx;
+ public int cellHeightPx;
- float dragViewScale;
+ // Folder
+ public int folderBackgroundOffset;
+ public int folderIconSizePx;
+ public int folderCellWidthPx;
+ public int folderCellHeightPx;
- int allAppsShortEdgeCount = -1;
- int allAppsLongEdgeCount = -1;
+ // Hotseat
+ public int hotseatCellWidthPx;
+ public int hotseatCellHeightPx;
+ public int hotseatIconSizePx;
+ private int hotseatBarHeightPx;
- private ArrayList mCallbacks = new ArrayList();
+ // All apps
+ public int allAppsNumCols;
+ public int allAppsNumPredictiveCols;
+ public int allAppsButtonVisualSize;
+ public final int allAppsIconSizePx;
+ public final int allAppsIconTextSizePx;
- DeviceProfile(String n, float w, float h, float r, float c,
- float is, float its, float hs, float his, int dlId) {
- // Ensure that we have an odd number of hotseat items (since we need to place all apps)
- if (!LauncherAppState.isDisableAllApps() && hs % 2 == 0) {
- throw new RuntimeException("All Device Profiles must have an odd number of hotseat spaces");
- }
+ // QSB
+ private int searchBarSpaceWidthPx;
+ private int searchBarSpaceHeightPx;
- name = n;
- minWidthDps = w;
- minHeightDps = h;
- numRows = r;
- numColumns = c;
- iconSize = is;
- iconTextSize = its;
- numHotseatIcons = hs;
- hotseatIconSize = his;
- defaultLayoutId = dlId;
- }
+ public DeviceProfile(Context context, InvariantDeviceProfile inv,
+ Point minSize, Point maxSize,
+ int width, int height, boolean isLandscape) {
- DeviceProfile() {
- }
+ this.inv = inv;
+ this.isLandscape = isLandscape;
- DeviceProfile(Context context,
- ArrayList profiles,
- float minWidth, float minHeight,
- int wPx, int hPx,
- int awPx, int ahPx,
- Resources res) {
+ Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
- ArrayList points =
- new ArrayList();
+
+ // Constants from resources
+ isTablet = res.getBoolean(R.bool.is_tablet);
+ isLargeTablet = res.getBoolean(R.bool.is_large_tablet);
+ isPhone = !isTablet && !isLargeTablet;
+
+ // Some more constants
transposeLayoutWithOrientation =
res.getBoolean(R.bool.hotseat_transpose_layout_with_orientation);
- minWidthDps = minWidth;
- minHeightDps = minHeight;
ComponentName cn = new ComponentName(context.getPackageName(),
this.getClass().getName());
@@ -178,8 +126,6 @@ public class DeviceProfile {
res.getDimensionPixelSize(R.dimen.dynamic_grid_page_indicator_height);
defaultPageSpacingPx =
res.getDimensionPixelSize(R.dimen.dynamic_grid_workspace_page_spacing);
- allAppsCellPaddingPx =
- res.getDimensionPixelSize(R.dimen.dynamic_grid_all_apps_cell_padding);
overviewModeMinIconZoneHeightPx =
res.getDimensionPixelSize(R.dimen.dynamic_grid_overview_min_icon_zone_height);
overviewModeMaxIconZoneHeightPx =
@@ -192,91 +138,31 @@ public class DeviceProfile {
res.getInteger(R.integer.config_dynamic_grid_overview_icon_zone_percentage) / 100f;
overviewModeScaleFactor =
res.getInteger(R.integer.config_dynamic_grid_overview_scale_percentage) / 100f;
-
- // Find the closes profile given the width/height
- for (DeviceProfile p : profiles) {
- points.add(new DeviceProfileQuery(p, 0f));
- }
- DeviceProfile closestProfile = findClosestDeviceProfile(minWidth, minHeight, points);
-
- // Snap to the closest row count
- numRows = closestProfile.numRows;
-
- // Snap to the closest column count
- numColumns = closestProfile.numColumns;
-
- // Snap to the closest hotseat size
- numHotseatIcons = closestProfile.numHotseatIcons;
- hotseatAllAppsRank = (int) (numHotseatIcons / 2);
-
- // Snap to the closest default layout id
- defaultLayoutId = closestProfile.defaultLayoutId;
-
- // Interpolate the icon size
- points.clear();
- for (DeviceProfile p : profiles) {
- points.add(new DeviceProfileQuery(p, p.iconSize));
- }
- iconSize = invDistWeightedInterpolate(minWidth, minHeight, points);
-
- // AllApps uses the original non-scaled icon size
- allAppsIconSizePx = DynamicGrid.pxFromDp(iconSize, dm);
-
- // Interpolate the icon text size
- points.clear();
- for (DeviceProfile p : profiles) {
- points.add(new DeviceProfileQuery(p, p.iconTextSize));
- }
- iconTextSize = invDistWeightedInterpolate(minWidth, minHeight, points);
iconDrawablePaddingOriginalPx =
res.getDimensionPixelSize(R.dimen.dynamic_grid_icon_drawable_padding);
+
// AllApps uses the original non-scaled icon text size
- allAppsIconTextSizePx = DynamicGrid.pxFromDp(iconTextSize, dm);
+ allAppsIconTextSizePx = Utilities.pxFromDp(inv.iconTextSize, dm);
- // Interpolate the hotseat icon size
- points.clear();
- for (DeviceProfile p : profiles) {
- points.add(new DeviceProfileQuery(p, p.hotseatIconSize));
+ // AllApps uses the original non-scaled icon size
+ allAppsIconSizePx = Utilities.pxFromDp(inv.iconSize, dm);
+
+ // Determine sizes.
+ widthPx = width;
+ heightPx = height;
+ if (isLandscape) {
+ availableWidthPx = maxSize.x;
+ availableHeightPx = minSize.y;
+ } else {
+ availableWidthPx = minSize.x;
+ availableHeightPx = maxSize.y;
}
- // Hotseat
- hotseatIconSize = invDistWeightedInterpolate(minWidth, minHeight, points);
-
- // If the partner customization apk contains any grid overrides, apply them
- applyPartnerDeviceProfileOverrides(context, dm);
// Calculate the remaining vars
- updateFromConfiguration(context, res, wPx, hPx, awPx, ahPx);
- updateAvailableDimensions(context);
+ updateAvailableDimensions(dm, res);
computeAllAppsButtonSize(context);
}
- /**
- * Apply any Partner customization grid overrides.
- *
- * Currently we support: all apps row / column count.
- */
- private void applyPartnerDeviceProfileOverrides(Context ctx, DisplayMetrics dm) {
- Partner p = Partner.get(ctx.getPackageManager());
- if (p != null) {
- DeviceProfile partnerDp = p.getDeviceProfileOverride(dm);
- if (partnerDp != null) {
- if (partnerDp.numRows > 0 && partnerDp.numColumns > 0) {
- numRows = partnerDp.numRows;
- numColumns = partnerDp.numColumns;
- }
- if (partnerDp.allAppsShortEdgeCount > 0 && partnerDp.allAppsLongEdgeCount > 0) {
- allAppsShortEdgeCount = partnerDp.allAppsShortEdgeCount;
- allAppsLongEdgeCount = partnerDp.allAppsLongEdgeCount;
- }
- if (partnerDp.iconSize > 0) {
- iconSize = partnerDp.iconSize;
- // AllApps uses the original non-scaled icon size
- allAppsIconSizePx = DynamicGrid.pxFromDp(iconSize, dm);
- }
- }
- }
- }
-
/**
* Determine the exact visual footprint of the all apps button, taking into account scaling
* and internal padding of the drawable.
@@ -284,96 +170,39 @@ public class DeviceProfile {
private void computeAllAppsButtonSize(Context context) {
Resources res = context.getResources();
float padding = res.getInteger(R.integer.config_allAppsButtonPaddingPercent) / 100f;
- LauncherAppState app = LauncherAppState.getInstance();
allAppsButtonVisualSize = (int) (hotseatIconSizePx * (1 - padding));
}
- void addCallback(DeviceProfileCallbacks cb) {
- mCallbacks.add(cb);
- cb.onAvailableSizeChanged(this);
- }
- void removeCallback(DeviceProfileCallbacks cb) {
- mCallbacks.remove(cb);
- }
-
- private int getDeviceOrientation(Context context) {
- WindowManager windowManager = (WindowManager)
- context.getSystemService(Context.WINDOW_SERVICE);
- Resources resources = context.getResources();
- DisplayMetrics dm = resources.getDisplayMetrics();
- Configuration config = resources.getConfiguration();
- int rotation = windowManager.getDefaultDisplay().getRotation();
-
- boolean isLandscape = (config.orientation == Configuration.ORIENTATION_LANDSCAPE) &&
- (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180);
- boolean isRotatedPortrait = (config.orientation == Configuration.ORIENTATION_PORTRAIT) &&
- (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270);
- if (isLandscape || isRotatedPortrait) {
- return CellLayout.LANDSCAPE;
- } else {
- return CellLayout.PORTRAIT;
- }
- }
-
- private void updateAvailableDimensions(Context context) {
- WindowManager windowManager = (WindowManager)
- context.getSystemService(Context.WINDOW_SERVICE);
- Display display = windowManager.getDefaultDisplay();
- Resources resources = context.getResources();
- DisplayMetrics dm = resources.getDisplayMetrics();
- Configuration config = resources.getConfiguration();
-
- // There are three possible configurations that the dynamic grid accounts for, portrait,
- // landscape with the nav bar at the bottom, and landscape with the nav bar at the side.
- // To prevent waiting for fitSystemWindows(), we make the observation that in landscape,
- // the height is the smallest height (either with the nav bar at the bottom or to the
- // side) and otherwise, the height is simply the largest possible height for a portrait
- // device.
- Point size = new Point();
- Point smallestSize = new Point();
- Point largestSize = new Point();
- display.getSize(size);
- display.getCurrentSizeRange(smallestSize, largestSize);
- availableWidthPx = size.x;
- if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
- availableHeightPx = smallestSize.y;
- } else {
- availableHeightPx = largestSize.y;
- }
-
+ private void updateAvailableDimensions(DisplayMetrics dm, Resources res) {
// Check to see if the icons fit in the new available height. If not, then we need to
// shrink the icon size.
float scale = 1f;
int drawablePadding = iconDrawablePaddingOriginalPx;
- updateIconSize(1f, drawablePadding, resources, dm);
- float usedHeight = (cellHeightPx * numRows);
+ updateIconSize(1f, drawablePadding, res, dm);
+ float usedHeight = (cellHeightPx * inv.numRows);
- Rect workspacePadding = getWorkspacePadding();
+ // We only care about the top and bottom workspace padding, which is not affected by RTL.
+ Rect workspacePadding = getWorkspacePadding(false /* isLayoutRtl */);
int maxHeight = (availableHeightPx - workspacePadding.top - workspacePadding.bottom);
if (usedHeight > maxHeight) {
scale = maxHeight / usedHeight;
drawablePadding = 0;
}
- updateIconSize(scale, drawablePadding, resources, dm);
-
- // Make the callbacks
- for (DeviceProfileCallbacks cb : mCallbacks) {
- cb.onAvailableSizeChanged(this);
- }
+ updateIconSize(scale, drawablePadding, res, dm);
}
- private void updateIconSize(float scale, int drawablePadding, Resources resources,
+ private void updateIconSize(float scale, int drawablePadding, Resources res,
DisplayMetrics dm) {
- iconSizePx = (int) (DynamicGrid.pxFromDp(iconSize, dm) * scale);
- iconTextSizePx = (int) (DynamicGrid.pxFromSp(iconTextSize, dm) * scale);
+ iconSizePx = (int) (Utilities.pxFromDp(inv.iconSize, dm) * scale);
+ iconTextSizePx = (int) (Utilities.pxFromSp(inv.iconTextSize, dm) * scale);
iconDrawablePaddingPx = drawablePadding;
- hotseatIconSizePx = (int) (DynamicGrid.pxFromDp(hotseatIconSize, dm) * scale);
+ hotseatIconSizePx = (int) (Utilities.pxFromDp(inv.hotseatIconSize, dm) * scale);
// Search Bar
searchBarSpaceWidthPx = Math.min(widthPx,
- resources.getDimensionPixelSize(R.dimen.dynamic_grid_search_bar_max_width));
+ res.getDimensionPixelSize(R.dimen.dynamic_grid_search_bar_max_width));
searchBarSpaceHeightPx = getSearchBarTopOffset()
- + resources.getDimensionPixelSize(R.dimen.dynamic_grid_search_bar_height);
+ + res.getDimensionPixelSize(R.dimen.dynamic_grid_search_bar_height);
// Calculate the actual text height
Paint textPaint = new Paint();
@@ -381,7 +210,7 @@ public class DeviceProfile {
FontMetrics fm = textPaint.getFontMetrics();
cellWidthPx = iconSizePx;
cellHeightPx = iconSizePx + iconDrawablePaddingPx + (int) Math.ceil(fm.bottom - fm.top);
- final float scaleDps = resources.getDimensionPixelSize(R.dimen.dragViewScale);
+ final float scaleDps = res.getDimensionPixelSize(R.dimen.dragViewScale);
dragViewScale = (iconSizePx + scaleDps) / iconSizePx;
// Hotseat
@@ -394,123 +223,27 @@ public class DeviceProfile {
folderCellHeightPx = cellHeightPx + edgeMarginPx;
folderBackgroundOffset = -edgeMarginPx;
folderIconSizePx = iconSizePx + 2 * -folderBackgroundOffset;
-
- // All Apps
- allAppsCellWidthPx = allAppsIconSizePx;
- allAppsCellHeightPx = allAppsIconSizePx + drawablePadding + iconTextSizePx;
- int maxLongEdgeCellCount =
- resources.getInteger(R.integer.config_dynamic_grid_max_long_edge_cell_count);
- int maxShortEdgeCellCount =
- resources.getInteger(R.integer.config_dynamic_grid_max_short_edge_cell_count);
- int minEdgeCellCount =
- resources.getInteger(R.integer.config_dynamic_grid_min_edge_cell_count);
- int maxRows = (isLandscape ? maxShortEdgeCellCount : maxLongEdgeCellCount);
- int maxCols = (isLandscape ? maxLongEdgeCellCount : maxShortEdgeCellCount);
-
- if (allAppsShortEdgeCount > 0 && allAppsLongEdgeCount > 0) {
- allAppsNumRows = isLandscape ? allAppsShortEdgeCount : allAppsLongEdgeCount;
- allAppsNumCols = isLandscape ? allAppsLongEdgeCount : allAppsShortEdgeCount;
- } else {
- allAppsNumRows = (availableHeightPx - pageIndicatorHeightPx) /
- (allAppsCellHeightPx + allAppsCellPaddingPx);
- allAppsNumRows = Math.max(minEdgeCellCount, Math.min(maxRows, allAppsNumRows));
- allAppsNumCols = (availableWidthPx) /
- (allAppsCellWidthPx + allAppsCellPaddingPx);
- allAppsNumCols = Math.max(minEdgeCellCount, Math.min(maxCols, allAppsNumCols));
- }
}
- void updateFromConfiguration(Context context, Resources resources, int wPx, int hPx,
- int awPx, int ahPx) {
- Configuration configuration = resources.getConfiguration();
- isLandscape = (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE);
- isTablet = resources.getBoolean(R.bool.is_tablet);
- isLargeTablet = resources.getBoolean(R.bool.is_large_tablet);
- if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
- isLayoutRtl = (configuration.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
- } else {
- isLayoutRtl = false;
- }
- widthPx = wPx;
- heightPx = hPx;
- availableWidthPx = awPx;
- availableHeightPx = ahPx;
-
- updateAvailableDimensions(context);
- }
-
- private float dist(PointF p0, PointF p1) {
- return (float) Math.sqrt((p1.x - p0.x)*(p1.x-p0.x) +
- (p1.y-p0.y)*(p1.y-p0.y));
- }
-
- private float weight(PointF a, PointF b,
- float pow) {
- float d = dist(a, b);
- if (d == 0f) {
- return Float.POSITIVE_INFINITY;
- }
- return (float) (1f / Math.pow(d, pow));
- }
-
- /** Returns the closest device profile given the width and height and a list of profiles */
- private DeviceProfile findClosestDeviceProfile(float width, float height,
- ArrayList points) {
- return findClosestDeviceProfiles(width, height, points).get(0).profile;
- }
-
- /** Returns the closest device profiles ordered by closeness to the specified width and height */
- private ArrayList findClosestDeviceProfiles(float width, float height,
- ArrayList points) {
- final PointF xy = new PointF(width, height);
-
- // Sort the profiles by their closeness to the dimensions
- ArrayList pointsByNearness = points;
- Collections.sort(pointsByNearness, new Comparator() {
- public int compare(DeviceProfileQuery a, DeviceProfileQuery b) {
- return (int) (dist(xy, a.dimens) - dist(xy, b.dimens));
- }
- });
-
- return pointsByNearness;
- }
-
- private float invDistWeightedInterpolate(float width, float height,
- ArrayList points) {
- float sum = 0;
- float weights = 0;
- float pow = 5;
- float kNearestNeighbors = 3;
- final PointF xy = new PointF(width, height);
-
- ArrayList pointsByNearness = findClosestDeviceProfiles(width, height,
- points);
-
- for (int i = 0; i < pointsByNearness.size(); ++i) {
- DeviceProfileQuery p = pointsByNearness.get(i);
- if (i < kNearestNeighbors) {
- float w = weight(xy, p.dimens, pow);
- if (w == Float.POSITIVE_INFINITY) {
- return p.value;
- }
- weights += w;
- }
- }
-
- for (int i = 0; i < pointsByNearness.size(); ++i) {
- DeviceProfileQuery p = pointsByNearness.get(i);
- if (i < kNearestNeighbors) {
- float w = weight(xy, p.dimens, pow);
- sum += w * p.value / weights;
- }
- }
-
- return sum;
+ /**
+ * @param recyclerViewWidth the available width of the AllAppsRecyclerView
+ */
+ public void updateAppsViewNumCols(Resources res, int recyclerViewWidth) {
+ int appsViewLeftMarginPx =
+ res.getDimensionPixelSize(R.dimen.all_apps_grid_view_start_margin);
+ int allAppsCellWidthGap =
+ res.getDimensionPixelSize(R.dimen.all_apps_icon_width_gap);
+ int availableAppsWidthPx = (recyclerViewWidth > 0) ? recyclerViewWidth : availableWidthPx;
+ int numAppsCols = (availableAppsWidthPx - appsViewLeftMarginPx) /
+ (allAppsIconSizePx + allAppsCellWidthGap);
+ int numPredictiveAppCols = Math.max(inv.minAllAppsPredictionColumns, numAppsCols);
+ allAppsNumCols = numAppsCols;
+ allAppsNumPredictiveCols = numPredictiveAppCols;
}
/** Returns the search bar top offset */
- int getSearchBarTopOffset() {
- if (isTablet() && !isVerticalBarLayout()) {
+ private int getSearchBarTopOffset() {
+ if (isTablet && !isVerticalBarLayout()) {
return 4 * edgeMarginPx;
} else {
return 2 * edgeMarginPx;
@@ -518,14 +251,9 @@ public class DeviceProfile {
}
/** Returns the search bar bounds in the current orientation */
- Rect getSearchBarBounds() {
- return getSearchBarBounds(isLandscape ? CellLayout.LANDSCAPE : CellLayout.PORTRAIT);
- }
- /** Returns the search bar bounds in the specified orientation */
- Rect getSearchBarBounds(int orientation) {
+ public Rect getSearchBarBounds(boolean isLayoutRtl) {
Rect bounds = new Rect();
- if (orientation == CellLayout.LANDSCAPE &&
- transposeLayoutWithOrientation) {
+ if (isLandscape && transposeLayoutWithOrientation) {
if (isLayoutRtl) {
bounds.set(availableWidthPx - searchBarSpaceHeightPx, edgeMarginPx,
availableWidthPx, availableHeightPx - edgeMarginPx);
@@ -534,16 +262,14 @@ public class DeviceProfile {
availableHeightPx - edgeMarginPx);
}
} else {
- if (isTablet()) {
+ if (isTablet) {
// Pad the left and right of the workspace to ensure consistent spacing
// between all icons
- int width = (orientation == CellLayout.LANDSCAPE)
- ? Math.max(widthPx, heightPx)
- : Math.min(widthPx, heightPx);
+ int width = getCurrentWidth();
// XXX: If the icon size changes across orientations, we will have to take
// that into account here too.
int gap = (int) ((width - 2 * edgeMarginPx -
- (numColumns * cellWidthPx)) / (2 * (numColumns + 1)));
+ (inv.numColumns * cellWidthPx)) / (2 * (inv.numColumns + 1)));
bounds.set(edgeMarginPx + gap, getSearchBarTopOffset(),
availableWidthPx - (edgeMarginPx + gap),
searchBarSpaceHeightPx);
@@ -557,36 +283,11 @@ public class DeviceProfile {
return bounds;
}
- /** Returns the bounds of the workspace page indicators. */
- Rect getWorkspacePageIndicatorBounds(Rect insets) {
- Rect workspacePadding = getWorkspacePadding();
- if (isLandscape && transposeLayoutWithOrientation) {
- if (isLayoutRtl) {
- return new Rect(workspacePadding.left, workspacePadding.top,
- workspacePadding.left + pageIndicatorHeightPx,
- heightPx - workspacePadding.bottom - insets.bottom);
- } else {
- int pageIndicatorLeft = widthPx - workspacePadding.right;
- return new Rect(pageIndicatorLeft, workspacePadding.top,
- pageIndicatorLeft + pageIndicatorHeightPx,
- heightPx - workspacePadding.bottom - insets.bottom);
- }
- } else {
- int pageIndicatorTop = heightPx - insets.bottom - workspacePadding.bottom;
- return new Rect(workspacePadding.left, pageIndicatorTop,
- widthPx - workspacePadding.right, pageIndicatorTop + pageIndicatorHeightPx);
- }
- }
-
/** Returns the workspace padding in the specified orientation */
- Rect getWorkspacePadding() {
- return getWorkspacePadding(isLandscape ? CellLayout.LANDSCAPE : CellLayout.PORTRAIT);
- }
- Rect getWorkspacePadding(int orientation) {
- Rect searchBarBounds = getSearchBarBounds(orientation);
+ Rect getWorkspacePadding(boolean isLayoutRtl) {
+ Rect searchBarBounds = getSearchBarBounds(isLayoutRtl);
Rect padding = new Rect();
- if (orientation == CellLayout.LANDSCAPE &&
- transposeLayoutWithOrientation) {
+ if (isLandscape && transposeLayoutWithOrientation) {
// Pad the left and right of the workspace with search/hotseat bar sizes
if (isLayoutRtl) {
padding.set(hotseatBarHeightPx, edgeMarginPx,
@@ -596,22 +297,18 @@ public class DeviceProfile {
hotseatBarHeightPx, edgeMarginPx);
}
} else {
- if (isTablet()) {
+ if (isTablet) {
// Pad the left and right of the workspace to ensure consistent spacing
// between all icons
float gapScale = 1f + (dragViewScale - 1f) / 2f;
- int width = (orientation == CellLayout.LANDSCAPE)
- ? Math.max(widthPx, heightPx)
- : Math.min(widthPx, heightPx);
- int height = (orientation != CellLayout.LANDSCAPE)
- ? Math.max(widthPx, heightPx)
- : Math.min(widthPx, heightPx);
+ int width = getCurrentWidth();
+ int height = getCurrentHeight();
int paddingTop = searchBarBounds.bottom;
int paddingBottom = hotseatBarHeightPx + pageIndicatorHeightPx;
- int availableWidth = Math.max(0, width - (int) ((numColumns * cellWidthPx) +
- (numColumns * gapScale * cellWidthPx)));
+ int availableWidth = Math.max(0, width - (int) ((inv.numColumns * cellWidthPx) +
+ (inv.numColumns * gapScale * cellWidthPx)));
int availableHeight = Math.max(0, height - paddingTop - paddingBottom
- - (int) (2 * numRows * cellHeightPx));
+ - (int) (2 * inv.numRows * cellHeightPx));
padding.set(availableWidth / 2, paddingTop + availableHeight / 2,
availableWidth / 2, paddingBottom + availableHeight / 2);
} else {
@@ -625,16 +322,15 @@ public class DeviceProfile {
return padding;
}
- int getWorkspacePageSpacing(int orientation) {
- if ((orientation == CellLayout.LANDSCAPE &&
- transposeLayoutWithOrientation) || isLargeTablet()) {
+ private int getWorkspacePageSpacing(boolean isLayoutRtl) {
+ if ((isLandscape && transposeLayoutWithOrientation) || isLargeTablet) {
// In landscape mode the page spacing is set to the default.
return defaultPageSpacingPx;
} else {
// In portrait, we want the pages spaced such that there is no
// overhang of the previous / next page into the current page viewport.
// We assume symmetrical padding in portrait mode.
- return Math.max(defaultPageSpacingPx, 2 * getWorkspacePadding().left);
+ return Math.max(defaultPageSpacingPx, 2 * getWorkspacePadding(isLayoutRtl).left);
}
}
@@ -645,8 +341,8 @@ public class DeviceProfile {
return new Rect(0, availableHeightPx - zoneHeight, 0, availableHeightPx);
}
- float getOverviewModeScale() {
- Rect workspacePadding = getWorkspacePadding();
+ public float getOverviewModeScale(boolean isLayoutRtl) {
+ Rect workspacePadding = getWorkspacePadding(isLayoutRtl);
Rect overviewBar = getOverviewModeButtonBarRect();
int pageSpace = availableHeightPx - workspacePadding.top - workspacePadding.bottom;
return (overviewModeScaleFactor * (pageSpace - overviewBar.height())) / pageSpace;
@@ -663,32 +359,26 @@ public class DeviceProfile {
}
}
- int calculateCellWidth(int width, int countX) {
+ public static int calculateCellWidth(int width, int countX) {
return width / countX;
}
- int calculateCellHeight(int height, int countY) {
+ public static int calculateCellHeight(int height, int countY) {
return height / countY;
}
- boolean isPhone() {
- return !isTablet && !isLargeTablet;
- }
- boolean isTablet() {
- return isTablet;
- }
- boolean isLargeTablet() {
- return isLargeTablet;
- }
-
+ /**
+ * When {@code true}, hotseat is on the bottom row when in landscape mode.
+ * If {@code false}, hotseat is on the right column when in landscape mode.
+ */
boolean isVerticalBarLayout() {
return isLandscape && transposeLayoutWithOrientation;
}
boolean shouldFadeAdjacentWorkspaceScreens() {
- return isVerticalBarLayout() || isLargeTablet();
+ return isVerticalBarLayout() || isLargeTablet;
}
- int getVisibleChildCount(ViewGroup parent) {
+ private int getVisibleChildCount(ViewGroup parent) {
int visibleChildren = 0;
for (int i = 0; i < parent.getChildCount(); i++) {
if (parent.getChildAt(i).getVisibility() != View.GONE) {
@@ -700,25 +390,31 @@ public class DeviceProfile {
public void layout(Launcher launcher) {
FrameLayout.LayoutParams lp;
- Resources res = launcher.getResources();
boolean hasVerticalBarLayout = isVerticalBarLayout();
+ final boolean isLayoutRtl = Utilities.isRtl(launcher.getResources());
// Layout the search bar space
View searchBar = launcher.getSearchBar();
lp = (FrameLayout.LayoutParams) searchBar.getLayoutParams();
if (hasVerticalBarLayout) {
- // Vertical search bar space
- lp.gravity = Gravity.TOP | Gravity.LEFT;
+ // Vertical search bar space -- The search bar is fixed in the layout to be on the left
+ // of the screen regardless of RTL
+ lp.gravity = Gravity.LEFT;
lp.width = searchBarSpaceHeightPx;
- lp.height = LayoutParams.WRAP_CONTENT;
LinearLayout targets = (LinearLayout) searchBar.findViewById(R.id.drag_target_bar);
targets.setOrientation(LinearLayout.VERTICAL);
+ FrameLayout.LayoutParams targetsLp = (FrameLayout.LayoutParams) targets.getLayoutParams();
+ targetsLp.gravity = Gravity.TOP;
+ targetsLp.height = LayoutParams.WRAP_CONTENT;
+
} else {
// Horizontal search bar space
- lp.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
- lp.width = searchBarSpaceWidthPx;
+ lp.gravity = Gravity.TOP;
lp.height = searchBarSpaceHeightPx;
+
+ LinearLayout targets = (LinearLayout) searchBar.findViewById(R.id.drag_target_bar);
+ targets.getLayoutParams().width = searchBarSpaceWidthPx;
}
searchBar.setLayoutParams(lp);
@@ -726,22 +422,22 @@ public class DeviceProfile {
PagedView workspace = (PagedView) launcher.findViewById(R.id.workspace);
lp = (FrameLayout.LayoutParams) workspace.getLayoutParams();
lp.gravity = Gravity.CENTER;
- int orientation = isLandscape ? CellLayout.LANDSCAPE : CellLayout.PORTRAIT;
- Rect padding = getWorkspacePadding(orientation);
+ Rect padding = getWorkspacePadding(isLayoutRtl);
workspace.setLayoutParams(lp);
workspace.setPadding(padding.left, padding.top, padding.right, padding.bottom);
- workspace.setPageSpacing(getWorkspacePageSpacing(orientation));
+ workspace.setPageSpacing(getWorkspacePageSpacing(isLayoutRtl));
// Layout the hotseat
View hotseat = launcher.findViewById(R.id.hotseat);
lp = (FrameLayout.LayoutParams) hotseat.getLayoutParams();
if (hasVerticalBarLayout) {
- // Vertical hotseat
- lp.gravity = Gravity.END;
+ // Vertical hotseat -- The hotseat is fixed in the layout to be on the right of the
+ // screen regardless of RTL
+ lp.gravity = Gravity.RIGHT;
lp.width = hotseatBarHeightPx;
lp.height = LayoutParams.MATCH_PARENT;
hotseat.findViewById(R.id.layout).setPadding(0, 2 * edgeMarginPx, 0, 2 * edgeMarginPx);
- } else if (isTablet()) {
+ } else if (isTablet) {
// Pad the hotseat with the workspace padding calculated above
lp.gravity = Gravity.BOTTOM;
lp.width = LayoutParams.MATCH_PARENT;
@@ -777,64 +473,6 @@ public class DeviceProfile {
}
}
- // Layout AllApps
- AppsCustomizeTabHost host = (AppsCustomizeTabHost)
- launcher.findViewById(R.id.apps_customize_pane);
- if (host != null) {
- // Center the all apps page indicator
- int pageIndicatorHeight = (int) (pageIndicatorHeightPx * Math.min(1f,
- (allAppsIconSizePx / DynamicGrid.DEFAULT_ICON_SIZE_PX)));
- pageIndicator = host.findViewById(R.id.apps_customize_page_indicator);
- if (pageIndicator != null) {
- LinearLayout.LayoutParams lllp = (LinearLayout.LayoutParams) pageIndicator.getLayoutParams();
- lllp.width = LayoutParams.WRAP_CONTENT;
- lllp.height = pageIndicatorHeight;
- pageIndicator.setLayoutParams(lllp);
- }
-
- AppsCustomizePagedView pagedView = (AppsCustomizePagedView)
- host.findViewById(R.id.apps_customize_pane_content);
-
- FrameLayout fakePageContainer = (FrameLayout)
- host.findViewById(R.id.fake_page_container);
- FrameLayout fakePage = (FrameLayout) host.findViewById(R.id.fake_page);
-
- padding = new Rect();
- if (pagedView != null) {
- // Constrain the dimensions of all apps so that it does not span the full width
- int paddingLR = (availableWidthPx - (allAppsCellWidthPx * allAppsNumCols)) /
- (2 * (allAppsNumCols + 1));
- int paddingTB = (availableHeightPx - (allAppsCellHeightPx * allAppsNumRows)) /
- (2 * (allAppsNumRows + 1));
- paddingLR = Math.min(paddingLR, (int)((paddingLR + paddingTB) * 0.75f));
- paddingTB = Math.min(paddingTB, (int)((paddingLR + paddingTB) * 0.75f));
- int maxAllAppsWidth = (allAppsNumCols * (allAppsCellWidthPx + 2 * paddingLR));
- int gridPaddingLR = (availableWidthPx - maxAllAppsWidth) / 2;
- // Only adjust the side paddings on landscape phones, or tablets
- if ((isTablet() || isLandscape) && gridPaddingLR > (allAppsCellWidthPx / 4)) {
- padding.left = padding.right = gridPaddingLR;
- }
-
- // The icons are centered, so we can't just offset by the page indicator height
- // because the empty space will actually be pageIndicatorHeight + paddingTB
- padding.bottom = Math.max(0, pageIndicatorHeight - paddingTB);
-
- pagedView.setWidgetsPageIndicatorPadding(pageIndicatorHeight);
- fakePage.setBackground(res.getDrawable(R.drawable.quantum_panel));
-
- // Horizontal padding for the whole paged view
- int pagedFixedViewPadding =
- res.getDimensionPixelSize(R.dimen.apps_customize_horizontal_padding);
-
- padding.left += pagedFixedViewPadding;
- padding.right += pagedFixedViewPadding;
-
- pagedView.setPadding(padding.left, padding.top, padding.right, padding.bottom);
- fakePageContainer.setPadding(padding.left, padding.top, padding.right, padding.bottom);
-
- }
- }
-
// Layout the Overview Mode
ViewGroup overviewMode = launcher.getOverviewPanel();
if (overviewMode != null) {
@@ -875,4 +513,16 @@ public class DeviceProfile {
}
}
}
+
+ private int getCurrentWidth() {
+ return isLandscape
+ ? Math.max(widthPx, heightPx)
+ : Math.min(widthPx, heightPx);
+ }
+
+ private int getCurrentHeight() {
+ return isLandscape
+ ? Math.min(widthPx, heightPx)
+ : Math.max(widthPx, heightPx);
+ }
}
diff --git a/src/com/android/launcher3/DragController.java b/src/com/android/launcher3/DragController.java
index 480dce9998..2191455d53 100644
--- a/src/com/android/launcher3/DragController.java
+++ b/src/com/android/launcher3/DragController.java
@@ -34,6 +34,8 @@ import android.view.View;
import android.view.ViewConfiguration;
import android.view.inputmethod.InputMethodManager;
+import com.android.launcher3.util.Thunk;
+
import java.util.ArrayList;
import java.util.HashSet;
@@ -49,8 +51,8 @@ public class DragController {
/** Indicates the drag is a copy. */
public static int DRAG_ACTION_COPY = 1;
- private static final int SCROLL_DELAY = 500;
- private static final int RESCROLL_DELAY = PagedView.PAGE_SNAP_ANIMATION_DURATION + 150;
+ public static final int SCROLL_DELAY = 500;
+ public static final int RESCROLL_DELAY = PagedView.PAGE_SNAP_ANIMATION_DURATION + 150;
private static final boolean PROFILE_DRAWING_DURING_DRAG = false;
@@ -63,16 +65,20 @@ public class DragController {
private static final float MAX_FLING_DEGREES = 35f;
- private Launcher mLauncher;
+ @Thunk Launcher mLauncher;
private Handler mHandler;
// temporaries to avoid gc thrash
private Rect mRectTemp = new Rect();
private final int[] mCoordinatesTemp = new int[2];
+ private final boolean mIsRtl;
/** Whether or not we're dragging. */
private boolean mDragging;
+ /** Whether or not this is an accessible drag operation */
+ private boolean mIsAccessibleDrag;
+
/** X coordinate of the down event. */
private int mMotionDownX;
@@ -99,17 +105,17 @@ public class DragController {
private View mMoveTarget;
- private DragScroller mDragScroller;
- private int mScrollState = SCROLL_OUTSIDE_ZONE;
+ @Thunk DragScroller mDragScroller;
+ @Thunk int mScrollState = SCROLL_OUTSIDE_ZONE;
private ScrollRunnable mScrollRunnable = new ScrollRunnable();
private DropTarget mLastDropTarget;
private InputMethodManager mInputMethodManager;
- private int mLastTouch[] = new int[2];
- private long mLastTouchUpTime = -1;
- private int mDistanceSinceScroll = 0;
+ @Thunk int mLastTouch[] = new int[2];
+ @Thunk long mLastTouchUpTime = -1;
+ @Thunk int mDistanceSinceScroll = 0;
private int mTmpPoint[] = new int[2];
private Rect mDragLayerRect = new Rect();
@@ -120,7 +126,7 @@ public class DragController {
/**
* Interface to receive notifications when a drag starts or stops
*/
- interface DragListener {
+ public interface DragListener {
/**
* A drag has begun
*
@@ -152,6 +158,7 @@ public class DragController {
float density = r.getDisplayMetrics().density;
mFlingToDeleteThresholdVelocity =
(int) (r.getInteger(R.integer.config_flingToDeleteMinVelocity) * density);
+ mIsRtl = Utilities.isRtl(r);
}
public boolean dragging() {
@@ -167,22 +174,21 @@ public class DragController {
* @param dragInfo The data associated with the object that is being dragged
* @param dragAction The drag action: either {@link #DRAG_ACTION_MOVE} or
* {@link #DRAG_ACTION_COPY}
+ * @param viewImageBounds the position of the image inside the view
* @param dragRegion Coordinates within the bitmap b for the position of item being dragged.
* Makes dragging feel more precise, e.g. you can clip out a transparent border
*/
- public void startDrag(View v, Bitmap bmp, DragSource source, Object dragInfo, int dragAction,
- Point extraPadding, float initialDragViewScale) {
+ public void startDrag(View v, Bitmap bmp, DragSource source, Object dragInfo,
+ Rect viewImageBounds, int dragAction, float initialDragViewScale) {
int[] loc = mCoordinatesTemp;
mLauncher.getDragLayer().getLocationInDragLayer(v, loc);
- int viewExtraPaddingLeft = extraPadding != null ? extraPadding.x : 0;
- int viewExtraPaddingTop = extraPadding != null ? extraPadding.y : 0;
- int dragLayerX = loc[0] + v.getPaddingLeft() + viewExtraPaddingLeft +
- (int) ((initialDragViewScale * bmp.getWidth() - bmp.getWidth()) / 2);
- int dragLayerY = loc[1] + v.getPaddingTop() + viewExtraPaddingTop +
- (int) ((initialDragViewScale * bmp.getHeight() - bmp.getHeight()) / 2);
+ int dragLayerX = loc[0] + viewImageBounds.left
+ + (int) ((initialDragViewScale * bmp.getWidth() - bmp.getWidth()) / 2);
+ int dragLayerY = loc[1] + viewImageBounds.top
+ + (int) ((initialDragViewScale * bmp.getHeight() - bmp.getHeight()) / 2);
startDrag(bmp, dragLayerX, dragLayerY, source, dragInfo, dragAction, null,
- null, initialDragViewScale);
+ null, initialDragViewScale, false);
if (dragAction == DRAG_ACTION_MOVE) {
v.setVisibility(View.GONE);
@@ -202,10 +208,11 @@ public class DragController {
* {@link #DRAG_ACTION_COPY}
* @param dragRegion Coordinates within the bitmap b for the position of item being dragged.
* Makes dragging feel more precise, e.g. you can clip out a transparent border
+ * @param accessible whether this drag should occur in accessibility mode
*/
public DragView startDrag(Bitmap b, int dragLayerX, int dragLayerY,
DragSource source, Object dragInfo, int dragAction, Point dragOffset, Rect dragRegion,
- float initialDragViewScale) {
+ float initialDragViewScale, boolean accessible) {
if (PROFILE_DRAWING_DURING_DRAG) {
android.os.Debug.startMethodTracing("Launcher");
}
@@ -228,12 +235,21 @@ public class DragController {
final int dragRegionTop = dragRegion == null ? 0 : dragRegion.top;
mDragging = true;
+ mIsAccessibleDrag = accessible;
mDragObject = new DropTarget.DragObject();
mDragObject.dragComplete = false;
- mDragObject.xOffset = mMotionDownX - (dragLayerX + dragRegionLeft);
- mDragObject.yOffset = mMotionDownY - (dragLayerY + dragRegionTop);
+ if (mIsAccessibleDrag) {
+ // For an accessible drag, we assume the view is being dragged from the center.
+ mDragObject.xOffset = b.getWidth() / 2;
+ mDragObject.yOffset = b.getHeight() / 2;
+ mDragObject.accessibleDrag = true;
+ } else {
+ mDragObject.xOffset = mMotionDownX - (dragLayerX + dragRegionLeft);
+ mDragObject.yOffset = mMotionDownY - (dragLayerY + dragRegionTop);
+ }
+
mDragObject.dragSource = source;
mDragObject.dragInfo = dragInfo;
@@ -349,6 +365,7 @@ public class DragController {
private void endDrag() {
if (mDragging) {
mDragging = false;
+ mIsAccessibleDrag = false;
clearScrollRunnable();
boolean isDeferred = false;
if (mDragObject.dragView != null) {
@@ -361,7 +378,7 @@ public class DragController {
// Only end the drag if we are not deferred
if (!isDeferred) {
- for (DragListener listener : mListeners) {
+ for (DragListener listener : new ArrayList<>(mListeners)) {
listener.onDragEnd();
}
}
@@ -378,13 +395,13 @@ public class DragController {
if (mDragObject.deferDragViewCleanupPostAnimation) {
// If we skipped calling onDragEnd() before, do it now
- for (DragListener listener : mListeners) {
+ for (DragListener listener : new ArrayList<>(mListeners)) {
listener.onDragEnd();
}
}
}
- void onDeferredEndFling(DropTarget.DragObject d) {
+ public void onDeferredEndFling(DropTarget.DragObject d) {
d.dragSource.onFlingToDeleteCompleted();
}
@@ -421,6 +438,10 @@ public class DragController {
+ mDragging);
}
+ if (mIsAccessibleDrag) {
+ return false;
+ }
+
// Update the velocity tracker
acquireVelocityTrackerAndAddMovement(ev);
@@ -442,7 +463,7 @@ public class DragController {
mLastTouchUpTime = System.currentTimeMillis();
if (mDragging) {
PointF vec = isFlingingToDelete(mDragObject.dragSource);
- if (!DeleteDropTarget.willAcceptDrop(mDragObject.dragInfo)) {
+ if (!DeleteDropTarget.supportsDrop(mDragObject.dragInfo)) {
vec = null;
}
if (vec != null) {
@@ -493,8 +514,7 @@ public class DragController {
checkTouchMove(dropTarget);
// Check if we are hovering over the scroll areas
- mDistanceSinceScroll +=
- Math.sqrt(Math.pow(mLastTouch[0] - x, 2) + Math.pow(mLastTouch[1] - y, 2));
+ mDistanceSinceScroll += Math.hypot(mLastTouch[0] - x, mLastTouch[1] - y);
mLastTouch[0] = x;
mLastTouch[1] = y;
checkScrollState(x, y);
@@ -525,13 +545,12 @@ public class DragController {
mLastDropTarget = dropTarget;
}
- private void checkScrollState(int x, int y) {
+ @Thunk void checkScrollState(int x, int y) {
final int slop = ViewConfiguration.get(mLauncher).getScaledWindowTouchSlop();
final int delay = mDistanceSinceScroll < slop ? RESCROLL_DELAY : SCROLL_DELAY;
final DragLayer dragLayer = mLauncher.getDragLayer();
- final boolean isRtl = (dragLayer.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
- final int forwardDirection = isRtl ? SCROLL_RIGHT : SCROLL_LEFT;
- final int backwardsDirection = isRtl ? SCROLL_LEFT : SCROLL_RIGHT;
+ final int forwardDirection = mIsRtl ? SCROLL_RIGHT : SCROLL_LEFT;
+ final int backwardsDirection = mIsRtl ? SCROLL_LEFT : SCROLL_RIGHT;
if (x < mScrollZone) {
if (mScrollState == SCROLL_OUTSIDE_ZONE) {
@@ -560,7 +579,7 @@ public class DragController {
* Call this from a drag source view.
*/
public boolean onTouchEvent(MotionEvent ev) {
- if (!mDragging) {
+ if (!mDragging || mIsAccessibleDrag) {
return false;
}
@@ -596,7 +615,7 @@ public class DragController {
if (mDragging) {
PointF vec = isFlingingToDelete(mDragObject.dragSource);
- if (!DeleteDropTarget.willAcceptDrop(mDragObject.dragInfo)) {
+ if (!DeleteDropTarget.supportsDrop(mDragObject.dragInfo)) {
vec = null;
}
if (vec != null) {
@@ -616,6 +635,35 @@ public class DragController {
return true;
}
+ /**
+ * Since accessible drag and drop won't cause the same sequence of touch events, we manually
+ * inject the appropriate state.
+ */
+ public void prepareAccessibleDrag(int x, int y) {
+ mMotionDownX = x;
+ mMotionDownY = y;
+ mLastDropTarget = null;
+ }
+
+ /**
+ * As above, since accessible drag and drop won't cause the same sequence of touch events,
+ * we manually ensure appropriate drag and drop events get emulated for accessible drag.
+ */
+ public void completeAccessibleDrag(int[] location) {
+ final int[] coordinates = mCoordinatesTemp;
+
+ // We make sure that we prime the target for drop.
+ DropTarget dropTarget = findDropTarget(location[0], location[1], coordinates);
+ mDragObject.x = coordinates[0];
+ mDragObject.y = coordinates[1];
+ checkTouchMove(dropTarget);
+
+ dropTarget.prepareAccessibilityDrop();
+ // Perform the drop
+ drop(location[0], location[1]);
+ endDrag();
+ }
+
/**
* Determines whether the user flung the current item to delete it.
*
@@ -662,8 +710,7 @@ public class DragController {
mDragObject.dragComplete = true;
mFlingToDeleteDropTarget.onDragExit(mDragObject);
if (mFlingToDeleteDropTarget.acceptDrop(mDragObject)) {
- mFlingToDeleteDropTarget.onFlingToDelete(mDragObject, mDragObject.x, mDragObject.y,
- vel);
+ mFlingToDeleteDropTarget.onFlingToDelete(mDragObject, vel);
accepted = true;
}
mDragObject.dragSource.onDropCompleted((View) mFlingToDeleteDropTarget, mDragObject, true,
diff --git a/src/com/android/launcher3/DragLayer.java b/src/com/android/launcher3/DragLayer.java
index a352b79146..aaa14e6a6c 100644
--- a/src/com/android/launcher3/DragLayer.java
+++ b/src/com/android/launcher3/DragLayer.java
@@ -24,6 +24,7 @@ import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
+import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
@@ -38,7 +39,8 @@ import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.TextView;
-import com.android.launcher3.InsettableFrameLayout.LayoutParams;
+import com.android.launcher3.accessibility.LauncherAccessibilityDelegate;
+import com.android.launcher3.util.Thunk;
import java.util.ArrayList;
@@ -46,30 +48,34 @@ import java.util.ArrayList;
* A ViewGroup that coordinates dragging across its descendants
*/
public class DragLayer extends InsettableFrameLayout {
- private DragController mDragController;
- private int[] mTmpXY = new int[2];
+
+ public static final int ANIMATION_END_DISAPPEAR = 0;
+ public static final int ANIMATION_END_REMAIN_VISIBLE = 2;
+
+ // Scrim color without any alpha component.
+ private static final int SCRIM_COLOR = Color.BLACK & 0x00FFFFFF;
+
+ private final int[] mTmpXY = new int[2];
+
+ @Thunk DragController mDragController;
private int mXDown, mYDown;
private Launcher mLauncher;
// Variables relating to resizing widgets
- private final ArrayList mResizeFrames =
- new ArrayList();
+ private final ArrayList mResizeFrames = new ArrayList<>();
+ private final boolean mIsRtl;
private AppWidgetResizeFrame mCurrentResizeFrame;
// Variables relating to animation of views after drop
private ValueAnimator mDropAnim = null;
- private ValueAnimator mFadeOutAnim = null;
- private TimeInterpolator mCubicEaseOutInterpolator = new DecelerateInterpolator(1.5f);
- private DragView mDropView = null;
- private int mAnchorViewInitialScrollX = 0;
- private View mAnchorView = null;
+ private final TimeInterpolator mCubicEaseOutInterpolator = new DecelerateInterpolator(1.5f);
+ @Thunk DragView mDropView = null;
+ @Thunk int mAnchorViewInitialScrollX = 0;
+ @Thunk View mAnchorView = null;
private boolean mHoverPointClosesFolder = false;
- private Rect mHitRect = new Rect();
- public static final int ANIMATION_END_DISAPPEAR = 0;
- public static final int ANIMATION_END_FADE_OUT = 1;
- public static final int ANIMATION_END_REMAIN_VISIBLE = 2;
+ private final Rect mHitRect = new Rect();
private TouchCompleteListener mTouchCompleteListener;
@@ -78,10 +84,10 @@ public class DragLayer extends InsettableFrameLayout {
private int mChildCountOnLastUpdate = -1;
// Darkening scrim
- private Drawable mBackground;
private float mBackgroundAlpha = 0;
// Related to adjacent page hints
+ private final Rect mScrollChildPosition = new Rect();
private boolean mInScrollArea;
private boolean mShowPageHints;
private Drawable mLeftHoverDrawable;
@@ -109,7 +115,7 @@ public class DragLayer extends InsettableFrameLayout {
mRightHoverDrawable = res.getDrawable(R.drawable.page_hover_right);
mLeftHoverDrawableActive = res.getDrawable(R.drawable.page_hover_left_active);
mRightHoverDrawableActive = res.getDrawable(R.drawable.page_hover_right_active);
- mBackground = res.getDrawable(R.drawable.apps_customize_bg);
+ mIsRtl = Utilities.isRtl(res);
}
public void setup(Launcher launcher, DragController controller) {
@@ -152,6 +158,14 @@ public class DragLayer extends InsettableFrameLayout {
return false;
}
+ private boolean isEventOverDropTargetBar(MotionEvent ev) {
+ getDescendantRectRelativeToSelf(mLauncher.getSearchBar(), mHitRect);
+ if (mHitRect.contains((int) ev.getX(), (int) ev.getY())) {
+ return true;
+ }
+ return false;
+ }
+
public void setBlockTouch(boolean block) {
mBlockTouches = block;
}
@@ -187,10 +201,16 @@ public class DragLayer extends InsettableFrameLayout {
}
}
- getDescendantRectRelativeToSelf(currentFolder, hitRect);
if (!isEventOverFolder(currentFolder, ev)) {
- mLauncher.closeFolder();
- return true;
+ if (isInAccessibleDrag()) {
+ // Do not close the folder if in drag and drop.
+ if (!isEventOverDropTargetBar(ev)) {
+ return true;
+ }
+ } else {
+ mLauncher.closeFolder();
+ return true;
+ }
}
}
return false;
@@ -227,11 +247,12 @@ public class DragLayer extends InsettableFrameLayout {
getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
if (accessibilityManager.isTouchExplorationEnabled()) {
final int action = ev.getAction();
- boolean isOverFolder;
+ boolean isOverFolderOrSearchBar;
switch (action) {
case MotionEvent.ACTION_HOVER_ENTER:
- isOverFolder = isEventOverFolder(currentFolder, ev);
- if (!isOverFolder) {
+ isOverFolderOrSearchBar = isEventOverFolder(currentFolder, ev) ||
+ (isInAccessibleDrag() && isEventOverDropTargetBar(ev));
+ if (!isOverFolderOrSearchBar) {
sendTapOutsideFolderAccessibilityEvent(currentFolder.isEditingName());
mHoverPointClosesFolder = true;
return true;
@@ -239,12 +260,13 @@ public class DragLayer extends InsettableFrameLayout {
mHoverPointClosesFolder = false;
break;
case MotionEvent.ACTION_HOVER_MOVE:
- isOverFolder = isEventOverFolder(currentFolder, ev);
- if (!isOverFolder && !mHoverPointClosesFolder) {
+ isOverFolderOrSearchBar = isEventOverFolder(currentFolder, ev) ||
+ (isInAccessibleDrag() && isEventOverDropTargetBar(ev));
+ if (!isOverFolderOrSearchBar && !mHoverPointClosesFolder) {
sendTapOutsideFolderAccessibilityEvent(currentFolder.isEditingName());
mHoverPointClosesFolder = true;
return true;
- } else if (!isOverFolder) {
+ } else if (!isOverFolderOrSearchBar) {
return true;
}
mHoverPointClosesFolder = false;
@@ -267,6 +289,12 @@ public class DragLayer extends InsettableFrameLayout {
}
}
+ private boolean isInAccessibleDrag() {
+ LauncherAccessibilityDelegate delegate = LauncherAppState
+ .getInstance().getAccessibilityDelegate();
+ return delegate != null && delegate.isInAccessibleDrag();
+ }
+
@Override
public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) {
Folder currentFolder = mLauncher.getWorkspace().getOpenFolder();
@@ -274,6 +302,10 @@ public class DragLayer extends InsettableFrameLayout {
if (child == currentFolder) {
return super.onRequestSendAccessibilityEvent(child, event);
}
+
+ if (isInAccessibleDrag() && child instanceof SearchDropTargetBar) {
+ return super.onRequestSendAccessibilityEvent(child, event);
+ }
// Skip propagating onRequestSendAccessibilityEvent all for other children
// when a folder is open
return false;
@@ -287,6 +319,10 @@ public class DragLayer extends InsettableFrameLayout {
if (currentFolder != null) {
// Only add the folder as a child for accessibility when it is open
childrenForAccessibility.add(currentFolder);
+
+ if (isInAccessibleDrag()) {
+ childrenForAccessibility.add(mLauncher.getSearchBar());
+ }
} else {
super.addChildrenForAccessibility(childrenForAccessibility);
}
@@ -656,8 +692,7 @@ public class DragLayer extends InsettableFrameLayout {
final Runnable onCompleteRunnable, final int animationEndStyle, View anchorView) {
// Calculate the duration of the animation based on the object's distance
- final float dist = (float) Math.sqrt(Math.pow(to.left - from.left, 2) +
- Math.pow(to.top - from.top, 2));
+ final float dist = (float) Math.hypot(to.left - from.left, to.top - from.top);
final Resources res = getResources();
final float maxDist = (float) res.getInteger(R.integer.config_dropAnimMaxDist);
@@ -725,7 +760,6 @@ public class DragLayer extends InsettableFrameLayout {
final int animationEndStyle, View anchorView) {
// Clean up the previous animations
if (mDropAnim != null) mDropAnim.cancel();
- if (mFadeOutAnim != null) mFadeOutAnim.cancel();
// Show the drop view if it was previously hidden
mDropView = view;
@@ -753,9 +787,6 @@ public class DragLayer extends InsettableFrameLayout {
case ANIMATION_END_DISAPPEAR:
clearAnimatedView();
break;
- case ANIMATION_END_FADE_OUT:
- fadeOutDragView();
- break;
case ANIMATION_END_REMAIN_VISIBLE:
break;
}
@@ -779,31 +810,6 @@ public class DragLayer extends InsettableFrameLayout {
return mDropView;
}
- private void fadeOutDragView() {
- mFadeOutAnim = new ValueAnimator();
- mFadeOutAnim.setDuration(150);
- mFadeOutAnim.setFloatValues(0f, 1f);
- mFadeOutAnim.removeAllUpdateListeners();
- mFadeOutAnim.addUpdateListener(new AnimatorUpdateListener() {
- public void onAnimationUpdate(ValueAnimator animation) {
- final float percent = (Float) animation.getAnimatedValue();
-
- float alpha = 1 - percent;
- mDropView.setAlpha(alpha);
- }
- });
- mFadeOutAnim.addListener(new AnimatorListenerAdapter() {
- public void onAnimationEnd(Animator animation) {
- if (mDropView != null) {
- mDragController.onDeferredEndDrag(mDropView);
- }
- mDropView = null;
- invalidate();
- }
- });
- mFadeOutAnim.start();
- }
-
@Override
public void onChildViewAdded(View parent, View child) {
super.onChildViewAdded(parent, child);
@@ -880,6 +886,9 @@ public class DragLayer extends InsettableFrameLayout {
void showPageHints() {
mShowPageHints = true;
+ Workspace workspace = mLauncher.getWorkspace();
+ getDescendantRectRelativeToSelf(workspace.getChildAt(workspace.numCustomPages()),
+ mScrollChildPosition);
invalidate();
}
@@ -888,21 +897,12 @@ public class DragLayer extends InsettableFrameLayout {
invalidate();
}
- /**
- * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
- */
- private boolean isLayoutRtl() {
- return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
- }
-
@Override
protected void dispatchDraw(Canvas canvas) {
- // Draw the background gradient below children.
- if (mBackground != null && mBackgroundAlpha > 0.0f) {
+ // Draw the background below children.
+ if (mBackgroundAlpha > 0.0f) {
int alpha = (int) (mBackgroundAlpha * 255);
- mBackground.setAlpha(alpha);
- mBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
- mBackground.draw(canvas);
+ canvas.drawColor((alpha << 24) | SCRIM_COLOR);
}
super.dispatchDraw(canvas);
@@ -912,27 +912,22 @@ public class DragLayer extends InsettableFrameLayout {
if (mShowPageHints) {
Workspace workspace = mLauncher.getWorkspace();
int width = getMeasuredWidth();
- Rect childRect = new Rect();
- getDescendantRectRelativeToSelf(workspace.getChildAt(workspace.getChildCount() - 1),
- childRect);
-
int page = workspace.getNextPage();
- final boolean isRtl = isLayoutRtl();
- CellLayout leftPage = (CellLayout) workspace.getChildAt(isRtl ? page + 1 : page - 1);
- CellLayout rightPage = (CellLayout) workspace.getChildAt(isRtl ? page - 1 : page + 1);
+ CellLayout leftPage = (CellLayout) workspace.getChildAt(mIsRtl ? page + 1 : page - 1);
+ CellLayout rightPage = (CellLayout) workspace.getChildAt(mIsRtl ? page - 1 : page + 1);
if (leftPage != null && leftPage.isDragTarget()) {
Drawable left = mInScrollArea && leftPage.getIsDragOverlapping() ?
mLeftHoverDrawableActive : mLeftHoverDrawable;
- left.setBounds(0, childRect.top,
- left.getIntrinsicWidth(), childRect.bottom);
+ left.setBounds(0, mScrollChildPosition.top,
+ left.getIntrinsicWidth(), mScrollChildPosition.bottom);
left.draw(canvas);
}
if (rightPage != null && rightPage.isDragTarget()) {
Drawable right = mInScrollArea && rightPage.getIsDragOverlapping() ?
mRightHoverDrawableActive : mRightHoverDrawable;
right.setBounds(width - right.getIntrinsicWidth(),
- childRect.top, width, childRect.bottom);
+ mScrollChildPosition.top, width, mScrollChildPosition.bottom);
right.draw(canvas);
}
}
diff --git a/src/com/android/launcher3/DragSource.java b/src/com/android/launcher3/DragSource.java
index 7369eeac2c..2a1346ef5d 100644
--- a/src/com/android/launcher3/DragSource.java
+++ b/src/com/android/launcher3/DragSource.java
@@ -22,9 +22,9 @@ import com.android.launcher3.DropTarget.DragObject;
/**
* Interface defining an object that can originate a drag.
- *
*/
public interface DragSource {
+
/**
* @return whether items dragged from this source supports
*/
diff --git a/src/com/android/launcher3/DragView.java b/src/com/android/launcher3/DragView.java
index ea34e46f9e..dfa8202a73 100644
--- a/src/com/android/launcher3/DragView.java
+++ b/src/com/android/launcher3/DragView.java
@@ -16,25 +16,35 @@
package com.android.launcher3;
+import android.animation.FloatArrayEvaluator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
+import android.annotation.TargetApi;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.ColorMatrix;
+import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Point;
-import android.graphics.PorterDuff;
-import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
+import android.os.Build;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
+import com.android.launcher3.util.Thunk;
+
+import java.util.Arrays;
+
public class DragView extends View {
- private static float sDragAlpha = 1f;
+ public static int COLOR_CHANGE_DURATION = 120;
+
+ @Thunk static float sDragAlpha = 1f;
private Bitmap mBitmap;
private Bitmap mCrossFadeBitmap;
- private Paint mPaint;
+ @Thunk Paint mPaint;
private int mRegistrationX;
private int mRegistrationY;
@@ -42,16 +52,19 @@ public class DragView extends View {
private Rect mDragRegion = null;
private DragLayer mDragLayer = null;
private boolean mHasDrawn = false;
- private float mCrossFadeProgress = 0f;
+ @Thunk float mCrossFadeProgress = 0f;
ValueAnimator mAnim;
- private float mOffsetX = 0.0f;
- private float mOffsetY = 0.0f;
+ @Thunk float mOffsetX = 0.0f;
+ @Thunk float mOffsetY = 0.0f;
private float mInitialScale = 1f;
// The intrinsic icon scale factor is the scale factor for a drag icon over the workspace
// size. This is ignored for non-icons.
private float mIntrinsicIconScale = 1f;
+ @Thunk float[] mCurrentFilter;
+ private ValueAnimator mFilterAnimator;
+
/**
* Construct the drag view.
*
@@ -63,6 +76,7 @@ public class DragView extends View {
* @param registrationX The x coordinate of the registration point.
* @param registrationY The y coordinate of the registration point.
*/
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
public DragView(Launcher launcher, Bitmap bitmap, int registrationX, int registrationY,
int left, int top, int width, int height, final float initialScale) {
super(launcher);
@@ -70,8 +84,6 @@ public class DragView extends View {
mInitialScale = initialScale;
final Resources res = getResources();
- final float offsetX = res.getDimensionPixelSize(R.dimen.dragViewOffsetX);
- final float offsetY = res.getDimensionPixelSize(R.dimen.dragViewOffsetY);
final float scaleDps = res.getDimensionPixelSize(R.dimen.dragViewScale);
final float scale = (width + scaleDps) / width;
@@ -87,8 +99,8 @@ public class DragView extends View {
public void onAnimationUpdate(ValueAnimator animation) {
final float value = (Float) animation.getAnimatedValue();
- final int deltaX = (int) ((value * offsetX) - mOffsetX);
- final int deltaY = (int) ((value * offsetY) - mOffsetY);
+ final int deltaX = (int) (-mOffsetX);
+ final int deltaY = (int) (-mOffsetY);
mOffsetX += deltaX;
mOffsetY += deltaY;
@@ -118,6 +130,10 @@ public class DragView extends View {
int ms = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
measure(ms, ms);
mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
+
+ if (Utilities.isLmpOrAbove()) {
+ setElevation(getResources().getDimension(R.dimen.drag_elevation));
+ }
}
/** Sets the scale of the view over the normal workspace icon size. */
@@ -229,11 +245,49 @@ public class DragView extends View {
mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
}
if (color != 0) {
- mPaint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP));
+ ColorMatrix m1 = new ColorMatrix();
+ m1.setSaturation(0);
+
+ ColorMatrix m2 = new ColorMatrix();
+ setColorScale(color, m2);
+ m1.postConcat(m2);
+
+ if (Utilities.isLmpOrAbove()) {
+ animateFilterTo(m1.getArray());
+ } else {
+ mPaint.setColorFilter(new ColorMatrixColorFilter(m1));
+ invalidate();
+ }
} else {
- mPaint.setColorFilter(null);
+ if (!Utilities.isLmpOrAbove() || mCurrentFilter == null) {
+ mPaint.setColorFilter(null);
+ invalidate();
+ } else {
+ animateFilterTo(new ColorMatrix().getArray());
+ }
}
- invalidate();
+ }
+
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+ private void animateFilterTo(float[] targetFilter) {
+ float[] oldFilter = mCurrentFilter == null ? new ColorMatrix().getArray() : mCurrentFilter;
+ mCurrentFilter = Arrays.copyOf(oldFilter, oldFilter.length);
+
+ if (mFilterAnimator != null) {
+ mFilterAnimator.cancel();
+ }
+ mFilterAnimator = ValueAnimator.ofObject(new FloatArrayEvaluator(mCurrentFilter),
+ oldFilter, targetFilter);
+ mFilterAnimator.setDuration(COLOR_CHANGE_DURATION);
+ mFilterAnimator.addUpdateListener(new AnimatorUpdateListener() {
+
+ @Override
+ public void onAnimationUpdate(ValueAnimator animation) {
+ mPaint.setColorFilter(new ColorMatrixColorFilter(mCurrentFilter));
+ invalidate();
+ }
+ });
+ mFilterAnimator.start();
}
public boolean hasDrawn() {
@@ -300,5 +354,9 @@ public class DragView extends View {
mDragLayer.removeView(DragView.this);
}
}
-}
+ public static void setColorScale(int color, ColorMatrix target) {
+ target.setScale(Color.red(color) / 255f, Color.green(color) / 255f,
+ Color.blue(color) / 255f, Color.alpha(color) / 255f);
+ }
+}
diff --git a/src/com/android/launcher3/DropTarget.java b/src/com/android/launcher3/DropTarget.java
index 64f0ac867c..c8fac54669 100644
--- a/src/com/android/launcher3/DropTarget.java
+++ b/src/com/android/launcher3/DropTarget.java
@@ -16,10 +16,8 @@
package com.android.launcher3;
-import android.content.Context;
import android.graphics.PointF;
import android.graphics.Rect;
-import android.util.Log;
/**
* Interface defining an object that can receive a drag.
@@ -29,7 +27,7 @@ public interface DropTarget {
public static final String TAG = "DropTarget";
- class DragObject {
+ public static class DragObject {
public int x = -1;
public int y = -1;
@@ -54,6 +52,9 @@ public interface DropTarget {
/** Where the drag originated */
public DragSource dragSource = null;
+ /** The object is part of an accessible drag operation */
+ public boolean accessibleDrag;
+
/** Post drag animation runnable */
public Runnable postAnimationRunnable = null;
@@ -65,42 +66,28 @@ public interface DropTarget {
public DragObject() {
}
- }
- public static class DragEnforcer implements DragController.DragListener {
- int dragParity = 0;
+ /**
+ * This is used to compute the visual center of the dragView. This point is then
+ * used to visualize drop locations and determine where to drop an item. The idea is that
+ * the visual center represents the user's interpretation of where the item is, and hence
+ * is the appropriate point to use when determining drop location.
+ */
+ public final float[] getVisualCenter(float[] recycle) {
+ final float res[] = (recycle == null) ? new float[2] : recycle;
- public DragEnforcer(Context context) {
- Launcher launcher = (Launcher) context;
- launcher.getDragController().addDragListener(this);
- }
+ // These represent the visual top and left of drag view if a dragRect was provided.
+ // If a dragRect was not provided, then they correspond to the actual view left and
+ // top, as the dragRect is in that case taken to be the entire dragView.
+ // R.dimen.dragViewOffsetY.
+ int left = x - xOffset;
+ int top = y - yOffset;
- void onDragEnter() {
- dragParity++;
- if (dragParity != 1) {
- Log.e(TAG, "onDragEnter: Drag contract violated: " + dragParity);
- }
- }
+ // In order to find the visual center, we shift by half the dragRect
+ res[0] = left + dragView.getDragRegion().width() / 2;
+ res[1] = top + dragView.getDragRegion().height() / 2;
- void onDragExit() {
- dragParity--;
- if (dragParity != 0) {
- Log.e(TAG, "onDragExit: Drag contract violated: " + dragParity);
- }
- }
-
- @Override
- public void onDragStart(DragSource source, Object info, int dragAction) {
- if (dragParity != 0) {
- Log.e(TAG, "onDragEnter: Drag contract violated: " + dragParity);
- }
- }
-
- @Override
- public void onDragEnd() {
- if (dragParity != 0) {
- Log.e(TAG, "onDragExit: Drag contract violated: " + dragParity);
- }
+ return res;
}
}
@@ -113,7 +100,7 @@ public interface DropTarget {
/**
* Handle an object being dropped on the DropTarget
- *
+ *
* @param source DragSource where the drag started
* @param x X coordinate of the drop location
* @param y Y coordinate of the drop location
@@ -138,12 +125,12 @@ public interface DropTarget {
* of onDrop(). (This is only called on objects that are set as the DragController's
* fling-to-delete target.
*/
- void onFlingToDelete(DragObject dragObject, int x, int y, PointF vec);
+ void onFlingToDelete(DragObject dragObject, PointF vec);
/**
* Check if a drop action can occur at, or near, the requested location.
* This will be called just before onDrop.
- *
+ *
* @param source DragSource where the drag started
* @param x X coordinate of the drop location
* @param y Y coordinate of the drop location
@@ -157,6 +144,8 @@ public interface DropTarget {
*/
boolean acceptDrop(DragObject dragObject);
+ void prepareAccessibilityDrop();
+
// These methods are implemented in Views
void getHitRectRelativeToDragLayer(Rect outRect);
void getLocationInDragLayer(int[] loc);
diff --git a/src/com/android/launcher3/DummyWidget.java b/src/com/android/launcher3/DummyWidget.java
new file mode 100644
index 0000000000..59cd805012
--- /dev/null
+++ b/src/com/android/launcher3/DummyWidget.java
@@ -0,0 +1,50 @@
+package com.android.launcher3;
+
+import android.appwidget.AppWidgetProviderInfo;
+
+public class DummyWidget implements CustomAppWidget {
+ @Override
+ public String getLabel() {
+ return "Dumb Launcher Widget";
+ }
+
+ @Override
+ public int getPreviewImage() {
+ return 0;
+ }
+
+ @Override
+ public int getIcon() {
+ return 0;
+ }
+
+ @Override
+ public int getWidgetLayout() {
+ return R.layout.dummy_widget;
+ }
+
+ @Override
+ public int getSpanX() {
+ return 2;
+ }
+
+ @Override
+ public int getSpanY() {
+ return 2;
+ }
+
+ @Override
+ public int getMinSpanX() {
+ return 1;
+ }
+
+ @Override
+ public int getMinSpanY() {
+ return 1;
+ }
+
+ @Override
+ public int getResizeMode() {
+ return AppWidgetProviderInfo.RESIZE_BOTH;
+ }
+}
diff --git a/src/com/android/launcher3/DynamicGrid.java b/src/com/android/launcher3/DynamicGrid.java
deleted file mode 100644
index aa08148d2a..0000000000
--- a/src/com/android/launcher3/DynamicGrid.java
+++ /dev/null
@@ -1,109 +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.content.Context;
-import android.content.res.Resources;
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
-
-import java.util.ArrayList;
-
-
-public class DynamicGrid {
- @SuppressWarnings("unused")
- private static final String TAG = "DynamicGrid";
-
- private DeviceProfile mProfile;
- private float mMinWidth;
- private float mMinHeight;
-
- // This is a static that we use for the default icon size on a 4/5-inch phone
- static float DEFAULT_ICON_SIZE_DP = 60;
- static float DEFAULT_ICON_SIZE_PX = 0;
-
- public static float dpiFromPx(int size, DisplayMetrics metrics){
- float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT;
- return (size / densityRatio);
- }
- public static int pxFromDp(float size, DisplayMetrics metrics) {
- return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
- size, metrics));
- }
- public static int pxFromSp(float size, DisplayMetrics metrics) {
- return (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
- size, metrics));
- }
-
- public DynamicGrid(Context context, Resources resources,
- int minWidthPx, int minHeightPx,
- int widthPx, int heightPx,
- int awPx, int ahPx) {
- DisplayMetrics dm = resources.getDisplayMetrics();
- ArrayList deviceProfiles =
- new ArrayList();
- boolean hasAA = !LauncherAppState.isDisableAllApps();
- DEFAULT_ICON_SIZE_PX = pxFromDp(DEFAULT_ICON_SIZE_DP, dm);
- // Our phone profiles include the bar sizes in each orientation
- deviceProfiles.add(new DeviceProfile("Super Short Stubby",
- 255, 300, 2, 3, 48, 13, (hasAA ? 3 : 5), 48, R.xml.default_workspace_4x4));
- deviceProfiles.add(new DeviceProfile("Shorter Stubby",
- 255, 400, 3, 3, 48, 13, (hasAA ? 3 : 5), 48, R.xml.default_workspace_4x4));
- deviceProfiles.add(new DeviceProfile("Short Stubby",
- 275, 420, 3, 4, 48, 13, (hasAA ? 5 : 5), 48, R.xml.default_workspace_4x4));
- deviceProfiles.add(new DeviceProfile("Stubby",
- 255, 450, 3, 4, 48, 13, (hasAA ? 5 : 5), 48, R.xml.default_workspace_4x4));
- deviceProfiles.add(new DeviceProfile("Nexus S",
- 296, 491.33f, 4, 4, 48, 13, (hasAA ? 5 : 5), 48, R.xml.default_workspace_4x4));
- deviceProfiles.add(new DeviceProfile("Nexus 4",
- 335, 567, 4, 4, DEFAULT_ICON_SIZE_DP, 13, (hasAA ? 5 : 5), 56, R.xml.default_workspace_4x4));
- deviceProfiles.add(new DeviceProfile("Nexus 5",
- 359, 567, 4, 4, DEFAULT_ICON_SIZE_DP, 13, (hasAA ? 5 : 5), 56, R.xml.default_workspace_4x4));
- deviceProfiles.add(new DeviceProfile("Large Phone",
- 406, 694, 5, 5, 64, 14.4f, 5, 56, R.xml.default_workspace_5x5));
- // The tablet profile is odd in that the landscape orientation
- // also includes the nav bar on the side
- deviceProfiles.add(new DeviceProfile("Nexus 7",
- 575, 904, 5, 6, 72, 14.4f, 7, 60, R.xml.default_workspace_5x6));
- // Larger tablet profiles always have system bars on the top & bottom
- deviceProfiles.add(new DeviceProfile("Nexus 10",
- 727, 1207, 5, 6, 76, 14.4f, 7, 64, R.xml.default_workspace_5x6));
- deviceProfiles.add(new DeviceProfile("20-inch Tablet",
- 1527, 2527, 7, 7, 100, 20, 7, 72, R.xml.default_workspace_4x4));
- mMinWidth = dpiFromPx(minWidthPx, dm);
- mMinHeight = dpiFromPx(minHeightPx, dm);
- mProfile = new DeviceProfile(context, deviceProfiles,
- mMinWidth, mMinHeight,
- widthPx, heightPx,
- awPx, ahPx,
- resources);
- }
-
- public DeviceProfile getDeviceProfile() {
- return mProfile;
- }
-
- public String toString() {
- return "-------- DYNAMIC GRID ------- \n" +
- "Wd: " + mProfile.minWidthDps + ", Hd: " + mProfile.minHeightDps +
- ", W: " + mProfile.widthPx + ", H: " + mProfile.heightPx +
- " [r: " + mProfile.numRows + ", c: " + mProfile.numColumns +
- ", is: " + mProfile.iconSizePx + ", its: " + mProfile.iconTextSizePx +
- ", cw: " + mProfile.cellWidthPx + ", ch: " + mProfile.cellHeightPx +
- ", hc: " + mProfile.numHotseatIcons + ", his: " + mProfile.hotseatIconSizePx + "]";
- }
-}
diff --git a/src/com/android/launcher3/FastBitmapDrawable.java b/src/com/android/launcher3/FastBitmapDrawable.java
index ff02bbbc33..28e923e67a 100644
--- a/src/com/android/launcher3/FastBitmapDrawable.java
+++ b/src/com/android/launcher3/FastBitmapDrawable.java
@@ -32,7 +32,7 @@ import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.SparseArray;
-class FastBitmapDrawable extends Drawable {
+public class FastBitmapDrawable extends Drawable {
static final TimeInterpolator CLICK_FEEDBACK_INTERPOLATOR = new TimeInterpolator() {
@@ -72,7 +72,7 @@ class FastBitmapDrawable extends Drawable {
private boolean mPressed = false;
private ObjectAnimator mPressedAnimator;
- FastBitmapDrawable(Bitmap b) {
+ public FastBitmapDrawable(Bitmap b) {
mAlpha = 255;
mBitmap = b;
setBounds(0, 0, b.getWidth(), b.getHeight());
diff --git a/src/com/android/launcher3/FastBitmapView.java b/src/com/android/launcher3/FastBitmapView.java
deleted file mode 100644
index 0937eb75eb..0000000000
--- a/src/com/android/launcher3/FastBitmapView.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2014 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.Context;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Paint;
-import android.view.View;
-
-public class FastBitmapView extends View {
-
- private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
- private Bitmap mBitmap;
-
- public FastBitmapView(Context context) {
- super(context);
- }
-
- /**
- * Applies the new bitmap.
- * @return true if the view was invalidated.
- */
- public boolean setBitmap(Bitmap b) {
- if (b != mBitmap){
- if (mBitmap != null) {
- invalidate(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
- }
- mBitmap = b;
- if (mBitmap != null) {
- invalidate(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
- }
- return true;
- }
- return false;
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- if (mBitmap != null) {
- canvas.drawBitmap(mBitmap, 0, 0, mPaint);
- }
- }
-}
diff --git a/src/com/android/launcher3/FirstFrameAnimatorHelper.java b/src/com/android/launcher3/FirstFrameAnimatorHelper.java
index 095c5631d5..a51ddd4b88 100644
--- a/src/com/android/launcher3/FirstFrameAnimatorHelper.java
+++ b/src/com/android/launcher3/FirstFrameAnimatorHelper.java
@@ -24,6 +24,8 @@ import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.ViewTreeObserver;
+import com.android.launcher3.util.Thunk;
+
/*
* This is a helper class that listens to updates from the corresponding animation.
* For the first two frames, it adjusts the current play time of the animation to
@@ -41,7 +43,7 @@ public class FirstFrameAnimatorHelper extends AnimatorListenerAdapter
private boolean mAdjustedSecondFrameTime;
private static ViewTreeObserver.OnDrawListener sGlobalDrawListener;
- private static long sGlobalFrameCounter;
+ @Thunk static long sGlobalFrameCounter;
private static boolean sVisible;
public FirstFrameAnimatorHelper(ValueAnimator animator, View target) {
diff --git a/src/com/android/launcher3/FocusHelper.java b/src/com/android/launcher3/FocusHelper.java
index e607047188..57aec32801 100644
--- a/src/com/android/launcher3/FocusHelper.java
+++ b/src/com/android/launcher3/FocusHelper.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2015 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.
@@ -16,658 +16,445 @@
package com.android.launcher3;
-import android.content.res.Configuration;
+import android.util.Log;
import android.view.KeyEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewGroup;
-import android.widget.ScrollView;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
+import com.android.launcher3.util.FocusLogic;
+import com.android.launcher3.util.Thunk;
/**
* A keyboard listener we set on all the workspace icons.
*/
class IconKeyEventListener implements View.OnKeyListener {
+ @Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return FocusHelper.handleIconKeyEvent(v, keyCode, event);
}
}
-/**
- * A keyboard listener we set on all the workspace icons.
- */
-class FolderKeyEventListener implements View.OnKeyListener {
- public boolean onKey(View v, int keyCode, KeyEvent event) {
- return FocusHelper.handleFolderKeyEvent(v, keyCode, event);
- }
-}
-
/**
* A keyboard listener we set on all the hotseat buttons.
*/
class HotseatIconKeyEventListener implements View.OnKeyListener {
+ @Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
- final Configuration configuration = v.getResources().getConfiguration();
- return FocusHelper.handleHotseatButtonKeyEvent(v, keyCode, event, configuration.orientation);
+ return FocusHelper.handleHotseatButtonKeyEvent(v, keyCode, event);
}
}
public class FocusHelper {
+ private static final String TAG = "FocusHelper";
+ private static final boolean DEBUG = false;
+
/**
- * Returns the Viewgroup containing page contents for the page at the index specified.
+ * Handles key events in paged folder.
*/
- private static ViewGroup getAppsCustomizePage(ViewGroup container, int index) {
- ViewGroup page = (ViewGroup) ((PagedView) container).getPageAt(index);
- if (page instanceof CellLayout) {
- // There are two layers, a PagedViewCellLayout and PagedViewCellLayoutChildren
- page = ((CellLayout) page).getShortcutsAndWidgets();
+ public static class PagedFolderKeyEventListener implements View.OnKeyListener {
+
+ private final Folder mFolder;
+
+ public PagedFolderKeyEventListener(Folder folder) {
+ mFolder = folder;
+ }
+
+ @Override
+ public boolean onKey(View v, int keyCode, KeyEvent e) {
+ boolean consume = FocusLogic.shouldConsume(keyCode);
+ if (e.getAction() == KeyEvent.ACTION_UP) {
+ return consume;
+ }
+ if (DEBUG) {
+ Log.v(TAG, String.format("Handle ALL Folders keyevent=[%s].",
+ KeyEvent.keyCodeToString(keyCode)));
+ }
+
+
+ if (!(v.getParent() instanceof ShortcutAndWidgetContainer)) {
+ if (LauncherAppState.isDogfoodBuild()) {
+ throw new IllegalStateException("Parent of the focused item is not supported.");
+ } else {
+ return false;
+ }
+ }
+
+ // Initialize variables.
+ final ShortcutAndWidgetContainer itemContainer = (ShortcutAndWidgetContainer) v.getParent();
+ final CellLayout cellLayout = (CellLayout) itemContainer.getParent();
+ final int countX = cellLayout.getCountX();
+ final int countY = cellLayout.getCountY();
+
+ final int iconIndex = itemContainer.indexOfChild(v);
+ final FolderPagedView pagedView = (FolderPagedView) cellLayout.getParent();
+
+ final int pageIndex = pagedView.indexOfChild(cellLayout);
+ final int pageCount = pagedView.getPageCount();
+ final boolean isLayoutRtl = Utilities.isRtl(v.getResources());
+
+ int[][] matrix = FocusLogic.createSparseMatrix(cellLayout);
+ // Process focus.
+ int newIconIndex = FocusLogic.handleKeyEvent(keyCode, countX,
+ countY, matrix, iconIndex, pageIndex, pageCount, isLayoutRtl);
+ if (newIconIndex == FocusLogic.NOOP) {
+ handleNoopKey(keyCode, v);
+ return consume;
+ }
+ ShortcutAndWidgetContainer newParent = null;
+ View child = null;
+
+ switch (newIconIndex) {
+ case FocusLogic.PREVIOUS_PAGE_RIGHT_COLUMN:
+ case FocusLogic.PREVIOUS_PAGE_LEFT_COLUMN:
+ newParent = getCellLayoutChildrenForIndex(pagedView, pageIndex - 1);
+ if (newParent != null) {
+ int row = ((CellLayout.LayoutParams) v.getLayoutParams()).cellY;
+ pagedView.snapToPage(pageIndex - 1);
+ child = newParent.getChildAt(
+ ((newIconIndex == FocusLogic.PREVIOUS_PAGE_LEFT_COLUMN)
+ ^ newParent.invertLayoutHorizontally()) ? 0 : countX - 1, row);
+ }
+ break;
+ case FocusLogic.PREVIOUS_PAGE_FIRST_ITEM:
+ newParent = getCellLayoutChildrenForIndex(pagedView, pageIndex - 1);
+ if (newParent != null) {
+ pagedView.snapToPage(pageIndex - 1);
+ child = newParent.getChildAt(0, 0);
+ }
+ break;
+ case FocusLogic.PREVIOUS_PAGE_LAST_ITEM:
+ newParent = getCellLayoutChildrenForIndex(pagedView, pageIndex - 1);
+ if (newParent != null) {
+ pagedView.snapToPage(pageIndex - 1);
+ child = newParent.getChildAt(countX - 1, countY - 1);
+ }
+ break;
+ case FocusLogic.NEXT_PAGE_FIRST_ITEM:
+ newParent = getCellLayoutChildrenForIndex(pagedView, pageIndex + 1);
+ if (newParent != null) {
+ pagedView.snapToPage(pageIndex + 1);
+ child = newParent.getChildAt(0, 0);
+ }
+ break;
+ case FocusLogic.NEXT_PAGE_LEFT_COLUMN:
+ case FocusLogic.NEXT_PAGE_RIGHT_COLUMN:
+ newParent = getCellLayoutChildrenForIndex(pagedView, pageIndex + 1);
+ if (newParent != null) {
+ pagedView.snapToPage(pageIndex + 1);
+ child = FocusLogic.getAdjacentChildInNextPage(newParent, v, newIconIndex);
+ }
+ break;
+ case FocusLogic.CURRENT_PAGE_FIRST_ITEM:
+ child = cellLayout.getChildAt(0, 0);
+ break;
+ case FocusLogic.CURRENT_PAGE_LAST_ITEM:
+ child = pagedView.getLastItem();
+ break;
+ default: // Go to some item on the current page.
+ child = itemContainer.getChildAt(newIconIndex);
+ break;
+ }
+ if (child != null) {
+ child.requestFocus();
+ playSoundEffect(keyCode, v);
+ } else {
+ handleNoopKey(keyCode, v);
+ }
+ return consume;
+ }
+
+ public void handleNoopKey(int keyCode, View v) {
+ if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
+ mFolder.mFolderName.requestFocus();
+ playSoundEffect(keyCode, v);
+ }
}
- return page;
}
/**
- * Handles key events in a PageViewCellLayout containing PagedViewIcons.
+ * Handles key events in the workspace hot seat (bottom of the screen).
+ * Currently we don't special case for the phone UI in different orientations, even though
+ * the hotseat is on the side in landscape mode. This is to ensure that accessibility
+ * consistency is maintained across rotations.
*/
- static boolean handleAppsCustomizeKeyEvent(View v, int keyCode, KeyEvent e) {
- ViewGroup parentLayout;
- ViewGroup itemContainer;
- int countX;
- int countY;
- if (v.getParent() instanceof ShortcutAndWidgetContainer) {
- itemContainer = (ViewGroup) v.getParent();
- parentLayout = (ViewGroup) itemContainer.getParent();
- countX = ((CellLayout) parentLayout).getCountX();
- countY = ((CellLayout) parentLayout).getCountY();
- } else {
- itemContainer = parentLayout = (ViewGroup) v.getParent();
- countX = ((PagedViewGridLayout) parentLayout).getCellCountX();
- countY = ((PagedViewGridLayout) parentLayout).getCellCountY();
+ static boolean handleHotseatButtonKeyEvent(View v, int keyCode, KeyEvent e) {
+ boolean consume = FocusLogic.shouldConsume(keyCode);
+ if (e.getAction() == KeyEvent.ACTION_UP || !consume) {
+ return consume;
}
- // Note we have an extra parent because of the
- // PagedViewCellLayout/PagedViewCellLayoutChildren relationship
- final PagedView container = (PagedView) parentLayout.getParent();
- final int iconIndex = itemContainer.indexOfChild(v);
- final int itemCount = itemContainer.getChildCount();
- final int pageIndex = ((PagedView) container).indexToPage(container.indexOfChild(parentLayout));
- final int pageCount = container.getChildCount();
+ DeviceProfile profile = ((Launcher) v.getContext()).getDeviceProfile();
- final int x = iconIndex % countX;
- final int y = iconIndex / countX;
-
- final int action = e.getAction();
- final boolean handleKeyEvent = (action != KeyEvent.ACTION_UP);
- ViewGroup newParent = null;
- // Side pages do not always load synchronously, so check before focusing child siblings
- // willy-nilly
- View child = null;
- boolean wasHandled = false;
- switch (keyCode) {
- case KeyEvent.KEYCODE_DPAD_LEFT:
- if (handleKeyEvent) {
- // Select the previous icon or the last icon on the previous page
- if (iconIndex > 0) {
- itemContainer.getChildAt(iconIndex - 1).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_LEFT);
- } else {
- if (pageIndex > 0) {
- newParent = getAppsCustomizePage(container, pageIndex - 1);
- if (newParent != null) {
- container.snapToPage(pageIndex - 1);
- child = newParent.getChildAt(newParent.getChildCount() - 1);
- if (child != null) {
- child.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_LEFT);
- }
- }
- }
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_DPAD_RIGHT:
- if (handleKeyEvent) {
- // Select the next icon or the first icon on the next page
- if (iconIndex < (itemCount - 1)) {
- itemContainer.getChildAt(iconIndex + 1).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_RIGHT);
- } else {
- if (pageIndex < (pageCount - 1)) {
- newParent = getAppsCustomizePage(container, pageIndex + 1);
- if (newParent != null) {
- container.snapToPage(pageIndex + 1);
- child = newParent.getChildAt(0);
- if (child != null) {
- child.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_RIGHT);
- }
- }
- }
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_DPAD_UP:
- if (handleKeyEvent) {
- // Select the closest icon in the previous row, otherwise select the tab bar
- if (y > 0) {
- int newiconIndex = ((y - 1) * countX) + x;
- itemContainer.getChildAt(newiconIndex).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_DPAD_DOWN:
- if (handleKeyEvent) {
- // Select the closest icon in the next row, otherwise do nothing
- if (y < (countY - 1)) {
- int newiconIndex = Math.min(itemCount - 1, ((y + 1) * countX) + x);
- int newIconY = newiconIndex / countX;
- if (newIconY != y) {
- itemContainer.getChildAt(newiconIndex).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- }
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_PAGE_UP:
- if (handleKeyEvent) {
- // Select the first icon on the previous page, or the first icon on this page
- // if there is no previous page
- if (pageIndex > 0) {
- newParent = getAppsCustomizePage(container, pageIndex - 1);
- if (newParent != null) {
- container.snapToPage(pageIndex - 1);
- child = newParent.getChildAt(0);
- if (child != null) {
- child.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- }
- }
- } else {
- itemContainer.getChildAt(0).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_PAGE_DOWN:
- if (handleKeyEvent) {
- // Select the first icon on the next page, or the last icon on this page
- // if there is no next page
- if (pageIndex < (pageCount - 1)) {
- newParent = getAppsCustomizePage(container, pageIndex + 1);
- if (newParent != null) {
- container.snapToPage(pageIndex + 1);
- child = newParent.getChildAt(0);
- if (child != null) {
- child.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- }
- }
- } else {
- itemContainer.getChildAt(itemCount - 1).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_MOVE_HOME:
- if (handleKeyEvent) {
- // Select the first icon on this page
- itemContainer.getChildAt(0).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_MOVE_END:
- if (handleKeyEvent) {
- // Select the last icon on this page
- itemContainer.getChildAt(itemCount - 1).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- }
- wasHandled = true;
- break;
- default: break;
+ if (DEBUG) {
+ Log.v(TAG, String.format(
+ "Handle HOTSEAT BUTTONS keyevent=[%s] on hotseat buttons, isVertical=%s",
+ KeyEvent.keyCodeToString(keyCode), profile.isVerticalBarLayout()));
}
- return wasHandled;
+
+ // Initialize the variables.
+ final ShortcutAndWidgetContainer hotseatParent = (ShortcutAndWidgetContainer) v.getParent();
+ final CellLayout hotseatLayout = (CellLayout) hotseatParent.getParent();
+ Hotseat hotseat = (Hotseat) hotseatLayout.getParent();
+
+ Workspace workspace = (Workspace) v.getRootView().findViewById(R.id.workspace);
+ int pageIndex = workspace.getNextPage();
+ int pageCount = workspace.getChildCount();
+ int countX = -1;
+ int countY = -1;
+ int iconIndex = hotseatParent.indexOfChild(v);
+ int iconRank = ((CellLayout.LayoutParams) hotseatLayout.getShortcutsAndWidgets()
+ .getChildAt(iconIndex).getLayoutParams()).cellX;
+
+ final CellLayout iconLayout = (CellLayout) workspace.getChildAt(pageIndex);
+ if (iconLayout == null) {
+ // This check is to guard against cases where key strokes rushes in when workspace
+ // child creation/deletion is still in flux. (e.g., during drop or fling
+ // animation.)
+ return consume;
+ }
+ final ViewGroup iconParent = iconLayout.getShortcutsAndWidgets();
+
+ ViewGroup parent = null;
+ int[][] matrix = null;
+
+ if (keyCode == KeyEvent.KEYCODE_DPAD_UP &&
+ !profile.isVerticalBarLayout()) {
+ matrix = FocusLogic.createSparseMatrix(iconLayout, hotseatLayout,
+ true /* hotseat horizontal */, profile.inv.hotseatAllAppsRank,
+ iconRank == profile.inv.hotseatAllAppsRank /* include all apps icon */);
+ iconIndex += iconParent.getChildCount();
+ countX = iconLayout.getCountX();
+ countY = iconLayout.getCountY() + hotseatLayout.getCountY();
+ parent = iconParent;
+ } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT &&
+ profile.isVerticalBarLayout()) {
+ matrix = FocusLogic.createSparseMatrix(iconLayout, hotseatLayout,
+ false /* hotseat horizontal */, profile.inv.hotseatAllAppsRank,
+ iconRank == profile.inv.hotseatAllAppsRank /* include all apps icon */);
+ iconIndex += iconParent.getChildCount();
+ countX = iconLayout.getCountX() + hotseatLayout.getCountX();
+ countY = iconLayout.getCountY();
+ parent = iconParent;
+ } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT &&
+ profile.isVerticalBarLayout()) {
+ keyCode = KeyEvent.KEYCODE_PAGE_DOWN;
+ }else {
+ // For other KEYCODE_DPAD_LEFT and KEYCODE_DPAD_RIGHT navigation, do not use the
+ // matrix extended with hotseat.
+ matrix = FocusLogic.createSparseMatrix(hotseatLayout);
+ countX = hotseatLayout.getCountX();
+ countY = hotseatLayout.getCountY();
+ parent = hotseatParent;
+ }
+
+ // Process the focus.
+ int newIconIndex = FocusLogic.handleKeyEvent(keyCode, countX,
+ countY, matrix, iconIndex, pageIndex, pageCount, Utilities.isRtl(v.getResources()));
+
+ View newIcon = null;
+ if (newIconIndex == FocusLogic.NEXT_PAGE_FIRST_ITEM) {
+ parent = getCellLayoutChildrenForIndex(workspace, pageIndex + 1);
+ newIcon = parent.getChildAt(0);
+ // TODO(hyunyoungs): handle cases where the child is not an icon but
+ // a folder or a widget.
+ workspace.snapToPage(pageIndex + 1);
+ }
+ if (parent == iconParent && newIconIndex >= iconParent.getChildCount()) {
+ newIconIndex -= iconParent.getChildCount();
+ }
+ if (parent != null) {
+ if (newIcon == null && newIconIndex >=0) {
+ newIcon = parent.getChildAt(newIconIndex);
+ }
+ if (newIcon != null) {
+ newIcon.requestFocus();
+ playSoundEffect(keyCode, v);
+ }
+ }
+ return consume;
}
/**
- * Handles key events in the workspace hotseat (bottom of the screen).
+ * Handles key events in a workspace containing icons.
*/
- static boolean handleHotseatButtonKeyEvent(View v, int keyCode, KeyEvent e, int orientation) {
+ static boolean handleIconKeyEvent(View v, int keyCode, KeyEvent e) {
+ boolean consume = FocusLogic.shouldConsume(keyCode);
+ if (e.getAction() == KeyEvent.ACTION_UP || !consume) {
+ return consume;
+ }
+
+ Launcher launcher = (Launcher) v.getContext();
+ DeviceProfile profile = launcher.getDeviceProfile();
+
+ if (DEBUG) {
+ Log.v(TAG, String.format("Handle WORKSPACE ICONS keyevent=[%s] isVerticalBar=%s",
+ KeyEvent.keyCodeToString(keyCode), profile.isVerticalBarLayout()));
+ }
+
+ // Initialize the variables.
ShortcutAndWidgetContainer parent = (ShortcutAndWidgetContainer) v.getParent();
- final CellLayout layout = (CellLayout) parent.getParent();
+ CellLayout iconLayout = (CellLayout) parent.getParent();
+ final Workspace workspace = (Workspace) iconLayout.getParent();
+ final ViewGroup dragLayer = (ViewGroup) workspace.getParent();
+ final ViewGroup tabs = (ViewGroup) dragLayer.findViewById(R.id.search_drop_target_bar);
+ final Hotseat hotseat = (Hotseat) dragLayer.findViewById(R.id.hotseat);
- // NOTE: currently we don't special case for the phone UI in different
- // orientations, even though the hotseat is on the side in landscape mode. This
- // is to ensure that accessibility consistency is maintained across rotations.
- final int action = e.getAction();
- final boolean handleKeyEvent = (action != KeyEvent.ACTION_UP);
- boolean wasHandled = false;
- switch (keyCode) {
- case KeyEvent.KEYCODE_DPAD_LEFT:
- if (handleKeyEvent) {
- ArrayList views = getCellLayoutChildrenSortedSpatially(layout, parent);
- int myIndex = views.indexOf(v);
- // Select the previous button, otherwise do nothing
- if (myIndex > 0) {
- views.get(myIndex - 1).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_LEFT);
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_DPAD_RIGHT:
- if (handleKeyEvent) {
- ArrayList views = getCellLayoutChildrenSortedSpatially(layout, parent);
- int myIndex = views.indexOf(v);
- // Select the next button, otherwise do nothing
- if (myIndex < views.size() - 1) {
- views.get(myIndex + 1).requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_RIGHT);
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_DPAD_UP:
- if (handleKeyEvent) {
- final Workspace workspace = (Workspace)
- v.getRootView().findViewById(R.id.workspace);
- if (workspace != null) {
- int pageIndex = workspace.getCurrentPage();
- CellLayout topLayout = (CellLayout) workspace.getChildAt(pageIndex);
- ShortcutAndWidgetContainer children = topLayout.getShortcutsAndWidgets();
- final View newIcon = getIconInDirection(layout, children, -1, 1);
- // Select the first bubble text view in the current page of the workspace
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- } else {
- workspace.requestFocus();
- }
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_DPAD_DOWN:
- // Do nothing
- wasHandled = true;
- break;
- default: break;
+ final int iconIndex = parent.indexOfChild(v);
+ final int pageIndex = workspace.indexOfChild(iconLayout);
+ final int pageCount = workspace.getChildCount();
+ int countX = iconLayout.getCountX();
+ int countY = iconLayout.getCountY();
+
+ CellLayout hotseatLayout = (CellLayout) hotseat.getChildAt(0);
+ ShortcutAndWidgetContainer hotseatParent = hotseatLayout.getShortcutsAndWidgets();
+ int[][] matrix;
+
+ // KEYCODE_DPAD_DOWN in portrait (KEYCODE_DPAD_RIGHT in landscape) is the only key allowed
+ // to take a user to the hotseat. For other dpad navigation, do not use the matrix extended
+ // with the hotseat.
+ if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && !profile.isVerticalBarLayout()) {
+ matrix = FocusLogic.createSparseMatrix(iconLayout, hotseatLayout, true /* horizontal */,
+ profile.inv.hotseatAllAppsRank,
+ !hotseat.hasIcons() /* ignore all apps icon, unless there are no other icons */);
+ countY = countY + 1;
+ } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT &&
+ profile.isVerticalBarLayout()) {
+ matrix = FocusLogic.createSparseMatrix(iconLayout, hotseatLayout, false /* horizontal */,
+ profile.inv.hotseatAllAppsRank,
+ !hotseat.hasIcons() /* ignore all apps icon, unless there are no other icons */);
+ countX = countX + 1;
+ } else if (keyCode == KeyEvent.KEYCODE_DEL || keyCode == KeyEvent.KEYCODE_FORWARD_DEL) {
+ workspace.removeWorkspaceItem(v);
+ return consume;
+ } else {
+ matrix = FocusLogic.createSparseMatrix(iconLayout);
}
- return wasHandled;
+
+ // Process the focus.
+ int newIconIndex = FocusLogic.handleKeyEvent(keyCode, countX,
+ countY, matrix, iconIndex, pageIndex, pageCount, Utilities.isRtl(v.getResources()));
+ View newIcon = null;
+ switch (newIconIndex) {
+ case FocusLogic.NOOP:
+ if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
+ newIcon = tabs;
+ }
+ break;
+ case FocusLogic.PREVIOUS_PAGE_RIGHT_COLUMN:
+ case FocusLogic.NEXT_PAGE_RIGHT_COLUMN:
+ int newPageIndex = pageIndex - 1;
+ if (newIconIndex == FocusLogic.NEXT_PAGE_RIGHT_COLUMN) {
+ newPageIndex = pageIndex + 1;
+ }
+ int row = ((CellLayout.LayoutParams) v.getLayoutParams()).cellY;
+ parent = getCellLayoutChildrenForIndex(workspace, newPageIndex);
+ workspace.snapToPage(newPageIndex);
+ if (parent != null) {
+ workspace.snapToPage(newPageIndex);
+ iconLayout = (CellLayout) parent.getParent();
+ matrix = FocusLogic.createSparseMatrix(iconLayout,
+ iconLayout.getCountX(), row);
+ newIconIndex = FocusLogic.handleKeyEvent(keyCode, countX + 1, countY,
+ matrix, FocusLogic.PIVOT, newPageIndex, pageCount,
+ Utilities.isRtl(v.getResources()));
+ newIcon = parent.getChildAt(newIconIndex);
+ }
+ break;
+ case FocusLogic.PREVIOUS_PAGE_FIRST_ITEM:
+ parent = getCellLayoutChildrenForIndex(workspace, pageIndex - 1);
+ newIcon = parent.getChildAt(0);
+ workspace.snapToPage(pageIndex - 1);
+ break;
+ case FocusLogic.PREVIOUS_PAGE_LAST_ITEM:
+ parent = getCellLayoutChildrenForIndex(workspace, pageIndex - 1);
+ newIcon = parent.getChildAt(parent.getChildCount() - 1);
+ workspace.snapToPage(pageIndex - 1);
+ break;
+ case FocusLogic.NEXT_PAGE_FIRST_ITEM:
+ parent = getCellLayoutChildrenForIndex(workspace, pageIndex + 1);
+ newIcon = parent.getChildAt(0);
+ workspace.snapToPage(pageIndex + 1);
+ break;
+ case FocusLogic.NEXT_PAGE_LEFT_COLUMN:
+ case FocusLogic.PREVIOUS_PAGE_LEFT_COLUMN:
+ newPageIndex = pageIndex + 1;
+ if (newIconIndex == FocusLogic.PREVIOUS_PAGE_LEFT_COLUMN) {
+ newPageIndex = pageIndex - 1;
+ }
+ workspace.snapToPage(newPageIndex);
+ row = ((CellLayout.LayoutParams) v.getLayoutParams()).cellY;
+ parent = getCellLayoutChildrenForIndex(workspace, newPageIndex);
+ if (parent != null) {
+ workspace.snapToPage(newPageIndex);
+ iconLayout = (CellLayout) parent.getParent();
+ matrix = FocusLogic.createSparseMatrix(iconLayout, -1, row);
+ newIconIndex = FocusLogic.handleKeyEvent(keyCode, countX + 1, countY,
+ matrix, FocusLogic.PIVOT, newPageIndex, pageCount,
+ Utilities.isRtl(v.getResources()));
+ newIcon = parent.getChildAt(newIconIndex);
+ }
+ break;
+ case FocusLogic.CURRENT_PAGE_FIRST_ITEM:
+ newIcon = parent.getChildAt(0);
+ break;
+ case FocusLogic.CURRENT_PAGE_LAST_ITEM:
+ newIcon = parent.getChildAt(parent.getChildCount() - 1);
+ break;
+ default:
+ // current page, some item.
+ if (0 <= newIconIndex && newIconIndex < parent.getChildCount()) {
+ newIcon = parent.getChildAt(newIconIndex);
+ } else if (parent.getChildCount() <= newIconIndex &&
+ newIconIndex < parent.getChildCount() + hotseatParent.getChildCount()) {
+ newIcon = hotseatParent.getChildAt(newIconIndex - parent.getChildCount());
+ }
+ break;
+ }
+ if (newIcon != null) {
+ newIcon.requestFocus();
+ playSoundEffect(keyCode, v);
+ }
+ return consume;
}
+ //
+ // Helper methods.
+ //
+
/**
* Private helper method to get the CellLayoutChildren given a CellLayout index.
*/
- private static ShortcutAndWidgetContainer getCellLayoutChildrenForIndex(
+ @Thunk static ShortcutAndWidgetContainer getCellLayoutChildrenForIndex(
ViewGroup container, int i) {
CellLayout parent = (CellLayout) container.getChildAt(i);
return parent.getShortcutsAndWidgets();
}
/**
- * Private helper method to sort all the CellLayout children in order of their (x,y) spatially
- * from top left to bottom right.
+ * Helper method to be used for playing sound effects.
*/
- private static ArrayList getCellLayoutChildrenSortedSpatially(CellLayout layout,
- ViewGroup parent) {
- // First we order each the CellLayout children by their x,y coordinates
- final int cellCountX = layout.getCountX();
- final int count = parent.getChildCount();
- ArrayList views = new ArrayList();
- for (int j = 0; j < count; ++j) {
- views.add(parent.getChildAt(j));
- }
- Collections.sort(views, new Comparator() {
- @Override
- public int compare(View lhs, View rhs) {
- CellLayout.LayoutParams llp = (CellLayout.LayoutParams) lhs.getLayoutParams();
- CellLayout.LayoutParams rlp = (CellLayout.LayoutParams) rhs.getLayoutParams();
- int lvIndex = (llp.cellY * cellCountX) + llp.cellX;
- int rvIndex = (rlp.cellY * cellCountX) + rlp.cellX;
- return lvIndex - rvIndex;
- }
- });
- return views;
- }
- /**
- * Private helper method to find the index of the next BubbleTextView or FolderIcon in the
- * direction delta.
- *
- * @param delta either -1 or 1 depending on the direction we want to search
- */
- private static View findIndexOfIcon(ArrayList views, int i, int delta) {
- // Then we find the next BubbleTextView offset by delta from i
- final int count = views.size();
- int newI = i + delta;
- while (0 <= newI && newI < count) {
- View newV = views.get(newI);
- if (newV instanceof BubbleTextView || newV instanceof FolderIcon) {
- return newV;
- }
- newI += delta;
- }
- return null;
- }
- private static View getIconInDirection(CellLayout layout, ViewGroup parent, int i,
- int delta) {
- final ArrayList views = getCellLayoutChildrenSortedSpatially(layout, parent);
- return findIndexOfIcon(views, i, delta);
- }
- private static View getIconInDirection(CellLayout layout, ViewGroup parent, View v,
- int delta) {
- final ArrayList views = getCellLayoutChildrenSortedSpatially(layout, parent);
- return findIndexOfIcon(views, views.indexOf(v), delta);
- }
- /**
- * Private helper method to find the next closest BubbleTextView or FolderIcon in the direction
- * delta on the next line.
- *
- * @param delta either -1 or 1 depending on the line and direction we want to search
- */
- private static View getClosestIconOnLine(CellLayout layout, ViewGroup parent, View v,
- int lineDelta) {
- final ArrayList views = getCellLayoutChildrenSortedSpatially(layout, parent);
- final CellLayout.LayoutParams lp = (CellLayout.LayoutParams) v.getLayoutParams();
- final int cellCountY = layout.getCountY();
- final int row = lp.cellY;
- final int newRow = row + lineDelta;
- if (0 <= newRow && newRow < cellCountY) {
- float closestDistance = Float.MAX_VALUE;
- int closestIndex = -1;
- int index = views.indexOf(v);
- int endIndex = (lineDelta < 0) ? -1 : views.size();
- while (index != endIndex) {
- View newV = views.get(index);
- CellLayout.LayoutParams tmpLp = (CellLayout.LayoutParams) newV.getLayoutParams();
- boolean satisfiesRow = (lineDelta < 0) ? (tmpLp.cellY < row) : (tmpLp.cellY > row);
- if (satisfiesRow &&
- (newV instanceof BubbleTextView || newV instanceof FolderIcon)) {
- float tmpDistance = (float) Math.sqrt(Math.pow(tmpLp.cellX - lp.cellX, 2) +
- Math.pow(tmpLp.cellY - lp.cellY, 2));
- if (tmpDistance < closestDistance) {
- closestIndex = index;
- closestDistance = tmpDistance;
- }
- }
- if (index <= endIndex) {
- ++index;
- } else {
- --index;
- }
- }
- if (closestIndex > -1) {
- return views.get(closestIndex);
- }
- }
- return null;
- }
-
- /**
- * Handles key events in a Workspace containing.
- */
- static boolean handleIconKeyEvent(View v, int keyCode, KeyEvent e) {
- ShortcutAndWidgetContainer parent = (ShortcutAndWidgetContainer) v.getParent();
- final CellLayout layout = (CellLayout) parent.getParent();
- final Workspace workspace = (Workspace) layout.getParent();
- final ViewGroup launcher = (ViewGroup) workspace.getParent();
- final ViewGroup tabs = (ViewGroup) launcher.findViewById(R.id.search_drop_target_bar);
- final ViewGroup hotseat = (ViewGroup) launcher.findViewById(R.id.hotseat);
- int pageIndex = workspace.indexOfChild(layout);
- int pageCount = workspace.getChildCount();
-
- final int action = e.getAction();
- final boolean handleKeyEvent = (action != KeyEvent.ACTION_UP);
- boolean wasHandled = false;
+ @Thunk static void playSoundEffect(int keyCode, View v) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
- if (handleKeyEvent) {
- // Select the previous icon or the last icon on the previous page if possible
- View newIcon = getIconInDirection(layout, parent, v, -1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_LEFT);
- } else {
- if (pageIndex > 0) {
- parent = getCellLayoutChildrenForIndex(workspace, pageIndex - 1);
- newIcon = getIconInDirection(layout, parent,
- parent.getChildCount(), -1);
- if (newIcon != null) {
- newIcon.requestFocus();
- } else {
- // Snap to the previous page
- workspace.snapToPage(pageIndex - 1);
- }
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_LEFT);
- }
- }
- }
- wasHandled = true;
+ v.playSoundEffect(SoundEffectConstants.NAVIGATION_LEFT);
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
- if (handleKeyEvent) {
- // Select the next icon or the first icon on the next page if possible
- View newIcon = getIconInDirection(layout, parent, v, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_RIGHT);
- } else {
- if (pageIndex < (pageCount - 1)) {
- parent = getCellLayoutChildrenForIndex(workspace, pageIndex + 1);
- newIcon = getIconInDirection(layout, parent, -1, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- } else {
- // Snap to the next page
- workspace.snapToPage(pageIndex + 1);
- }
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_RIGHT);
- }
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_DPAD_UP:
- if (handleKeyEvent) {
- // Select the closest icon in the previous line, otherwise select the tab bar
- View newIcon = getClosestIconOnLine(layout, parent, v, -1);
- if (newIcon != null) {
- newIcon.requestFocus();
- wasHandled = true;
- } else {
- tabs.requestFocus();
- }
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- }
+ v.playSoundEffect(SoundEffectConstants.NAVIGATION_RIGHT);
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
- if (handleKeyEvent) {
- // Select the closest icon in the next line, otherwise select the button bar
- View newIcon = getClosestIconOnLine(layout, parent, v, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- wasHandled = true;
- } else if (hotseat != null) {
- hotseat.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- }
- }
- break;
- case KeyEvent.KEYCODE_PAGE_UP:
- if (handleKeyEvent) {
- // Select the first icon on the previous page or the first icon on this page
- // if there is no previous page
- if (pageIndex > 0) {
- parent = getCellLayoutChildrenForIndex(workspace, pageIndex - 1);
- View newIcon = getIconInDirection(layout, parent, -1, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- } else {
- // Snap to the previous page
- workspace.snapToPage(pageIndex - 1);
- }
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- } else {
- View newIcon = getIconInDirection(layout, parent, -1, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- }
- }
- }
- wasHandled = true;
- break;
case KeyEvent.KEYCODE_PAGE_DOWN:
- if (handleKeyEvent) {
- // Select the first icon on the next page or the last icon on this page
- // if there is no previous page
- if (pageIndex < (pageCount - 1)) {
- parent = getCellLayoutChildrenForIndex(workspace, pageIndex + 1);
- View newIcon = getIconInDirection(layout, parent, -1, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- } else {
- // Snap to the next page
- workspace.snapToPage(pageIndex + 1);
- }
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- } else {
- View newIcon = getIconInDirection(layout, parent,
- parent.getChildCount(), -1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- }
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_MOVE_HOME:
- if (handleKeyEvent) {
- // Select the first icon on this page
- View newIcon = getIconInDirection(layout, parent, -1, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- }
- }
- wasHandled = true;
- break;
case KeyEvent.KEYCODE_MOVE_END:
- if (handleKeyEvent) {
- // Select the last icon on this page
- View newIcon = getIconInDirection(layout, parent,
- parent.getChildCount(), -1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- }
- }
- wasHandled = true;
- break;
- default: break;
- }
- return wasHandled;
- }
-
- /**
- * Handles key events for items in a Folder.
- */
- static boolean handleFolderKeyEvent(View v, int keyCode, KeyEvent e) {
- ShortcutAndWidgetContainer parent = (ShortcutAndWidgetContainer) v.getParent();
- final CellLayout layout = (CellLayout) parent.getParent();
- final ScrollView scrollView = (ScrollView) layout.getParent();
- final Folder folder = (Folder) scrollView.getParent();
- View title = folder.mFolderName;
-
- final int action = e.getAction();
- final boolean handleKeyEvent = (action != KeyEvent.ACTION_UP);
- boolean wasHandled = false;
- switch (keyCode) {
- case KeyEvent.KEYCODE_DPAD_LEFT:
- if (handleKeyEvent) {
- // Select the previous icon
- View newIcon = getIconInDirection(layout, parent, v, -1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_LEFT);
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_DPAD_RIGHT:
- if (handleKeyEvent) {
- // Select the next icon
- View newIcon = getIconInDirection(layout, parent, v, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- } else {
- title.requestFocus();
- }
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_RIGHT);
- }
- wasHandled = true;
+ v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
break;
case KeyEvent.KEYCODE_DPAD_UP:
- if (handleKeyEvent) {
- // Select the closest icon in the previous line
- View newIcon = getClosestIconOnLine(layout, parent, v, -1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- }
- }
- wasHandled = true;
- break;
- case KeyEvent.KEYCODE_DPAD_DOWN:
- if (handleKeyEvent) {
- // Select the closest icon in the next line
- View newIcon = getClosestIconOnLine(layout, parent, v, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- } else {
- title.requestFocus();
- }
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- }
- wasHandled = true;
- break;
+ case KeyEvent.KEYCODE_PAGE_UP:
case KeyEvent.KEYCODE_MOVE_HOME:
- if (handleKeyEvent) {
- // Select the first icon on this page
- View newIcon = getIconInDirection(layout, parent, -1, 1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
- }
- }
- wasHandled = true;
+ v.playSoundEffect(SoundEffectConstants.NAVIGATION_UP);
break;
- case KeyEvent.KEYCODE_MOVE_END:
- if (handleKeyEvent) {
- // Select the last icon on this page
- View newIcon = getIconInDirection(layout, parent,
- parent.getChildCount(), -1);
- if (newIcon != null) {
- newIcon.requestFocus();
- v.playSoundEffect(SoundEffectConstants.NAVIGATION_DOWN);
- }
- }
- wasHandled = true;
+ default:
break;
- default: break;
}
- return wasHandled;
}
}
diff --git a/src/com/android/launcher3/FocusIndicatorView.java b/src/com/android/launcher3/FocusIndicatorView.java
index 7d4664abb1..ecf93e4b3d 100644
--- a/src/com/android/launcher3/FocusIndicatorView.java
+++ b/src/com/android/launcher3/FocusIndicatorView.java
@@ -23,7 +23,8 @@ import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.View;
-import android.view.ViewParent;
+
+import com.android.launcher3.util.Thunk;
public class FocusIndicatorView extends View implements View.OnFocusChangeListener {
@@ -32,9 +33,6 @@ public class FocusIndicatorView extends View implements View.OnFocusChangeListen
private static final float MIN_VISIBLE_ALPHA = 0.2f;
private static final long ANIM_DURATION = 150;
- private static final int[] sTempPos = new int[2];
- private static final int[] sTempShift = new int[2];
-
private final int[] mIndicatorPos = new int[2];
private final int[] mTargetViewPos = new int[2];
@@ -80,7 +78,8 @@ public class FocusIndicatorView extends View implements View.OnFocusChangeListen
}
if (!mInitiated) {
- getLocationRelativeToParentPagedView(this, mIndicatorPos);
+ // The parent view should always the a parent of the target view.
+ computeLocationRelativeToParent(this, (View) getParent(), mIndicatorPos);
mInitiated = true;
}
@@ -93,7 +92,7 @@ public class FocusIndicatorView extends View implements View.OnFocusChangeListen
nextState.scaleX = v.getScaleX() * v.getWidth() / indicatorWidth;
nextState.scaleY = v.getScaleY() * v.getHeight() / indicatorHeight;
- getLocationRelativeToParentPagedView(v, mTargetViewPos);
+ computeLocationRelativeToParent(v, (View) getParent(), mTargetViewPos);
nextState.x = mTargetViewPos[0] - mIndicatorPos[0] - (1 - nextState.scaleX) * indicatorWidth / 2;
nextState.y = mTargetViewPos[1] - mIndicatorPos[1] - (1 - nextState.scaleY) * indicatorHeight / 2;
@@ -150,31 +149,36 @@ public class FocusIndicatorView extends View implements View.OnFocusChangeListen
}
/**
- * Gets the location of a view relative in the window, off-setting any shift due to
- * page view scroll
+ * Computes the location of a view relative to {@param parent}, off-setting
+ * any shift due to page view scroll.
+ * @param pos an array of two integers in which to hold the coordinates
*/
- private static void getLocationRelativeToParentPagedView(View v, int[] pos) {
- getPagedViewScrollShift(v, sTempShift);
- v.getLocationInWindow(sTempPos);
- pos[0] = sTempPos[0] + sTempShift[0];
- pos[1] = sTempPos[1] + sTempShift[1];
+ private static void computeLocationRelativeToParent(View v, View parent, int[] pos) {
+ pos[0] = pos[1] = 0;
+ computeLocationRelativeToParentHelper(v, parent, pos);
+
+ // If a view is scaled, its position will also shift accordingly. For optimization, only
+ // consider this for the last node.
+ pos[0] += (1 - v.getScaleX()) * v.getWidth() / 2;
+ pos[1] += (1 - v.getScaleY()) * v.getHeight() / 2;
}
- private static void getPagedViewScrollShift(View child, int[] shift) {
- ViewParent parent = child.getParent();
+ private static void computeLocationRelativeToParentHelper(View child,
+ View commonParent, int[] shift) {
+ View parent = (View) child.getParent();
+ shift[0] += child.getLeft();
+ shift[1] += child.getTop();
if (parent instanceof PagedView) {
- View parentView = (View) parent;
- child.getLocationInWindow(sTempPos);
- shift[0] = parentView.getPaddingLeft() - sTempPos[0];
- shift[1] = -(int) child.getTranslationY();
- } else if (parent instanceof View) {
- getPagedViewScrollShift((View) parent, shift);
- } else {
- shift[0] = shift[1] = 0;
+ PagedView page = (PagedView) parent;
+ shift[0] -= page.getScrollForPage(page.indexOfChild(child));
+ }
+
+ if (parent != commonParent) {
+ computeLocationRelativeToParentHelper(parent, commonParent, shift);
}
}
- private static final class ViewAnimState {
+ @Thunk static final class ViewAnimState {
float x, y, scaleX, scaleY;
}
}
diff --git a/src/com/android/launcher3/FocusOnlyTabWidget.java b/src/com/android/launcher3/FocusOnlyTabWidget.java
deleted file mode 100644
index 08fc311bca..0000000000
--- a/src/com/android/launcher3/FocusOnlyTabWidget.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2011 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.Context;
-import android.util.AttributeSet;
-import android.view.View;
-import android.widget.TabWidget;
-
-public class FocusOnlyTabWidget extends TabWidget {
- public FocusOnlyTabWidget(Context context) {
- super(context);
- }
-
- public FocusOnlyTabWidget(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public FocusOnlyTabWidget(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- public View getSelectedTab() {
- final int count = getTabCount();
- for (int i = 0; i < count; ++i) {
- View v = getChildTabViewAt(i);
- if (v.isSelected()) {
- return v;
- }
- }
- return null;
- }
-
- public int getChildTabIndex(View v) {
- final int tabCount = getTabCount();
- for (int i = 0; i < tabCount; ++i) {
- if (getChildTabViewAt(i) == v) {
- return i;
- }
- }
- return -1;
- }
-
- public void setCurrentTabToFocusedTab() {
- View tab = null;
- int index = -1;
- final int count = getTabCount();
- for (int i = 0; i < count; ++i) {
- View v = getChildTabViewAt(i);
- if (v.hasFocus()) {
- tab = v;
- index = i;
- break;
- }
- }
- if (index > -1) {
- super.setCurrentTab(index);
- super.onFocusChange(tab, true);
- }
- }
- public void superOnFocusChange(View v, boolean hasFocus) {
- super.onFocusChange(v, hasFocus);
- }
-
- @Override
- public void onFocusChange(android.view.View v, boolean hasFocus) {
- if (v == this && hasFocus && getTabCount() > 0) {
- getSelectedTab().requestFocus();
- return;
- }
- }
-}
diff --git a/src/com/android/launcher3/Folder.java b/src/com/android/launcher3/Folder.java
index 1890af47dd..2e19f6eba2 100644
--- a/src/com/android/launcher3/Folder.java
+++ b/src/com/android/launcher3/Folder.java
@@ -21,12 +21,15 @@ import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
+import android.annotation.SuppressLint;
+import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
+import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
-import android.os.SystemClock;
-import android.support.v4.widget.AutoScrollHelper;
+import android.os.Build;
+import android.os.Bundle;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
@@ -34,21 +37,28 @@ import android.util.AttributeSet;
import android.util.Log;
import android.view.ActionMode;
import android.view.KeyEvent;
-import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
+import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.AccelerateInterpolator;
+import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
-import android.widget.ScrollView;
import android.widget.TextView;
+import com.android.launcher3.CellLayout.CellInfo;
+import com.android.launcher3.DragController.DragListener;
import com.android.launcher3.FolderInfo.FolderListener;
+import com.android.launcher3.UninstallDropTarget.UninstallSource;
+import com.android.launcher3.Workspace.ItemOperator;
+import com.android.launcher3.accessibility.LauncherAccessibilityDelegate.AccessibilityDragSource;
+import com.android.launcher3.util.Thunk;
+import com.android.launcher3.util.UiThreadCircularReveal;
import java.util.ArrayList;
import java.util.Collections;
@@ -59,106 +69,109 @@ import java.util.Comparator;
*/
public class Folder extends LinearLayout implements DragSource, View.OnClickListener,
View.OnLongClickListener, DropTarget, FolderListener, TextView.OnEditorActionListener,
- View.OnFocusChangeListener {
+ View.OnFocusChangeListener, DragListener, UninstallSource, AccessibilityDragSource,
+ Stats.LaunchSourceProvider {
private static final String TAG = "Launcher.Folder";
- protected DragController mDragController;
- protected Launcher mLauncher;
- protected FolderInfo mInfo;
+ /**
+ * We avoid measuring {@link #mContentWrapper} with a 0 width or height, as this
+ * results in CellLayout being measured as UNSPECIFIED, which it does not support.
+ */
+ private static final int MIN_CONTENT_DIMEN = 5;
static final int STATE_NONE = -1;
static final int STATE_SMALL = 0;
static final int STATE_ANIMATING = 1;
static final int STATE_OPEN = 2;
- private static final int CLOSE_FOLDER_DELAY_MS = 150;
+ /**
+ * Time for which the scroll hint is shown before automatically changing page.
+ */
+ public static final int SCROLL_HINT_DURATION = DragController.SCROLL_DELAY;
+
+ /**
+ * Fraction of icon width which behave as scroll region.
+ */
+ private static final float ICON_OVERSCROLL_WIDTH_FACTOR = 0.45f;
+
+ private static final int FOLDER_NAME_ANIMATION_DURATION = 633;
- private int mExpandDuration;
- private int mMaterialExpandDuration;
- private int mMaterialExpandStagger;
- protected CellLayout mContent;
- private ScrollView mScrollView;
- private final LayoutInflater mInflater;
- private final IconCache mIconCache;
- private int mState = STATE_NONE;
- private static final int REORDER_ANIMATION_DURATION = 230;
private static final int REORDER_DELAY = 250;
private static final int ON_EXIT_CLOSE_DELAY = 400;
+ private static final Rect sTempRect = new Rect();
+
+ private static String sDefaultFolderName;
+ private static String sHintText;
+
+ private final Alarm mReorderAlarm = new Alarm();
+ private final Alarm mOnExitAlarm = new Alarm();
+ private final Alarm mOnScrollHintAlarm = new Alarm();
+ @Thunk final Alarm mScrollPauseAlarm = new Alarm();
+
+ @Thunk final ArrayList mItemsInReadingOrder = new ArrayList();
+
+ private final int mExpandDuration;
+ private final int mMaterialExpandDuration;
+ private final int mMaterialExpandStagger;
+
+ private final InputMethodManager mInputMethodManager;
+
+ protected final Launcher mLauncher;
+ protected DragController mDragController;
+ protected FolderInfo mInfo;
+
+ @Thunk FolderIcon mFolderIcon;
+
+ @Thunk FolderPagedView mContent;
+ @Thunk View mContentWrapper;
+ FolderEditText mFolderName;
+
+ private View mFooter;
+ private int mFooterHeight;
+
+ // Cell ranks used for drag and drop
+ @Thunk int mTargetRank, mPrevTargetRank, mEmptyCellRank;
+
+ @Thunk int mState = STATE_NONE;
private boolean mRearrangeOnClose = false;
- private FolderIcon mFolderIcon;
- private int mMaxCountX;
- private int mMaxCountY;
- private int mMaxNumItems;
- private ArrayList mItemsInReadingOrder = new ArrayList();
boolean mItemsInvalidated = false;
private ShortcutInfo mCurrentDragInfo;
private View mCurrentDragView;
private boolean mIsExternalDrag;
boolean mSuppressOnAdd = false;
- private int[] mTargetCell = new int[2];
- private int[] mPreviousTargetCell = new int[2];
- private int[] mEmptyCell = new int[2];
- private Alarm mReorderAlarm = new Alarm();
- private Alarm mOnExitAlarm = new Alarm();
- private int mFolderNameHeight;
- private Rect mTempRect = new Rect();
private boolean mDragInProgress = false;
private boolean mDeleteFolderOnDropCompleted = false;
private boolean mSuppressFolderDeletion = false;
private boolean mItemAddedBackToSelfViaIcon = false;
- FolderEditText mFolderName;
- private float mFolderIconPivotX;
- private float mFolderIconPivotY;
-
+ @Thunk float mFolderIconPivotX;
+ @Thunk float mFolderIconPivotY;
private boolean mIsEditingName = false;
- private InputMethodManager mInputMethodManager;
-
- private static String sDefaultFolderName;
- private static String sHintText;
-
- private FocusIndicatorView mFocusIndicatorHandler;
-
- // We avoid measuring the scroll view with a 0 width or height, as this
- // results in CellLayout being measured as UNSPECIFIED, which it does
- // not support.
- private static final int MIN_CONTENT_DIMEN = 5;
private boolean mDestroyed;
- private AutoScrollHelper mAutoScrollHelper;
-
- private Runnable mDeferredAction;
+ @Thunk Runnable mDeferredAction;
private boolean mDeferDropAfterUninstall;
private boolean mUninstallSuccessful;
+ // Folder scrolling
+ private int mScrollAreaOffset;
+
+ @Thunk int mScrollHintDir = DragController.SCROLL_NONE;
+ @Thunk int mCurrentScrollDir = DragController.SCROLL_NONE;
+
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
- * @param attrs The attribtues set containing the Workspace's customization values.
+ * @param attrs The attributes set containing the Workspace's customization values.
*/
public Folder(Context context, AttributeSet attrs) {
super(context, attrs);
-
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
setAlwaysDrawnWithCacheEnabled(false);
- mInflater = LayoutInflater.from(context);
- mIconCache = app.getIconCache();
-
- Resources res = getResources();
- mMaxCountX = (int) grid.numColumns;
- // Allow scrolling folders when DISABLE_ALL_APPS is true.
- if (LauncherAppState.isDisableAllApps()) {
- mMaxCountY = mMaxNumItems = Integer.MAX_VALUE;
- } else {
- mMaxCountY = (int) grid.numRows;
- mMaxNumItems = mMaxCountX * mMaxCountY;
- }
-
mInputMethodManager = (InputMethodManager)
getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+ Resources res = getResources();
mExpandDuration = res.getInteger(R.integer.config_folderExpandDuration);
mMaterialExpandDuration = res.getInteger(R.integer.config_materialFolderExpandDuration);
mMaterialExpandStagger = res.getInteger(R.integer.config_materialFolderExpandStagger);
@@ -172,45 +185,35 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
mLauncher = (Launcher) context;
// We need this view to be focusable in touch mode so that when text editing of the folder
// name is complete, we have something to focus on, thus hiding the cursor and giving
- // reliable behvior when clicking the text field (since it will always gain focus on click).
+ // reliable behavior when clicking the text field (since it will always gain focus on click).
setFocusableInTouchMode(true);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
- mScrollView = (ScrollView) findViewById(R.id.scroll_view);
- mContent = (CellLayout) findViewById(R.id.folder_content);
+ mContentWrapper = findViewById(R.id.folder_content_wrapper);
+ mContent = (FolderPagedView) findViewById(R.id.folder_content);
+ mContent.setFolder(this);
- mFocusIndicatorHandler = new FocusIndicatorView(getContext());
- mContent.addView(mFocusIndicatorHandler, 0);
- mFocusIndicatorHandler.getLayoutParams().height = FocusIndicatorView.DEFAULT_LAYOUT_SIZE;
- mFocusIndicatorHandler.getLayoutParams().width = FocusIndicatorView.DEFAULT_LAYOUT_SIZE;
-
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
-
- mContent.setCellDimensions(grid.folderCellWidthPx, grid.folderCellHeightPx);
- mContent.setGridSize(0, 0);
- mContent.getShortcutsAndWidgets().setMotionEventSplittingEnabled(false);
- mContent.setInvertIfRtl(true);
mFolderName = (FolderEditText) findViewById(R.id.folder_name);
mFolderName.setFolder(this);
mFolderName.setOnFocusChangeListener(this);
- // We find out how tall the text view wants to be (it is set to wrap_content), so that
- // we can allocate the appropriate amount of space for it.
- int measureSpec = MeasureSpec.UNSPECIFIED;
- mFolderName.measure(measureSpec, measureSpec);
- mFolderNameHeight = mFolderName.getMeasuredHeight();
-
// We disable action mode for now since it messes up the view on phones
mFolderName.setCustomSelectionActionModeCallback(mActionModeCallback);
mFolderName.setOnEditorActionListener(this);
mFolderName.setSelectAllOnFocus(true);
mFolderName.setInputType(mFolderName.getInputType() |
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
- mAutoScrollHelper = new FolderAutoScrollHelper(mScrollView);
+
+ mFooter = findViewById(R.id.folder_footer);
+
+ // We find out how tall footer wants to be (it is set to wrap_content), so that
+ // we can allocate the appropriate amount of space for it.
+ int measureSpec = MeasureSpec.UNSPECIFIED;
+ mFooter.measure(measureSpec, measureSpec);
+ mFooterHeight = mFooter.getMeasuredHeight();
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
@@ -240,7 +243,10 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
public boolean onLongClick(View v) {
// Return if global dragging is not enabled
if (!mLauncher.isDraggingEnabled()) return true;
+ return beginDrag(v, false);
+ }
+ private boolean beginDrag(View v, boolean accessible) {
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
ShortcutInfo item = (ShortcutInfo) tag;
@@ -248,14 +254,13 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
return false;
}
- mLauncher.getWorkspace().beginDragShared(v, this);
+ mLauncher.getWorkspace().beginDragShared(v, new Point(), this, accessible);
mCurrentDragInfo = item;
- mEmptyCell[0] = item.cellX;
- mEmptyCell[1] = item.cellY;
+ mEmptyCellRank = item.rank;
mCurrentDragView = v;
- mContent.removeView(mCurrentDragView);
+ mContent.removeItem(mCurrentDragView);
mInfo.remove(mCurrentDragInfo);
mDragInProgress = true;
mItemAddedBackToSelfViaIcon = false;
@@ -263,6 +268,23 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
return true;
}
+ @Override
+ public void startDrag(CellInfo cellInfo, boolean accessible) {
+ beginDrag(cellInfo.cell, accessible);
+ }
+
+ @Override
+ public void enableAccessibleDrag(boolean enable) {
+ mLauncher.getSearchBar().enableAccessibleDrag(enable);
+ for (int i = 0; i < mContent.getChildCount(); i++) {
+ mContent.getPageAt(i).enableAccessibleDrag(enable, CellLayout.FOLDER_ACCESSIBILITY_DRAG);
+ }
+
+ mFooter.setImportantForAccessibility(enable ? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS :
+ IMPORTANT_FOR_ACCESSIBILITY_AUTO);
+ mLauncher.getWorkspace().setAddNewPageOnDrag(!enable);
+ }
+
public boolean isEditingName() {
return mIsEditingName;
}
@@ -309,13 +331,10 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
return mFolderName;
}
- public CellLayout getContent() {
- return mContent;
- }
-
/**
* We need to handle touch events to prevent them from falling through to the workspace below.
*/
+ @SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent ev) {
return true;
@@ -325,7 +344,7 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
mDragController = dragController;
}
- void setFolderIcon(FolderIcon icon) {
+ public void setFolderIcon(FolderIcon icon) {
mFolderIcon = icon;
}
@@ -338,64 +357,16 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
/**
* @return the FolderInfo object associated with this folder
*/
- FolderInfo getInfo() {
+ public FolderInfo getInfo() {
return mInfo;
}
- private class GridComparator implements Comparator {
- int mNumCols;
- public GridComparator(int numCols) {
- mNumCols = numCols;
- }
-
- @Override
- public int compare(ShortcutInfo lhs, ShortcutInfo rhs) {
- int lhIndex = lhs.cellY * mNumCols + lhs.cellX;
- int rhIndex = rhs.cellY * mNumCols + rhs.cellX;
- return (lhIndex - rhIndex);
- }
- }
-
- private void placeInReadingOrder(ArrayList items) {
- int maxX = 0;
- int count = items.size();
- for (int i = 0; i < count; i++) {
- ShortcutInfo item = items.get(i);
- if (item.cellX > maxX) {
- maxX = item.cellX;
- }
- }
-
- GridComparator gridComparator = new GridComparator(maxX + 1);
- Collections.sort(items, gridComparator);
- final int countX = mContent.getCountX();
- for (int i = 0; i < count; i++) {
- int x = i % countX;
- int y = i / countX;
- ShortcutInfo item = items.get(i);
- item.cellX = x;
- item.cellY = y;
- }
- }
-
void bind(FolderInfo info) {
mInfo = info;
ArrayList children = info.contents;
- ArrayList overflow = new ArrayList();
- setupContentForNumItems(children.size());
- placeInReadingOrder(children);
- int count = 0;
- for (int i = 0; i < children.size(); i++) {
- ShortcutInfo child = (ShortcutInfo) children.get(i);
- if (createAndAddShortcut(child) == null) {
- overflow.add(child);
- } else {
- count++;
- }
- }
+ Collections.sort(children, ITEM_POS_COMPARATOR);
- // We rearrange the items in case there are any empty gaps
- setupContentForNumItems(count);
+ ArrayList overflow = mContent.bindItems(children);
// If our folder has too many items we prune them from the list. This is an issue
// when upgrading from the old Folders implementation which could contain an unlimited
@@ -405,6 +376,14 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
LauncherModel.deleteItemFromDatabase(mLauncher, item);
}
+ DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
+ if (lp == null) {
+ lp = new DragLayer.LayoutParams(0, 0);
+ lp.customPosition = true;
+ setLayoutParams(lp);
+ }
+ centerAboutIcon();
+
mItemsInvalidated = true;
updateTextViewFocus();
mInfo.addListener(this);
@@ -414,7 +393,6 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
} else {
mFolderName.setText("");
}
- updateItemLocationsInDatabase();
// In case any children didn't come across during loading, clean up the folder accordingly
mFolderIcon.post(new Runnable() {
@@ -433,8 +411,9 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
*
* @return A new UserFolder.
*/
- static Folder fromXml(Context context) {
- return (Folder) LayoutInflater.from(context).inflate(R.layout.user_folder, null);
+ @SuppressLint("InflateParams")
+ static Folder fromXml(Launcher launcher) {
+ return (Folder) launcher.getLayoutInflater().inflate(R.layout.user_folder, null);
}
/**
@@ -459,6 +438,12 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
public void animateOpen() {
if (!(getParent() instanceof DragLayer)) return;
+ mContent.completePendingPageChanges();
+ if (!mDragInProgress) {
+ // Open on the first page.
+ mContent.snapToPageImmediately(0);
+ }
+
Animator openFolderAnim = null;
final Runnable onCompleteRunnable;
if (!Utilities.isLmpOrAbove()) {
@@ -484,6 +469,7 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
prepareReveal();
centerAboutIcon();
+ AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
int height = getFolderHeight();
@@ -494,32 +480,32 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
PropertyValuesHolder tx = PropertyValuesHolder.ofFloat("translationX", transX, 0);
PropertyValuesHolder ty = PropertyValuesHolder.ofFloat("translationY", transY, 0);
+ Animator drift = ObjectAnimator.ofPropertyValuesHolder(this, tx, ty);
+ drift.setDuration(mMaterialExpandDuration);
+ drift.setStartDelay(mMaterialExpandStagger);
+ drift.setInterpolator(new LogDecelerateInterpolator(100, 0));
+
int rx = (int) Math.max(Math.max(width - getPivotX(), 0), getPivotX());
int ry = (int) Math.max(Math.max(height - getPivotY(), 0), getPivotY());
- float radius = (float) Math.sqrt(rx * rx + ry * ry);
- AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
- Animator reveal = LauncherAnimUtils.createCircularReveal(this, (int) getPivotX(),
+ float radius = (float) Math.hypot(rx, ry);
+
+ Animator reveal = UiThreadCircularReveal.createCircularReveal(this, (int) getPivotX(),
(int) getPivotY(), 0, radius);
reveal.setDuration(mMaterialExpandDuration);
reveal.setInterpolator(new LogDecelerateInterpolator(100, 0));
- mContent.setAlpha(0f);
- Animator iconsAlpha = LauncherAnimUtils.ofFloat(mContent, "alpha", 0f, 1f);
+ mContentWrapper.setAlpha(0f);
+ Animator iconsAlpha = ObjectAnimator.ofFloat(mContentWrapper, "alpha", 0f, 1f);
iconsAlpha.setDuration(mMaterialExpandDuration);
iconsAlpha.setStartDelay(mMaterialExpandStagger);
iconsAlpha.setInterpolator(new AccelerateInterpolator(1.5f));
- mFolderName.setAlpha(0f);
- Animator textAlpha = LauncherAnimUtils.ofFloat(mFolderName, "alpha", 0f, 1f);
+ mFooter.setAlpha(0f);
+ Animator textAlpha = ObjectAnimator.ofFloat(mFooter, "alpha", 0f, 1f);
textAlpha.setDuration(mMaterialExpandDuration);
textAlpha.setStartDelay(mMaterialExpandStagger);
textAlpha.setInterpolator(new AccelerateInterpolator(1.5f));
- Animator drift = LauncherAnimUtils.ofPropertyValuesHolder(this, tx, ty);
- drift.setDuration(mMaterialExpandDuration);
- drift.setStartDelay(mMaterialExpandStagger);
- drift.setInterpolator(new LogDecelerateInterpolator(60, 0));
-
anim.play(drift);
anim.play(iconsAlpha);
anim.play(textAlpha);
@@ -527,11 +513,13 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
openFolderAnim = anim;
- mContent.setLayerType(LAYER_TYPE_HARDWARE, null);
+ mContentWrapper.setLayerType(LAYER_TYPE_HARDWARE, null);
+ mFooter.setLayerType(LAYER_TYPE_HARDWARE, null);
onCompleteRunnable = new Runnable() {
@Override
public void run() {
- mContent.setLayerType(LAYER_TYPE_NONE, null);
+ mContentWrapper.setLayerType(LAYER_TYPE_NONE, null);
+ mContentWrapper.setLayerType(LAYER_TYPE_NONE, null);
}
};
}
@@ -539,8 +527,7 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
@Override
public void onAnimationStart(Animator animation) {
sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
- String.format(getContext().getString(R.string.folder_opened),
- mContent.getCountX(), mContent.getCountY()));
+ mContent.getAccessibilityDescription());
mState = STATE_ANIMATING;
}
@Override
@@ -551,30 +538,79 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
onCompleteRunnable.run();
}
- setFocusOnFirstChild();
+ mContent.setFocusOnFirstChild();
}
});
+
+ // Footer animation
+ if (mContent.getPageCount() > 1 && !mInfo.hasOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION)) {
+ int footerWidth = mContent.getDesiredWidth()
+ - mFooter.getPaddingLeft() - mFooter.getPaddingRight();
+
+ float textWidth = mFolderName.getPaint().measureText(mFolderName.getText().toString());
+ float translation = (footerWidth - textWidth) / 2;
+ mFolderName.setTranslationX(mContent.mIsRtl ? -translation : translation);
+ mContent.setMarkerScale(0);
+
+ // Do not update the flag if we are in drag mode. The flag will be updated, when we
+ // actually drop the icon.
+ final boolean updateAnimationFlag = !mDragInProgress;
+ openFolderAnim.addListener(new AnimatorListenerAdapter() {
+
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ mFolderName.animate().setDuration(FOLDER_NAME_ANIMATION_DURATION)
+ .translationX(0)
+ .setInterpolator(Utilities.isLmpOrAbove() ?
+ AnimationUtils.loadInterpolator(mLauncher,
+ android.R.interpolator.fast_out_slow_in)
+ : new LogDecelerateInterpolator(100, 0));
+ mContent.animateMarkers();
+
+ if (updateAnimationFlag) {
+ mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true, mLauncher);
+ }
+ }
+ });
+ } else {
+ mFolderName.setTranslationX(0);
+ mContent.setMarkerScale(1);
+ }
+
openFolderAnim.start();
// Make sure the folder picks up the last drag move even if the finger doesn't move.
if (mDragController.isDragging()) {
mDragController.forceTouchMove();
}
+
+ FolderPagedView pages = (FolderPagedView) mContent;
+ pages.verifyVisibleHighResIcons(pages.getNextPage());
}
public void beginExternalDrag(ShortcutInfo item) {
- setupContentForNumItems(getItemCount() + 1);
- findAndSetEmptyCells(item);
-
mCurrentDragInfo = item;
- mEmptyCell[0] = item.cellX;
- mEmptyCell[1] = item.cellY;
+ mEmptyCellRank = mContent.allocateRankForNewItem(item);
mIsExternalDrag = true;
-
mDragInProgress = true;
+
+ // Since this folder opened by another controller, it might not get onDrop or
+ // onDropComplete. Perform cleanup once drag-n-drop ends.
+ mDragController.addDragListener(this);
}
- private void sendCustomAccessibilityEvent(int type, String text) {
+ @Override
+ public void onDragStart(DragSource source, Object info, int dragAction) { }
+
+ @Override
+ public void onDragEnd() {
+ if (mIsExternalDrag && mDragInProgress) {
+ completeDragExit();
+ }
+ mDragController.removeDragListener(this);
+ }
+
+ @Thunk void sendCustomAccessibilityEvent(int type, String text) {
AccessibilityManager accessibilityManager = (AccessibilityManager)
getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
if (accessibilityManager.isEnabled()) {
@@ -585,13 +621,6 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
}
}
- private void setFocusOnFirstChild() {
- View firstChild = mContent.getChildAt(0, 0);
- if (firstChild != null) {
- firstChild.requestFocus();
- }
- }
-
public void animateClosed() {
if (!(getParent() instanceof DragLayer)) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
@@ -627,174 +656,90 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
!isFull());
}
- protected boolean findAndSetEmptyCells(ShortcutInfo item) {
- int[] emptyCell = new int[2];
- if (mContent.findCellForSpan(emptyCell, item.spanX, item.spanY)) {
- item.cellX = emptyCell[0];
- item.cellY = emptyCell[1];
- return true;
- } else {
- return false;
- }
- }
-
- protected View createAndAddShortcut(ShortcutInfo item) {
- final BubbleTextView textView =
- (BubbleTextView) mInflater.inflate(R.layout.folder_application, this, false);
- textView.applyFromShortcutInfo(item, mIconCache, false);
-
- textView.setOnClickListener(this);
- textView.setOnLongClickListener(this);
- textView.setOnFocusChangeListener(mFocusIndicatorHandler);
-
- // We need to check here to verify that the given item's location isn't already occupied
- // by another item.
- if (mContent.getChildAt(item.cellX, item.cellY) != null || item.cellX < 0 || item.cellY < 0
- || item.cellX >= mContent.getCountX() || item.cellY >= mContent.getCountY()) {
- // This shouldn't happen, log it.
- Log.e(TAG, "Folder order not properly persisted during bind");
- if (!findAndSetEmptyCells(item)) {
- return null;
- }
- }
-
- CellLayout.LayoutParams lp =
- new CellLayout.LayoutParams(item.cellX, item.cellY, item.spanX, item.spanY);
- boolean insert = false;
- textView.setOnKeyListener(new FolderKeyEventListener());
- mContent.addViewToCellLayout(textView, insert ? 0 : -1, (int)item.id, lp, true);
- return textView;
- }
-
public void onDragEnter(DragObject d) {
- mPreviousTargetCell[0] = -1;
- mPreviousTargetCell[1] = -1;
+ mPrevTargetRank = -1;
mOnExitAlarm.cancelAlarm();
+ // Get the area offset such that the folder only closes if half the drag icon width
+ // is outside the folder area
+ mScrollAreaOffset = d.dragView.getDragRegionWidth() / 2 - d.xOffset;
}
OnAlarmListener mReorderAlarmListener = new OnAlarmListener() {
public void onAlarm(Alarm alarm) {
- realTimeReorder(mEmptyCell, mTargetCell);
+ mContent.realTimeReorder(mEmptyCellRank, mTargetRank);
+ mEmptyCellRank = mTargetRank;
}
};
- boolean readingOrderGreaterThan(int[] v1, int[] v2) {
- if (v1[1] > v2[1] || (v1[1] == v2[1] && v1[0] > v2[0])) {
- return true;
- } else {
- return false;
- }
- }
-
- private void realTimeReorder(int[] empty, int[] target) {
- boolean wrap;
- int startX;
- int endX;
- int startY;
- int delay = 0;
- float delayAmount = 30;
- if (readingOrderGreaterThan(target, empty)) {
- wrap = empty[0] >= mContent.getCountX() - 1;
- startY = wrap ? empty[1] + 1 : empty[1];
- for (int y = startY; y <= target[1]; y++) {
- startX = y == empty[1] ? empty[0] + 1 : 0;
- endX = y < target[1] ? mContent.getCountX() - 1 : target[0];
- for (int x = startX; x <= endX; x++) {
- View v = mContent.getChildAt(x,y);
- if (mContent.animateChildToPosition(v, empty[0], empty[1],
- REORDER_ANIMATION_DURATION, delay, true, true)) {
- empty[0] = x;
- empty[1] = y;
- delay += delayAmount;
- delayAmount *= 0.9;
- }
- }
- }
- } else {
- wrap = empty[0] == 0;
- startY = wrap ? empty[1] - 1 : empty[1];
- for (int y = startY; y >= target[1]; y--) {
- startX = y == empty[1] ? empty[0] - 1 : mContent.getCountX() - 1;
- endX = y > target[1] ? 0 : target[0];
- for (int x = startX; x >= endX; x--) {
- View v = mContent.getChildAt(x,y);
- if (mContent.animateChildToPosition(v, empty[0], empty[1],
- REORDER_ANIMATION_DURATION, delay, true, true)) {
- empty[0] = x;
- empty[1] = y;
- delay += delayAmount;
- delayAmount *= 0.9;
- }
- }
- }
- }
- }
-
+ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public boolean isLayoutRtl() {
return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
}
+ @Override
public void onDragOver(DragObject d) {
- final DragView dragView = d.dragView;
- final int scrollOffset = mScrollView.getScrollY();
- final float[] r = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, dragView, null);
- r[0] -= getPaddingLeft();
- r[1] -= getPaddingTop();
+ onDragOver(d, REORDER_DELAY);
+ }
- final long downTime = SystemClock.uptimeMillis();
- final MotionEvent translatedEv = MotionEvent.obtain(
- downTime, downTime, MotionEvent.ACTION_MOVE, d.x, d.y, 0);
+ private int getTargetRank(DragObject d, float[] recycle) {
+ recycle = d.getVisualCenter(recycle);
+ return mContent.findNearestArea(
+ (int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop());
+ }
- if (!mAutoScrollHelper.isEnabled()) {
- mAutoScrollHelper.setEnabled(true);
+ @Thunk void onDragOver(DragObject d, int reorderDelay) {
+ if (mScrollPauseAlarm.alarmPending()) {
+ return;
+ }
+ final float[] r = new float[2];
+ mTargetRank = getTargetRank(d, r);
+
+ if (mTargetRank != mPrevTargetRank) {
+ mReorderAlarm.cancelAlarm();
+ mReorderAlarm.setOnAlarmListener(mReorderAlarmListener);
+ mReorderAlarm.setAlarm(REORDER_DELAY);
+ mPrevTargetRank = mTargetRank;
}
- final boolean handled = mAutoScrollHelper.onTouch(this, translatedEv);
- translatedEv.recycle();
+ float x = r[0];
+ int currentPage = mContent.getNextPage();
- if (handled) {
- mReorderAlarm.cancelAlarm();
+ float cellOverlap = mContent.getCurrentCellLayout().getCellWidth()
+ * ICON_OVERSCROLL_WIDTH_FACTOR;
+ boolean isOutsideLeftEdge = x < cellOverlap;
+ boolean isOutsideRightEdge = x > (getWidth() - cellOverlap);
+
+ if (currentPage > 0 && (mContent.mIsRtl ? isOutsideRightEdge : isOutsideLeftEdge)) {
+ showScrollHint(DragController.SCROLL_LEFT, d);
+ } else if (currentPage < (mContent.getPageCount() - 1)
+ && (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) {
+ showScrollHint(DragController.SCROLL_RIGHT, d);
} else {
- mTargetCell = mContent.findNearestArea(
- (int) r[0], (int) r[1] + scrollOffset, 1, 1, mTargetCell);
- if (isLayoutRtl()) {
- mTargetCell[0] = mContent.getCountX() - mTargetCell[0] - 1;
- }
- if (mTargetCell[0] != mPreviousTargetCell[0]
- || mTargetCell[1] != mPreviousTargetCell[1]) {
- mReorderAlarm.cancelAlarm();
- mReorderAlarm.setOnAlarmListener(mReorderAlarmListener);
- mReorderAlarm.setAlarm(REORDER_DELAY);
- mPreviousTargetCell[0] = mTargetCell[0];
- mPreviousTargetCell[1] = mTargetCell[1];
+ mOnScrollHintAlarm.cancelAlarm();
+ if (mScrollHintDir != DragController.SCROLL_NONE) {
+ mContent.clearScrollHint();
+ mScrollHintDir = DragController.SCROLL_NONE;
}
}
}
- // This is used to compute the visual center of the dragView. The idea is that
- // the visual center represents the user's interpretation of where the item is, and hence
- // is the appropriate point to use when determining drop location.
- private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
- DragView dragView, float[] recycle) {
- float res[];
- if (recycle == null) {
- res = new float[2];
- } else {
- res = recycle;
+ private void showScrollHint(int direction, DragObject d) {
+ // Show scroll hint on the right
+ if (mScrollHintDir != direction) {
+ mContent.showScrollHint(direction);
+ mScrollHintDir = direction;
}
- // These represent the visual top and left of drag view if a dragRect was provided.
- // If a dragRect was not provided, then they correspond to the actual view left and
- // top, as the dragRect is in that case taken to be the entire dragView.
- // R.dimen.dragViewOffsetY.
- int left = x - xOffset;
- int top = y - yOffset;
+ // Set alarm for when the hint is complete
+ if (!mOnScrollHintAlarm.alarmPending() || mCurrentScrollDir != direction) {
+ mCurrentScrollDir = direction;
+ mOnScrollHintAlarm.cancelAlarm();
+ mOnScrollHintAlarm.setOnAlarmListener(new OnScrollHintListener(d));
+ mOnScrollHintAlarm.setAlarm(SCROLL_HINT_DURATION);
- // In order to find the visual center, we shift by half the dragRect
- res[0] = left + dragView.getDragRegion().width() / 2;
- res[1] = top + dragView.getDragRegion().height() / 2;
-
- return res;
+ mReorderAlarm.cancelAlarm();
+ mTargetRank = mEmptyCellRank;
+ }
}
OnAlarmListener mOnExitAlarmListener = new OnAlarmListener() {
@@ -804,17 +749,25 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
};
public void completeDragExit() {
- mLauncher.closeFolder();
+ if (mInfo.opened) {
+ mLauncher.closeFolder();
+ mRearrangeOnClose = true;
+ } else if (mState == STATE_ANIMATING) {
+ mRearrangeOnClose = true;
+ } else {
+ rearrangeChildren();
+ clearDragInfo();
+ }
+ }
+
+ private void clearDragInfo() {
mCurrentDragInfo = null;
mCurrentDragView = null;
mSuppressOnAdd = false;
- mRearrangeOnClose = true;
mIsExternalDrag = false;
}
public void onDragExit(DragObject d) {
- // Exiting folder; stop the auto scroller.
- mAutoScrollHelper.setEnabled(false);
// We only close the folder if this is a true drag exit, ie. not because
// a drop has occurred above the folder.
if (!d.dragComplete) {
@@ -822,6 +775,25 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
mOnExitAlarm.setAlarm(ON_EXIT_CLOSE_DELAY);
}
mReorderAlarm.cancelAlarm();
+
+ mOnScrollHintAlarm.cancelAlarm();
+ mScrollPauseAlarm.cancelAlarm();
+ if (mScrollHintDir != DragController.SCROLL_NONE) {
+ mContent.clearScrollHint();
+ mScrollHintDir = DragController.SCROLL_NONE;
+ }
+ }
+
+ /**
+ * When performing an accessibility drop, onDrop is sent immediately after onDragEnter. So we
+ * need to complete all transient states based on timers.
+ */
+ @Override
+ public void prepareAccessibilityDrop() {
+ if (mReorderAlarm.alarmPending()) {
+ mReorderAlarm.cancelAlarm();
+ mReorderAlarmListener.onAlarm(mReorderAlarm);
+ }
}
public void onDropCompleted(final View target, final DragObject d,
@@ -846,9 +818,18 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
replaceFolderWithFinalItem();
}
} else {
- setupContentForNumItems(getItemCount());
// The drag failed, we need to return the item to the folder
+ ShortcutInfo info = (ShortcutInfo) d.dragInfo;
+ View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info)
+ ? mCurrentDragView : mContent.createNewView(info);
+ ArrayList views = getItemsInReadingOrder();
+ views.add(info.rank, icon);
+ mContent.arrangeChildren(views, views.size());
+ mItemsInvalidated = true;
+
+ mSuppressOnAdd = true;
mFolderIcon.onDrop(d);
+ mSuppressOnAdd = false;
}
if (target != this) {
@@ -857,6 +838,7 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
if (!successfulDrop) {
mSuppressFolderDeletion = true;
}
+ mScrollPauseAlarm.cancelAlarm();
completeDragExit();
}
}
@@ -871,12 +853,22 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
// Reordering may have occured, and we need to save the new item locations. We do this once
// at the end to prevent unnecessary database operations.
updateItemLocationsInDatabaseBatch();
+
+ // Use the item count to check for multi-page as the folder UI may not have
+ // been refreshed yet.
+ if (getItemCount() <= mContent.itemsPerPage()) {
+ // Show the animation, next time something is added to the folder.
+ mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, false, mLauncher);
+ }
+
}
+ @Override
public void deferCompleteDropAfterUninstallActivity() {
mDeferDropAfterUninstall = true;
}
+ @Override
public void onUninstallActivityReturned(boolean success) {
mDeferDropAfterUninstall = false;
mUninstallSuccessful = success;
@@ -905,7 +897,8 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
return true;
}
- public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
+ @Override
+ public void onFlingToDelete(DragObject d, PointF vec) {
// Do nothing
}
@@ -914,22 +907,13 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
// Do nothing
}
- private void updateItemLocationsInDatabase() {
- ArrayList list = getItemsInReadingOrder();
- for (int i = 0; i < list.size(); i++) {
- View v = list.get(i);
- ItemInfo info = (ItemInfo) v.getTag();
- LauncherModel.moveItemInDatabase(mLauncher, info, mInfo.id, 0,
- info.cellX, info.cellY);
- }
- }
-
private void updateItemLocationsInDatabaseBatch() {
ArrayList list = getItemsInReadingOrder();
ArrayList items = new ArrayList();
for (int i = 0; i < list.size(); i++) {
View v = list.get(i);
ItemInfo info = (ItemInfo) v.getTag();
+ info.rank = i;
items.add(info);
}
@@ -942,7 +926,7 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
View v = list.get(i);
ItemInfo info = (ItemInfo) v.getTag();
LauncherModel.addItemToDatabase(mLauncher, info, mInfo.id, 0,
- info.cellX, info.cellY, false);
+ info.cellX, info.cellY);
}
}
@@ -956,37 +940,8 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
return true;
}
- private void setupContentDimensions(int count) {
- ArrayList list = getItemsInReadingOrder();
-
- int countX = mContent.getCountX();
- int countY = mContent.getCountY();
- boolean done = false;
-
- while (!done) {
- int oldCountX = countX;
- int oldCountY = countY;
- if (countX * countY < count) {
- // Current grid is too small, expand it
- if ((countX <= countY || countY == mMaxCountY) && countX < mMaxCountX) {
- countX++;
- } else if (countY < mMaxCountY) {
- countY++;
- }
- if (countY == 0) countY++;
- } else if ((countY - 1) * countX >= count && countY >= countX) {
- countY = Math.max(0, countY - 1);
- } else if ((countX - 1) * countY >= count) {
- countX = Math.max(0, countX - 1);
- }
- done = countX == oldCountX && countY == oldCountY;
- }
- mContent.setGridSize(countX, countY);
- arrangeChildren(list);
- }
-
public boolean isFull() {
- return getItemCount() >= mMaxNumItems;
+ return mContent.isFull();
}
private void centerAboutIcon() {
@@ -996,41 +951,30 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
int height = getFolderHeight();
- float scale = parent.getDescendantRectRelativeToSelf(mFolderIcon, mTempRect);
+ float scale = parent.getDescendantRectRelativeToSelf(mFolderIcon, sTempRect);
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
+ DeviceProfile grid = mLauncher.getDeviceProfile();
- int centerX = (int) (mTempRect.left + mTempRect.width() * scale / 2);
- int centerY = (int) (mTempRect.top + mTempRect.height() * scale / 2);
+ int centerX = (int) (sTempRect.left + sTempRect.width() * scale / 2);
+ int centerY = (int) (sTempRect.top + sTempRect.height() * scale / 2);
int centeredLeft = centerX - width / 2;
int centeredTop = centerY - height / 2;
- int currentPage = mLauncher.getWorkspace().getNextPage();
- // In case the workspace is scrolling, we need to use the final scroll to compute
- // the folders bounds.
- mLauncher.getWorkspace().setFinalScrollForPageChange(currentPage);
- // We first fetch the currently visible CellLayoutChildren
- CellLayout currentLayout = (CellLayout) mLauncher.getWorkspace().getChildAt(currentPage);
- ShortcutAndWidgetContainer boundingLayout = currentLayout.getShortcutsAndWidgets();
- Rect bounds = new Rect();
- parent.getDescendantRectRelativeToSelf(boundingLayout, bounds);
- // We reset the workspaces scroll
- mLauncher.getWorkspace().resetFinalScrollForPageChange(currentPage);
- // We need to bound the folder to the currently visible CellLayoutChildren
- int left = Math.min(Math.max(bounds.left, centeredLeft),
- bounds.left + bounds.width() - width);
- int top = Math.min(Math.max(bounds.top, centeredTop),
- bounds.top + bounds.height() - height);
- if (grid.isPhone() && (grid.availableWidthPx - width) < grid.iconSizePx) {
+ // We need to bound the folder to the currently visible workspace area
+ mLauncher.getWorkspace().getPageAreaRelativeToDragLayer(sTempRect);
+ int left = Math.min(Math.max(sTempRect.left, centeredLeft),
+ sTempRect.left + sTempRect.width() - width);
+ int top = Math.min(Math.max(sTempRect.top, centeredTop),
+ sTempRect.top + sTempRect.height() - height);
+ if (grid.isPhone && (grid.availableWidthPx - width) < grid.iconSizePx) {
// Center the folder if it is full (on phones only)
left = (grid.availableWidthPx - width) / 2;
- } else if (width >= bounds.width()) {
+ } else if (width >= sTempRect.width()) {
// If the folder doesn't fit within the bounds, center it about the desired bounds
- left = bounds.left + (bounds.width() - width) / 2;
+ left = sTempRect.left + (sTempRect.width() - width) / 2;
}
- if (height >= bounds.height()) {
- top = bounds.top + (bounds.height() - height) / 2;
+ if (height >= sTempRect.height()) {
+ top = sTempRect.top + (sTempRect.height() - height) / 2;
}
int folderPivotX = width / 2 + (centeredLeft - left);
@@ -1055,26 +999,12 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
return mFolderIconPivotY;
}
- private void setupContentForNumItems(int count) {
- setupContentDimensions(count);
-
- DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
- if (lp == null) {
- lp = new DragLayer.LayoutParams(0, 0);
- lp.customPosition = true;
- setLayoutParams(lp);
- }
- centerAboutIcon();
- }
-
private int getContentAreaHeight() {
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
- Rect workspacePadding = grid.getWorkspacePadding(grid.isLandscape ?
- CellLayout.LANDSCAPE : CellLayout.PORTRAIT);
+ DeviceProfile grid = mLauncher.getDeviceProfile();
+ Rect workspacePadding = grid.getWorkspacePadding(mContent.mIsRtl);
int maxContentAreaHeight = grid.availableHeightPx -
workspacePadding.top - workspacePadding.bottom -
- mFolderNameHeight;
+ mFooterHeight;
int height = Math.min(maxContentAreaHeight,
mContent.getDesiredHeight());
return Math.max(height, MIN_CONTENT_DIMEN);
@@ -1085,67 +1015,67 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
}
private int getFolderHeight() {
- int height = getPaddingTop() + getPaddingBottom()
- + getContentAreaHeight() + mFolderNameHeight;
- return height;
+ return getFolderHeight(getContentAreaHeight());
+ }
+
+ private int getFolderHeight(int contentAreaHeight) {
+ return getPaddingTop() + getPaddingBottom() + contentAreaHeight + mFooterHeight;
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
- int height = getFolderHeight();
- int contentAreaWidthSpec = MeasureSpec.makeMeasureSpec(getContentAreaWidth(),
- MeasureSpec.EXACTLY);
- int contentAreaHeightSpec = MeasureSpec.makeMeasureSpec(getContentAreaHeight(),
- MeasureSpec.EXACTLY);
+ int contentWidth = getContentAreaWidth();
+ int contentHeight = getContentAreaHeight();
- if (LauncherAppState.isDisableAllApps()) {
- // Don't cap the height of the content to allow scrolling.
- mContent.setFixedSize(getContentAreaWidth(), mContent.getDesiredHeight());
- } else {
- mContent.setFixedSize(getContentAreaWidth(), getContentAreaHeight());
+ int contentAreaWidthSpec = MeasureSpec.makeMeasureSpec(contentWidth, MeasureSpec.EXACTLY);
+ int contentAreaHeightSpec = MeasureSpec.makeMeasureSpec(contentHeight, MeasureSpec.EXACTLY);
+
+ mContent.setFixedSize(contentWidth, contentHeight);
+ mContentWrapper.measure(contentAreaWidthSpec, contentAreaHeightSpec);
+
+ if (mContent.getChildCount() > 0) {
+ int cellIconGap = (mContent.getPageAt(0).getCellWidth()
+ - mLauncher.getDeviceProfile().iconSizePx) / 2;
+ mFooter.setPadding(mContent.getPaddingLeft() + cellIconGap,
+ mFooter.getPaddingTop(),
+ mContent.getPaddingRight() + cellIconGap,
+ mFooter.getPaddingBottom());
}
+ mFooter.measure(contentAreaWidthSpec,
+ MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY));
- mScrollView.measure(contentAreaWidthSpec, contentAreaHeightSpec);
- mFolderName.measure(contentAreaWidthSpec,
- MeasureSpec.makeMeasureSpec(mFolderNameHeight, MeasureSpec.EXACTLY));
- setMeasuredDimension(width, height);
+ int folderWidth = getPaddingLeft() + getPaddingRight() + contentWidth;
+ int folderHeight = getFolderHeight(contentHeight);
+ setMeasuredDimension(folderWidth, folderHeight);
}
- private void arrangeChildren(ArrayList list) {
- int[] vacant = new int[2];
- if (list == null) {
- list = getItemsInReadingOrder();
- }
- mContent.removeAllViews();
+ /**
+ * Rearranges the children based on their rank.
+ */
+ public void rearrangeChildren() {
+ rearrangeChildren(-1);
+ }
- for (int i = 0; i < list.size(); i++) {
- View v = list.get(i);
- mContent.getVacantCell(vacant, 1, 1);
- CellLayout.LayoutParams lp = (CellLayout.LayoutParams) v.getLayoutParams();
- lp.cellX = vacant[0];
- lp.cellY = vacant[1];
- ItemInfo info = (ItemInfo) v.getTag();
- if (info.cellX != vacant[0] || info.cellY != vacant[1]) {
- info.cellX = vacant[0];
- info.cellY = vacant[1];
- LauncherModel.addOrMoveItemInDatabase(mLauncher, info, mInfo.id, 0,
- info.cellX, info.cellY);
- }
- boolean insert = false;
- mContent.addViewToCellLayout(v, insert ? 0 : -1, (int)info.id, lp, true);
- }
+ /**
+ * Rearranges the children based on their rank.
+ * @param itemCount if greater than the total children count, empty spaces are left at the end,
+ * otherwise it is ignored.
+ */
+ public void rearrangeChildren(int itemCount) {
+ ArrayList views = getItemsInReadingOrder();
+ mContent.arrangeChildren(views, Math.max(itemCount, views.size()));
mItemsInvalidated = true;
}
+ // TODO remove this once GSA code fix is submitted
+ public ViewGroup getContent() {
+ return (ViewGroup) mContent;
+ }
+
public int getItemCount() {
- return mContent.getShortcutsAndWidgets().getChildCount();
+ return mContent.getItemCount();
}
- public View getItemAt(int index) {
- return mContent.getShortcutsAndWidgets().getChildAt(index);
- }
-
- private void onCloseComplete() {
+ @Thunk void onCloseComplete() {
DragLayer parent = (DragLayer) getParent();
if (parent != null) {
parent.removeView(this);
@@ -1155,7 +1085,7 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
mFolderIcon.requestFocus();
if (mRearrangeOnClose) {
- setupContentForNumItems(getItemCount());
+ rearrangeChildren();
mRearrangeOnClose = false;
}
if (getItemCount() <= 1) {
@@ -1166,9 +1096,10 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
}
}
mSuppressFolderDeletion = false;
+ clearDragInfo();
}
- private void replaceFolderWithFinalItem() {
+ @Thunk void replaceFolderWithFinalItem() {
// Add the last remaining child to the workspace in place of the folder
Runnable onCompleteRunnable = new Runnable() {
@Override
@@ -1179,8 +1110,7 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
// Move the item from the folder to the workspace, in the position of the folder
if (getItemCount() == 1) {
ShortcutInfo finalItem = mInfo.contents.get(0);
- child = mLauncher.createShortcut(R.layout.application, cellLayout,
- finalItem);
+ child = mLauncher.createShortcut(cellLayout, finalItem);
LauncherModel.addOrMoveItemInDatabase(mLauncher, finalItem, mInfo.container,
mInfo.screenId, mInfo.cellX, mInfo.cellY);
}
@@ -1205,7 +1135,7 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
}
}
};
- View finalChild = getItemAt(0);
+ View finalChild = mContent.getLastItem();
if (finalChild != null) {
mFolderIcon.performDestroyAnimation(finalChild, onCompleteRunnable);
} else {
@@ -1220,9 +1150,8 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
// This method keeps track of the last item in the folder for the purposes
// of keyboard focus
- private void updateTextViewFocus() {
- View lastChild = getItemAt(getItemCount() - 1);
- getItemAt(getItemCount() - 1);
+ public void updateTextViewFocus() {
+ View lastChild = mContent.getLastItem();
if (lastChild != null) {
mFolderName.setNextFocusDownId(lastChild.getId());
mFolderName.setNextFocusRightId(lastChild.getId());
@@ -1247,12 +1176,24 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
};
}
+ // If the icon was dropped while the page was being scrolled, we need to compute
+ // the target location again such that the icon is placed of the final page.
+ if (!mContent.rankOnCurrentPage(mEmptyCellRank)) {
+ // Reorder again.
+ mTargetRank = getTargetRank(d, null);
+
+ // Rearrange items immediately.
+ mReorderAlarmListener.onAlarm(mReorderAlarm);
+
+ mOnScrollHintAlarm.cancelAlarm();
+ mScrollPauseAlarm.cancelAlarm();
+ }
+ mContent.completePendingPageChanges();
+
View currentDragView;
ShortcutInfo si = mCurrentDragInfo;
if (mIsExternalDrag) {
- si.cellX = mEmptyCell[0];
- si.cellY = mEmptyCell[1];
-
+ currentDragView = mContent.createAndAddViewForRank(si, mEmptyCellRank);
// Actually move the item in the database if it was an external drag. Call this
// before creating the view, so that ShortcutInfo is updated appropriately.
LauncherModel.addOrMoveItemInDatabase(
@@ -1263,14 +1204,9 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
updateItemLocationsInDatabaseBatch();
}
mIsExternalDrag = false;
-
- currentDragView = createAndAddShortcut(si);
} else {
currentDragView = mCurrentDragView;
- CellLayout.LayoutParams lp = (CellLayout.LayoutParams) currentDragView.getLayoutParams();
- si.cellX = lp.cellX = mEmptyCell[0];
- si.cellX = lp.cellY = mEmptyCell[1];
- mContent.addViewToCellLayout(currentDragView, -1, (int) si.id, lp, true);
+ mContent.addViewForRank(currentDragView, si, mEmptyCellRank);
}
if (d.dragView.hasDrawn()) {
@@ -1289,7 +1225,7 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
currentDragView.setVisibility(VISIBLE);
}
mItemsInvalidated = true;
- setupContentDimensions(getItemCount());
+ rearrangeChildren();
// Temporarily suppress the listener, as we did all the work already here.
mSuppressOnAdd = true;
@@ -1297,6 +1233,12 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
mSuppressOnAdd = false;
// Clear the drag info, as it is no longer being dragged.
mCurrentDragInfo = null;
+ mDragInProgress = false;
+
+ if (mContent.getPageCount() > 1) {
+ // The animation has already been shown while opening the folder.
+ mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true, mLauncher);
+ }
}
// This is used so the item doesn't immediately appear in the folder when added. In one case
@@ -1311,17 +1253,13 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
v.setVisibility(VISIBLE);
}
+ @Override
public void onAdd(ShortcutInfo item) {
- mItemsInvalidated = true;
// If the item was dropped onto this open folder, we have done the work associated
// with adding the item to the folder, as indicated by mSuppressOnAdd being set
if (mSuppressOnAdd) return;
- if (!findAndSetEmptyCells(item)) {
- // The current layout is full, can we expand it?
- setupContentForNumItems(getItemCount() + 1);
- findAndSetEmptyCells(item);
- }
- createAndAddShortcut(item);
+ mContent.createAndAddViewForRank(item, mContent.allocateRankForNewItem(item));
+ mItemsInvalidated = true;
LauncherModel.addOrMoveItemInDatabase(
mLauncher, item, mInfo.id, 0, item.cellX, item.cellY);
}
@@ -1332,27 +1270,25 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
// the work associated with removing the item, so we don't have to do anything here.
if (item == mCurrentDragInfo) return;
View v = getViewForInfo(item);
- mContent.removeView(v);
+ mContent.removeItem(v);
if (mState == STATE_ANIMATING) {
mRearrangeOnClose = true;
} else {
- setupContentForNumItems(getItemCount());
+ rearrangeChildren();
}
if (getItemCount() <= 1) {
replaceFolderWithFinalItem();
}
}
- private View getViewForInfo(ShortcutInfo item) {
- for (int j = 0; j < mContent.getCountY(); j++) {
- for (int i = 0; i < mContent.getCountX(); i++) {
- View v = mContent.getChildAt(i, j);
- if (v.getTag() == item) {
- return v;
- }
+ private View getViewForInfo(final ShortcutInfo item) {
+ return mContent.iterateOverItems(new ItemOperator() {
+
+ @Override
+ public boolean evaluate(ItemInfo info, View view, View parent) {
+ return info == item;
}
- }
- return null;
+ });
}
public void onItemsChanged() {
@@ -1365,14 +1301,14 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
public ArrayList getItemsInReadingOrder() {
if (mItemsInvalidated) {
mItemsInReadingOrder.clear();
- for (int j = 0; j < mContent.getCountY(); j++) {
- for (int i = 0; i < mContent.getCountX(); i++) {
- View v = mContent.getChildAt(i, j);
- if (v != null) {
- mItemsInReadingOrder.add(v);
- }
+ mContent.iterateOverItems(new ItemOperator() {
+
+ @Override
+ public boolean evaluate(ItemInfo info, View view, View parent) {
+ mItemsInReadingOrder.add(view);
+ return false;
}
- }
+ });
mItemsInvalidated = false;
}
return mItemsInReadingOrder;
@@ -1391,5 +1327,79 @@ public class Folder extends LinearLayout implements DragSource, View.OnClickList
@Override
public void getHitRectRelativeToDragLayer(Rect outRect) {
getHitRect(outRect);
+ outRect.left -= mScrollAreaOffset;
+ outRect.right += mScrollAreaOffset;
}
+
+ @Override
+ public void fillInLaunchSourceData(Bundle sourceData) {
+ // Fill in from the folder icon's launch source provider first
+ Stats.LaunchSourceUtils.populateSourceDataFromAncestorProvider(mFolderIcon, sourceData);
+ sourceData.putString(Stats.SOURCE_EXTRA_SUB_CONTAINER, Stats.SUB_CONTAINER_FOLDER);
+ sourceData.putInt(Stats.SOURCE_EXTRA_SUB_CONTAINER_PAGE, mContent.getCurrentPage());
+ }
+
+ private class OnScrollHintListener implements OnAlarmListener {
+
+ private final DragObject mDragObject;
+
+ OnScrollHintListener(DragObject object) {
+ mDragObject = object;
+ }
+
+ /**
+ * Scroll hint has been shown long enough. Now scroll to appropriate page.
+ */
+ @Override
+ public void onAlarm(Alarm alarm) {
+ if (mCurrentScrollDir == DragController.SCROLL_LEFT) {
+ mContent.scrollLeft();
+ mScrollHintDir = DragController.SCROLL_NONE;
+ } else if (mCurrentScrollDir == DragController.SCROLL_RIGHT) {
+ mContent.scrollRight();
+ mScrollHintDir = DragController.SCROLL_NONE;
+ } else {
+ // This should not happen
+ return;
+ }
+ mCurrentScrollDir = DragController.SCROLL_NONE;
+
+ // Pause drag event until the scrolling is finished
+ mScrollPauseAlarm.setOnAlarmListener(new OnScrollFinishedListener(mDragObject));
+ mScrollPauseAlarm.setAlarm(DragController.RESCROLL_DELAY);
+ }
+ }
+
+ private class OnScrollFinishedListener implements OnAlarmListener {
+
+ private final DragObject mDragObject;
+
+ OnScrollFinishedListener(DragObject object) {
+ mDragObject = object;
+ }
+
+ /**
+ * Page scroll is complete.
+ */
+ @Override
+ public void onAlarm(Alarm alarm) {
+ // Reorder immediately on page change.
+ onDragOver(mDragObject, 1);
+ }
+ }
+
+ // Compares item position based on rank and position giving priority to the rank.
+ private static final Comparator ITEM_POS_COMPARATOR = new Comparator() {
+
+ @Override
+ public int compare(ItemInfo lhs, ItemInfo rhs) {
+ if (lhs.rank != rhs.rank) {
+ return lhs.rank - rhs.rank;
+ } else if (lhs.cellY != rhs.cellY) {
+ return lhs.cellY - rhs.cellY;
+ } else {
+ return lhs.cellX - rhs.cellX;
+ }
+ }
+ };
}
diff --git a/src/com/android/launcher3/FolderAutoScrollHelper.java b/src/com/android/launcher3/FolderAutoScrollHelper.java
deleted file mode 100644
index 40e8884647..0000000000
--- a/src/com/android/launcher3/FolderAutoScrollHelper.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2013 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.support.v4.widget.AutoScrollHelper;
-import android.widget.ScrollView;
-
-/**
- * An implementation of {@link AutoScrollHelper} that knows how to scroll
- * through a {@link Folder}.
- */
-public class FolderAutoScrollHelper extends AutoScrollHelper {
- private static final float MAX_SCROLL_VELOCITY = 1500f;
-
- private final ScrollView mTarget;
-
- public FolderAutoScrollHelper(ScrollView target) {
- super(target);
-
- mTarget = target;
-
- setActivationDelay(0);
- setEdgeType(EDGE_TYPE_INSIDE_EXTEND);
- setExclusive(true);
- setMaximumVelocity(MAX_SCROLL_VELOCITY, MAX_SCROLL_VELOCITY);
- setRampDownDuration(0);
- setRampUpDuration(0);
- }
-
- @Override
- public void scrollTargetBy(int deltaX, int deltaY) {
- mTarget.scrollBy(deltaX, deltaY);
- }
-
- @Override
- public boolean canTargetScrollHorizontally(int direction) {
- // List do not scroll horizontally.
- return false;
- }
-
- @Override
- public boolean canTargetScrollVertically(int direction) {
- return mTarget.canScrollVertically(direction);
- }
-}
\ No newline at end of file
diff --git a/src/com/android/launcher3/FolderIcon.java b/src/com/android/launcher3/FolderIcon.java
index a359f11805..8d534d2fef 100644
--- a/src/com/android/launcher3/FolderIcon.java
+++ b/src/com/android/launcher3/FolderIcon.java
@@ -43,6 +43,7 @@ import android.widget.TextView;
import com.android.launcher3.DropTarget.DragObject;
import com.android.launcher3.FolderInfo.FolderListener;
+import com.android.launcher3.util.Thunk;
import java.util.ArrayList;
@@ -50,15 +51,16 @@ import java.util.ArrayList;
* An icon that can appear on in the workspace representing an {@link UserFolder}.
*/
public class FolderIcon extends FrameLayout implements FolderListener {
- private Launcher mLauncher;
- private Folder mFolder;
+ @Thunk Launcher mLauncher;
+ @Thunk Folder mFolder;
private FolderInfo mInfo;
- private static boolean sStaticValuesDirty = true;
+ @Thunk static boolean sStaticValuesDirty = true;
private CheckLongPressHelper mLongPressHelper;
+ private StylusEventHelper mStylusEventHelper;
// The number of icons to display in the
- private static final int NUM_ITEMS_IN_PREVIEW = 3;
+ public static final int NUM_ITEMS_IN_PREVIEW = 3;
private static final int CONSUMPTION_ANIMATION_DURATION = 100;
private static final int DROP_IN_ANIMATION_DURATION = 400;
private static final int INITIAL_ITEM_ANIMATION_DURATION = 350;
@@ -88,8 +90,8 @@ public class FolderIcon extends FrameLayout implements FolderListener {
public static Drawable sSharedFolderLeaveBehind = null;
- private ImageView mPreviewBackground;
- private BubbleTextView mFolderName;
+ @Thunk ImageView mPreviewBackground;
+ @Thunk BubbleTextView mFolderName;
FolderRingAnimator mFolderRingAnimator = null;
@@ -109,11 +111,11 @@ public class FolderIcon extends FrameLayout implements FolderListener {
private float mSlop;
private PreviewItemDrawingParams mParams = new PreviewItemDrawingParams(0, 0, 0, 0);
- private PreviewItemDrawingParams mAnimParams = new PreviewItemDrawingParams(0, 0, 0, 0);
- private ArrayList mHiddenItems = new ArrayList();
+ @Thunk PreviewItemDrawingParams mAnimParams = new PreviewItemDrawingParams(0, 0, 0, 0);
+ @Thunk ArrayList mHiddenItems = new ArrayList();
private Alarm mOpenAlarm = new Alarm();
- private ItemInfo mDragInfo;
+ @Thunk ItemInfo mDragInfo;
public FolderIcon(Context context, AttributeSet attrs) {
super(context, attrs);
@@ -127,6 +129,8 @@ public class FolderIcon extends FrameLayout implements FolderListener {
private void init() {
mLongPressHelper = new CheckLongPressHelper(this);
+ mStylusEventHelper = new StylusEventHelper(this);
+ setAccessibilityDelegate(LauncherAppState.getInstance().getAccessibilityDelegate());
}
public boolean isDropEnabled() {
@@ -145,8 +149,8 @@ public class FolderIcon extends FrameLayout implements FolderListener {
"INITIAL_ITEM_ANIMATION_DURATION, as sequencing of adding first two items " +
"is dependent on this");
}
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
+
+ DeviceProfile grid = launcher.getDeviceProfile();
FolderIcon icon = (FolderIcon) LayoutInflater.from(launcher).inflate(resId, group, false);
icon.setClipToPadding(false);
@@ -191,7 +195,7 @@ public class FolderIcon extends FrameLayout implements FolderListener {
public static class FolderRingAnimator {
public int mCellX;
public int mCellY;
- private CellLayout mCellLayout;
+ @Thunk CellLayout mCellLayout;
public float mOuterRingSize;
public float mInnerRingSize;
public FolderIcon mFolderIcon = null;
@@ -215,12 +219,11 @@ public class FolderIcon extends FrameLayout implements FolderListener {
+ Thread.currentThread());
}
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
+ DeviceProfile grid = launcher.getDeviceProfile();
sPreviewSize = grid.folderIconSizePx;
sPreviewPadding = res.getDimensionPixelSize(R.dimen.folder_preview_padding);
- sSharedOuterRingDrawable = res.getDrawable(R.drawable.portal_ring_outer_holo);
- sSharedInnerRingDrawable = res.getDrawable(R.drawable.portal_ring_inner_nolip_holo);
+ sSharedOuterRingDrawable = res.getDrawable(R.drawable.portal_ring_outer);
+ sSharedInnerRingDrawable = res.getDrawable(R.drawable.portal_ring_inner_nolip);
sSharedFolderLeaveBehind = res.getDrawable(R.drawable.portal_ring_rest);
sStaticValuesDirty = false;
}
@@ -488,8 +491,7 @@ public class FolderIcon extends FrameLayout implements FolderListener {
private void computePreviewDrawingParams(int drawableSize, int totalSize) {
if (mIntrinsicIconSize != drawableSize || mTotalWidth != totalSize) {
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
+ DeviceProfile grid = mLauncher.getDeviceProfile();
mIntrinsicIconSize = drawableSize;
mTotalWidth = totalSize;
@@ -643,9 +645,10 @@ public class FolderIcon extends FrameLayout implements FolderListener {
final Runnable onCompleteRunnable) {
final PreviewItemDrawingParams finalParams = computePreviewItemDrawingParams(0, null);
- final float scale0 = 1.0f;
- final float transX0 = (mAvailableSpaceInPreview - d.getIntrinsicWidth()) / 2;
- final float transY0 = (mAvailableSpaceInPreview - d.getIntrinsicHeight()) / 2 + getPaddingTop();
+ float iconSize = mLauncher.getDeviceProfile().iconSizePx;
+ final float scale0 = iconSize / d.getIntrinsicWidth() ;
+ final float transX0 = (mAvailableSpaceInPreview - iconSize) / 2;
+ final float transY0 = (mAvailableSpaceInPreview - iconSize) / 2 + getPaddingTop();
mAnimParams.drawable = d;
ValueAnimator va = LauncherAnimUtils.ofFloat(this, 0f, 1.0f);
@@ -708,7 +711,7 @@ public class FolderIcon extends FrameLayout implements FolderListener {
}
public void onTitleChanged(CharSequence title) {
- mFolderName.setText(title.toString());
+ mFolderName.setText(title);
setContentDescription(String.format(getContext().getString(R.string.folder_name_format),
title));
}
@@ -719,6 +722,12 @@ public class FolderIcon extends FrameLayout implements FolderListener {
// isPressed() on an ACTION_UP
boolean result = super.onTouchEvent(event);
+ // Check for a stylus button press, if it occurs cancel any long press checks.
+ if (mStylusEventHelper.checkAndPerformStylusEvent(event)) {
+ mLongPressHelper.cancelLongPress();
+ return true;
+ }
+
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLongPressHelper.postCheckForLongPress();
diff --git a/src/com/android/launcher3/FolderInfo.java b/src/com/android/launcher3/FolderInfo.java
index 85a792f4b4..aea21c95b5 100644
--- a/src/com/android/launcher3/FolderInfo.java
+++ b/src/com/android/launcher3/FolderInfo.java
@@ -29,19 +29,38 @@ import java.util.Arrays;
*/
public class FolderInfo extends ItemInfo {
+ public static final int NO_FLAGS = 0x00000000;
+
+ /**
+ * The folder is locked in sorted mode
+ */
+ public static final int FLAG_ITEMS_SORTED = 0x00000001;
+
+ /**
+ * It is a work folder
+ */
+ public static final int FLAG_WORK_FOLDER = 0x00000002;
+
+ /**
+ * The multi-page animation has run for this folder
+ */
+ public static final int FLAG_MULTI_PAGE_ANIMATION = 0x00000004;
+
/**
* Whether this folder has been opened
*/
boolean opened;
+ public int options;
+
/**
* The apps and shortcuts
*/
- ArrayList contents = new ArrayList();
+ public ArrayList contents = new ArrayList();
ArrayList listeners = new ArrayList();
- FolderInfo() {
+ public FolderInfo() {
itemType = LauncherSettings.Favorites.ITEM_TYPE_FOLDER;
user = UserHandleCompat.myUserHandle();
}
@@ -83,6 +102,8 @@ public class FolderInfo extends ItemInfo {
void onAddToDatabase(Context context, ContentValues values) {
super.onAddToDatabase(context, values);
values.put(LauncherSettings.Favorites.TITLE, title.toString());
+ values.put(LauncherSettings.Favorites.OPTIONS, options);
+
}
void addListener(FolderListener listener) {
@@ -121,4 +142,25 @@ public class FolderInfo extends ItemInfo {
+ " cellX=" + cellX + " cellY=" + cellY + " spanX=" + spanX
+ " spanY=" + spanY + " dropPos=" + Arrays.toString(dropPos) + ")";
}
+
+ public boolean hasOption(int optionFlag) {
+ return (options & optionFlag) != 0;
+ }
+
+ /**
+ * @param option flag to set or clear
+ * @param isEnabled whether to set or clear the flag
+ * @param context if not null, save changes to the db.
+ */
+ public void setOption(int option, boolean isEnabled, Context context) {
+ int oldOptions = options;
+ if (isEnabled) {
+ options |= option;
+ } else {
+ options &= ~option;
+ }
+ if (context != null && oldOptions != options) {
+ LauncherModel.updateItemInDatabase(context, this);
+ }
+ }
}
diff --git a/src/com/android/launcher3/FolderPagedView.java b/src/com/android/launcher3/FolderPagedView.java
new file mode 100644
index 0000000000..f2ec1b68c5
--- /dev/null
+++ b/src/com/android/launcher3/FolderPagedView.java
@@ -0,0 +1,678 @@
+/**
+ * Copyright (C) 2015 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.annotation.SuppressLint;
+import android.content.Context;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.animation.DecelerateInterpolator;
+import android.view.animation.Interpolator;
+import android.view.animation.OvershootInterpolator;
+
+import com.android.launcher3.FocusHelper.PagedFolderKeyEventListener;
+import com.android.launcher3.PageIndicator.PageMarkerResources;
+import com.android.launcher3.Workspace.ItemOperator;
+import com.android.launcher3.util.Thunk;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+public class FolderPagedView extends PagedView {
+
+ private static final String TAG = "FolderPagedView";
+
+ private static final boolean ALLOW_FOLDER_SCROLL = true;
+
+ private static final int REORDER_ANIMATION_DURATION = 230;
+ private static final int START_VIEW_REORDER_DELAY = 30;
+ private static final float VIEW_REORDER_DELAY_FACTOR = 0.9f;
+
+ private static final int PAGE_INDICATOR_ANIMATION_START_DELAY = 300;
+ private static final int PAGE_INDICATOR_ANIMATION_STAGGERED_DELAY = 150;
+ private static final int PAGE_INDICATOR_ANIMATION_DURATION = 400;
+
+ // This value approximately overshoots to 1.5 times the original size.
+ private static final float PAGE_INDICATOR_OVERSHOOT_TENSION = 4.9f;
+
+ /**
+ * Fraction of the width to scroll when showing the next page hint.
+ */
+ private static final float SCROLL_HINT_FRACTION = 0.07f;
+
+ private static final int[] sTempPosArray = new int[2];
+
+ public final boolean mIsRtl;
+
+ private final LayoutInflater mInflater;
+ private final IconCache mIconCache;
+
+ @Thunk final HashMap mPendingAnimations = new HashMap<>();
+
+ private final int mMaxCountX;
+ private final int mMaxCountY;
+ private final int mMaxItemsPerPage;
+
+ private int mAllocatedContentSize;
+ private int mGridCountX;
+ private int mGridCountY;
+
+ private Folder mFolder;
+ private FocusIndicatorView mFocusIndicatorView;
+ private PagedFolderKeyEventListener mKeyListener;
+
+ private PageIndicator mPageIndicator;
+
+ public FolderPagedView(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ LauncherAppState app = LauncherAppState.getInstance();
+
+ InvariantDeviceProfile profile = app.getInvariantDeviceProfile();
+ mMaxCountX = profile.numFolderColumns;
+ mMaxCountY = profile.numFolderRows;
+
+ mMaxItemsPerPage = mMaxCountX * mMaxCountY;
+
+ mInflater = LayoutInflater.from(context);
+ mIconCache = app.getIconCache();
+
+ mIsRtl = Utilities.isRtl(getResources());
+ setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
+
+ setEdgeGlowColor(getResources().getColor(R.color.folder_edge_effect_color));
+ }
+
+ public void setFolder(Folder folder) {
+ mFolder = folder;
+ mFocusIndicatorView = (FocusIndicatorView) folder.findViewById(R.id.focus_indicator);
+ mKeyListener = new PagedFolderKeyEventListener(folder);
+ mPageIndicator = (PageIndicator) folder.findViewById(R.id.folder_page_indicator);
+ }
+
+ /**
+ * Sets up the grid size such that {@param count} items can fit in the grid.
+ * The grid size is calculated such that countY <= countX and countX = ceil(sqrt(count)) while
+ * maintaining the restrictions of {@link #mMaxCountX} & {@link #mMaxCountY}.
+ */
+ private void setupContentDimensions(int count) {
+ mAllocatedContentSize = count;
+ boolean done;
+ if (count >= mMaxItemsPerPage) {
+ mGridCountX = mMaxCountX;
+ mGridCountY = mMaxCountY;
+ done = true;
+ } else {
+ done = false;
+ }
+
+ while (!done) {
+ int oldCountX = mGridCountX;
+ int oldCountY = mGridCountY;
+ if (mGridCountX * mGridCountY < count) {
+ // Current grid is too small, expand it
+ if ((mGridCountX <= mGridCountY || mGridCountY == mMaxCountY) && mGridCountX < mMaxCountX) {
+ mGridCountX++;
+ } else if (mGridCountY < mMaxCountY) {
+ mGridCountY++;
+ }
+ if (mGridCountY == 0) mGridCountY++;
+ } else if ((mGridCountY - 1) * mGridCountX >= count && mGridCountY >= mGridCountX) {
+ mGridCountY = Math.max(0, mGridCountY - 1);
+ } else if ((mGridCountX - 1) * mGridCountY >= count) {
+ mGridCountX = Math.max(0, mGridCountX - 1);
+ }
+ done = mGridCountX == oldCountX && mGridCountY == oldCountY;
+ }
+
+ // Update grid size
+ for (int i = getPageCount() - 1; i >= 0; i--) {
+ getPageAt(i).setGridSize(mGridCountX, mGridCountY);
+ }
+ }
+
+ /**
+ * Binds items to the layout.
+ * @return list of items that could not be bound, probably because we hit the max size limit.
+ */
+ public ArrayList bindItems(ArrayList items) {
+ ArrayList icons = new ArrayList();
+ ArrayList extra = new ArrayList();
+
+ for (ShortcutInfo item : items) {
+ if (!ALLOW_FOLDER_SCROLL && icons.size() >= mMaxItemsPerPage) {
+ extra.add(item);
+ } else {
+ icons.add(createNewView(item));
+ }
+ }
+ arrangeChildren(icons, icons.size(), false);
+ return extra;
+ }
+
+ /**
+ * Create space for a new item at the end, and returns the rank for that item.
+ * Also sets the current page to the last page.
+ */
+ public int allocateRankForNewItem(ShortcutInfo info) {
+ int rank = getItemCount();
+ ArrayList views = new ArrayList(mFolder.getItemsInReadingOrder());
+ views.add(rank, null);
+ arrangeChildren(views, views.size(), false);
+ setCurrentPage(rank / mMaxItemsPerPage);
+ return rank;
+ }
+
+ public View createAndAddViewForRank(ShortcutInfo item, int rank) {
+ View icon = createNewView(item);
+ addViewForRank(icon, item, rank);
+ return icon;
+ }
+
+ /**
+ * Adds the {@param view} to the layout based on {@param rank} and updated the position
+ * related attributes. It assumes that {@param item} is already attached to the view.
+ */
+ public void addViewForRank(View view, ShortcutInfo item, int rank) {
+ int pagePos = rank % mMaxItemsPerPage;
+ int pageNo = rank / mMaxItemsPerPage;
+
+ item.rank = rank;
+ item.cellX = pagePos % mGridCountX;
+ item.cellY = pagePos / mGridCountX;
+
+ CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
+ lp.cellX = item.cellX;
+ lp.cellY = item.cellY;
+ getPageAt(pageNo).addViewToCellLayout(
+ view, -1, mFolder.mLauncher.getViewIdForItem(item), lp, true);
+ }
+
+ @SuppressLint("InflateParams")
+ public View createNewView(ShortcutInfo item) {
+ final BubbleTextView textView = (BubbleTextView) mInflater.inflate(
+ R.layout.folder_application, null, false);
+ textView.applyFromShortcutInfo(item, mIconCache);
+ textView.setOnClickListener(mFolder);
+ textView.setOnLongClickListener(mFolder);
+ textView.setOnFocusChangeListener(mFocusIndicatorView);
+ textView.setOnKeyListener(mKeyListener);
+
+ textView.setLayoutParams(new CellLayout.LayoutParams(
+ item.cellX, item.cellY, item.spanX, item.spanY));
+ return textView;
+ }
+
+ @Override
+ public CellLayout getPageAt(int index) {
+ return (CellLayout) getChildAt(index);
+ }
+
+ public void removeCellLayoutView(View view) {
+ for (int i = getChildCount() - 1; i >= 0; i --) {
+ getPageAt(i).removeView(view);
+ }
+ }
+
+ public CellLayout getCurrentCellLayout() {
+ return getPageAt(getNextPage());
+ }
+
+ private CellLayout createAndAddNewPage() {
+ DeviceProfile grid = ((Launcher) getContext()).getDeviceProfile();
+ CellLayout page = new CellLayout(getContext());
+ page.setCellDimensions(grid.folderCellWidthPx, grid.folderCellHeightPx);
+ page.getShortcutsAndWidgets().setMotionEventSplittingEnabled(false);
+ page.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
+ page.setInvertIfRtl(true);
+ page.setGridSize(mGridCountX, mGridCountY);
+
+ addView(page, -1, generateDefaultLayoutParams());
+ return page;
+ }
+
+ @Override
+ protected int getChildGap() {
+ return getPaddingLeft() + getPaddingRight();
+ }
+
+ public void setFixedSize(int width, int height) {
+ width -= (getPaddingLeft() + getPaddingRight());
+ height -= (getPaddingTop() + getPaddingBottom());
+ for (int i = getChildCount() - 1; i >= 0; i --) {
+ ((CellLayout) getChildAt(i)).setFixedSize(width, height);
+ }
+ }
+
+ public void removeItem(View v) {
+ for (int i = getChildCount() - 1; i >= 0; i --) {
+ getPageAt(i).removeView(v);
+ }
+ }
+
+ /**
+ * Updates position and rank of all the children in the view.
+ * It essentially removes all views from all the pages and then adds them again in appropriate
+ * page.
+ *
+ * @param list the ordered list of children.
+ * @param itemCount if greater than the total children count, empty spaces are left
+ * at the end, otherwise it is ignored.
+ *
+ */
+ public void arrangeChildren(ArrayList list, int itemCount) {
+ arrangeChildren(list, itemCount, true);
+ }
+
+ @SuppressLint("RtlHardcoded")
+ private void arrangeChildren(ArrayList list, int itemCount, boolean saveChanges) {
+ ArrayList pages = new ArrayList();
+ for (int i = 0; i < getChildCount(); i++) {
+ CellLayout page = (CellLayout) getChildAt(i);
+ page.removeAllViews();
+ pages.add(page);
+ }
+ setupContentDimensions(itemCount);
+
+ Iterator pageItr = pages.iterator();
+ CellLayout currentPage = null;
+
+ int position = 0;
+ int newX, newY, rank;
+
+ rank = 0;
+ for (int i = 0; i < itemCount; i++) {
+ View v = list.size() > i ? list.get(i) : null;
+ if (currentPage == null || position >= mMaxItemsPerPage) {
+ // Next page
+ if (pageItr.hasNext()) {
+ currentPage = pageItr.next();
+ } else {
+ currentPage = createAndAddNewPage();
+ }
+ position = 0;
+ }
+
+ if (v != null) {
+ CellLayout.LayoutParams lp = (CellLayout.LayoutParams) v.getLayoutParams();
+ newX = position % mGridCountX;
+ newY = position / mGridCountX;
+ ItemInfo info = (ItemInfo) v.getTag();
+ if (info.cellX != newX || info.cellY != newY || info.rank != rank) {
+ info.cellX = newX;
+ info.cellY = newY;
+ info.rank = rank;
+ if (saveChanges) {
+ LauncherModel.addOrMoveItemInDatabase(getContext(), info,
+ mFolder.mInfo.id, 0, info.cellX, info.cellY);
+ }
+ }
+ lp.cellX = info.cellX;
+ lp.cellY = info.cellY;
+ currentPage.addViewToCellLayout(
+ v, -1, mFolder.mLauncher.getViewIdForItem(info), lp, true);
+ }
+
+ rank ++;
+ position++;
+ }
+
+ // Remove extra views.
+ boolean removed = false;
+ while (pageItr.hasNext()) {
+ removeView(pageItr.next());
+ removed = true;
+ }
+ if (removed) {
+ setCurrentPage(0);
+ }
+
+ setEnableOverscroll(getPageCount() > 1);
+
+ // Update footer
+ mPageIndicator.setVisibility(getPageCount() > 1 ? View.VISIBLE : View.GONE);
+ // Set the gravity as LEFT or RIGHT instead of START, as START depends on the actual text.
+ mFolder.mFolderName.setGravity(getPageCount() > 1 ?
+ (mIsRtl ? Gravity.RIGHT : Gravity.LEFT) : Gravity.CENTER_HORIZONTAL);
+ }
+
+ public int getDesiredWidth() {
+ return getPageCount() > 0 ?
+ (getPageAt(0).getDesiredWidth() + getPaddingLeft() + getPaddingRight()) : 0;
+ }
+
+ public int getDesiredHeight() {
+ return getPageCount() > 0 ?
+ (getPageAt(0).getDesiredHeight() + getPaddingTop() + getPaddingBottom()) : 0;
+ }
+
+ public int getItemCount() {
+ int lastPageIndex = getChildCount() - 1;
+ if (lastPageIndex < 0) {
+ // If there are no pages, nothing has yet been added to the folder.
+ return 0;
+ }
+ return getPageAt(lastPageIndex).getShortcutsAndWidgets().getChildCount()
+ + lastPageIndex * mMaxItemsPerPage;
+ }
+
+ /**
+ * @return the rank of the cell nearest to the provided pixel position.
+ */
+ public int findNearestArea(int pixelX, int pixelY) {
+ int pageIndex = getNextPage();
+ CellLayout page = getPageAt(pageIndex);
+ page.findNearestArea(pixelX, pixelY, 1, 1, sTempPosArray);
+ if (mFolder.isLayoutRtl()) {
+ sTempPosArray[0] = page.getCountX() - sTempPosArray[0] - 1;
+ }
+ return Math.min(mAllocatedContentSize - 1,
+ pageIndex * mMaxItemsPerPage + sTempPosArray[1] * mGridCountX + sTempPosArray[0]);
+ }
+
+ @Override
+ protected PageMarkerResources getPageIndicatorMarker(int pageIndex) {
+ return new PageMarkerResources(R.drawable.ic_pageindicator_current_folder,
+ R.drawable.ic_pageindicator_default_folder);
+ }
+
+ public boolean isFull() {
+ return !ALLOW_FOLDER_SCROLL && getItemCount() >= mMaxItemsPerPage;
+ }
+
+ public View getLastItem() {
+ if (getChildCount() < 1) {
+ return null;
+ }
+ ShortcutAndWidgetContainer lastContainer = getCurrentCellLayout().getShortcutsAndWidgets();
+ int lastRank = lastContainer.getChildCount() - 1;
+ if (mGridCountX > 0) {
+ return lastContainer.getChildAt(lastRank % mGridCountX, lastRank / mGridCountX);
+ } else {
+ return lastContainer.getChildAt(lastRank);
+ }
+ }
+
+ /**
+ * Iterates over all its items in a reading order.
+ * @return the view for which the operator returned true.
+ */
+ public View iterateOverItems(ItemOperator op) {
+ for (int k = 0 ; k < getChildCount(); k++) {
+ CellLayout page = getPageAt(k);
+ for (int j = 0; j < page.getCountY(); j++) {
+ for (int i = 0; i < page.getCountX(); i++) {
+ View v = page.getChildAt(i, j);
+ if ((v != null) && op.evaluate((ItemInfo) v.getTag(), v, this)) {
+ return v;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ public String getAccessibilityDescription() {
+ return String.format(getContext().getString(R.string.folder_opened),
+ mGridCountX, mGridCountY);
+ }
+
+ /**
+ * Sets the focus on the first visible child.
+ */
+ public void setFocusOnFirstChild() {
+ View firstChild = getCurrentCellLayout().getChildAt(0, 0);
+ if (firstChild != null) {
+ firstChild.requestFocus();
+ }
+ }
+
+ @Override
+ protected void notifyPageSwitchListener() {
+ super.notifyPageSwitchListener();
+ if (mFolder != null) {
+ mFolder.updateTextViewFocus();
+ }
+ }
+
+ /**
+ * Scrolls the current view by a fraction
+ */
+ public void showScrollHint(int direction) {
+ float fraction = (direction == DragController.SCROLL_LEFT) ^ mIsRtl
+ ? -SCROLL_HINT_FRACTION : SCROLL_HINT_FRACTION;
+ int hint = (int) (fraction * getWidth());
+ int scroll = getScrollForPage(getNextPage()) + hint;
+ int delta = scroll - getScrollX();
+ if (delta != 0) {
+ mScroller.setInterpolator(new DecelerateInterpolator());
+ mScroller.startScroll(getScrollX(), 0, delta, 0, Folder.SCROLL_HINT_DURATION);
+ invalidate();
+ }
+ }
+
+ public void clearScrollHint() {
+ if (getScrollX() != getScrollForPage(getNextPage())) {
+ snapToPage(getNextPage());
+ }
+ }
+
+ /**
+ * Finish animation all the views which are animating across pages
+ */
+ public void completePendingPageChanges() {
+ if (!mPendingAnimations.isEmpty()) {
+ HashMap pendingViews = new HashMap<>(mPendingAnimations);
+ for (Map.Entry e : pendingViews.entrySet()) {
+ e.getKey().animate().cancel();
+ e.getValue().run();
+ }
+ }
+ }
+
+ public boolean rankOnCurrentPage(int rank) {
+ int p = rank / mMaxItemsPerPage;
+ return p == getNextPage();
+ }
+
+ @Override
+ protected void onPageBeginMoving() {
+ super.onPageBeginMoving();
+ getVisiblePages(sTempPosArray);
+ for (int i = sTempPosArray[0]; i <= sTempPosArray[1]; i++) {
+ verifyVisibleHighResIcons(i);
+ }
+ }
+
+ /**
+ * Ensures that all the icons on the given page are of high-res
+ */
+ public void verifyVisibleHighResIcons(int pageNo) {
+ CellLayout page = getPageAt(pageNo);
+ if (page != null) {
+ ShortcutAndWidgetContainer parent = page.getShortcutsAndWidgets();
+ for (int i = parent.getChildCount() - 1; i >= 0; i--) {
+ ((BubbleTextView) parent.getChildAt(i)).verifyHighRes();
+ }
+ }
+ }
+
+ public int getAllocatedContentSize() {
+ return mAllocatedContentSize;
+ }
+
+ /**
+ * Reorders the items such that the {@param empty} spot moves to {@param target}
+ */
+ public void realTimeReorder(int empty, int target) {
+ completePendingPageChanges();
+ int delay = 0;
+ float delayAmount = START_VIEW_REORDER_DELAY;
+
+ // Animation only happens on the current page.
+ int pageToAnimate = getNextPage();
+
+ int pageT = target / mMaxItemsPerPage;
+ int pagePosT = target % mMaxItemsPerPage;
+
+ if (pageT != pageToAnimate) {
+ Log.e(TAG, "Cannot animate when the target cell is invisible");
+ }
+ int pagePosE = empty % mMaxItemsPerPage;
+ int pageE = empty / mMaxItemsPerPage;
+
+ int startPos, endPos;
+ int moveStart, moveEnd;
+ int direction;
+
+ if (target == empty) {
+ // No animation
+ return;
+ } else if (target > empty) {
+ // Items will move backwards to make room for the empty cell.
+ direction = 1;
+
+ // If empty cell is in a different page, move them instantly.
+ if (pageE < pageToAnimate) {
+ moveStart = empty;
+ // Instantly move the first item in the current page.
+ moveEnd = pageToAnimate * mMaxItemsPerPage;
+ // Animate the 2nd item in the current page, as the first item was already moved to
+ // the last page.
+ startPos = 0;
+ } else {
+ moveStart = moveEnd = -1;
+ startPos = pagePosE;
+ }
+
+ endPos = pagePosT;
+ } else {
+ // The items will move forward.
+ direction = -1;
+
+ if (pageE > pageToAnimate) {
+ // Move the items immediately.
+ moveStart = empty;
+ // Instantly move the last item in the current page.
+ moveEnd = (pageToAnimate + 1) * mMaxItemsPerPage - 1;
+
+ // Animations start with the second last item in the page
+ startPos = mMaxItemsPerPage - 1;
+ } else {
+ moveStart = moveEnd = -1;
+ startPos = pagePosE;
+ }
+
+ endPos = pagePosT;
+ }
+
+ // Instant moving views.
+ while (moveStart != moveEnd) {
+ int rankToMove = moveStart + direction;
+ int p = rankToMove / mMaxItemsPerPage;
+ int pagePos = rankToMove % mMaxItemsPerPage;
+ int x = pagePos % mGridCountX;
+ int y = pagePos / mGridCountX;
+
+ final CellLayout page = getPageAt(p);
+ final View v = page.getChildAt(x, y);
+ if (v != null) {
+ if (pageToAnimate != p) {
+ page.removeView(v);
+ addViewForRank(v, (ShortcutInfo) v.getTag(), moveStart);
+ } else {
+ // Do a fake animation before removing it.
+ final int newRank = moveStart;
+ final float oldTranslateX = v.getTranslationX();
+
+ Runnable endAction = new Runnable() {
+
+ @Override
+ public void run() {
+ mPendingAnimations.remove(v);
+ v.setTranslationX(oldTranslateX);
+ ((CellLayout) v.getParent().getParent()).removeView(v);
+ addViewForRank(v, (ShortcutInfo) v.getTag(), newRank);
+ }
+ };
+ v.animate()
+ .translationXBy((direction > 0 ^ mIsRtl) ? -v.getWidth() : v.getWidth())
+ .setDuration(REORDER_ANIMATION_DURATION)
+ .setStartDelay(0)
+ .withEndAction(endAction);
+ mPendingAnimations.put(v, endAction);
+ }
+ }
+ moveStart = rankToMove;
+ }
+
+ if ((endPos - startPos) * direction <= 0) {
+ // No animation
+ return;
+ }
+
+ CellLayout page = getPageAt(pageToAnimate);
+ for (int i = startPos; i != endPos; i += direction) {
+ int nextPos = i + direction;
+ View v = page.getChildAt(nextPos % mGridCountX, nextPos / mGridCountX);
+ if (v != null) {
+ ((ItemInfo) v.getTag()).rank -= direction;
+ }
+ if (page.animateChildToPosition(v, i % mGridCountX, i / mGridCountX,
+ REORDER_ANIMATION_DURATION, delay, true, true)) {
+ delay += delayAmount;
+ delayAmount *= VIEW_REORDER_DELAY_FACTOR;
+ }
+ }
+ }
+
+ public void setMarkerScale(float scale) {
+ int count = mPageIndicator.getChildCount();
+ for (int i = 0; i < count; i++) {
+ View marker = mPageIndicator.getChildAt(i);
+ marker.animate().cancel();
+ marker.setScaleX(scale);
+ marker.setScaleY(scale);
+ }
+ }
+
+ public void animateMarkers() {
+ int count = mPageIndicator.getChildCount();
+ Interpolator interpolator = new OvershootInterpolator(PAGE_INDICATOR_OVERSHOOT_TENSION);
+ for (int i = 0; i < count; i++) {
+ mPageIndicator.getChildAt(i).animate().scaleX(1).scaleY(1)
+ .setInterpolator(interpolator)
+ .setDuration(PAGE_INDICATOR_ANIMATION_DURATION)
+ .setStartDelay(PAGE_INDICATOR_ANIMATION_STAGGERED_DELAY * i
+ + PAGE_INDICATOR_ANIMATION_START_DELAY);
+ }
+ }
+
+ public int itemsPerPage() {
+ return mMaxItemsPerPage;
+ }
+
+ @Override
+ protected void getEdgeVerticalPostion(int[] pos) {
+ pos[0] = 0;
+ pos[1] = getViewportHeight();
+ }
+}
diff --git a/src/com/android/launcher3/HolographicOutlineHelper.java b/src/com/android/launcher3/HolographicOutlineHelper.java
index b1e0e68a4c..5ff85d664c 100644
--- a/src/com/android/launcher3/HolographicOutlineHelper.java
+++ b/src/com/android/launcher3/HolographicOutlineHelper.java
@@ -17,6 +17,7 @@
package com.android.launcher3;
import android.content.Context;
+import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
@@ -25,11 +26,16 @@ import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
-import android.graphics.Region.Op;
+import android.graphics.drawable.Drawable;
+import android.util.SparseArray;
+/**
+ * Utility class to generate shadow and outline effect, which are used for click feedback
+ * and drag-n-drop respectively.
+ */
public class HolographicOutlineHelper {
- private static final Rect sTempRect = new Rect();
+ private static HolographicOutlineHelper sInstance;
private final Canvas mCanvas = new Canvas();
private final Paint mDrawPaint = new Paint();
@@ -40,26 +46,23 @@ public class HolographicOutlineHelper {
private final BlurMaskFilter mThinOuterBlurMaskFilter;
private final BlurMaskFilter mMediumInnerBlurMaskFilter;
- private final BlurMaskFilter mShaowBlurMaskFilter;
- private final int mShadowOffset;
+ private final BlurMaskFilter mShadowBlurMaskFilter;
- /**
- * Padding used when creating shadow bitmap;
- */
- final int shadowBitmapPadding;
-
- static HolographicOutlineHelper INSTANCE;
+ // We have 4 different icon sizes: homescreen, hotseat, folder & all-apps
+ private final SparseArray mBitmapCache = new SparseArray<>(4);
private HolographicOutlineHelper(Context context) {
- final float scale = LauncherAppState.getInstance().getScreenDensity();
+ Resources res = context.getResources();
- mMediumOuterBlurMaskFilter = new BlurMaskFilter(scale * 2.0f, BlurMaskFilter.Blur.OUTER);
- mThinOuterBlurMaskFilter = new BlurMaskFilter(scale * 1.0f, BlurMaskFilter.Blur.OUTER);
- mMediumInnerBlurMaskFilter = new BlurMaskFilter(scale * 2.0f, BlurMaskFilter.Blur.NORMAL);
+ float mediumBlur = res.getDimension(R.dimen.blur_size_medium_outline);
+ mMediumOuterBlurMaskFilter = new BlurMaskFilter(mediumBlur, BlurMaskFilter.Blur.OUTER);
+ mMediumInnerBlurMaskFilter = new BlurMaskFilter(mediumBlur, BlurMaskFilter.Blur.NORMAL);
- mShaowBlurMaskFilter = new BlurMaskFilter(scale * 4.0f, BlurMaskFilter.Blur.NORMAL);
- mShadowOffset = (int) (scale * 2.0f);
- shadowBitmapPadding = (int) (scale * 4.0f);
+ mThinOuterBlurMaskFilter = new BlurMaskFilter(
+ res.getDimension(R.dimen.blur_size_thin_outline), BlurMaskFilter.Blur.OUTER);
+
+ mShadowBlurMaskFilter = new BlurMaskFilter(
+ res.getDimension(R.dimen.blur_size_click_shadow), BlurMaskFilter.Blur.NORMAL);
mDrawPaint.setFilterBitmap(true);
mDrawPaint.setAntiAlias(true);
@@ -71,10 +74,10 @@ public class HolographicOutlineHelper {
}
public static HolographicOutlineHelper obtain(Context context) {
- if (INSTANCE == null) {
- INSTANCE = new HolographicOutlineHelper(context);
+ if (sInstance == null) {
+ sInstance = new HolographicOutlineHelper(context);
}
- return INSTANCE;
+ return sInstance;
}
/**
@@ -153,51 +156,34 @@ public class HolographicOutlineHelper {
}
Bitmap createMediumDropShadow(BubbleTextView view) {
- final Bitmap result = Bitmap.createBitmap(
- view.getWidth() + shadowBitmapPadding + shadowBitmapPadding,
- view.getHeight() + shadowBitmapPadding + shadowBitmapPadding + mShadowOffset,
- Bitmap.Config.ARGB_8888);
+ Drawable icon = view.getIcon();
+ if (icon == null) {
+ return null;
+ }
+ Rect rect = icon.getBounds();
- mCanvas.setBitmap(result);
+ int bitmapWidth = (int) (rect.width() * view.getScaleX());
+ int bitmapHeight = (int) (rect.height() * view.getScaleY());
- final Rect clipRect = sTempRect;
- view.getDrawingRect(sTempRect);
- // adjust the clip rect so that we don't include the text label
- clipRect.bottom = view.getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V
- + view.getLayout().getLineTop(0);
+ int key = (bitmapWidth << 16) | bitmapHeight;
+ Bitmap cache = mBitmapCache.get(key);
+ if (cache == null) {
+ cache = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
+ mCanvas.setBitmap(cache);
+ mBitmapCache.put(key, cache);
+ } else {
+ mCanvas.setBitmap(cache);
+ mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
+ }
- // Draw the View into the bitmap.
- // The translate of scrollX and scrollY is necessary when drawing TextViews, because
- // they set scrollX and scrollY to large values to achieve centered text
- mCanvas.save();
- mCanvas.scale(view.getScaleX(), view.getScaleY(),
- view.getWidth() / 2 + shadowBitmapPadding,
- view.getHeight() / 2 + shadowBitmapPadding);
- mCanvas.translate(-view.getScrollX() + shadowBitmapPadding,
- -view.getScrollY() + shadowBitmapPadding);
- mCanvas.clipRect(clipRect, Op.REPLACE);
- view.draw(mCanvas);
+ mCanvas.save(Canvas.MATRIX_SAVE_FLAG);
+ mCanvas.scale(view.getScaleX(), view.getScaleY());
+ mCanvas.translate(-rect.left, -rect.top);
+ icon.draw(mCanvas);
mCanvas.restore();
-
- int[] blurOffst = new int[2];
- mBlurPaint.setMaskFilter(mShaowBlurMaskFilter);
- Bitmap blurBitmap = result.extractAlpha(mBlurPaint, blurOffst);
-
- mCanvas.save();
- mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
- mCanvas.translate(blurOffst[0], blurOffst[1]);
-
- mDrawPaint.setColor(Color.BLACK);
- mDrawPaint.setAlpha(30);
- mCanvas.drawBitmap(blurBitmap, 0, 0, mDrawPaint);
-
- mDrawPaint.setAlpha(60);
- mCanvas.drawBitmap(blurBitmap, 0, mShadowOffset, mDrawPaint);
- mCanvas.restore();
-
mCanvas.setBitmap(null);
- blurBitmap.recycle();
- return result;
+ mBlurPaint.setMaskFilter(mShadowBlurMaskFilter);
+ return cache.extractAlpha(mBlurPaint, null);
}
}
diff --git a/src/com/android/launcher3/Hotseat.java b/src/com/android/launcher3/Hotseat.java
index b08272f369..17fdeb1dc8 100644
--- a/src/com/android/launcher3/Hotseat.java
+++ b/src/com/android/launcher3/Hotseat.java
@@ -16,24 +16,19 @@
package com.android.launcher3;
-import android.content.ComponentName;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
-import android.graphics.Rect;
import android.graphics.drawable.Drawable;
+import android.os.Bundle;
import android.util.AttributeSet;
-import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
-import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
-import java.util.ArrayList;
-
-public class Hotseat extends FrameLayout {
- private static final String TAG = "Hotseat";
+public class Hotseat extends FrameLayout
+ implements Stats.LaunchSourceProvider{
private CellLayout mContent;
@@ -41,8 +36,7 @@ public class Hotseat extends FrameLayout {
private int mAllAppsButtonRank;
- private boolean mTransposeLayoutWithOrientation;
- private boolean mIsLandscape;
+ private final boolean mHasVerticalHotseat;
public Hotseat(Context context) {
this(context, null);
@@ -54,22 +48,21 @@ public class Hotseat extends FrameLayout {
public Hotseat(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
-
- Resources r = context.getResources();
- mTransposeLayoutWithOrientation =
- r.getBoolean(R.bool.hotseat_transpose_layout_with_orientation);
- mIsLandscape = context.getResources().getConfiguration().orientation ==
- Configuration.ORIENTATION_LANDSCAPE;
- }
-
- public void setup(Launcher launcher) {
- mLauncher = launcher;
+ mLauncher = (Launcher) context;
+ mHasVerticalHotseat = mLauncher.getDeviceProfile().isVerticalBarLayout();
}
CellLayout getLayout() {
return mContent;
}
+ /**
+ * Returns whether there are other icons than the all apps button in the hotseat.
+ */
+ public boolean hasIcons() {
+ return mContent.getShortcutsAndWidgets().getChildCount() > 1;
+ }
+
/**
* Registers the specified listener on the cell layout of the hotseat.
*/
@@ -78,60 +71,35 @@ public class Hotseat extends FrameLayout {
mContent.setOnLongClickListener(l);
}
- private boolean hasVerticalHotseat() {
- return (mIsLandscape && mTransposeLayoutWithOrientation);
- }
-
/* Get the orientation invariant order of the item in the hotseat for persistence. */
int getOrderInHotseat(int x, int y) {
- return hasVerticalHotseat() ? (mContent.getCountY() - y - 1) : x;
+ return mHasVerticalHotseat ? (mContent.getCountY() - y - 1) : x;
}
+
/* Get the orientation specific coordinates given an invariant order in the hotseat. */
int getCellXFromOrder(int rank) {
- return hasVerticalHotseat() ? 0 : rank;
+ return mHasVerticalHotseat ? 0 : rank;
}
+
int getCellYFromOrder(int rank) {
- return hasVerticalHotseat() ? (mContent.getCountY() - (rank + 1)) : 0;
+ return mHasVerticalHotseat ? (mContent.getCountY() - (rank + 1)) : 0;
}
+
public boolean isAllAppsButtonRank(int rank) {
- if (LauncherAppState.isDisableAllApps()) {
- return false;
- } else {
- return rank == mAllAppsButtonRank;
- }
- }
-
- /** This returns the coordinates of an app in a given cell, relative to the DragLayer */
- Rect getCellCoordinates(int cellX, int cellY) {
- Rect coords = new Rect();
- mContent.cellToRect(cellX, cellY, 1, 1, coords);
- int[] hotseatInParent = new int[2];
- Utilities.getDescendantCoordRelativeToParent(this, mLauncher.getDragLayer(),
- hotseatInParent, false);
- coords.offset(hotseatInParent[0], hotseatInParent[1]);
-
- // Center the icon
- int cWidth = mContent.getShortcutsAndWidgets().getCellContentWidth();
- int cHeight = mContent.getShortcutsAndWidgets().getCellContentHeight();
- int cellPaddingX = (int) Math.max(0, ((coords.width() - cWidth) / 2f));
- int cellPaddingY = (int) Math.max(0, ((coords.height() - cHeight) / 2f));
- coords.offset(cellPaddingX, cellPaddingY);
-
- return coords;
+ return rank == mAllAppsButtonRank;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
- LauncherAppState app = LauncherAppState.getInstance();
- DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
+ DeviceProfile grid = mLauncher.getDeviceProfile();
- mAllAppsButtonRank = grid.hotseatAllAppsRank;
+ mAllAppsButtonRank = grid.inv.hotseatAllAppsRank;
mContent = (CellLayout) findViewById(R.id.layout);
- if (grid.isLandscape && !grid.isLargeTablet()) {
- mContent.setGridSize(1, (int) grid.numHotseatIcons);
+ if (grid.isLandscape && !grid.isLargeTablet) {
+ mContent.setGridSize(1, (int) grid.inv.numHotseatIcons);
} else {
- mContent.setGridSize((int) grid.numHotseatIcons, 1);
+ mContent.setGridSize((int) grid.inv.numHotseatIcons, 1);
}
mContent.setIsHotseat(true);
@@ -141,35 +109,34 @@ public class Hotseat extends FrameLayout {
void resetLayout() {
mContent.removeAllViewsInLayout();
- if (!LauncherAppState.isDisableAllApps()) {
- // Add the Apps button
- Context context = getContext();
+ // Add the Apps button
+ Context context = getContext();
- LayoutInflater inflater = LayoutInflater.from(context);
- TextView allAppsButton = (TextView)
- inflater.inflate(R.layout.all_apps_button, mContent, false);
- Drawable d = context.getResources().getDrawable(R.drawable.all_apps_button_icon);
+ LayoutInflater inflater = LayoutInflater.from(context);
+ TextView allAppsButton = (TextView)
+ inflater.inflate(R.layout.all_apps_button, mContent, false);
+ Drawable d = context.getResources().getDrawable(R.drawable.all_apps_button_icon);
- Utilities.resizeIconDrawable(d);
- allAppsButton.setCompoundDrawables(null, d, null, null);
+ mLauncher.resizeIconDrawable(d);
+ allAppsButton.setCompoundDrawables(null, d, null, null);
- allAppsButton.setContentDescription(context.getString(R.string.all_apps_button_label));
- allAppsButton.setOnKeyListener(new HotseatIconKeyEventListener());
- if (mLauncher != null) {
- allAppsButton.setOnTouchListener(mLauncher.getHapticFeedbackTouchListener());
- mLauncher.setAllAppsButton(allAppsButton);
- allAppsButton.setOnClickListener(mLauncher);
- allAppsButton.setOnFocusChangeListener(mLauncher.mFocusHandler);
- }
-
- // Note: We do this to ensure that the hotseat is always laid out in the orientation of
- // the hotseat in order regardless of which orientation they were added
- int x = getCellXFromOrder(mAllAppsButtonRank);
- int y = getCellYFromOrder(mAllAppsButtonRank);
- CellLayout.LayoutParams lp = new CellLayout.LayoutParams(x,y,1,1);
- lp.canReorder = false;
- mContent.addViewToCellLayout(allAppsButton, -1, allAppsButton.getId(), lp, true);
+ allAppsButton.setContentDescription(context.getString(R.string.all_apps_button_label));
+ allAppsButton.setOnKeyListener(new HotseatIconKeyEventListener());
+ if (mLauncher != null) {
+ mLauncher.setAllAppsButton(allAppsButton);
+ allAppsButton.setOnTouchListener(mLauncher.getHapticFeedbackTouchListener());
+ allAppsButton.setOnClickListener(mLauncher);
+ allAppsButton.setOnLongClickListener(mLauncher);
+ allAppsButton.setOnFocusChangeListener(mLauncher.mFocusHandler);
}
+
+ // Note: We do this to ensure that the hotseat is always laid out in the orientation of
+ // the hotseat in order regardless of which orientation they were added
+ int x = getCellXFromOrder(mAllAppsButtonRank);
+ int y = getCellYFromOrder(mAllAppsButtonRank);
+ CellLayout.LayoutParams lp = new CellLayout.LayoutParams(x,y,1,1);
+ lp.canReorder = false;
+ mContent.addViewToCellLayout(allAppsButton, -1, allAppsButton.getId(), lp, true);
}
@Override
@@ -182,54 +149,8 @@ public class Hotseat extends FrameLayout {
return false;
}
- void addAllAppsFolder(IconCache iconCache,
- ArrayList allApps, ArrayList onWorkspace,
- Launcher launcher, Workspace workspace) {
- if (LauncherAppState.isDisableAllApps()) {
- FolderInfo fi = new FolderInfo();
-
- fi.cellX = getCellXFromOrder(mAllAppsButtonRank);
- fi.cellY = getCellYFromOrder(mAllAppsButtonRank);
- fi.spanX = 1;
- fi.spanY = 1;
- fi.container = LauncherSettings.Favorites.CONTAINER_HOTSEAT;
- fi.screenId = mAllAppsButtonRank;
- fi.itemType = LauncherSettings.Favorites.ITEM_TYPE_FOLDER;
- fi.title = "More Apps";
- LauncherModel.addItemToDatabase(launcher, fi, fi.container, fi.screenId, fi.cellX,
- fi.cellY, false);
- FolderIcon folder = FolderIcon.fromXml(R.layout.folder_icon, launcher,
- getLayout(), fi, iconCache);
- workspace.addInScreen(folder, fi.container, fi.screenId, fi.cellX, fi.cellY,
- fi.spanX, fi.spanY);
-
- for (AppInfo info: allApps) {
- ComponentName cn = info.intent.getComponent();
- if (!onWorkspace.contains(cn)) {
- Log.d(TAG, "Adding to 'more apps': " + info.intent);
- ShortcutInfo si = info.makeShortcut();
- fi.add(si);
- }
- }
- }
- }
-
- void addAppsToAllAppsFolder(ArrayList apps) {
- if (LauncherAppState.isDisableAllApps()) {
- View v = mContent.getChildAt(getCellXFromOrder(mAllAppsButtonRank), getCellYFromOrder(mAllAppsButtonRank));
- FolderIcon fi = null;
-
- if (v instanceof FolderIcon) {
- fi = (FolderIcon) v;
- } else {
- return;
- }
-
- FolderInfo info = fi.getFolderInfo();
- for (AppInfo a: apps) {
- ShortcutInfo si = a.makeShortcut();
- info.add(si);
- }
- }
+ @Override
+ public void fillInLaunchSourceData(Bundle sourceData) {
+ sourceData.putString(Stats.SOURCE_EXTRA_CONTAINER, Stats.CONTAINER_HOTSEAT);
}
}
diff --git a/src/com/android/launcher3/IconCache.java b/src/com/android/launcher3/IconCache.java
index 5a0875b305..916418f18c 100644
--- a/src/com/android/launcher3/IconCache.java
+++ b/src/com/android/launcher3/IconCache.java
@@ -16,19 +16,28 @@
package com.android.launcher3;
-import android.app.ActivityManager;
import android.content.ComponentName;
+import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteOpenHelper;
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.Handler;
+import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
@@ -36,17 +45,17 @@ import com.android.launcher3.compat.LauncherActivityInfoCompat;
import com.android.launcher3.compat.LauncherAppsCompat;
import com.android.launcher3.compat.UserHandleCompat;
import com.android.launcher3.compat.UserManagerCompat;
+import com.android.launcher3.model.PackageItemInfo;
+import com.android.launcher3.util.ComponentKey;
+import com.android.launcher3.util.Thunk;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map.Entry;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import java.util.Stack;
/**
* Cache of application icons. Icons can be made from any thread.
@@ -56,66 +65,71 @@ public class IconCache {
private static final String TAG = "Launcher.IconCache";
private static final int INITIAL_ICON_CACHE_CAPACITY = 50;
- private static final String RESOURCE_FILE_PREFIX = "icon_";
// Empty class name is used for storing package default entry.
private static final String EMPTY_CLASS_NAME = ".";
private static final boolean DEBUG = false;
- private static class CacheEntry {
+ private static final int LOW_RES_SCALE_FACTOR = 5;
+
+ @Thunk static final Object ICON_UPDATE_TOKEN = new Object();
+
+ @Thunk static class CacheEntry {
public Bitmap icon;
- public CharSequence title;
- public CharSequence contentDescription;
+ public CharSequence title = "";
+ public CharSequence contentDescription = "";
+ public boolean isLowResIcon;
}
- private static class CacheKey {
- public ComponentName componentName;
- public UserHandleCompat user;
+ private final HashMap mDefaultIcons = new HashMap<>();
+ @Thunk final MainThreadExecutor mMainThreadExecutor = new MainThreadExecutor();
- CacheKey(ComponentName componentName, UserHandleCompat user) {
- this.componentName = componentName;
- this.user = user;
- }
-
- @Override
- public int hashCode() {
- return componentName.hashCode() + user.hashCode();
- }
-
- @Override
- public boolean equals(Object o) {
- CacheKey other = (CacheKey) o;
- return other.componentName.equals(componentName) && other.user.equals(user);
- }
- }
-
- private final HashMap mDefaultIcons =
- new HashMap();
private final Context mContext;
private final PackageManager mPackageManager;
- private final UserManagerCompat mUserManager;
+ @Thunk final UserManagerCompat mUserManager;
private final LauncherAppsCompat mLauncherApps;
- private final HashMap mCache =
- new HashMap(INITIAL_ICON_CACHE_CAPACITY);
- private int mIconDpi;
+ private final HashMap mCache =
+ new HashMap(INITIAL_ICON_CACHE_CAPACITY);
+ private final int mIconDpi;
+ @Thunk final IconDB mIconDb;
- public IconCache(Context context) {
- ActivityManager activityManager =
- (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
+ @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 String mSystemState;
+ private Bitmap mLowResBitmap;
+ private Canvas mLowResCanvas;
+ private Paint mLowResPaint;
+
+ public IconCache(Context context, InvariantDeviceProfile inv) {
mContext = context;
mPackageManager = context.getPackageManager();
mUserManager = UserManagerCompat.getInstance(mContext);
mLauncherApps = LauncherAppsCompat.getInstance(mContext);
- mIconDpi = activityManager.getLauncherLargeIconDensity();
+ mIconDpi = inv.fillResIconDpi;
+ mIconDb = new IconDB(context);
- // need to set mIconDpi before getting default icon
- UserHandleCompat myUser = UserHandleCompat.myUserHandle();
- mDefaultIcons.put(myUser, makeDefaultIcon(myUser));
+ mWorkerHandler = new Handler(LauncherModel.getWorkerLooper());
+
+ mActivityBgColor = context.getResources().getColor(R.color.quantum_panel_bg_color);
+ mPackageBgColor = context.getResources().getColor(R.color.quantum_panel_bg_color_dark);
+ 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.
+ mLowResOptions.inPreferredConfig = Bitmap.Config.RGB_565;
+ updateSystemStateString();
}
- public Drawable getFullResDefaultActivityIcon() {
+ private Drawable getFullResDefaultActivityIcon() {
return getFullResIcon(Resources.getSystem(), android.R.mipmap.sym_def_app_icon);
}
@@ -145,10 +159,6 @@ public class IconCache {
return getFullResDefaultActivityIcon();
}
- public int getFullResIconDpi() {
- return mIconDpi;
- }
-
public Drawable getFullResIcon(ActivityInfo info) {
Resources resources;
try {
@@ -184,59 +194,269 @@ public class IconCache {
* Remove any records for the supplied ComponentName.
*/
public synchronized void remove(ComponentName componentName, UserHandleCompat user) {
- mCache.remove(new CacheKey(componentName, user));
+ mCache.remove(new ComponentKey(componentName, user));
}
/**
- * Remove any records for the supplied package name.
+ * Remove any records for the supplied package name from memory.
*/
- public synchronized void remove(String packageName, UserHandleCompat user) {
- HashSet forDeletion = new HashSet();
- for (CacheKey key: mCache.keySet()) {
+ private void removeFromMemCacheLocked(String packageName, UserHandleCompat user) {
+ HashSet forDeletion = new HashSet();
+ for (ComponentKey key: mCache.keySet()) {
if (key.componentName.getPackageName().equals(packageName)
&& key.user.equals(user)) {
forDeletion.add(key);
}
}
- for (CacheKey condemned: forDeletion) {
+ for (ComponentKey condemned: forDeletion) {
mCache.remove(condemned);
}
}
/**
- * Empty out the cache.
+ * Updates the entries related to the given package in memory and persistent DB.
*/
- public synchronized void flush() {
- mCache.clear();
+ public synchronized void updateIconsForPkg(String packageName, UserHandleCompat user) {
+ removeIconsForPkg(packageName, user);
+ try {
+ PackageInfo info = mPackageManager.getPackageInfo(packageName,
+ PackageManager.GET_UNINSTALLED_PACKAGES);
+ long userSerial = mUserManager.getSerialNumberForUser(user);
+ for (LauncherActivityInfoCompat app : mLauncherApps.getActivityList(packageName, user)) {
+ addIconToDBAndMemCache(app, info, userSerial);
+ }
+ } catch (NameNotFoundException e) {
+ Log.d(TAG, "Package not found", e);
+ return;
+ }
}
/**
- * Empty out the cache that aren't of the correct grid size
+ * Removes the entries related to the given package in memory and persistent DB.
*/
- public synchronized void flushInvalidIcons(DeviceProfile grid) {
- Iterator> it = mCache.entrySet().iterator();
- while (it.hasNext()) {
- final CacheEntry e = it.next().getValue();
- if ((e.icon != null) && (e.icon.getWidth() < grid.iconSizePx
- || e.icon.getHeight() < grid.iconSizePx)) {
- it.remove();
+ public synchronized void removeIconsForPkg(String packageName, UserHandleCompat user) {
+ removeFromMemCacheLocked(packageName, user);
+ long userSerial = mUserManager.getSerialNumberForUser(user);
+ mIconDb.getWritableDatabase().delete(IconDB.TABLE_NAME,
+ IconDB.COLUMN_COMPONENT + " LIKE ? AND " + IconDB.COLUMN_USER + " = ?",
+ new String[] {packageName + "/%", Long.toString(userSerial)});
+ }
+
+ public void updateDbIcons(Set ignorePackagesForMainUser) {
+ // Remove all active icon update tasks.
+ mWorkerHandler.removeCallbacksAndMessages(ICON_UPDATE_TOKEN);
+
+ updateSystemStateString();
+ for (UserHandleCompat user : mUserManager.getUserProfiles()) {
+ // Query for the set of apps
+ final List apps = mLauncherApps.getActivityList(null, user);
+ // Fail if we don't have any apps
+ // TODO: Fix this. Only fail for the current user.
+ if (apps == null || apps.isEmpty()) {
+ return;
+ }
+
+ // Update icon cache. This happens in segments and {@link #onPackageIconsUpdated}
+ // is called by the icon cache when the job is complete.
+ updateDBIcons(user, apps, UserHandleCompat.myUserHandle().equals(user)
+ ? ignorePackagesForMainUser : Collections.emptySet());
+ }
+ }
+
+ /**
+ * Updates the persistent DB, such that only entries corresponding to {@param apps} remain in
+ * the DB and are updated.
+ * @return The set of packages for which icons have updated.
+ */
+ private void updateDBIcons(UserHandleCompat user, List apps,
+ Set ignorePackages) {
+ long userSerial = mUserManager.getSerialNumberForUser(user);
+ PackageManager pm = mContext.getPackageManager();
+ HashMap pkgInfoMap = new HashMap();
+ for (PackageInfo info : pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES)) {
+ pkgInfoMap.put(info.packageName, info);
+ }
+
+ HashMap componentMap = new HashMap<>();
+ for (LauncherActivityInfoCompat app : apps) {
+ componentMap.put(app.getComponentName(), app);
+ }
+
+ Cursor c = mIconDb.getReadableDatabase().query(IconDB.TABLE_NAME,
+ new String[] {IconDB.COLUMN_ROWID, IconDB.COLUMN_COMPONENT,
+ IconDB.COLUMN_LAST_UPDATED, IconDB.COLUMN_VERSION,
+ IconDB.COLUMN_SYSTEM_STATE},
+ IconDB.COLUMN_USER + " = ? ",
+ new String[] {Long.toString(userSerial)},
+ null, null, null);
+
+ final int indexComponent = c.getColumnIndex(IconDB.COLUMN_COMPONENT);
+ final int indexLastUpdate = c.getColumnIndex(IconDB.COLUMN_LAST_UPDATED);
+ final int indexVersion = c.getColumnIndex(IconDB.COLUMN_VERSION);
+ final int rowIndex = c.getColumnIndex(IconDB.COLUMN_ROWID);
+ final int systemStateIndex = c.getColumnIndex(IconDB.COLUMN_SYSTEM_STATE);
+
+ HashSet itemsToRemove = new HashSet();
+ Stack appsToUpdate = new Stack<>();
+
+ while (c.moveToNext()) {
+ String cn = c.getString(indexComponent);
+ ComponentName component = ComponentName.unflattenFromString(cn);
+ PackageInfo info = pkgInfoMap.get(component.getPackageName());
+ if (info == null) {
+ if (!ignorePackages.contains(component.getPackageName())) {
+ remove(component, user);
+ itemsToRemove.add(c.getInt(rowIndex));
+ }
+ continue;
+ }
+ if ((info.applicationInfo.flags & ApplicationInfo.FLAG_IS_DATA_ONLY) != 0) {
+ // Application is not present
+ continue;
+ }
+
+ long updateTime = c.getLong(indexLastUpdate);
+ int version = c.getInt(indexVersion);
+ LauncherActivityInfoCompat app = componentMap.remove(component);
+ if (version == info.versionCode && updateTime == info.lastUpdateTime &&
+ TextUtils.equals(mSystemState, c.getString(systemStateIndex))) {
+ continue;
+ }
+ if (app == null) {
+ remove(component, user);
+ itemsToRemove.add(c.getInt(rowIndex));
+ } else {
+ appsToUpdate.add(app);
}
}
+ c.close();
+ if (!itemsToRemove.isEmpty()) {
+ mIconDb.getWritableDatabase().delete(IconDB.TABLE_NAME,
+ Utilities.createDbSelectionQuery(IconDB.COLUMN_ROWID, itemsToRemove),
+ null);
+ }
+
+ // Insert remaining apps.
+ if (!componentMap.isEmpty() || !appsToUpdate.isEmpty()) {
+ Stack appsToAdd = new Stack<>();
+ appsToAdd.addAll(componentMap.values());
+ new SerializedIconUpdateTask(userSerial, pkgInfoMap,
+ appsToAdd, appsToUpdate).scheduleNext();
+ }
+ }
+
+ @Thunk void addIconToDBAndMemCache(LauncherActivityInfoCompat app, PackageInfo info,
+ long userSerial) {
+ // Reuse the existing entry if it already exists in the DB. This ensures that we do not
+ // create bitmap if it was already created during loader.
+ ContentValues values = updateCacheAndGetContentValues(app, false);
+ addIconToDB(values, app.getComponentName(), info, userSerial);
+ }
+
+ /**
+ * Updates {@param values} to contain versoning information and adds it to the DB.
+ * @param values {@link ContentValues} containing icon & title
+ */
+ private void addIconToDB(ContentValues values, ComponentName key,
+ PackageInfo info, long userSerial) {
+ values.put(IconDB.COLUMN_COMPONENT, key.flattenToString());
+ values.put(IconDB.COLUMN_USER, userSerial);
+ values.put(IconDB.COLUMN_LAST_UPDATED, info.lastUpdateTime);
+ values.put(IconDB.COLUMN_VERSION, info.versionCode);
+ mIconDb.getWritableDatabase().insertWithOnConflict(IconDB.TABLE_NAME, null, values,
+ SQLiteDatabase.CONFLICT_REPLACE);
+ }
+
+ @Thunk ContentValues updateCacheAndGetContentValues(LauncherActivityInfoCompat app,
+ boolean replaceExisting) {
+ final ComponentKey key = new ComponentKey(app.getComponentName(), app.getUser());
+ CacheEntry entry = null;
+ if (!replaceExisting) {
+ entry = mCache.get(key);
+ // We can't reuse the entry if the high-res icon is not present.
+ if (entry == null || entry.isLowResIcon || entry.icon == null) {
+ entry = null;
+ }
+ }
+ if (entry == null) {
+ entry = new CacheEntry();
+ entry.icon = Utilities.createIconBitmap(app.getBadgedIcon(mIconDpi), mContext);
+ }
+ entry.title = app.getLabel();
+ entry.contentDescription = mUserManager.getBadgedLabelForUser(entry.title, app.getUser());
+ mCache.put(new ComponentKey(app.getComponentName(), app.getUser()), entry);
+
+ return newContentValues(entry.icon, entry.title.toString(), mActivityBgColor);
+ }
+
+ /**
+ * Fetches high-res icon for the provided ItemInfo and updates the caller when done.
+ * @return a request ID that can be used to cancel the request.
+ */
+ public IconLoadRequest updateIconInBackground(final BubbleTextView caller, final ItemInfo info) {
+ Runnable request = new Runnable() {
+
+ @Override
+ public void run() {
+ if (info instanceof AppInfo) {
+ getTitleAndIcon((AppInfo) info, null, false);
+ } else if (info instanceof ShortcutInfo) {
+ ShortcutInfo st = (ShortcutInfo) info;
+ getTitleAndIcon(st,
+ st.promisedIntent != null ? st.promisedIntent : st.intent,
+ st.user, false);
+ } else if (info instanceof PackageItemInfo) {
+ PackageItemInfo pti = (PackageItemInfo) info;
+ getTitleAndIconForApp(pti.packageName, pti.user, false, pti);
+ }
+ mMainThreadExecutor.execute(new Runnable() {
+
+ @Override
+ public void run() {
+ caller.reapplyItemInfo(info);
+ }
+ });
+ }
+ };
+ mWorkerHandler.post(request);
+ return new IconLoadRequest(request, mWorkerHandler);
+ }
+
+ private Bitmap getNonNullIcon(CacheEntry entry, UserHandleCompat user) {
+ return entry.icon == null ? getDefaultIcon(user) : entry.icon;
}
/**
* Fill in "application" with the icon and label for "info."
*/
- public synchronized void getTitleAndIcon(AppInfo application, LauncherActivityInfoCompat info,
- HashMap