blob: 27f1ac611f49829697c64f08df2c0f8e65169856 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Joe Onorato4be866d2010-10-10 11:26:02 -070019import android.animation.Animator;
Michael Jurka629758f2012-06-14 16:18:21 -070020import android.animation.AnimatorListenerAdapter;
Brandon Keely50e6e562012-05-08 16:28:49 -070021import android.animation.AnimatorSet;
Chet Haase00397b12010-10-07 11:13:10 -070022import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070023import android.animation.ValueAnimator;
24import android.animation.ValueAnimator.AnimatorUpdateListener;
Adam Cohenc9735cf2015-01-23 16:11:55 -080025import android.annotation.TargetApi;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040027import android.content.res.Resources;
Winson Chungaafa03c2010-06-11 17:34:16 -070028import android.content.res.TypedArray;
Joe Onorato4be866d2010-10-10 11:26:02 -070029import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070030import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080031import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070032import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070033import android.graphics.Point;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080035import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070036import android.graphics.drawable.Drawable;
Adam Cohenc9735cf2015-01-23 16:11:55 -080037import android.os.Build;
Adam Cohen1462de32012-07-24 22:34:36 -070038import android.os.Parcelable;
Adam Cohenc9735cf2015-01-23 16:11:55 -080039import android.support.v4.view.ViewCompat;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070041import android.util.Log;
Adam Cohen1462de32012-07-24 22:34:36 -070042import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.view.MotionEvent;
44import android.view.View;
45import android.view.ViewDebug;
46import android.view.ViewGroup;
Adam Cohenc9735cf2015-01-23 16:11:55 -080047import android.view.accessibility.AccessibilityEvent;
Winson Chung150fbab2010-09-29 17:14:26 -070048import android.view.animation.DecelerateInterpolator;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049
Sunny Goyal4b6eb262015-05-14 19:24:40 -070050import com.android.launcher3.BubbleTextView.BubbleTextShadowHandler;
Daniel Sandler325dc232013-06-05 22:57:57 -040051import com.android.launcher3.FolderIcon.FolderRingAnimator;
Sunny Goyale9b651e2015-04-24 11:44:51 -070052import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
53import com.android.launcher3.accessibility.FolderAccessibilityHelper;
54import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
Adam Cohen091440a2015-03-18 14:16:05 -070055import com.android.launcher3.util.Thunk;
Hyunyoung Song3f471442015-04-08 19:01:34 -070056import com.android.launcher3.widget.PendingAddWidgetInfo;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070057
Adam Cohen69ce2e52011-07-03 19:25:21 -070058import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070059import java.util.Arrays;
Adam Cohenf3900c22012-11-16 18:28:11 -080060import java.util.Collections;
61import java.util.Comparator;
Adam Cohenbfbfd262011-06-13 16:55:12 -070062import java.util.HashMap;
Adam Cohend41fbf52012-02-16 23:53:59 -080063import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070064
Sunny Goyal4b6eb262015-05-14 19:24:40 -070065public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
Sunny Goyale9b651e2015-04-24 11:44:51 -070066 public static final int WORKSPACE_ACCESSIBILITY_DRAG = 2;
67 public static final int FOLDER_ACCESSIBILITY_DRAG = 1;
68
Winson Chungaafa03c2010-06-11 17:34:16 -070069 static final String TAG = "CellLayout";
70
Adam Cohen2acce882012-03-28 19:03:19 -070071 private Launcher mLauncher;
Adam Cohen091440a2015-03-18 14:16:05 -070072 @Thunk int mCellWidth;
73 @Thunk int mCellHeight;
Winson Chung11a1a532013-09-13 11:14:45 -070074 private int mFixedCellWidth;
75 private int mFixedCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070076
Adam Cohen091440a2015-03-18 14:16:05 -070077 @Thunk int mCountX;
78 @Thunk int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Adam Cohen234c4cd2011-07-17 21:03:04 -070080 private int mOriginalWidthGap;
81 private int mOriginalHeightGap;
Adam Cohen091440a2015-03-18 14:16:05 -070082 @Thunk int mWidthGap;
83 @Thunk int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070084 private int mMaxGap;
Adam Cohen917e3882013-10-31 15:03:35 -070085 private boolean mDropPending = false;
Adam Cohenc50438c2014-08-19 17:43:05 -070086 private boolean mIsDragTarget = true;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Patrick Dubroyde7658b2010-09-27 11:15:43 -070088 // These are temporary variables to prevent having to allocate a new object just to
89 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Winson Chung0be025d2011-05-23 17:45:09 -070090 private final int[] mTmpXY = new int[2];
Adam Cohen091440a2015-03-18 14:16:05 -070091 @Thunk final int[] mTmpPoint = new int[2];
Adam Cohen69ce2e52011-07-03 19:25:21 -070092 int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070093
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -080095 boolean[][] mTmpOccupied;
Michael Jurkad771c962011-08-09 15:00:48 -070096 private boolean mLastDownOnOccupiedCell = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097
Michael Jurkadee05892010-07-27 10:01:56 -070098 private OnTouchListener mInterceptTouchListener;
99
Adam Cohen69ce2e52011-07-03 19:25:21 -0700100 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -0700101 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -0700102
Adam Cohen02dcfcc2013-10-01 12:37:33 -0700103 private float FOREGROUND_ALPHA_DAMPER = 0.65f;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700104 private int mForegroundAlpha = 0;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700105 private float mBackgroundAlpha;
Adam Cohenf34bab52010-09-30 14:11:56 -0700106
Michael Jurka33945b22010-12-21 18:19:38 -0800107 private Drawable mNormalBackground;
Michael Jurka33945b22010-12-21 18:19:38 -0800108 private Drawable mActiveGlowBackground;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700109 private Drawable mOverScrollForegroundDrawable;
110 private Drawable mOverScrollLeft;
111 private Drawable mOverScrollRight;
Michael Jurka18014792010-10-14 09:01:34 -0700112 private Rect mBackgroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700113 private Rect mForegroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700114 private int mForegroundPadding;
Patrick Dubroy1262e362010-10-06 15:49:50 -0700115
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700116 // These values allow a fixed measurement to be set on the CellLayout.
117 private int mFixedWidth = -1;
118 private int mFixedHeight = -1;
119
Michael Jurka33945b22010-12-21 18:19:38 -0800120 // If we're actively dragging something over this screen, mIsDragOverlapping is true
121 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700122
Winson Chung150fbab2010-09-29 17:14:26 -0700123 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700124 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohen091440a2015-03-18 14:16:05 -0700125 @Thunk Rect[] mDragOutlines = new Rect[4];
126 @Thunk float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700127 private InterruptibleInOutAnimator[] mDragOutlineAnims =
128 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700129
130 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700131 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700132 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700133
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700134 private final ClickShadowView mTouchFeedbackView;
Patrick Dubroy96864c32011-03-10 17:17:23 -0800135
Adam Cohen091440a2015-03-18 14:16:05 -0700136 @Thunk HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new
Adam Cohen482ed822012-03-02 14:15:13 -0800137 HashMap<CellLayout.LayoutParams, Animator>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800138 private HashMap<View, ReorderPreviewAnimation>
139 mShakeAnimators = new HashMap<View, ReorderPreviewAnimation>();
Adam Cohen19f37922012-03-21 11:59:11 -0700140
141 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700142
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700143 // When a drag operation is in progress, holds the nearest cell to the touch point
144 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800145
Joe Onorato4be866d2010-10-10 11:26:02 -0700146 private boolean mDragging = false;
147
Patrick Dubroyce34a972010-10-19 10:34:32 -0700148 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700149 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700150
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800151 private boolean mIsHotseat = false;
Adam Cohen307fe232012-08-16 17:55:58 -0700152 private float mHotseatScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800153
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800154 public static final int MODE_SHOW_REORDER_HINT = 0;
155 public static final int MODE_DRAG_OVER = 1;
156 public static final int MODE_ON_DROP = 2;
157 public static final int MODE_ON_DROP_EXTERNAL = 3;
158 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700159 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800160 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
161
Adam Cohena897f392012-04-27 18:12:05 -0700162 static final int LANDSCAPE = 0;
163 static final int PORTRAIT = 1;
164
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800165 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700166 private static final int REORDER_ANIMATION_DURATION = 150;
Adam Cohen091440a2015-03-18 14:16:05 -0700167 @Thunk float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700168
Adam Cohen482ed822012-03-02 14:15:13 -0800169 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
170 private Rect mOccupiedRect = new Rect();
171 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700172 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700173 private static final int INVALID_DIRECTION = -100;
Adam Cohenc6cc61d2012-04-04 12:47:08 -0700174 private DropTarget.DragEnforcer mDragEnforcer;
Adam Cohen482ed822012-03-02 14:15:13 -0800175
Winson Chung3a6e7f32013-10-09 15:50:52 -0700176 private Rect mTempRect = new Rect();
177
Michael Jurkaca993832012-06-29 15:17:04 -0700178 private final static Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700179
Adam Cohenc9735cf2015-01-23 16:11:55 -0800180 // Related to accessible drag and drop
Sunny Goyale9b651e2015-04-24 11:44:51 -0700181 private DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800182 private boolean mUseTouchHelper = false;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800183
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184 public CellLayout(Context context) {
185 this(context, null);
186 }
187
188 public CellLayout(Context context, AttributeSet attrs) {
189 this(context, attrs, 0);
190 }
191
192 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
193 super(context, attrs, defStyle);
Michael Jurka8b805b12012-04-18 14:23:14 -0700194 mDragEnforcer = new DropTarget.DragEnforcer(context);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700195
196 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
197 // the user where a dragged item will land when dropped.
198 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800199 setClipToPadding(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700200 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700201
Adam Cohen2e6da152015-05-06 11:42:25 -0700202 DeviceProfile grid = mLauncher.getDeviceProfile();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800203 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
204
Winson Chung11a1a532013-09-13 11:14:45 -0700205 mCellWidth = mCellHeight = -1;
Nilesh Agrawal5f7099a2014-01-02 15:54:57 -0800206 mFixedCellWidth = mFixedCellHeight = -1;
Winson Chung5f8afe62013-08-12 16:19:28 -0700207 mWidthGap = mOriginalWidthGap = 0;
208 mHeightGap = mOriginalHeightGap = 0;
209 mMaxGap = Integer.MAX_VALUE;
Adam Cohen2e6da152015-05-06 11:42:25 -0700210 mCountX = (int) grid.inv.numColumns;
211 mCountY = (int) grid.inv.numRows;
Michael Jurka0280c3b2010-09-17 15:00:07 -0700212 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800213 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700214 mPreviousReorderDirection[0] = INVALID_DIRECTION;
215 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216
217 a.recycle();
218
219 setAlwaysDrawnWithCacheEnabled(false);
220
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700221 final Resources res = getResources();
Winson Chung6e1c0d32013-10-25 15:24:24 -0700222 mHotseatScale = (float) grid.hotseatIconSizePx / grid.iconSizePx;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700223
Adam Cohen410f3cd2013-09-22 12:09:32 -0700224 mNormalBackground = res.getDrawable(R.drawable.screenpanel);
225 mActiveGlowBackground = res.getDrawable(R.drawable.screenpanel_hover);
Michael Jurka33945b22010-12-21 18:19:38 -0800226
Adam Cohenb5ba0972011-09-07 18:02:31 -0700227 mOverScrollLeft = res.getDrawable(R.drawable.overscroll_glow_left);
228 mOverScrollRight = res.getDrawable(R.drawable.overscroll_glow_right);
229 mForegroundPadding =
230 res.getDimensionPixelSize(R.dimen.workspace_overscroll_drawable_padding);
Michael Jurka33945b22010-12-21 18:19:38 -0800231
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800232 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE *
Winson Chung5f8afe62013-08-12 16:19:28 -0700233 grid.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700234
Winson Chungb26f3d62011-06-02 10:49:29 -0700235 mNormalBackground.setFilterBitmap(true);
Winson Chungb26f3d62011-06-02 10:49:29 -0700236 mActiveGlowBackground.setFilterBitmap(true);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700237
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700238 // Initialize the data structures used for the drag visualization.
Patrick Dubroyce34a972010-10-19 10:34:32 -0700239 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700240 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700241 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800242 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700243 }
244
245 // When dragging things around the home screens, we show a green outline of
246 // where the item will land. The outlines gradually fade out, leaving a trail
247 // behind the drag path.
248 // Set up all the animations that are used to implement this fading.
249 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700250 final float fromAlphaValue = 0;
251 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700252
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700253 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700254
255 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700256 final InterruptibleInOutAnimator anim =
Michael Jurkaf1ad6082013-03-13 12:55:46 +0100257 new InterruptibleInOutAnimator(this, duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700258 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700259 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700260 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700261 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700262 final Bitmap outline = (Bitmap)anim.getTag();
263
264 // If an animation is started and then stopped very quickly, we can still
265 // get spurious updates we've cleared the tag. Guard against this.
266 if (outline == null) {
Michael Jurka3a9fced2012-04-13 14:44:29 -0700267 @SuppressWarnings("all") // suppress dead code warning
268 final boolean debug = false;
269 if (debug) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700270 Object val = animation.getAnimatedValue();
271 Log.d(TAG, "anim " + thisIndex + " update: " + val +
272 ", isStopped " + anim.isStopped());
273 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700274 // Try to prevent it from continuing to run
275 animation.cancel();
276 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700277 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800278 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700279 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700280 }
281 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700282 // The animation holds a reference to the drag outline bitmap as long is it's
283 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700284 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700285 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700286 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700287 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700288 anim.setTag(null);
289 }
290 }
291 });
292 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700293 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700294
Michael Jurka18014792010-10-14 09:01:34 -0700295 mBackgroundRect = new Rect();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700296 mForegroundRect = new Rect();
Michael Jurkabea15192010-11-17 12:33:46 -0800297
Michael Jurkaa52570f2012-03-20 03:18:20 -0700298 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
Adam Cohen2374abf2013-04-16 14:56:57 -0700299 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700300 mCountX, mCountY);
Adam Cohen2374abf2013-04-16 14:56:57 -0700301
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700302 mTouchFeedbackView = new ClickShadowView(context);
303 addView(mTouchFeedbackView);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700304 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700305 }
306
Adam Cohenc9735cf2015-01-23 16:11:55 -0800307 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
Sunny Goyale9b651e2015-04-24 11:44:51 -0700308 public void enableAccessibleDrag(boolean enable, int dragType) {
Adam Cohenc9735cf2015-01-23 16:11:55 -0800309 mUseTouchHelper = enable;
310 if (!enable) {
311 ViewCompat.setAccessibilityDelegate(this, null);
312 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
313 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
314 setOnClickListener(mLauncher);
315 } else {
Sunny Goyale9b651e2015-04-24 11:44:51 -0700316 if (dragType == WORKSPACE_ACCESSIBILITY_DRAG &&
317 !(mTouchHelper instanceof WorkspaceAccessibilityHelper)) {
318 mTouchHelper = new WorkspaceAccessibilityHelper(this);
319 } else if (dragType == FOLDER_ACCESSIBILITY_DRAG &&
320 !(mTouchHelper instanceof FolderAccessibilityHelper)) {
321 mTouchHelper = new FolderAccessibilityHelper(this);
322 }
Adam Cohenc9735cf2015-01-23 16:11:55 -0800323 ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
324 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
325 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
326 setOnClickListener(mTouchHelper);
327 }
328
329 // Invalidate the accessibility hierarchy
330 if (getParent() != null) {
331 getParent().notifySubtreeAccessibilityStateChanged(
332 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
333 }
334 }
335
336 @Override
337 public boolean dispatchHoverEvent(MotionEvent event) {
338 // Always attempt to dispatch hover events to accessibility first.
339 if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
340 return true;
341 }
342 return super.dispatchHoverEvent(event);
343 }
344
345 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800346 public boolean onInterceptTouchEvent(MotionEvent ev) {
347 if (mUseTouchHelper ||
348 (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
349 return true;
350 }
351 return false;
352 }
353
Chris Craik01f2d7f2013-10-01 14:41:56 -0700354 public void enableHardwareLayer(boolean hasLayer) {
355 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700356 }
357
358 public void buildHardwareLayer() {
359 mShortcutsAndWidgets.buildLayer();
Adam Cohen2801caf2011-05-13 20:57:39 -0700360 }
361
Adam Cohen307fe232012-08-16 17:55:58 -0700362 public float getChildrenScale() {
363 return mIsHotseat ? mHotseatScale : 1.0f;
364 }
365
Winson Chung5f8afe62013-08-12 16:19:28 -0700366 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700367 mFixedCellWidth = mCellWidth = width;
368 mFixedCellHeight = mCellHeight = height;
Winson Chung5f8afe62013-08-12 16:19:28 -0700369 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
370 mCountX, mCountY);
371 }
372
Adam Cohen2801caf2011-05-13 20:57:39 -0700373 public void setGridSize(int x, int y) {
374 mCountX = x;
375 mCountY = y;
376 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800377 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700378 mTempRectStack.clear();
Adam Cohen2374abf2013-04-16 14:56:57 -0700379 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700380 mCountX, mCountY);
Adam Cohen76fc0852011-06-17 13:26:23 -0700381 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700382 }
383
Adam Cohen2374abf2013-04-16 14:56:57 -0700384 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
385 public void setInvertIfRtl(boolean invert) {
386 mShortcutsAndWidgets.setInvertIfRtl(invert);
387 }
388
Adam Cohen917e3882013-10-31 15:03:35 -0700389 public void setDropPending(boolean pending) {
390 mDropPending = pending;
391 }
392
393 public boolean isDropPending() {
394 return mDropPending;
395 }
396
Adam Cohenb5ba0972011-09-07 18:02:31 -0700397 void setOverScrollAmount(float r, boolean left) {
398 if (left && mOverScrollForegroundDrawable != mOverScrollLeft) {
399 mOverScrollForegroundDrawable = mOverScrollLeft;
400 } else if (!left && mOverScrollForegroundDrawable != mOverScrollRight) {
401 mOverScrollForegroundDrawable = mOverScrollRight;
402 }
403
Adam Cohen02dcfcc2013-10-01 12:37:33 -0700404 r *= FOREGROUND_ALPHA_DAMPER;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700405 mForegroundAlpha = (int) Math.round((r * 255));
406 mOverScrollForegroundDrawable.setAlpha(mForegroundAlpha);
407 invalidate();
408 }
409
Sunny Goyal4b6eb262015-05-14 19:24:40 -0700410 @Override
411 public void setPressedIcon(BubbleTextView icon, Bitmap background) {
Sunny Goyal508da152014-08-14 10:53:27 -0700412 if (icon == null || background == null) {
413 mTouchFeedbackView.setBitmap(null);
414 mTouchFeedbackView.animate().cancel();
415 } else {
Sunny Goyal508da152014-08-14 10:53:27 -0700416 if (mTouchFeedbackView.setBitmap(background)) {
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700417 mTouchFeedbackView.alignWithIconView(icon, mShortcutsAndWidgets);
418 mTouchFeedbackView.animateShadow();
Sunny Goyal508da152014-08-14 10:53:27 -0700419 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800420 }
421 }
422
Adam Cohenc50438c2014-08-19 17:43:05 -0700423 void disableDragTarget() {
424 mIsDragTarget = false;
425 }
426
427 boolean isDragTarget() {
428 return mIsDragTarget;
429 }
430
431 void setIsDragOverlapping(boolean isDragOverlapping) {
432 if (mIsDragOverlapping != isDragOverlapping) {
433 mIsDragOverlapping = isDragOverlapping;
Adam Cohenc50438c2014-08-19 17:43:05 -0700434 invalidate();
435 }
436 }
437
Michael Jurka33945b22010-12-21 18:19:38 -0800438 boolean getIsDragOverlapping() {
439 return mIsDragOverlapping;
440 }
441
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700442 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700443 protected void onDraw(Canvas canvas) {
Sunny Goyal05739772015-05-19 19:59:09 -0700444 if (!mIsDragTarget) {
445 return;
446 }
447
Michael Jurka3e7c7632010-10-02 16:01:03 -0700448 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
449 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
450 // When we're small, we are either drawn normally or in the "accepts drops" state (during
451 // a drag). However, we also drag the mini hover background *over* one of those two
452 // backgrounds
Sunny Goyal05739772015-05-19 19:59:09 -0700453 if (mBackgroundAlpha > 0.0f) {
Adam Cohenf34bab52010-09-30 14:11:56 -0700454 Drawable bg;
Michael Jurka33945b22010-12-21 18:19:38 -0800455
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700456 if (mIsDragOverlapping) {
Michael Jurka33945b22010-12-21 18:19:38 -0800457 // In the mini case, we draw the active_glow bg *over* the active background
Michael Jurkabdf78552011-10-31 14:34:25 -0700458 bg = mActiveGlowBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700459 } else {
Michael Jurkabdf78552011-10-31 14:34:25 -0700460 bg = mNormalBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700461 }
Michael Jurka33945b22010-12-21 18:19:38 -0800462
Sunny Goyal05739772015-05-19 19:59:09 -0700463 bg.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurka33945b22010-12-21 18:19:38 -0800464 bg.setBounds(mBackgroundRect);
465 bg.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700466 }
Romain Guya6abce82009-11-10 02:54:41 -0800467
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700468 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700469 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700470 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700471 if (alpha > 0) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800472 final Rect r = mDragOutlines[i];
Winson Chung3a6e7f32013-10-09 15:50:52 -0700473 mTempRect.set(r);
474 Utilities.scaleRectAboutCenter(mTempRect, getChildrenScale());
Joe Onorato4be866d2010-10-10 11:26:02 -0700475 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700476 paint.setAlpha((int)(alpha + .5f));
Winson Chung3a6e7f32013-10-09 15:50:52 -0700477 canvas.drawBitmap(b, null, mTempRect, paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700478 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700479 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800480
Adam Cohen482ed822012-03-02 14:15:13 -0800481 if (DEBUG_VISUALIZE_OCCUPIED) {
482 int[] pt = new int[2];
483 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700484 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800485 for (int i = 0; i < mCountX; i++) {
486 for (int j = 0; j < mCountY; j++) {
487 if (mOccupied[i][j]) {
488 cellToPoint(i, j, pt);
489 canvas.save();
490 canvas.translate(pt[0], pt[1]);
491 cd.draw(canvas);
492 canvas.restore();
493 }
494 }
495 }
496 }
497
Andrew Flynn850d2e72012-04-26 16:51:20 -0700498 int previewOffset = FolderRingAnimator.sPreviewSize;
499
Adam Cohen69ce2e52011-07-03 19:25:21 -0700500 // The folder outer / inner ring image(s)
Adam Cohen2e6da152015-05-06 11:42:25 -0700501 DeviceProfile grid = mLauncher.getDeviceProfile();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700502 for (int i = 0; i < mFolderOuterRings.size(); i++) {
503 FolderRingAnimator fra = mFolderOuterRings.get(i);
504
Adam Cohen5108bc02013-09-20 17:04:51 -0700505 Drawable d;
506 int width, height;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700507 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
Winson Chung5f8afe62013-08-12 16:19:28 -0700508 View child = getChildAt(fra.mCellX, fra.mCellY);
Adam Cohen558f1c22013-10-09 15:15:24 -0700509
Winson Chung89f97052013-09-20 11:32:26 -0700510 if (child != null) {
Adam Cohen558f1c22013-10-09 15:15:24 -0700511 int centerX = mTempLocation[0] + mCellWidth / 2;
512 int centerY = mTempLocation[1] + previewOffset / 2 +
513 child.getPaddingTop() + grid.folderBackgroundOffset;
514
Adam Cohen5108bc02013-09-20 17:04:51 -0700515 // Draw outer ring, if it exists
516 if (FolderIcon.HAS_OUTER_RING) {
517 d = FolderRingAnimator.sSharedOuterRingDrawable;
518 width = (int) (fra.getOuterRingSize() * getChildrenScale());
519 height = width;
520 canvas.save();
521 canvas.translate(centerX - width / 2, centerY - height / 2);
522 d.setBounds(0, 0, width, height);
523 d.draw(canvas);
524 canvas.restore();
525 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700526
Winson Chung89f97052013-09-20 11:32:26 -0700527 // Draw inner ring
528 d = FolderRingAnimator.sSharedInnerRingDrawable;
529 width = (int) (fra.getInnerRingSize() * getChildrenScale());
530 height = width;
Winson Chung89f97052013-09-20 11:32:26 -0700531 canvas.save();
532 canvas.translate(centerX - width / 2, centerY - width / 2);
533 d.setBounds(0, 0, width, height);
534 d.draw(canvas);
535 canvas.restore();
536 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700537 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700538
539 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
540 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
541 int width = d.getIntrinsicWidth();
542 int height = d.getIntrinsicHeight();
543
544 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
Winson Chung5f8afe62013-08-12 16:19:28 -0700545 View child = getChildAt(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1]);
Winson Chung89f97052013-09-20 11:32:26 -0700546 if (child != null) {
547 int centerX = mTempLocation[0] + mCellWidth / 2;
548 int centerY = mTempLocation[1] + previewOffset / 2 +
549 child.getPaddingTop() + grid.folderBackgroundOffset;
Adam Cohenc51934b2011-07-26 21:07:43 -0700550
Winson Chung89f97052013-09-20 11:32:26 -0700551 canvas.save();
552 canvas.translate(centerX - width / 2, centerY - width / 2);
553 d.setBounds(0, 0, width, height);
554 d.draw(canvas);
555 canvas.restore();
556 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700557 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700558 }
559
Adam Cohenb5ba0972011-09-07 18:02:31 -0700560 @Override
561 protected void dispatchDraw(Canvas canvas) {
562 super.dispatchDraw(canvas);
563 if (mForegroundAlpha > 0) {
564 mOverScrollForegroundDrawable.setBounds(mForegroundRect);
Adam Cohenb5ba0972011-09-07 18:02:31 -0700565 mOverScrollForegroundDrawable.draw(canvas);
Adam Cohenb5ba0972011-09-07 18:02:31 -0700566 }
567 }
568
Adam Cohen69ce2e52011-07-03 19:25:21 -0700569 public void showFolderAccept(FolderRingAnimator fra) {
570 mFolderOuterRings.add(fra);
571 }
572
573 public void hideFolderAccept(FolderRingAnimator fra) {
574 if (mFolderOuterRings.contains(fra)) {
575 mFolderOuterRings.remove(fra);
576 }
577 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700578 }
579
Adam Cohenc51934b2011-07-26 21:07:43 -0700580 public void setFolderLeaveBehindCell(int x, int y) {
581 mFolderLeaveBehindCell[0] = x;
582 mFolderLeaveBehindCell[1] = y;
583 invalidate();
584 }
585
586 public void clearFolderLeaveBehind() {
587 mFolderLeaveBehindCell[0] = -1;
588 mFolderLeaveBehindCell[1] = -1;
589 invalidate();
590 }
591
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700592 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700593 public boolean shouldDelayChildPressedState() {
594 return false;
595 }
596
Adam Cohen1462de32012-07-24 22:34:36 -0700597 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700598 try {
599 dispatchRestoreInstanceState(states);
600 } catch (IllegalArgumentException ex) {
601 if (LauncherAppState.isDogfoodBuild()) {
602 throw ex;
603 }
604 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
605 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
606 }
Adam Cohen1462de32012-07-24 22:34:36 -0700607 }
608
Michael Jurkae6235dd2011-10-04 15:02:05 -0700609 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700610 public void cancelLongPress() {
611 super.cancelLongPress();
612
613 // Cancel long press for all children
614 final int count = getChildCount();
615 for (int i = 0; i < count; i++) {
616 final View child = getChildAt(i);
617 child.cancelLongPress();
618 }
619 }
620
Michael Jurkadee05892010-07-27 10:01:56 -0700621 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
622 mInterceptTouchListener = listener;
623 }
624
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800625 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700626 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627 }
628
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800629 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700630 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800631 }
632
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800633 public void setIsHotseat(boolean isHotseat) {
634 mIsHotseat = isHotseat;
Winson Chung5f8afe62013-08-12 16:19:28 -0700635 mShortcutsAndWidgets.setIsHotseat(isHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800636 }
637
Sunny Goyale9b651e2015-04-24 11:44:51 -0700638 public boolean isHotseat() {
639 return mIsHotseat;
640 }
641
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800642 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700643 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700644 final LayoutParams lp = params;
645
Andrew Flynnde38e422012-05-08 11:22:15 -0700646 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800647 if (child instanceof BubbleTextView) {
648 BubbleTextView bubbleChild = (BubbleTextView) child;
Winson Chung5f8afe62013-08-12 16:19:28 -0700649 bubbleChild.setTextVisibility(!mIsHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800650 }
651
Adam Cohen307fe232012-08-16 17:55:58 -0700652 child.setScaleX(getChildrenScale());
653 child.setScaleY(getChildrenScale());
654
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800655 // Generate an id for each view, this assumes we have at most 256x256 cells
656 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700657 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700658 // If the horizontal or vertical span is set to -1, it is taken to
659 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700660 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
661 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800662
Winson Chungaafa03c2010-06-11 17:34:16 -0700663 child.setId(childId);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700664 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700665
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700666 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700667
Winson Chungaafa03c2010-06-11 17:34:16 -0700668 return true;
669 }
670 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800671 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700672
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800673 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700674 public void removeAllViews() {
675 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700676 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700677 }
678
679 @Override
680 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700681 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700682 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700683 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700684 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700685 }
686
687 @Override
688 public void removeView(View view) {
689 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700690 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700691 }
692
693 @Override
694 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700695 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
696 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700697 }
698
699 @Override
700 public void removeViewInLayout(View view) {
701 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700702 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700703 }
704
705 @Override
706 public void removeViews(int start, int count) {
707 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700708 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700709 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700710 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700711 }
712
713 @Override
714 public void removeViewsInLayout(int start, int count) {
715 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700716 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700717 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700718 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800719 }
720
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700721 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700722 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800723 * @param x X coordinate of the point
724 * @param y Y coordinate of the point
725 * @param result Array of 2 ints to hold the x and y coordinate of the cell
726 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700727 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700728 final int hStartPadding = getPaddingLeft();
729 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800730
731 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
732 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
733
Adam Cohend22015c2010-07-26 22:02:18 -0700734 final int xAxis = mCountX;
735 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800736
737 if (result[0] < 0) result[0] = 0;
738 if (result[0] >= xAxis) result[0] = xAxis - 1;
739 if (result[1] < 0) result[1] = 0;
740 if (result[1] >= yAxis) result[1] = yAxis - 1;
741 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700742
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800743 /**
744 * Given a point, return the cell that most closely encloses that point
745 * @param x X coordinate of the point
746 * @param y Y coordinate of the point
747 * @param result Array of 2 ints to hold the x and y coordinate of the cell
748 */
749 void pointToCellRounded(int x, int y, int[] result) {
750 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
751 }
752
753 /**
754 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700755 *
756 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800757 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700758 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800759 * @param result Array of 2 ints to hold the x and y coordinate of the point
760 */
761 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700762 final int hStartPadding = getPaddingLeft();
763 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800764
765 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
766 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
767 }
768
Adam Cohene3e27a82011-04-15 12:07:39 -0700769 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800770 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700771 *
772 * @param cellX X coordinate of the cell
773 * @param cellY Y coordinate of the cell
774 *
775 * @param result Array of 2 ints to hold the x and y coordinate of the point
776 */
777 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700778 regionToCenterPoint(cellX, cellY, 1, 1, result);
779 }
780
781 /**
782 * Given a cell coordinate and span return the point that represents the center of the regio
783 *
784 * @param cellX X coordinate of the cell
785 * @param cellY Y coordinate of the cell
786 *
787 * @param result Array of 2 ints to hold the x and y coordinate of the point
788 */
789 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700790 final int hStartPadding = getPaddingLeft();
791 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700792 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
793 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
794 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
795 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700796 }
797
Adam Cohen19f37922012-03-21 11:59:11 -0700798 /**
799 * Given a cell coordinate and span fills out a corresponding pixel rect
800 *
801 * @param cellX X coordinate of the cell
802 * @param cellY Y coordinate of the cell
803 * @param result Rect in which to write the result
804 */
805 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
806 final int hStartPadding = getPaddingLeft();
807 final int vStartPadding = getPaddingTop();
808 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
809 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
810 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
811 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
812 }
813
Adam Cohen482ed822012-03-02 14:15:13 -0800814 public float getDistanceFromCell(float x, float y, int[] cell) {
815 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700816 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800817 }
818
Romain Guy84f296c2009-11-04 15:00:44 -0800819 int getCellWidth() {
820 return mCellWidth;
821 }
822
823 int getCellHeight() {
824 return mCellHeight;
825 }
826
Adam Cohend4844c32011-02-18 19:25:06 -0800827 int getWidthGap() {
828 return mWidthGap;
829 }
830
831 int getHeightGap() {
832 return mHeightGap;
833 }
834
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700835 public void setFixedSize(int width, int height) {
836 mFixedWidth = width;
837 mFixedHeight = height;
838 }
839
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800840 @Override
841 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700842 DeviceProfile grid = mLauncher.getDeviceProfile();
Winson Chung5f8afe62013-08-12 16:19:28 -0700843
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800844 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800845 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700846 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
847 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700848 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
849 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Winson Chung11a1a532013-09-13 11:14:45 -0700850 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -0700851 int cw = grid.calculateCellWidth(childWidthSize, mCountX);
852 int ch = grid.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700853 if (cw != mCellWidth || ch != mCellHeight) {
854 mCellWidth = cw;
855 mCellHeight = ch;
856 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
857 mHeightGap, mCountX, mCountY);
858 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700859 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700860
Winson Chung2d75f122013-09-23 16:53:31 -0700861 int newWidth = childWidthSize;
862 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700863 if (mFixedWidth > 0 && mFixedHeight > 0) {
864 newWidth = mFixedWidth;
865 newHeight = mFixedHeight;
866 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800867 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
868 }
869
Adam Cohend22015c2010-07-26 22:02:18 -0700870 int numWidthGaps = mCountX - 1;
871 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800872
Adam Cohen234c4cd2011-07-17 21:03:04 -0700873 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -0700874 int hSpace = childWidthSize;
875 int vSpace = childHeightSize;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700876 int hFreeSpace = hSpace - (mCountX * mCellWidth);
877 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700878 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
879 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Winson Chung5f8afe62013-08-12 16:19:28 -0700880 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
881 mHeightGap, mCountX, mCountY);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700882 } else {
883 mWidthGap = mOriginalWidthGap;
884 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700885 }
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700886
887 // Make the feedback view large enough to hold the blur bitmap.
888 mTouchFeedbackView.measure(
889 MeasureSpec.makeMeasureSpec(mCellWidth + mTouchFeedbackView.getExtraSize(),
890 MeasureSpec.EXACTLY),
891 MeasureSpec.makeMeasureSpec(mCellHeight + mTouchFeedbackView.getExtraSize(),
892 MeasureSpec.EXACTLY));
893
894 mShortcutsAndWidgets.measure(
895 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
896 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
897
898 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
899 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700900 if (mFixedWidth > 0 && mFixedHeight > 0) {
901 setMeasuredDimension(maxWidth, maxHeight);
902 } else {
903 setMeasuredDimension(widthSize, heightSize);
904 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800905 }
906
907 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700908 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Winson Chung38848ca2013-10-08 12:03:44 -0700909 int offset = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() -
910 (mCountX * mCellWidth);
911 int left = getPaddingLeft() + (int) Math.ceil(offset / 2f);
912 int top = getPaddingTop();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700913
914 mTouchFeedbackView.layout(left, top,
915 left + mTouchFeedbackView.getMeasuredWidth(),
916 top + mTouchFeedbackView.getMeasuredHeight());
917 mShortcutsAndWidgets.layout(left, top,
918 left + r - l,
919 top + b - t);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800920 }
921
922 @Override
Michael Jurkadee05892010-07-27 10:01:56 -0700923 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
924 super.onSizeChanged(w, h, oldw, oldh);
Winson Chung82a9bd22013-10-08 16:02:34 -0700925
926 // Expand the background drawing bounds by the padding baked into the background drawable
927 Rect padding = new Rect();
928 mNormalBackground.getPadding(padding);
929 mBackgroundRect.set(-padding.left, -padding.top, w + padding.right, h + padding.bottom);
930
Adam Cohenb5ba0972011-09-07 18:02:31 -0700931 mForegroundRect.set(mForegroundPadding, mForegroundPadding,
Adam Cohen215b4162012-08-30 13:14:08 -0700932 w - mForegroundPadding, h - mForegroundPadding);
Michael Jurkadee05892010-07-27 10:01:56 -0700933 }
934
935 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800936 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700937 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800938 }
939
940 @Override
941 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700942 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800943 }
944
Michael Jurka5f1c5092010-09-03 14:15:02 -0700945 public float getBackgroundAlpha() {
946 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -0700947 }
948
Michael Jurka5f1c5092010-09-03 14:15:02 -0700949 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -0800950 if (mBackgroundAlpha != alpha) {
951 mBackgroundAlpha = alpha;
952 invalidate();
953 }
Michael Jurkadee05892010-07-27 10:01:56 -0700954 }
955
Michael Jurkaa52570f2012-03-20 03:18:20 -0700956 public void setShortcutAndWidgetAlpha(float alpha) {
Sunny Goyal02b50812014-09-10 15:44:42 -0700957 mShortcutsAndWidgets.setAlpha(alpha);
Michael Jurkadee05892010-07-27 10:01:56 -0700958 }
959
Michael Jurkaa52570f2012-03-20 03:18:20 -0700960 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -0700961 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700962 }
963
Patrick Dubroy440c3602010-07-13 17:50:32 -0700964 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700965 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -0700966 }
967
Adam Cohen76fc0852011-06-17 13:26:23 -0700968 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -0800969 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700970 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -0800971 boolean[][] occupied = mOccupied;
972 if (!permanent) {
973 occupied = mTmpOccupied;
974 }
975
Adam Cohen19f37922012-03-21 11:59:11 -0700976 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700977 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
978 final ItemInfo info = (ItemInfo) child.getTag();
979
980 // We cancel any existing animations
981 if (mReorderAnimators.containsKey(lp)) {
982 mReorderAnimators.get(lp).cancel();
983 mReorderAnimators.remove(lp);
984 }
985
Adam Cohen482ed822012-03-02 14:15:13 -0800986 final int oldX = lp.x;
987 final int oldY = lp.y;
988 if (adjustOccupied) {
989 occupied[lp.cellX][lp.cellY] = false;
990 occupied[cellX][cellY] = true;
991 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700992 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -0800993 if (permanent) {
994 lp.cellX = info.cellX = cellX;
995 lp.cellY = info.cellY = cellY;
996 } else {
997 lp.tmpCellX = cellX;
998 lp.tmpCellY = cellY;
999 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001000 clc.setupLp(lp);
1001 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001002 final int newX = lp.x;
1003 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001004
Adam Cohen76fc0852011-06-17 13:26:23 -07001005 lp.x = oldX;
1006 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001007
Adam Cohen482ed822012-03-02 14:15:13 -08001008 // Exit early if we're not actually moving the view
1009 if (oldX == newX && oldY == newY) {
1010 lp.isLockedToGrid = true;
1011 return true;
1012 }
1013
Michael Jurkaf1ad6082013-03-13 12:55:46 +01001014 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001015 va.setDuration(duration);
1016 mReorderAnimators.put(lp, va);
1017
1018 va.addUpdateListener(new AnimatorUpdateListener() {
1019 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001020 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001021 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001022 lp.x = (int) ((1 - r) * oldX + r * newX);
1023 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001024 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001025 }
1026 });
Adam Cohen482ed822012-03-02 14:15:13 -08001027 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001028 boolean cancelled = false;
1029 public void onAnimationEnd(Animator animation) {
1030 // If the animation was cancelled, it means that another animation
1031 // has interrupted this one, and we don't want to lock the item into
1032 // place just yet.
1033 if (!cancelled) {
1034 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001035 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001036 }
1037 if (mReorderAnimators.containsKey(lp)) {
1038 mReorderAnimators.remove(lp);
1039 }
1040 }
1041 public void onAnimationCancel(Animator animation) {
1042 cancelled = true;
1043 }
1044 });
Adam Cohen482ed822012-03-02 14:15:13 -08001045 va.setStartDelay(delay);
1046 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001047 return true;
1048 }
1049 return false;
1050 }
1051
Adam Cohen482ed822012-03-02 14:15:13 -08001052 void visualizeDropLocation(View v, Bitmap dragOutline, int originX, int originY, int cellX,
1053 int cellY, int spanX, int spanY, boolean resize, Point dragOffset, Rect dragRegion) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001054 final int oldDragCellX = mDragCell[0];
1055 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001056
Adam Cohen2801caf2011-05-13 20:57:39 -07001057 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001058 return;
1059 }
1060
Adam Cohen482ed822012-03-02 14:15:13 -08001061 if (cellX != oldDragCellX || cellY != oldDragCellY) {
1062 mDragCell[0] = cellX;
1063 mDragCell[1] = cellY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001064 // Find the top left corner of the rect the object will occupy
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001065 final int[] topLeft = mTmpPoint;
Adam Cohen482ed822012-03-02 14:15:13 -08001066 cellToPoint(cellX, cellY, topLeft);
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001067
Joe Onorato4be866d2010-10-10 11:26:02 -07001068 int left = topLeft[0];
1069 int top = topLeft[1];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001070
Winson Chungb8c69f32011-10-19 21:36:08 -07001071 if (v != null && dragOffset == null) {
Adam Cohen99e8b402011-03-25 19:23:43 -07001072 // When drawing the drag outline, it did not account for margin offsets
1073 // added by the view's parent.
1074 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1075 left += lp.leftMargin;
1076 top += lp.topMargin;
Winson Chung150fbab2010-09-29 17:14:26 -07001077
Adam Cohen99e8b402011-03-25 19:23:43 -07001078 // Offsets due to the size difference between the View and the dragOutline.
1079 // There is a size difference to account for the outer blur, which may lie
1080 // outside the bounds of the view.
Winson Chunga9abd0e2010-10-27 17:18:37 -07001081 top += (v.getHeight() - dragOutline.getHeight()) / 2;
Adam Cohenae915ce2011-08-25 13:47:22 -07001082 // We center about the x axis
1083 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1084 - dragOutline.getWidth()) / 2;
Adam Cohen66396872011-04-15 17:50:36 -07001085 } else {
Winson Chungb8c69f32011-10-19 21:36:08 -07001086 if (dragOffset != null && dragRegion != null) {
1087 // Center the drag region *horizontally* in the cell and apply a drag
1088 // outline offset
1089 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1090 - dragRegion.width()) / 2;
Winson Chung69737c32013-10-08 17:00:19 -07001091 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
1092 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
1093 top += dragOffset.y + cellPaddingY;
Winson Chungb8c69f32011-10-19 21:36:08 -07001094 } else {
1095 // Center the drag outline in the cell
1096 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1097 - dragOutline.getWidth()) / 2;
1098 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1099 - dragOutline.getHeight()) / 2;
1100 }
Winson Chunga9abd0e2010-10-27 17:18:37 -07001101 }
Joe Onorato4be866d2010-10-10 11:26:02 -07001102 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001103 mDragOutlineAnims[oldIndex].animateOut();
1104 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001105 Rect r = mDragOutlines[mDragOutlineCurrent];
1106 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
1107 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001108 cellToRect(cellX, cellY, spanX, spanY, r);
Adam Cohend41fbf52012-02-16 23:53:59 -08001109 }
Winson Chung150fbab2010-09-29 17:14:26 -07001110
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001111 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1112 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001113 }
1114 }
1115
Adam Cohene0310962011-04-18 16:15:31 -07001116 public void clearDragOutlines() {
1117 final int oldIndex = mDragOutlineCurrent;
1118 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001119 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001120 }
1121
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001122 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001123 * Find a vacant area that will fit the given bounds nearest the requested
1124 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001125 *
Romain Guy51afc022009-05-04 18:03:43 -07001126 * @param pixelX The X location at which you want to search for a vacant area.
1127 * @param pixelY The Y location at which you want to search for a vacant area.
Jeff Sharkey70864282009-04-07 21:08:40 -07001128 * @param spanX Horizontal span of the object.
1129 * @param spanY Vertical span of the object.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001130 * @param result Array in which to place the result, or null (in which case a new array will
1131 * be allocated)
Jeff Sharkey70864282009-04-07 21:08:40 -07001132 * @return The X, Y cell of a vacant area that can contain this object,
1133 * nearest the requested location.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001134 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001135 int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
1136 return findNearestVacantArea(pixelX, pixelY, spanX, spanY, spanX, spanY, result, null);
Michael Jurka6a1435d2010-09-27 17:35:12 -07001137 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001138
Michael Jurka6a1435d2010-09-27 17:35:12 -07001139 /**
1140 * Find a vacant area that will fit the given bounds nearest the requested
1141 * cell location. Uses Euclidean distance to score multiple vacant areas.
1142 *
1143 * @param pixelX The X location at which you want to search for a vacant area.
1144 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001145 * @param minSpanX The minimum horizontal span required
1146 * @param minSpanY The minimum vertical span required
1147 * @param spanX Horizontal span of the object.
1148 * @param spanY Vertical span of the object.
1149 * @param result Array in which to place the result, or null (in which case a new array will
1150 * be allocated)
1151 * @return The X, Y cell of a vacant area that can contain this object,
1152 * nearest the requested location.
1153 */
1154 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1155 int spanY, int[] result, int[] resultSpan) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001156 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
Adam Cohend41fbf52012-02-16 23:53:59 -08001157 result, resultSpan);
1158 }
1159
Adam Cohend41fbf52012-02-16 23:53:59 -08001160 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1161 private void lazyInitTempRectStack() {
1162 if (mTempRectStack.isEmpty()) {
1163 for (int i = 0; i < mCountX * mCountY; i++) {
1164 mTempRectStack.push(new Rect());
1165 }
1166 }
1167 }
Adam Cohen482ed822012-03-02 14:15:13 -08001168
Adam Cohend41fbf52012-02-16 23:53:59 -08001169 private void recycleTempRects(Stack<Rect> used) {
1170 while (!used.isEmpty()) {
1171 mTempRectStack.push(used.pop());
1172 }
1173 }
1174
1175 /**
1176 * Find a vacant area that will fit the given bounds nearest the requested
1177 * cell location. Uses Euclidean distance to score multiple vacant areas.
1178 *
1179 * @param pixelX The X location at which you want to search for a vacant area.
1180 * @param pixelY The Y location at which you want to search for a vacant area.
1181 * @param minSpanX The minimum horizontal span required
1182 * @param minSpanY The minimum vertical span required
1183 * @param spanX Horizontal span of the object.
1184 * @param spanY Vertical span of the object.
1185 * @param ignoreOccupied If true, the result can be an occupied cell
1186 * @param result Array in which to place the result, or null (in which case a new array will
1187 * be allocated)
1188 * @return The X, Y cell of a vacant area that can contain this object,
1189 * nearest the requested location.
1190 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001191 private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1192 int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001193 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001194
Adam Cohene3e27a82011-04-15 12:07:39 -07001195 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1196 // to the center of the item, but we are searching based on the top-left cell, so
1197 // we translate the point over to correspond to the top-left.
1198 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1199 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1200
Jeff Sharkey70864282009-04-07 21:08:40 -07001201 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001202 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001203 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001204 final Rect bestRect = new Rect(-1, -1, -1, -1);
1205 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001206
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001207 final int countX = mCountX;
1208 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001209
Adam Cohend41fbf52012-02-16 23:53:59 -08001210 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1211 spanX < minSpanX || spanY < minSpanY) {
1212 return bestXY;
1213 }
1214
1215 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001216 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001217 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1218 int ySize = -1;
1219 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001220 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001221 // First, let's see if this thing fits anywhere
1222 for (int i = 0; i < minSpanX; i++) {
1223 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001224 if (mOccupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001225 continue inner;
1226 }
Michael Jurkac28de512010-08-13 11:27:44 -07001227 }
1228 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001229 xSize = minSpanX;
1230 ySize = minSpanY;
1231
1232 // We know that the item will fit at _some_ acceptable size, now let's see
1233 // how big we can make it. We'll alternate between incrementing x and y spans
1234 // until we hit a limit.
1235 boolean incX = true;
1236 boolean hitMaxX = xSize >= spanX;
1237 boolean hitMaxY = ySize >= spanY;
1238 while (!(hitMaxX && hitMaxY)) {
1239 if (incX && !hitMaxX) {
1240 for (int j = 0; j < ySize; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001241 if (x + xSize > countX -1 || mOccupied[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001242 // We can't move out horizontally
1243 hitMaxX = true;
1244 }
1245 }
1246 if (!hitMaxX) {
1247 xSize++;
1248 }
1249 } else if (!hitMaxY) {
1250 for (int i = 0; i < xSize; i++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001251 if (y + ySize > countY - 1 || mOccupied[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001252 // We can't move out vertically
1253 hitMaxY = true;
1254 }
1255 }
1256 if (!hitMaxY) {
1257 ySize++;
1258 }
1259 }
1260 hitMaxX |= xSize >= spanX;
1261 hitMaxY |= ySize >= spanY;
1262 incX = !incX;
1263 }
1264 incX = true;
1265 hitMaxX = xSize >= spanX;
1266 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001267 }
Winson Chung0be025d2011-05-23 17:45:09 -07001268 final int[] cellXY = mTmpXY;
Adam Cohene3e27a82011-04-15 12:07:39 -07001269 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001270
Adam Cohend41fbf52012-02-16 23:53:59 -08001271 // We verify that the current rect is not a sub-rect of any of our previous
1272 // candidates. In this case, the current rect is disqualified in favour of the
1273 // containing rect.
1274 Rect currentRect = mTempRectStack.pop();
1275 currentRect.set(x, y, x + xSize, y + ySize);
1276 boolean contained = false;
1277 for (Rect r : validRegions) {
1278 if (r.contains(currentRect)) {
1279 contained = true;
1280 break;
1281 }
1282 }
1283 validRegions.push(currentRect);
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001284 double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
Adam Cohen482ed822012-03-02 14:15:13 -08001285
Adam Cohend41fbf52012-02-16 23:53:59 -08001286 if ((distance <= bestDistance && !contained) ||
1287 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001288 bestDistance = distance;
1289 bestXY[0] = x;
1290 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001291 if (resultSpan != null) {
1292 resultSpan[0] = xSize;
1293 resultSpan[1] = ySize;
1294 }
1295 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001296 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001297 }
1298 }
1299
Adam Cohenc0dcf592011-06-01 15:30:43 -07001300 // Return -1, -1 if no suitable location found
1301 if (bestDistance == Double.MAX_VALUE) {
1302 bestXY[0] = -1;
1303 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001304 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001305 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001306 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001307 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001308
Adam Cohen482ed822012-03-02 14:15:13 -08001309 /**
1310 * Find a vacant area that will fit the given bounds nearest the requested
1311 * cell location, and will also weigh in a suggested direction vector of the
1312 * desired location. This method computers distance based on unit grid distances,
1313 * not pixel distances.
1314 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001315 * @param cellX The X cell nearest to which you want to search for a vacant area.
1316 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001317 * @param spanX Horizontal span of the object.
1318 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001319 * @param direction The favored direction in which the views should move from x, y
1320 * @param exactDirectionOnly If this parameter is true, then only solutions where the direction
1321 * matches exactly. Otherwise we find the best matching direction.
1322 * @param occoupied The array which represents which cells in the CellLayout are occupied
1323 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001324 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001325 * @param result Array in which to place the result, or null (in which case a new array will
1326 * be allocated)
1327 * @return The X, Y cell of a vacant area that can contain this object,
1328 * nearest the requested location.
1329 */
1330 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001331 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001332 // Keep track of best-scoring drop area
1333 final int[] bestXY = result != null ? result : new int[2];
1334 float bestDistance = Float.MAX_VALUE;
1335 int bestDirectionScore = Integer.MIN_VALUE;
1336
1337 final int countX = mCountX;
1338 final int countY = mCountY;
1339
1340 for (int y = 0; y < countY - (spanY - 1); y++) {
1341 inner:
1342 for (int x = 0; x < countX - (spanX - 1); x++) {
1343 // First, let's see if this thing fits anywhere
1344 for (int i = 0; i < spanX; i++) {
1345 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001346 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001347 continue inner;
1348 }
1349 }
1350 }
1351
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001352 float distance = (float) Math.hypot(x - cellX, y - cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001353 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001354 computeDirectionVector(x - cellX, y - cellY, curDirection);
1355 // The direction score is just the dot product of the two candidate direction
1356 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001357 int curDirectionScore = direction[0] * curDirection[0] +
1358 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001359 boolean exactDirectionOnly = false;
1360 boolean directionMatches = direction[0] == curDirection[0] &&
1361 direction[0] == curDirection[0];
1362 if ((directionMatches || !exactDirectionOnly) &&
1363 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001364 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1365 bestDistance = distance;
1366 bestDirectionScore = curDirectionScore;
1367 bestXY[0] = x;
1368 bestXY[1] = y;
1369 }
1370 }
1371 }
1372
1373 // Return -1, -1 if no suitable location found
1374 if (bestDistance == Float.MAX_VALUE) {
1375 bestXY[0] = -1;
1376 bestXY[1] = -1;
1377 }
1378 return bestXY;
1379 }
1380
1381 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001382 int[] direction, ItemConfiguration currentState) {
1383 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001384 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001385 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001386 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1387
Adam Cohen8baab352012-03-20 17:39:21 -07001388 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001389
1390 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001391 c.x = mTempLocation[0];
1392 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001393 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001394 }
Adam Cohen8baab352012-03-20 17:39:21 -07001395 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001396 return success;
1397 }
1398
Adam Cohenf3900c22012-11-16 18:28:11 -08001399 /**
1400 * This helper class defines a cluster of views. It helps with defining complex edges
1401 * of the cluster and determining how those edges interact with other views. The edges
1402 * essentially define a fine-grained boundary around the cluster of views -- like a more
1403 * precise version of a bounding box.
1404 */
1405 private class ViewCluster {
1406 final static int LEFT = 0;
1407 final static int TOP = 1;
1408 final static int RIGHT = 2;
1409 final static int BOTTOM = 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001410
Adam Cohenf3900c22012-11-16 18:28:11 -08001411 ArrayList<View> views;
1412 ItemConfiguration config;
1413 Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001414
Adam Cohenf3900c22012-11-16 18:28:11 -08001415 int[] leftEdge = new int[mCountY];
1416 int[] rightEdge = new int[mCountY];
1417 int[] topEdge = new int[mCountX];
1418 int[] bottomEdge = new int[mCountX];
1419 boolean leftEdgeDirty, rightEdgeDirty, topEdgeDirty, bottomEdgeDirty, boundingRectDirty;
1420
1421 @SuppressWarnings("unchecked")
1422 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1423 this.views = (ArrayList<View>) views.clone();
1424 this.config = config;
1425 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001426 }
1427
Adam Cohenf3900c22012-11-16 18:28:11 -08001428 void resetEdges() {
1429 for (int i = 0; i < mCountX; i++) {
1430 topEdge[i] = -1;
1431 bottomEdge[i] = -1;
1432 }
1433 for (int i = 0; i < mCountY; i++) {
1434 leftEdge[i] = -1;
1435 rightEdge[i] = -1;
1436 }
1437 leftEdgeDirty = true;
1438 rightEdgeDirty = true;
1439 bottomEdgeDirty = true;
1440 topEdgeDirty = true;
1441 boundingRectDirty = true;
1442 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001443
Adam Cohenf3900c22012-11-16 18:28:11 -08001444 void computeEdge(int which, int[] edge) {
1445 int count = views.size();
1446 for (int i = 0; i < count; i++) {
1447 CellAndSpan cs = config.map.get(views.get(i));
1448 switch (which) {
1449 case LEFT:
1450 int left = cs.x;
1451 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1452 if (left < edge[j] || edge[j] < 0) {
1453 edge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001454 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001455 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001456 break;
1457 case RIGHT:
1458 int right = cs.x + cs.spanX;
1459 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1460 if (right > edge[j]) {
1461 edge[j] = right;
1462 }
1463 }
1464 break;
1465 case TOP:
1466 int top = cs.y;
1467 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1468 if (top < edge[j] || edge[j] < 0) {
1469 edge[j] = top;
1470 }
1471 }
1472 break;
1473 case BOTTOM:
1474 int bottom = cs.y + cs.spanY;
1475 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1476 if (bottom > edge[j]) {
1477 edge[j] = bottom;
1478 }
1479 }
1480 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001481 }
1482 }
1483 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001484
1485 boolean isViewTouchingEdge(View v, int whichEdge) {
1486 CellAndSpan cs = config.map.get(v);
1487
1488 int[] edge = getEdge(whichEdge);
1489
1490 switch (whichEdge) {
1491 case LEFT:
1492 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1493 if (edge[i] == cs.x + cs.spanX) {
1494 return true;
1495 }
1496 }
1497 break;
1498 case RIGHT:
1499 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1500 if (edge[i] == cs.x) {
1501 return true;
1502 }
1503 }
1504 break;
1505 case TOP:
1506 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1507 if (edge[i] == cs.y + cs.spanY) {
1508 return true;
1509 }
1510 }
1511 break;
1512 case BOTTOM:
1513 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1514 if (edge[i] == cs.y) {
1515 return true;
1516 }
1517 }
1518 break;
1519 }
1520 return false;
1521 }
1522
1523 void shift(int whichEdge, int delta) {
1524 for (View v: views) {
1525 CellAndSpan c = config.map.get(v);
1526 switch (whichEdge) {
1527 case LEFT:
1528 c.x -= delta;
1529 break;
1530 case RIGHT:
1531 c.x += delta;
1532 break;
1533 case TOP:
1534 c.y -= delta;
1535 break;
1536 case BOTTOM:
1537 default:
1538 c.y += delta;
1539 break;
1540 }
1541 }
1542 resetEdges();
1543 }
1544
1545 public void addView(View v) {
1546 views.add(v);
1547 resetEdges();
1548 }
1549
1550 public Rect getBoundingRect() {
1551 if (boundingRectDirty) {
1552 boolean first = true;
1553 for (View v: views) {
1554 CellAndSpan c = config.map.get(v);
1555 if (first) {
1556 boundingRect.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1557 first = false;
1558 } else {
1559 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1560 }
1561 }
1562 }
1563 return boundingRect;
1564 }
1565
1566 public int[] getEdge(int which) {
1567 switch (which) {
1568 case LEFT:
1569 return getLeftEdge();
1570 case RIGHT:
1571 return getRightEdge();
1572 case TOP:
1573 return getTopEdge();
1574 case BOTTOM:
1575 default:
1576 return getBottomEdge();
1577 }
1578 }
1579
1580 public int[] getLeftEdge() {
1581 if (leftEdgeDirty) {
1582 computeEdge(LEFT, leftEdge);
1583 }
1584 return leftEdge;
1585 }
1586
1587 public int[] getRightEdge() {
1588 if (rightEdgeDirty) {
1589 computeEdge(RIGHT, rightEdge);
1590 }
1591 return rightEdge;
1592 }
1593
1594 public int[] getTopEdge() {
1595 if (topEdgeDirty) {
1596 computeEdge(TOP, topEdge);
1597 }
1598 return topEdge;
1599 }
1600
1601 public int[] getBottomEdge() {
1602 if (bottomEdgeDirty) {
1603 computeEdge(BOTTOM, bottomEdge);
1604 }
1605 return bottomEdge;
1606 }
1607
1608 PositionComparator comparator = new PositionComparator();
1609 class PositionComparator implements Comparator<View> {
1610 int whichEdge = 0;
1611 public int compare(View left, View right) {
1612 CellAndSpan l = config.map.get(left);
1613 CellAndSpan r = config.map.get(right);
1614 switch (whichEdge) {
1615 case LEFT:
1616 return (r.x + r.spanX) - (l.x + l.spanX);
1617 case RIGHT:
1618 return l.x - r.x;
1619 case TOP:
1620 return (r.y + r.spanY) - (l.y + l.spanY);
1621 case BOTTOM:
1622 default:
1623 return l.y - r.y;
1624 }
1625 }
1626 }
1627
1628 public void sortConfigurationForEdgePush(int edge) {
1629 comparator.whichEdge = edge;
1630 Collections.sort(config.sortedViews, comparator);
1631 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001632 }
1633
Adam Cohenf3900c22012-11-16 18:28:11 -08001634 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1635 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001636
Adam Cohenf3900c22012-11-16 18:28:11 -08001637 ViewCluster cluster = new ViewCluster(views, currentState);
1638 Rect clusterRect = cluster.getBoundingRect();
1639 int whichEdge;
1640 int pushDistance;
1641 boolean fail = false;
1642
1643 // Determine the edge of the cluster that will be leading the push and how far
1644 // the cluster must be shifted.
1645 if (direction[0] < 0) {
1646 whichEdge = ViewCluster.LEFT;
1647 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001648 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001649 whichEdge = ViewCluster.RIGHT;
1650 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1651 } else if (direction[1] < 0) {
1652 whichEdge = ViewCluster.TOP;
1653 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1654 } else {
1655 whichEdge = ViewCluster.BOTTOM;
1656 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07001657 }
1658
Adam Cohenf3900c22012-11-16 18:28:11 -08001659 // Break early for invalid push distance.
1660 if (pushDistance <= 0) {
1661 return false;
Adam Cohene0489502012-08-27 15:18:53 -07001662 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001663
1664 // Mark the occupied state as false for the group of views we want to move.
1665 for (View v: views) {
1666 CellAndSpan c = currentState.map.get(v);
1667 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1668 }
1669
1670 // We save the current configuration -- if we fail to find a solution we will revert
1671 // to the initial state. The process of finding a solution modifies the configuration
1672 // in place, hence the need for revert in the failure case.
1673 currentState.save();
1674
1675 // The pushing algorithm is simplified by considering the views in the order in which
1676 // they would be pushed by the cluster. For example, if the cluster is leading with its
1677 // left edge, we consider sort the views by their right edge, from right to left.
1678 cluster.sortConfigurationForEdgePush(whichEdge);
1679
1680 while (pushDistance > 0 && !fail) {
1681 for (View v: currentState.sortedViews) {
1682 // For each view that isn't in the cluster, we see if the leading edge of the
1683 // cluster is contacting the edge of that view. If so, we add that view to the
1684 // cluster.
1685 if (!cluster.views.contains(v) && v != dragView) {
1686 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1687 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1688 if (!lp.canReorder) {
1689 // The push solution includes the all apps button, this is not viable.
1690 fail = true;
1691 break;
1692 }
1693 cluster.addView(v);
1694 CellAndSpan c = currentState.map.get(v);
1695
1696 // Adding view to cluster, mark it as not occupied.
1697 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1698 }
1699 }
1700 }
1701 pushDistance--;
1702
1703 // The cluster has been completed, now we move the whole thing over in the appropriate
1704 // direction.
1705 cluster.shift(whichEdge, 1);
1706 }
1707
1708 boolean foundSolution = false;
1709 clusterRect = cluster.getBoundingRect();
1710
1711 // Due to the nature of the algorithm, the only check required to verify a valid solution
1712 // is to ensure that completed shifted cluster lies completely within the cell layout.
1713 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1714 clusterRect.bottom <= mCountY) {
1715 foundSolution = true;
1716 } else {
1717 currentState.restore();
1718 }
1719
1720 // In either case, we set the occupied array as marked for the location of the views
1721 for (View v: cluster.views) {
1722 CellAndSpan c = currentState.map.get(v);
1723 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
1724 }
1725
1726 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07001727 }
1728
Adam Cohen482ed822012-03-02 14:15:13 -08001729 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08001730 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001731 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001732
Adam Cohen8baab352012-03-20 17:39:21 -07001733 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001734 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001735 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001736 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001737 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001738 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001739 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001740 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001741 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001742 }
1743 }
Adam Cohen8baab352012-03-20 17:39:21 -07001744
Adam Cohen8baab352012-03-20 17:39:21 -07001745 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08001746 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001747 CellAndSpan c = currentState.map.get(v);
1748 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1749 }
1750
Adam Cohen47a876d2012-03-19 13:21:41 -07001751 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1752 int top = boundingRect.top;
1753 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001754 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001755 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08001756 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001757 CellAndSpan c = currentState.map.get(v);
1758 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001759 }
1760
Adam Cohen482ed822012-03-02 14:15:13 -08001761 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1762
Adam Cohenf3900c22012-11-16 18:28:11 -08001763 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1764 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001765
Adam Cohen8baab352012-03-20 17:39:21 -07001766 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001767 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001768 int deltaX = mTempLocation[0] - boundingRect.left;
1769 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001770 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001771 CellAndSpan c = currentState.map.get(v);
1772 c.x += deltaX;
1773 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001774 }
1775 success = true;
1776 }
Adam Cohen8baab352012-03-20 17:39:21 -07001777
1778 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08001779 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001780 CellAndSpan c = currentState.map.get(v);
1781 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001782 }
1783 return success;
1784 }
1785
1786 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1787 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1788 }
1789
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001790 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1791 // to push items in each of the cardinal directions, in an order based on the direction vector
1792 // passed.
1793 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1794 int[] direction, View ignoreView, ItemConfiguration solution) {
1795 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001796 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001797 // separately in each of the components.
1798 int temp = direction[1];
1799 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001800
1801 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001802 ignoreView, solution)) {
1803 return true;
1804 }
1805 direction[1] = temp;
1806 temp = direction[0];
1807 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001808
1809 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001810 ignoreView, solution)) {
1811 return true;
1812 }
1813 // Revert the direction
1814 direction[0] = temp;
1815
1816 // Now we try pushing in each component of the opposite direction
1817 direction[0] *= -1;
1818 direction[1] *= -1;
1819 temp = direction[1];
1820 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001821 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001822 ignoreView, solution)) {
1823 return true;
1824 }
1825
1826 direction[1] = temp;
1827 temp = direction[0];
1828 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001829 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001830 ignoreView, solution)) {
1831 return true;
1832 }
1833 // revert the direction
1834 direction[0] = temp;
1835 direction[0] *= -1;
1836 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001837
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001838 } else {
1839 // If the direction vector has a single non-zero component, we push first in the
1840 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08001841 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001842 ignoreView, solution)) {
1843 return true;
1844 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001845 // Then we try the opposite direction
1846 direction[0] *= -1;
1847 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001848 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001849 ignoreView, solution)) {
1850 return true;
1851 }
1852 // Switch the direction back
1853 direction[0] *= -1;
1854 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001855
1856 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001857 // to find a solution by pushing along the perpendicular axis.
1858
1859 // Swap the components
1860 int temp = direction[1];
1861 direction[1] = direction[0];
1862 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08001863 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001864 ignoreView, solution)) {
1865 return true;
1866 }
1867
1868 // Then we try the opposite direction
1869 direction[0] *= -1;
1870 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001871 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001872 ignoreView, solution)) {
1873 return true;
1874 }
1875 // Switch the direction back
1876 direction[0] *= -1;
1877 direction[1] *= -1;
1878
1879 // Swap the components back
1880 temp = direction[1];
1881 direction[1] = direction[0];
1882 direction[0] = temp;
1883 }
1884 return false;
1885 }
1886
Adam Cohen482ed822012-03-02 14:15:13 -08001887 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001888 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001889 // Return early if get invalid cell positions
1890 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001891
Adam Cohen8baab352012-03-20 17:39:21 -07001892 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001893 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001894
Adam Cohen8baab352012-03-20 17:39:21 -07001895 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001896 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001897 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001898 if (c != null) {
1899 c.x = cellX;
1900 c.y = cellY;
1901 }
Adam Cohen482ed822012-03-02 14:15:13 -08001902 }
Adam Cohen482ed822012-03-02 14:15:13 -08001903 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1904 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001905 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001906 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001907 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001908 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001909 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001910 if (Rect.intersects(r0, r1)) {
1911 if (!lp.canReorder) {
1912 return false;
1913 }
1914 mIntersectingViews.add(child);
1915 }
1916 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001917
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001918 solution.intersectingViews = new ArrayList<View>(mIntersectingViews);
1919
Winson Chung5f8afe62013-08-12 16:19:28 -07001920 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001921 // we try to find a solution such that no displaced item travels through another item
1922 // without also displacing that item.
1923 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001924 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001925 return true;
1926 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001927
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001928 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08001929 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001930 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001931 return true;
1932 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001933
Adam Cohen482ed822012-03-02 14:15:13 -08001934 // Ok, they couldn't move as a block, let's move them individually
1935 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001936 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001937 return false;
1938 }
1939 }
1940 return true;
1941 }
1942
1943 /*
1944 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1945 * the provided point and the provided cell
1946 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001947 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001948 double angle = Math.atan(((float) deltaY) / deltaX);
1949
1950 result[0] = 0;
1951 result[1] = 0;
1952 if (Math.abs(Math.cos(angle)) > 0.5f) {
1953 result[0] = (int) Math.signum(deltaX);
1954 }
1955 if (Math.abs(Math.sin(angle)) > 0.5f) {
1956 result[1] = (int) Math.signum(deltaY);
1957 }
1958 }
1959
Adam Cohen8baab352012-03-20 17:39:21 -07001960 private void copyOccupiedArray(boolean[][] occupied) {
1961 for (int i = 0; i < mCountX; i++) {
1962 for (int j = 0; j < mCountY; j++) {
1963 occupied[i][j] = mOccupied[i][j];
1964 }
1965 }
1966 }
1967
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001968 private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001969 int spanX, int spanY, int[] direction, View dragView, boolean decX,
1970 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001971 // Copy the current state into the solution. This solution will be manipulated as necessary.
1972 copyCurrentStateToSolution(solution, false);
1973 // Copy the current occupied array into the temporary occupied array. This array will be
1974 // manipulated as necessary to find a solution.
1975 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001976
1977 // We find the nearest cell into which we would place the dragged item, assuming there's
1978 // nothing in its way.
1979 int result[] = new int[2];
1980 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1981
1982 boolean success = false;
1983 // First we try the exact nearest position of the item being dragged,
1984 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001985 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1986 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001987
1988 if (!success) {
1989 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1990 // x, then 1 in y etc.
1991 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001992 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
1993 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001994 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001995 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
1996 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001997 }
1998 solution.isSolution = false;
1999 } else {
2000 solution.isSolution = true;
2001 solution.dragViewX = result[0];
2002 solution.dragViewY = result[1];
2003 solution.dragViewSpanX = spanX;
2004 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002005 }
2006 return solution;
2007 }
2008
2009 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002010 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002011 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002012 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002013 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002014 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08002015 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07002016 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002017 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07002018 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002019 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002020 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08002021 }
2022 }
2023
2024 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
2025 for (int i = 0; i < mCountX; i++) {
2026 for (int j = 0; j < mCountY; j++) {
2027 mTmpOccupied[i][j] = false;
2028 }
2029 }
2030
Michael Jurkaa52570f2012-03-20 03:18:20 -07002031 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002032 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002033 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002034 if (child == dragView) continue;
2035 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002036 CellAndSpan c = solution.map.get(child);
2037 if (c != null) {
2038 lp.tmpCellX = c.x;
2039 lp.tmpCellY = c.y;
2040 lp.cellHSpan = c.spanX;
2041 lp.cellVSpan = c.spanY;
2042 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002043 }
2044 }
2045 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2046 solution.dragViewSpanY, mTmpOccupied, true);
2047 }
2048
2049 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
2050 commitDragView) {
2051
2052 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
2053 for (int i = 0; i < mCountX; i++) {
2054 for (int j = 0; j < mCountY; j++) {
2055 occupied[i][j] = false;
2056 }
2057 }
2058
Michael Jurkaa52570f2012-03-20 03:18:20 -07002059 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002060 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002061 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002062 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002063 CellAndSpan c = solution.map.get(child);
2064 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002065 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2066 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002067 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002068 }
2069 }
2070 if (commitDragView) {
2071 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2072 solution.dragViewSpanY, occupied, true);
2073 }
2074 }
2075
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002076
2077 // This method starts or changes the reorder preview animations
2078 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
2079 View dragView, int delay, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07002080 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002081 for (int i = 0; i < childCount; i++) {
2082 View child = mShortcutsAndWidgets.getChildAt(i);
2083 if (child == dragView) continue;
2084 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002085 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
2086 != null && !solution.intersectingViews.contains(child);
2087
Adam Cohen19f37922012-03-21 11:59:11 -07002088 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002089 if (c != null && !skip) {
2090 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
2091 lp.cellY, c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002092 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002093 }
2094 }
2095 }
2096
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002097 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07002098 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002099 class ReorderPreviewAnimation {
Adam Cohen19f37922012-03-21 11:59:11 -07002100 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002101 float finalDeltaX;
2102 float finalDeltaY;
2103 float initDeltaX;
2104 float initDeltaY;
2105 float finalScale;
2106 float initScale;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002107 int mode;
2108 boolean repeating = false;
2109 private static final int PREVIEW_DURATION = 300;
2110 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
2111
2112 public static final int MODE_HINT = 0;
2113 public static final int MODE_PREVIEW = 1;
2114
Adam Cohene7587d22012-05-24 18:50:02 -07002115 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002116
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002117 public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
2118 int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07002119 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2120 final int x0 = mTmpPoint[0];
2121 final int y0 = mTmpPoint[1];
2122 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2123 final int x1 = mTmpPoint[0];
2124 final int y1 = mTmpPoint[1];
2125 final int dX = x1 - x0;
2126 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002127 finalDeltaX = 0;
2128 finalDeltaY = 0;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002129 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07002130 if (dX == dY && dX == 0) {
2131 } else {
2132 if (dY == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002133 finalDeltaX = - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002134 } else if (dX == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002135 finalDeltaY = - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002136 } else {
2137 double angle = Math.atan( (float) (dY) / dX);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002138 finalDeltaX = (int) (- dir * Math.signum(dX) *
2139 Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
2140 finalDeltaY = (int) (- dir * Math.signum(dY) *
2141 Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002142 }
2143 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002144 this.mode = mode;
Adam Cohend024f982012-05-23 18:26:45 -07002145 initDeltaX = child.getTranslationX();
2146 initDeltaY = child.getTranslationY();
Adam Cohen307fe232012-08-16 17:55:58 -07002147 finalScale = getChildrenScale() - 4.0f / child.getWidth();
Adam Cohend024f982012-05-23 18:26:45 -07002148 initScale = child.getScaleX();
Adam Cohen19f37922012-03-21 11:59:11 -07002149 this.child = child;
2150 }
2151
Adam Cohend024f982012-05-23 18:26:45 -07002152 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002153 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002154 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002155 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002156 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002157 if (finalDeltaX == 0 && finalDeltaY == 0) {
2158 completeAnimationImmediately();
2159 return;
2160 }
Adam Cohen19f37922012-03-21 11:59:11 -07002161 }
Adam Cohend024f982012-05-23 18:26:45 -07002162 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002163 return;
2164 }
Michael Jurkaf1ad6082013-03-13 12:55:46 +01002165 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002166 a = va;
Adam Cohen19f37922012-03-21 11:59:11 -07002167 va.setRepeatMode(ValueAnimator.REVERSE);
2168 va.setRepeatCount(ValueAnimator.INFINITE);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002169 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002170 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002171 va.addUpdateListener(new AnimatorUpdateListener() {
2172 @Override
2173 public void onAnimationUpdate(ValueAnimator animation) {
2174 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002175 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : r;
2176 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2177 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002178 child.setTranslationX(x);
2179 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002180 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002181 child.setScaleX(s);
2182 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002183 }
2184 });
2185 va.addListener(new AnimatorListenerAdapter() {
2186 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002187 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002188 initDeltaX = 0;
2189 initDeltaY = 0;
Adam Cohen307fe232012-08-16 17:55:58 -07002190 initScale = getChildrenScale();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002191 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002192 }
2193 });
Adam Cohen19f37922012-03-21 11:59:11 -07002194 mShakeAnimators.put(child, this);
2195 va.start();
2196 }
2197
Adam Cohend024f982012-05-23 18:26:45 -07002198 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002199 if (a != null) {
2200 a.cancel();
2201 }
Adam Cohen19f37922012-03-21 11:59:11 -07002202 }
Adam Cohene7587d22012-05-24 18:50:02 -07002203
Adam Cohen091440a2015-03-18 14:16:05 -07002204 @Thunk void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002205 if (a != null) {
2206 a.cancel();
2207 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002208
Michael Jurka2ecf9952012-06-18 12:52:28 -07002209 AnimatorSet s = LauncherAnimUtils.createAnimatorSet();
Adam Cohene7587d22012-05-24 18:50:02 -07002210 a = s;
Brandon Keely50e6e562012-05-08 16:28:49 -07002211 s.playTogether(
Adam Cohen307fe232012-08-16 17:55:58 -07002212 LauncherAnimUtils.ofFloat(child, "scaleX", getChildrenScale()),
2213 LauncherAnimUtils.ofFloat(child, "scaleY", getChildrenScale()),
Michael Jurka2ecf9952012-06-18 12:52:28 -07002214 LauncherAnimUtils.ofFloat(child, "translationX", 0f),
2215 LauncherAnimUtils.ofFloat(child, "translationY", 0f)
Brandon Keely50e6e562012-05-08 16:28:49 -07002216 );
2217 s.setDuration(REORDER_ANIMATION_DURATION);
2218 s.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2219 s.start();
2220 }
Adam Cohen19f37922012-03-21 11:59:11 -07002221 }
2222
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002223 private void completeAndClearReorderPreviewAnimations() {
2224 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002225 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002226 }
2227 mShakeAnimators.clear();
2228 }
2229
Adam Cohen482ed822012-03-02 14:15:13 -08002230 private void commitTempPlacement() {
2231 for (int i = 0; i < mCountX; i++) {
2232 for (int j = 0; j < mCountY; j++) {
2233 mOccupied[i][j] = mTmpOccupied[i][j];
2234 }
2235 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002236 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002237 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002238 View child = mShortcutsAndWidgets.getChildAt(i);
2239 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2240 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002241 // We do a null check here because the item info can be null in the case of the
2242 // AllApps button in the hotseat.
2243 if (info != null) {
Adam Cohen487f7dd2012-06-28 18:12:10 -07002244 if (info.cellX != lp.tmpCellX || info.cellY != lp.tmpCellY ||
2245 info.spanX != lp.cellHSpan || info.spanY != lp.cellVSpan) {
2246 info.requiresDbUpdate = true;
2247 }
Adam Cohen2acce882012-03-28 19:03:19 -07002248 info.cellX = lp.cellX = lp.tmpCellX;
2249 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002250 info.spanX = lp.cellHSpan;
2251 info.spanY = lp.cellVSpan;
Adam Cohen2acce882012-03-28 19:03:19 -07002252 }
Adam Cohen482ed822012-03-02 14:15:13 -08002253 }
Adam Cohen2acce882012-03-28 19:03:19 -07002254 mLauncher.getWorkspace().updateItemLocationsInDatabase(this);
Adam Cohen482ed822012-03-02 14:15:13 -08002255 }
2256
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002257 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002258 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002259 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002260 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002261 lp.useTmpCoords = useTempCoords;
2262 }
2263 }
2264
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002265 private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002266 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2267 int[] result = new int[2];
2268 int[] resultSpan = new int[2];
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002269 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
Adam Cohen482ed822012-03-02 14:15:13 -08002270 resultSpan);
2271 if (result[0] >= 0 && result[1] >= 0) {
2272 copyCurrentStateToSolution(solution, false);
2273 solution.dragViewX = result[0];
2274 solution.dragViewY = result[1];
2275 solution.dragViewSpanX = resultSpan[0];
2276 solution.dragViewSpanY = resultSpan[1];
2277 solution.isSolution = true;
2278 } else {
2279 solution.isSolution = false;
2280 }
2281 return solution;
2282 }
2283
2284 public void prepareChildForDrag(View child) {
2285 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002286 }
2287
Adam Cohen19f37922012-03-21 11:59:11 -07002288 /* This seems like it should be obvious and straight-forward, but when the direction vector
2289 needs to match with the notion of the dragView pushing other views, we have to employ
2290 a slightly more subtle notion of the direction vector. The question is what two points is
2291 the vector between? The center of the dragView and its desired destination? Not quite, as
2292 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2293 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2294 or right, which helps make pushing feel right.
2295 */
2296 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2297 int spanY, View dragView, int[] resultDirection) {
2298 int[] targetDestination = new int[2];
2299
2300 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2301 Rect dragRect = new Rect();
2302 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2303 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2304
2305 Rect dropRegionRect = new Rect();
2306 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2307 dragView, dropRegionRect, mIntersectingViews);
2308
2309 int dropRegionSpanX = dropRegionRect.width();
2310 int dropRegionSpanY = dropRegionRect.height();
2311
2312 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2313 dropRegionRect.height(), dropRegionRect);
2314
2315 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2316 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2317
2318 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2319 deltaX = 0;
2320 }
2321 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2322 deltaY = 0;
2323 }
2324
2325 if (deltaX == 0 && deltaY == 0) {
2326 // No idea what to do, give a random direction.
2327 resultDirection[0] = 1;
2328 resultDirection[1] = 0;
2329 } else {
2330 computeDirectionVector(deltaX, deltaY, resultDirection);
2331 }
2332 }
2333
2334 // For a given cell and span, fetch the set of views intersecting the region.
2335 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2336 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2337 if (boundingRect != null) {
2338 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2339 }
2340 intersectingViews.clear();
2341 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2342 Rect r1 = new Rect();
2343 final int count = mShortcutsAndWidgets.getChildCount();
2344 for (int i = 0; i < count; i++) {
2345 View child = mShortcutsAndWidgets.getChildAt(i);
2346 if (child == dragView) continue;
2347 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2348 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2349 if (Rect.intersects(r0, r1)) {
2350 mIntersectingViews.add(child);
2351 if (boundingRect != null) {
2352 boundingRect.union(r1);
2353 }
2354 }
2355 }
2356 }
2357
2358 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2359 View dragView, int[] result) {
2360 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2361 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2362 mIntersectingViews);
2363 return !mIntersectingViews.isEmpty();
2364 }
2365
2366 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002367 completeAndClearReorderPreviewAnimations();
2368 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2369 final int count = mShortcutsAndWidgets.getChildCount();
2370 for (int i = 0; i < count; i++) {
2371 View child = mShortcutsAndWidgets.getChildAt(i);
2372 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2373 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2374 lp.tmpCellX = lp.cellX;
2375 lp.tmpCellY = lp.cellY;
2376 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2377 0, false, false);
2378 }
Adam Cohen19f37922012-03-21 11:59:11 -07002379 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002380 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002381 }
Adam Cohen19f37922012-03-21 11:59:11 -07002382 }
2383
Adam Cohenbebf0422012-04-11 18:06:28 -07002384 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2385 View dragView, int[] direction, boolean commit) {
2386 int[] pixelXY = new int[2];
2387 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2388
2389 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002390 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002391 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2392
2393 setUseTempCoords(true);
2394 if (swapSolution != null && swapSolution.isSolution) {
2395 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2396 // committing anything or animating anything as we just want to determine if a solution
2397 // exists
2398 copySolutionToTempState(swapSolution, dragView);
2399 setItemPlacementDirty(true);
2400 animateItemsToSolution(swapSolution, dragView, commit);
2401
2402 if (commit) {
2403 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002404 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002405 setItemPlacementDirty(false);
2406 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002407 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
2408 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002409 }
2410 mShortcutsAndWidgets.requestLayout();
2411 }
2412 return swapSolution.isSolution;
2413 }
2414
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002415 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002416 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002417 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002418 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002419
2420 if (resultSpan == null) {
2421 resultSpan = new int[2];
2422 }
2423
Adam Cohen19f37922012-03-21 11:59:11 -07002424 // When we are checking drop validity or actually dropping, we don't recompute the
2425 // direction vector, since we want the solution to match the preview, and it's possible
2426 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002427 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2428 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002429 mDirectionVector[0] = mPreviousReorderDirection[0];
2430 mDirectionVector[1] = mPreviousReorderDirection[1];
2431 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002432 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2433 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2434 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002435 }
2436 } else {
2437 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2438 mPreviousReorderDirection[0] = mDirectionVector[0];
2439 mPreviousReorderDirection[1] = mDirectionVector[1];
2440 }
2441
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002442 // Find a solution involving pushing / displacing any items in the way
2443 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002444 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2445
2446 // We attempt the approach which doesn't shuffle views at all
2447 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2448 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2449
2450 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002451
2452 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2453 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002454 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2455 finalSolution = swapSolution;
2456 } else if (noShuffleSolution.isSolution) {
2457 finalSolution = noShuffleSolution;
2458 }
2459
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002460 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002461 if (finalSolution != null) {
Adam Cohenfe692872013-12-11 14:47:23 -08002462 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
2463 ReorderPreviewAnimation.MODE_HINT);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002464 result[0] = finalSolution.dragViewX;
2465 result[1] = finalSolution.dragViewY;
2466 resultSpan[0] = finalSolution.dragViewSpanX;
2467 resultSpan[1] = finalSolution.dragViewSpanY;
2468 } else {
2469 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2470 }
2471 return result;
2472 }
2473
Adam Cohen482ed822012-03-02 14:15:13 -08002474 boolean foundSolution = true;
2475 if (!DESTRUCTIVE_REORDER) {
2476 setUseTempCoords(true);
2477 }
2478
2479 if (finalSolution != null) {
2480 result[0] = finalSolution.dragViewX;
2481 result[1] = finalSolution.dragViewY;
2482 resultSpan[0] = finalSolution.dragViewSpanX;
2483 resultSpan[1] = finalSolution.dragViewSpanY;
2484
2485 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2486 // committing anything or animating anything as we just want to determine if a solution
2487 // exists
2488 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2489 if (!DESTRUCTIVE_REORDER) {
2490 copySolutionToTempState(finalSolution, dragView);
2491 }
2492 setItemPlacementDirty(true);
2493 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2494
Adam Cohen19f37922012-03-21 11:59:11 -07002495 if (!DESTRUCTIVE_REORDER &&
2496 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002497 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002498 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002499 setItemPlacementDirty(false);
2500 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002501 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
2502 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002503 }
2504 }
2505 } else {
2506 foundSolution = false;
2507 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2508 }
2509
2510 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2511 setUseTempCoords(false);
2512 }
Adam Cohen482ed822012-03-02 14:15:13 -08002513
Michael Jurkaa52570f2012-03-20 03:18:20 -07002514 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002515 return result;
2516 }
2517
Adam Cohen19f37922012-03-21 11:59:11 -07002518 void setItemPlacementDirty(boolean dirty) {
2519 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002520 }
Adam Cohen19f37922012-03-21 11:59:11 -07002521 boolean isItemPlacementDirty() {
2522 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002523 }
2524
Adam Cohen091440a2015-03-18 14:16:05 -07002525 @Thunk class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002526 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohenf3900c22012-11-16 18:28:11 -08002527 private HashMap<View, CellAndSpan> savedMap = new HashMap<View, CellAndSpan>();
2528 ArrayList<View> sortedViews = new ArrayList<View>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002529 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002530 boolean isSolution = false;
2531 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2532
Adam Cohenf3900c22012-11-16 18:28:11 -08002533 void save() {
2534 // Copy current state into savedMap
2535 for (View v: map.keySet()) {
2536 map.get(v).copy(savedMap.get(v));
2537 }
2538 }
2539
2540 void restore() {
2541 // Restore current state from savedMap
2542 for (View v: savedMap.keySet()) {
2543 savedMap.get(v).copy(map.get(v));
2544 }
2545 }
2546
2547 void add(View v, CellAndSpan cs) {
2548 map.put(v, cs);
2549 savedMap.put(v, new CellAndSpan());
2550 sortedViews.add(v);
2551 }
2552
Adam Cohen482ed822012-03-02 14:15:13 -08002553 int area() {
2554 return dragViewSpanX * dragViewSpanY;
2555 }
Adam Cohen8baab352012-03-20 17:39:21 -07002556 }
2557
2558 private class CellAndSpan {
2559 int x, y;
2560 int spanX, spanY;
2561
Adam Cohenf3900c22012-11-16 18:28:11 -08002562 public CellAndSpan() {
2563 }
2564
2565 public void copy(CellAndSpan copy) {
2566 copy.x = x;
2567 copy.y = y;
2568 copy.spanX = spanX;
2569 copy.spanY = spanY;
2570 }
2571
Adam Cohen8baab352012-03-20 17:39:21 -07002572 public CellAndSpan(int x, int y, int spanX, int spanY) {
2573 this.x = x;
2574 this.y = y;
2575 this.spanX = spanX;
2576 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002577 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002578
2579 public String toString() {
2580 return "(" + x + ", " + y + ": " + spanX + ", " + spanY + ")";
2581 }
2582
Adam Cohen482ed822012-03-02 14:15:13 -08002583 }
2584
Adam Cohendf035382011-04-11 17:22:04 -07002585 /**
Adam Cohendf035382011-04-11 17:22:04 -07002586 * Find a starting cell position that will fit the given bounds nearest the requested
2587 * cell location. Uses Euclidean distance to score multiple vacant areas.
2588 *
2589 * @param pixelX The X location at which you want to search for a vacant area.
2590 * @param pixelY The Y location at which you want to search for a vacant area.
2591 * @param spanX Horizontal span of the object.
2592 * @param spanY Vertical span of the object.
2593 * @param ignoreView Considers space occupied by this view as unoccupied
2594 * @param result Previously returned value to possibly recycle.
2595 * @return The X, Y cell of a vacant area that can contain this object,
2596 * nearest the requested location.
2597 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002598 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2599 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002600 }
2601
Michael Jurka0280c3b2010-09-17 15:00:07 -07002602 boolean existsEmptyCell() {
2603 return findCellForSpan(null, 1, 1);
2604 }
2605
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002606 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002607 * Finds the upper-left coordinate of the first rectangle in the grid that can
2608 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2609 * then this method will only return coordinates for rectangles that contain the cell
2610 * (intersectX, intersectY)
2611 *
2612 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2613 * can be found.
2614 * @param spanX The horizontal span of the cell we want to find.
2615 * @param spanY The vertical span of the cell we want to find.
2616 *
2617 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002618 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002619 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Michael Jurka28750fb2010-09-24 17:43:49 -07002620 boolean foundCell = false;
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002621 final int endX = mCountX - (spanX - 1);
2622 final int endY = mCountY - (spanY - 1);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002623
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002624 for (int y = 0; y < endY && !foundCell; y++) {
2625 inner:
2626 for (int x = 0; x < endX; x++) {
2627 for (int i = 0; i < spanX; i++) {
2628 for (int j = 0; j < spanY; j++) {
2629 if (mOccupied[x + i][y + j]) {
2630 // small optimization: we can skip to after the column we just found
2631 // an occupied cell
2632 x += i;
2633 continue inner;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002634 }
2635 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002636 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002637 if (cellXY != null) {
2638 cellXY[0] = x;
2639 cellXY[1] = y;
2640 }
2641 foundCell = true;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002642 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002643 }
2644 }
2645
Michael Jurka28750fb2010-09-24 17:43:49 -07002646 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002647 }
2648
2649 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002650 * A drag event has begun over this layout.
2651 * It may have begun over this layout (in which case onDragChild is called first),
2652 * or it may have begun on another layout.
2653 */
2654 void onDragEnter() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002655 mDragEnforcer.onDragEnter();
Winson Chungc07918d2011-07-01 15:35:26 -07002656 mDragging = true;
2657 }
2658
2659 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002660 * Called when drag has left this CellLayout or has been completed (successfully or not)
2661 */
2662 void onDragExit() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002663 mDragEnforcer.onDragExit();
Joe Onorato4be866d2010-10-10 11:26:02 -07002664 // This can actually be called when we aren't in a drag, e.g. when adding a new
2665 // item to this layout via the customize drawer.
2666 // Guard against that case.
2667 if (mDragging) {
2668 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002669 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002670
2671 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002672 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002673 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2674 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002675 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002676 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002677 }
2678
2679 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002680 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002681 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002682 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002683 *
2684 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002685 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002686 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002687 if (child != null) {
2688 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002689 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002690 child.requestLayout();
Romain Guyd94533d2009-08-17 10:01:15 -07002691 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002692 }
2693
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002694 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002695 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002696 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002697 * @param cellX X coordinate of upper left corner expressed as a cell position
2698 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002699 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002700 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002701 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002702 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002703 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002704 final int cellWidth = mCellWidth;
2705 final int cellHeight = mCellHeight;
2706 final int widthGap = mWidthGap;
2707 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002708
Winson Chung4b825dcd2011-06-19 12:41:22 -07002709 final int hStartPadding = getPaddingLeft();
2710 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002711
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002712 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2713 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2714
2715 int x = hStartPadding + cellX * (cellWidth + widthGap);
2716 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002717
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002718 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002719 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002720
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002721 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002722 * Computes the required horizontal and vertical cell spans to always
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002723 * fit the given rectangle.
Winson Chungaafa03c2010-06-11 17:34:16 -07002724 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002725 * @param width Width in pixels
2726 * @param height Height in pixels
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002727 * @param result An array of length 2 in which to store the result (may be null).
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002728 */
Adam Cohen2e6da152015-05-06 11:42:25 -07002729 public static int[] rectToCell(Launcher launcher, int width, int height, int[] result) {
Winson Chung5f8afe62013-08-12 16:19:28 -07002730 LauncherAppState app = LauncherAppState.getInstance();
Adam Cohen2e6da152015-05-06 11:42:25 -07002731 DeviceProfile grid = launcher.getDeviceProfile();
Winson Chung66700732013-08-20 16:56:15 -07002732 Rect padding = grid.getWorkspacePadding(grid.isLandscape ?
2733 CellLayout.LANDSCAPE : CellLayout.PORTRAIT);
Winson Chung5f8afe62013-08-12 16:19:28 -07002734
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002735 // Always assume we're working with the smallest span to make sure we
2736 // reserve enough space in both orientations.
Winson Chung66700732013-08-20 16:56:15 -07002737 int parentWidth = grid.calculateCellWidth(grid.widthPx
Adam Cohen2e6da152015-05-06 11:42:25 -07002738 - padding.left - padding.right, (int) grid.inv.numColumns);
Winson Chung66700732013-08-20 16:56:15 -07002739 int parentHeight = grid.calculateCellHeight(grid.heightPx
Adam Cohen2e6da152015-05-06 11:42:25 -07002740 - padding.top - padding.bottom, (int) grid.inv.numRows);
Winson Chung66700732013-08-20 16:56:15 -07002741 int smallerSize = Math.min(parentWidth, parentHeight);
Joe Onorato79e56262009-09-21 15:23:04 -04002742
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002743 // Always round up to next largest cell
Winson Chung54c725c2011-08-03 12:03:40 -07002744 int spanX = (int) Math.ceil(width / (float) smallerSize);
2745 int spanY = (int) Math.ceil(height / (float) smallerSize);
Joe Onorato79e56262009-09-21 15:23:04 -04002746
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002747 if (result == null) {
2748 return new int[] { spanX, spanY };
2749 }
2750 result[0] = spanX;
2751 result[1] = spanY;
2752 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002753 }
2754
2755 /**
Patrick Dubroy047379a2010-12-19 22:02:04 -08002756 * Calculate the grid spans needed to fit given item
2757 */
2758 public void calculateSpans(ItemInfo info) {
2759 final int minWidth;
2760 final int minHeight;
2761
2762 if (info instanceof LauncherAppWidgetInfo) {
2763 minWidth = ((LauncherAppWidgetInfo) info).minWidth;
2764 minHeight = ((LauncherAppWidgetInfo) info).minHeight;
2765 } else if (info instanceof PendingAddWidgetInfo) {
2766 minWidth = ((PendingAddWidgetInfo) info).minWidth;
2767 minHeight = ((PendingAddWidgetInfo) info).minHeight;
2768 } else {
2769 // It's not a widget, so it must be 1x1
2770 info.spanX = info.spanY = 1;
2771 return;
2772 }
Adam Cohen2e6da152015-05-06 11:42:25 -07002773 int[] spans = rectToCell(mLauncher, minWidth, minHeight, null);
Patrick Dubroy047379a2010-12-19 22:02:04 -08002774 info.spanX = spans[0];
2775 info.spanY = spans[1];
2776 }
2777
Michael Jurka0280c3b2010-09-17 15:00:07 -07002778 private void clearOccupiedCells() {
2779 for (int x = 0; x < mCountX; x++) {
2780 for (int y = 0; y < mCountY; y++) {
2781 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002782 }
2783 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002784 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002785
Adam Cohend4844c32011-02-18 19:25:06 -08002786 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002787 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002788 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002789 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002790 }
2791
Adam Cohend4844c32011-02-18 19:25:06 -08002792 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002793 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002794 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002795 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002796 }
2797
Adam Cohen482ed822012-03-02 14:15:13 -08002798 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2799 boolean value) {
2800 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002801 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2802 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002803 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002804 }
2805 }
2806 }
2807
Adam Cohen2801caf2011-05-13 20:57:39 -07002808 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002809 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002810 (Math.max((mCountX - 1), 0) * mWidthGap);
2811 }
2812
2813 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002814 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002815 (Math.max((mCountY - 1), 0) * mHeightGap);
2816 }
2817
Michael Jurka66d72172011-04-12 16:29:25 -07002818 public boolean isOccupied(int x, int y) {
2819 if (x < mCountX && y < mCountY) {
2820 return mOccupied[x][y];
2821 } else {
2822 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2823 }
2824 }
2825
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002826 @Override
2827 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2828 return new CellLayout.LayoutParams(getContext(), attrs);
2829 }
2830
2831 @Override
2832 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2833 return p instanceof CellLayout.LayoutParams;
2834 }
2835
2836 @Override
2837 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2838 return new CellLayout.LayoutParams(p);
2839 }
2840
2841 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2842 /**
2843 * Horizontal location of the item in the grid.
2844 */
2845 @ViewDebug.ExportedProperty
2846 public int cellX;
2847
2848 /**
2849 * Vertical location of the item in the grid.
2850 */
2851 @ViewDebug.ExportedProperty
2852 public int cellY;
2853
2854 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002855 * Temporary horizontal location of the item in the grid during reorder
2856 */
2857 public int tmpCellX;
2858
2859 /**
2860 * Temporary vertical location of the item in the grid during reorder
2861 */
2862 public int tmpCellY;
2863
2864 /**
2865 * Indicates that the temporary coordinates should be used to layout the items
2866 */
2867 public boolean useTmpCoords;
2868
2869 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002870 * Number of cells spanned horizontally by the item.
2871 */
2872 @ViewDebug.ExportedProperty
2873 public int cellHSpan;
2874
2875 /**
2876 * Number of cells spanned vertically by the item.
2877 */
2878 @ViewDebug.ExportedProperty
2879 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002880
Adam Cohen1b607ed2011-03-03 17:26:50 -08002881 /**
2882 * Indicates whether the item will set its x, y, width and height parameters freely,
2883 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2884 */
Adam Cohend4844c32011-02-18 19:25:06 -08002885 public boolean isLockedToGrid = true;
2886
Adam Cohen482ed822012-03-02 14:15:13 -08002887 /**
Adam Cohenec40b2b2013-07-23 15:52:40 -07002888 * Indicates that this item should use the full extents of its parent.
2889 */
2890 public boolean isFullscreen = false;
2891
2892 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002893 * Indicates whether this item can be reordered. Always true except in the case of the
2894 * the AllApps button.
2895 */
2896 public boolean canReorder = true;
2897
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002898 // X coordinate of the view in the layout.
2899 @ViewDebug.ExportedProperty
2900 int x;
2901 // Y coordinate of the view in the layout.
2902 @ViewDebug.ExportedProperty
2903 int y;
2904
Romain Guy84f296c2009-11-04 15:00:44 -08002905 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002906
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002907 public LayoutParams(Context c, AttributeSet attrs) {
2908 super(c, attrs);
2909 cellHSpan = 1;
2910 cellVSpan = 1;
2911 }
2912
2913 public LayoutParams(ViewGroup.LayoutParams source) {
2914 super(source);
2915 cellHSpan = 1;
2916 cellVSpan = 1;
2917 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002918
2919 public LayoutParams(LayoutParams source) {
2920 super(source);
2921 this.cellX = source.cellX;
2922 this.cellY = source.cellY;
2923 this.cellHSpan = source.cellHSpan;
2924 this.cellVSpan = source.cellVSpan;
2925 }
2926
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002927 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002928 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002929 this.cellX = cellX;
2930 this.cellY = cellY;
2931 this.cellHSpan = cellHSpan;
2932 this.cellVSpan = cellVSpan;
2933 }
2934
Adam Cohen2374abf2013-04-16 14:56:57 -07002935 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap,
2936 boolean invertHorizontally, int colCount) {
Adam Cohend4844c32011-02-18 19:25:06 -08002937 if (isLockedToGrid) {
2938 final int myCellHSpan = cellHSpan;
2939 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002940 int myCellX = useTmpCoords ? tmpCellX : cellX;
2941 int myCellY = useTmpCoords ? tmpCellY : cellY;
2942
2943 if (invertHorizontally) {
2944 myCellX = colCount - myCellX - cellHSpan;
2945 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002946
Adam Cohend4844c32011-02-18 19:25:06 -08002947 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2948 leftMargin - rightMargin;
2949 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2950 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002951 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2952 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002953 }
2954 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002955
Winson Chungaafa03c2010-06-11 17:34:16 -07002956 public String toString() {
2957 return "(" + this.cellX + ", " + this.cellY + ")";
2958 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002959
2960 public void setWidth(int width) {
2961 this.width = width;
2962 }
2963
2964 public int getWidth() {
2965 return width;
2966 }
2967
2968 public void setHeight(int height) {
2969 this.height = height;
2970 }
2971
2972 public int getHeight() {
2973 return height;
2974 }
2975
2976 public void setX(int x) {
2977 this.x = x;
2978 }
2979
2980 public int getX() {
2981 return x;
2982 }
2983
2984 public void setY(int y) {
2985 this.y = y;
2986 }
2987
2988 public int getY() {
2989 return y;
2990 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002991 }
2992
Michael Jurka0280c3b2010-09-17 15:00:07 -07002993 // This class stores info for two purposes:
2994 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2995 // its spanX, spanY, and the screen it is on
2996 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2997 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2998 // the CellLayout that was long clicked
Sunny Goyal83a8f042015-05-19 12:52:12 -07002999 public static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003000 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07003001 int cellX = -1;
3002 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003003 int spanX;
3004 int spanY;
Adam Cohendcd297f2013-06-18 13:13:40 -07003005 long screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07003006 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003007
Sunny Goyal83a8f042015-05-19 12:52:12 -07003008 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07003009 cell = v;
3010 cellX = info.cellX;
3011 cellY = info.cellY;
3012 spanX = info.spanX;
3013 spanY = info.spanY;
3014 screenId = info.screenId;
3015 container = info.container;
3016 }
3017
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003018 @Override
3019 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07003020 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
3021 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003022 }
3023 }
Michael Jurkad771c962011-08-09 15:00:48 -07003024
3025 public boolean lastDownOnOccupiedCell() {
3026 return mLastDownOnOccupiedCell;
3027 }
Sunny Goyala9116722015-04-29 13:55:58 -07003028
3029 public boolean findVacantCell(int spanX, int spanY, int[] outXY) {
3030 return Utilities.findVacantCell(outXY, spanX, spanY, mCountX, mCountY, mOccupied);
3031 }
Sunny Goyal9ca9c132015-04-29 14:57:22 -07003032
3033 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
3034 int x2 = x + spanX - 1;
3035 int y2 = y + spanY - 1;
3036 if (x < 0 || y < 0 || x2 >= mCountX || y2 >= mCountY) {
3037 return false;
3038 }
3039 for (int i = x; i <= x2; i++) {
3040 for (int j = y; j <= y2; j++) {
3041 if (mOccupied[i][j]) {
3042 return false;
3043 }
3044 }
3045 }
3046
3047 return true;
3048 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003049}