blob: af37033146c1ab209e5281db0e17aabc4319e961 [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;
Chet Haase00397b12010-10-07 11:13:10 -070021import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070022import android.animation.ValueAnimator;
23import android.animation.ValueAnimator.AnimatorUpdateListener;
Adam Cohenc9735cf2015-01-23 16:11:55 -080024import android.annotation.TargetApi;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040026import android.content.res.Resources;
Joe Onorato4be866d2010-10-10 11:26:02 -070027import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070028import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080029import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070030import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070031import android.graphics.Point;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080033import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070034import android.graphics.drawable.Drawable;
Sunny Goyal26119432016-02-18 22:09:23 +000035import android.graphics.drawable.GradientDrawable;
Sunny Goyal2805e632015-05-20 15:35:32 -070036import android.graphics.drawable.TransitionDrawable;
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;
Sunny Goyalaa8ef112015-06-12 20:04:41 -070051import com.android.launcher3.LauncherSettings.Favorites;
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;
Tony Wickhame0c33232016-02-08 11:37:04 -080055import com.android.launcher3.config.FeatureFlags;
Sunny Goyal6c56c682015-07-16 14:09:05 -070056import com.android.launcher3.config.ProviderConfig;
Sunny Goyal26119432016-02-18 22:09:23 +000057import com.android.launcher3.folder.FolderIcon;
Sunny Goyale2fd14b2015-08-27 17:45:46 -070058import com.android.launcher3.util.ParcelableSparseArray;
Adam Cohen091440a2015-03-18 14:16:05 -070059import com.android.launcher3.util.Thunk;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070060
Adam Cohen69ce2e52011-07-03 19:25:21 -070061import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070062import java.util.Arrays;
Adam Cohenf3900c22012-11-16 18:28:11 -080063import java.util.Collections;
64import java.util.Comparator;
Adam Cohenbfbfd262011-06-13 16:55:12 -070065import java.util.HashMap;
Adam Cohend41fbf52012-02-16 23:53:59 -080066import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070067
Sunny Goyal4b6eb262015-05-14 19:24:40 -070068public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
Sunny Goyale9b651e2015-04-24 11:44:51 -070069 public static final int WORKSPACE_ACCESSIBILITY_DRAG = 2;
70 public static final int FOLDER_ACCESSIBILITY_DRAG = 1;
71
Tony Wickhama0628cc2015-10-14 15:23:04 -070072 private static final String TAG = "CellLayout";
73 private static final boolean LOGD = false;
Winson Chungaafa03c2010-06-11 17:34:16 -070074
Adam Cohen2acce882012-03-28 19:03:19 -070075 private Launcher mLauncher;
Sunny Goyal4ffec482016-02-09 11:28:52 -080076 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070077 @Thunk int mCellWidth;
Sunny Goyal4ffec482016-02-09 11:28:52 -080078 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070079 @Thunk int mCellHeight;
Winson Chung11a1a532013-09-13 11:14:45 -070080 private int mFixedCellWidth;
81 private int mFixedCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070082
Sunny Goyal4ffec482016-02-09 11:28:52 -080083 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070084 @Thunk int mCountX;
Sunny Goyal4ffec482016-02-09 11:28:52 -080085 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070086 @Thunk int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Adam Cohen234c4cd2011-07-17 21:03:04 -070088 private int mOriginalWidthGap;
89 private int mOriginalHeightGap;
Sunny Goyal4ffec482016-02-09 11:28:52 -080090 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070091 @Thunk int mWidthGap;
Sunny Goyal4ffec482016-02-09 11:28:52 -080092 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070093 @Thunk int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070094 private int mMaxGap;
Adam Cohen917e3882013-10-31 15:03:35 -070095 private boolean mDropPending = false;
Adam Cohenc50438c2014-08-19 17:43:05 -070096 private boolean mIsDragTarget = true;
Sunny Goyale2fd14b2015-08-27 17:45:46 -070097 private boolean mJailContent = true;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098
Patrick Dubroyde7658b2010-09-27 11:15:43 -070099 // These are temporary variables to prevent having to allocate a new object just to
100 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Adam Cohen091440a2015-03-18 14:16:05 -0700101 @Thunk final int[] mTmpPoint = new int[2];
Sunny Goyal2805e632015-05-20 15:35:32 -0700102 @Thunk final int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700103
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -0800105 boolean[][] mTmpOccupied;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800106
Michael Jurkadee05892010-07-27 10:01:56 -0700107 private OnTouchListener mInterceptTouchListener;
Mady Melloref044dd2015-06-02 15:35:07 -0700108 private StylusEventHelper mStylusEventHelper;
Michael Jurkadee05892010-07-27 10:01:56 -0700109
Adam Cohenefca0272016-02-24 19:19:06 -0800110 private ArrayList<FolderIcon.PreviewBackground> mFolderBackgrounds = new ArrayList<FolderIcon.PreviewBackground>();
111 FolderIcon.PreviewBackground mFolderLeaveBehind = new FolderIcon.PreviewBackground();
112 Paint mFolderBgPaint = new Paint();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700113
Michael Jurka5f1c5092010-09-03 14:15:02 -0700114 private float mBackgroundAlpha;
Adam Cohenf34bab52010-09-30 14:11:56 -0700115
Sunny Goyal2805e632015-05-20 15:35:32 -0700116 private static final int BACKGROUND_ACTIVATE_DURATION = 120;
117 private final TransitionDrawable mBackground;
118
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700119 // These values allow a fixed measurement to be set on the CellLayout.
120 private int mFixedWidth = -1;
121 private int mFixedHeight = -1;
122
Michael Jurka33945b22010-12-21 18:19:38 -0800123 // If we're actively dragging something over this screen, mIsDragOverlapping is true
124 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700125
Winson Chung150fbab2010-09-29 17:14:26 -0700126 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700127 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohen091440a2015-03-18 14:16:05 -0700128 @Thunk Rect[] mDragOutlines = new Rect[4];
129 @Thunk float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700130 private InterruptibleInOutAnimator[] mDragOutlineAnims =
131 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700132
133 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700134 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700135 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700136
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700137 private final ClickShadowView mTouchFeedbackView;
Patrick Dubroy96864c32011-03-10 17:17:23 -0800138
Sunny Goyal316490e2015-06-02 09:38:28 -0700139 @Thunk HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new HashMap<>();
140 @Thunk HashMap<View, ReorderPreviewAnimation> mShakeAnimators = new HashMap<>();
Adam Cohen19f37922012-03-21 11:59:11 -0700141
142 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700143
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700144 // When a drag operation is in progress, holds the nearest cell to the touch point
145 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800146
Joe Onorato4be866d2010-10-10 11:26:02 -0700147 private boolean mDragging = false;
148
Patrick Dubroyce34a972010-10-19 10:34:32 -0700149 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700150 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700151
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800152 private boolean mIsHotseat = false;
Adam Cohen307fe232012-08-16 17:55:58 -0700153 private float mHotseatScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800154
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800155 public static final int MODE_SHOW_REORDER_HINT = 0;
156 public static final int MODE_DRAG_OVER = 1;
157 public static final int MODE_ON_DROP = 2;
158 public static final int MODE_ON_DROP_EXTERNAL = 3;
159 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700160 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800161 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
162
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800163 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700164 private static final int REORDER_ANIMATION_DURATION = 150;
Adam Cohen091440a2015-03-18 14:16:05 -0700165 @Thunk float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700166
Adam Cohen482ed822012-03-02 14:15:13 -0800167 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
168 private Rect mOccupiedRect = new Rect();
169 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700170 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700171 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800172
Sunny Goyal2805e632015-05-20 15:35:32 -0700173 private final Rect mTempRect = new Rect();
Winson Chung3a6e7f32013-10-09 15:50:52 -0700174
Michael Jurkaca993832012-06-29 15:17:04 -0700175 private final static Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700176
Adam Cohenc9735cf2015-01-23 16:11:55 -0800177 // Related to accessible drag and drop
Sunny Goyale9b651e2015-04-24 11:44:51 -0700178 private DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800179 private boolean mUseTouchHelper = false;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800180
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 public CellLayout(Context context) {
182 this(context, null);
183 }
184
185 public CellLayout(Context context, AttributeSet attrs) {
186 this(context, attrs, 0);
187 }
188
189 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
190 super(context, attrs, defStyle);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700191
192 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
193 // the user where a dragged item will land when dropped.
194 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800195 setClipToPadding(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700196 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700197
Adam Cohen2e6da152015-05-06 11:42:25 -0700198 DeviceProfile grid = mLauncher.getDeviceProfile();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800199
Winson Chung11a1a532013-09-13 11:14:45 -0700200 mCellWidth = mCellHeight = -1;
Nilesh Agrawal5f7099a2014-01-02 15:54:57 -0800201 mFixedCellWidth = mFixedCellHeight = -1;
Winson Chung5f8afe62013-08-12 16:19:28 -0700202 mWidthGap = mOriginalWidthGap = 0;
203 mHeightGap = mOriginalHeightGap = 0;
204 mMaxGap = Integer.MAX_VALUE;
Adam Cohen2e6da152015-05-06 11:42:25 -0700205 mCountX = (int) grid.inv.numColumns;
206 mCountY = (int) grid.inv.numRows;
Michael Jurka0280c3b2010-09-17 15:00:07 -0700207 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800208 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700209 mPreviousReorderDirection[0] = INVALID_DIRECTION;
210 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800211
Adam Cohenefca0272016-02-24 19:19:06 -0800212 mFolderLeaveBehind.delegateCellX = -1;
213 mFolderLeaveBehind.delegateCellY = -1;
214
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800215 setAlwaysDrawnWithCacheEnabled(false);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700216 final Resources res = getResources();
Winson Chung6e1c0d32013-10-25 15:24:24 -0700217 mHotseatScale = (float) grid.hotseatIconSizePx / grid.iconSizePx;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700218
Tony Wickhame0c33232016-02-08 11:37:04 -0800219 mBackground = (TransitionDrawable) res.getDrawable(
220 FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND ? R.drawable.bg_screenpanel
221 : R.drawable.bg_celllayout);
Sunny Goyal2805e632015-05-20 15:35:32 -0700222 mBackground.setCallback(this);
Winson Chunge8f1d042015-07-31 12:39:57 -0700223 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurka33945b22010-12-21 18:19:38 -0800224
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800225 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE *
Winson Chung5f8afe62013-08-12 16:19:28 -0700226 grid.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700227
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700228 // Initialize the data structures used for the drag visualization.
Patrick Dubroyce34a972010-10-19 10:34:32 -0700229 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700230 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700231 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800232 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700233 }
234
235 // When dragging things around the home screens, we show a green outline of
236 // where the item will land. The outlines gradually fade out, leaving a trail
237 // behind the drag path.
238 // Set up all the animations that are used to implement this fading.
239 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700240 final float fromAlphaValue = 0;
241 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700242
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700243 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700244
245 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700246 final InterruptibleInOutAnimator anim =
Michael Jurkaf1ad6082013-03-13 12:55:46 +0100247 new InterruptibleInOutAnimator(this, duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700248 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700249 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700250 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700251 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700252 final Bitmap outline = (Bitmap)anim.getTag();
253
254 // If an animation is started and then stopped very quickly, we can still
255 // get spurious updates we've cleared the tag. Guard against this.
256 if (outline == null) {
Tony Wickhama0628cc2015-10-14 15:23:04 -0700257 if (LOGD) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700258 Object val = animation.getAnimatedValue();
259 Log.d(TAG, "anim " + thisIndex + " update: " + val +
260 ", isStopped " + anim.isStopped());
261 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700262 // Try to prevent it from continuing to run
263 animation.cancel();
264 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700265 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800266 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700267 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700268 }
269 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700270 // The animation holds a reference to the drag outline bitmap as long is it's
271 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700272 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700273 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700274 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700275 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700276 anim.setTag(null);
277 }
278 }
279 });
280 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700281 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700282
Michael Jurkaa52570f2012-03-20 03:18:20 -0700283 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
Adam Cohen2374abf2013-04-16 14:56:57 -0700284 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700285 mCountX, mCountY);
Adam Cohen2374abf2013-04-16 14:56:57 -0700286
Mady Mellorbb835202015-07-15 16:34:34 -0700287 mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
Mady Melloref044dd2015-06-02 15:35:07 -0700288
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700289 mTouchFeedbackView = new ClickShadowView(context);
290 addView(mTouchFeedbackView);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700291 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700292 }
293
Adam Cohenc9735cf2015-01-23 16:11:55 -0800294 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
Sunny Goyale9b651e2015-04-24 11:44:51 -0700295 public void enableAccessibleDrag(boolean enable, int dragType) {
Adam Cohenc9735cf2015-01-23 16:11:55 -0800296 mUseTouchHelper = enable;
297 if (!enable) {
298 ViewCompat.setAccessibilityDelegate(this, null);
299 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
300 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
301 setOnClickListener(mLauncher);
302 } else {
Sunny Goyale9b651e2015-04-24 11:44:51 -0700303 if (dragType == WORKSPACE_ACCESSIBILITY_DRAG &&
304 !(mTouchHelper instanceof WorkspaceAccessibilityHelper)) {
305 mTouchHelper = new WorkspaceAccessibilityHelper(this);
306 } else if (dragType == FOLDER_ACCESSIBILITY_DRAG &&
307 !(mTouchHelper instanceof FolderAccessibilityHelper)) {
308 mTouchHelper = new FolderAccessibilityHelper(this);
309 }
Adam Cohenc9735cf2015-01-23 16:11:55 -0800310 ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
311 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
312 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
313 setOnClickListener(mTouchHelper);
314 }
315
316 // Invalidate the accessibility hierarchy
317 if (getParent() != null) {
318 getParent().notifySubtreeAccessibilityStateChanged(
319 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
320 }
321 }
322
323 @Override
324 public boolean dispatchHoverEvent(MotionEvent event) {
325 // Always attempt to dispatch hover events to accessibility first.
326 if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
327 return true;
328 }
329 return super.dispatchHoverEvent(event);
330 }
331
332 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800333 public boolean onInterceptTouchEvent(MotionEvent ev) {
334 if (mUseTouchHelper ||
335 (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
336 return true;
337 }
338 return false;
339 }
340
Mady Melloref044dd2015-06-02 15:35:07 -0700341 @Override
342 public boolean onTouchEvent(MotionEvent ev) {
343 boolean handled = super.onTouchEvent(ev);
344 // Stylus button press on a home screen should not switch between overview mode and
345 // the home screen mode, however, once in overview mode stylus button press should be
346 // enabled to allow rearranging the different home screens. So check what mode
347 // the workspace is in, and only perform stylus button presses while in overview mode.
348 if (mLauncher.mWorkspace.isInOverviewMode()
Mady Mellorbb835202015-07-15 16:34:34 -0700349 && mStylusEventHelper.onMotionEvent(ev)) {
Mady Melloref044dd2015-06-02 15:35:07 -0700350 return true;
351 }
352 return handled;
353 }
354
Chris Craik01f2d7f2013-10-01 14:41:56 -0700355 public void enableHardwareLayer(boolean hasLayer) {
356 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700357 }
358
359 public void buildHardwareLayer() {
360 mShortcutsAndWidgets.buildLayer();
Adam Cohen2801caf2011-05-13 20:57:39 -0700361 }
362
Adam Cohen307fe232012-08-16 17:55:58 -0700363 public float getChildrenScale() {
364 return mIsHotseat ? mHotseatScale : 1.0f;
365 }
366
Winson Chung5f8afe62013-08-12 16:19:28 -0700367 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700368 mFixedCellWidth = mCellWidth = width;
369 mFixedCellHeight = mCellHeight = height;
Winson Chung5f8afe62013-08-12 16:19:28 -0700370 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
371 mCountX, mCountY);
372 }
373
Adam Cohen2801caf2011-05-13 20:57:39 -0700374 public void setGridSize(int x, int y) {
375 mCountX = x;
376 mCountY = y;
377 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800378 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700379 mTempRectStack.clear();
Adam Cohen2374abf2013-04-16 14:56:57 -0700380 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700381 mCountX, mCountY);
Adam Cohen76fc0852011-06-17 13:26:23 -0700382 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700383 }
384
Adam Cohen2374abf2013-04-16 14:56:57 -0700385 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
386 public void setInvertIfRtl(boolean invert) {
387 mShortcutsAndWidgets.setInvertIfRtl(invert);
388 }
389
Adam Cohen917e3882013-10-31 15:03:35 -0700390 public void setDropPending(boolean pending) {
391 mDropPending = pending;
392 }
393
394 public boolean isDropPending() {
395 return mDropPending;
396 }
397
Sunny Goyal4b6eb262015-05-14 19:24:40 -0700398 @Override
399 public void setPressedIcon(BubbleTextView icon, Bitmap background) {
Sunny Goyal508da152014-08-14 10:53:27 -0700400 if (icon == null || background == null) {
401 mTouchFeedbackView.setBitmap(null);
402 mTouchFeedbackView.animate().cancel();
403 } else {
Sunny Goyal508da152014-08-14 10:53:27 -0700404 if (mTouchFeedbackView.setBitmap(background)) {
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700405 mTouchFeedbackView.alignWithIconView(icon, mShortcutsAndWidgets);
406 mTouchFeedbackView.animateShadow();
Sunny Goyal508da152014-08-14 10:53:27 -0700407 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800408 }
409 }
410
Adam Cohenc50438c2014-08-19 17:43:05 -0700411 void disableDragTarget() {
412 mIsDragTarget = false;
413 }
414
Tony Wickham0f97b782015-12-02 17:55:07 -0800415 public boolean isDragTarget() {
416 return mIsDragTarget;
417 }
418
Adam Cohenc50438c2014-08-19 17:43:05 -0700419 void setIsDragOverlapping(boolean isDragOverlapping) {
420 if (mIsDragOverlapping != isDragOverlapping) {
421 mIsDragOverlapping = isDragOverlapping;
Sunny Goyal2805e632015-05-20 15:35:32 -0700422 if (mIsDragOverlapping) {
423 mBackground.startTransition(BACKGROUND_ACTIVATE_DURATION);
424 } else {
Winson Chunge8f1d042015-07-31 12:39:57 -0700425 if (mBackgroundAlpha > 0f) {
426 mBackground.reverseTransition(BACKGROUND_ACTIVATE_DURATION);
427 } else {
428 mBackground.resetTransition();
429 }
Sunny Goyal2805e632015-05-20 15:35:32 -0700430 }
Adam Cohenc50438c2014-08-19 17:43:05 -0700431 invalidate();
432 }
433 }
434
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700435 public void disableJailContent() {
436 mJailContent = false;
437 }
438
439 @Override
440 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
441 if (mJailContent) {
442 ParcelableSparseArray jail = getJailedArray(container);
443 super.dispatchSaveInstanceState(jail);
444 container.put(R.id.cell_layout_jail_id, jail);
445 } else {
446 super.dispatchSaveInstanceState(container);
447 }
448 }
449
450 @Override
451 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
452 super.dispatchRestoreInstanceState(mJailContent ? getJailedArray(container) : container);
453 }
454
455 private ParcelableSparseArray getJailedArray(SparseArray<Parcelable> container) {
456 final Parcelable parcelable = container.get(R.id.cell_layout_jail_id);
457 return parcelable instanceof ParcelableSparseArray ?
458 (ParcelableSparseArray) parcelable : new ParcelableSparseArray();
459 }
460
Tony Wickham0f97b782015-12-02 17:55:07 -0800461 public boolean getIsDragOverlapping() {
462 return mIsDragOverlapping;
463 }
464
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700465 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700466 protected void onDraw(Canvas canvas) {
Sunny Goyal05739772015-05-19 19:59:09 -0700467 if (!mIsDragTarget) {
468 return;
469 }
470
Michael Jurka3e7c7632010-10-02 16:01:03 -0700471 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
472 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
473 // When we're small, we are either drawn normally or in the "accepts drops" state (during
474 // a drag). However, we also drag the mini hover background *over* one of those two
475 // backgrounds
Sunny Goyal05739772015-05-19 19:59:09 -0700476 if (mBackgroundAlpha > 0.0f) {
Sunny Goyal2805e632015-05-20 15:35:32 -0700477 mBackground.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700478 }
Romain Guya6abce82009-11-10 02:54:41 -0800479
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700480 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700481 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700482 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700483 if (alpha > 0) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700484 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700485 paint.setAlpha((int)(alpha + .5f));
Sunny Goyal106bf642015-07-16 12:18:06 -0700486 canvas.drawBitmap(b, null, mDragOutlines[i], paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700487 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700488 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800489
Adam Cohen482ed822012-03-02 14:15:13 -0800490 if (DEBUG_VISUALIZE_OCCUPIED) {
491 int[] pt = new int[2];
492 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700493 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800494 for (int i = 0; i < mCountX; i++) {
495 for (int j = 0; j < mCountY; j++) {
496 if (mOccupied[i][j]) {
497 cellToPoint(i, j, pt);
498 canvas.save();
499 canvas.translate(pt[0], pt[1]);
500 cd.draw(canvas);
501 canvas.restore();
502 }
503 }
504 }
505 }
506
Adam Cohenefca0272016-02-24 19:19:06 -0800507 for (int i = 0; i < mFolderBackgrounds.size(); i++) {
508 FolderIcon.PreviewBackground bg = mFolderBackgrounds.get(i);
509 cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
510 canvas.save();
511 canvas.translate(mTempLocation[0], mTempLocation[1]);
512 bg.drawBackground(canvas, mFolderBgPaint);
513 canvas.restore();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700514 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700515
Adam Cohenefca0272016-02-24 19:19:06 -0800516 if (mFolderLeaveBehind.delegateCellX >= 0 && mFolderLeaveBehind.delegateCellY >= 0) {
517 cellToPoint(mFolderLeaveBehind.delegateCellX,
518 mFolderLeaveBehind.delegateCellY, mTempLocation);
519 canvas.save();
520 canvas.translate(mTempLocation[0], mTempLocation[1]);
521 mFolderLeaveBehind.drawLeaveBehind(canvas, mFolderBgPaint);
522 canvas.restore();
Adam Cohenc51934b2011-07-26 21:07:43 -0700523 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700524 }
525
Adam Cohenefca0272016-02-24 19:19:06 -0800526 @Override
527 protected void dispatchDraw(Canvas canvas) {
528 super.dispatchDraw(canvas);
529
530 for (int i = 0; i < mFolderBackgrounds.size(); i++) {
531 FolderIcon.PreviewBackground bg = mFolderBackgrounds.get(i);
532 cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
533 canvas.save();
534 canvas.translate(mTempLocation[0], mTempLocation[1]);
535 bg.drawBackgroundStroke(canvas, mFolderBgPaint);
536 canvas.restore();
537 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700538 }
539
Adam Cohenefca0272016-02-24 19:19:06 -0800540 public void addFolderBackground(FolderIcon.PreviewBackground bg) {
541 mFolderBackgrounds.add(bg);
542 }
543 public void removeFolderBackground(FolderIcon.PreviewBackground bg) {
544 mFolderBackgrounds.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700545 }
546
Adam Cohenc51934b2011-07-26 21:07:43 -0700547 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800548
549 DeviceProfile grid = mLauncher.getDeviceProfile();
550 View child = getChildAt(x, y);
551
552 mFolderLeaveBehind.setup(getResources().getDisplayMetrics(), grid, null,
553 child.getMeasuredWidth(), child.getPaddingTop());
554
555 mFolderLeaveBehind.delegateCellX = x;
556 mFolderLeaveBehind.delegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700557 invalidate();
558 }
559
560 public void clearFolderLeaveBehind() {
Adam Cohenefca0272016-02-24 19:19:06 -0800561 mFolderLeaveBehind.delegateCellX = -1;
562 mFolderLeaveBehind.delegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700563 invalidate();
564 }
565
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700566 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700567 public boolean shouldDelayChildPressedState() {
568 return false;
569 }
570
Adam Cohen1462de32012-07-24 22:34:36 -0700571 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700572 try {
573 dispatchRestoreInstanceState(states);
574 } catch (IllegalArgumentException ex) {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700575 if (ProviderConfig.IS_DOGFOOD_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700576 throw ex;
577 }
578 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
579 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
580 }
Adam Cohen1462de32012-07-24 22:34:36 -0700581 }
582
Michael Jurkae6235dd2011-10-04 15:02:05 -0700583 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700584 public void cancelLongPress() {
585 super.cancelLongPress();
586
587 // Cancel long press for all children
588 final int count = getChildCount();
589 for (int i = 0; i < count; i++) {
590 final View child = getChildAt(i);
591 child.cancelLongPress();
592 }
593 }
594
Michael Jurkadee05892010-07-27 10:01:56 -0700595 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
596 mInterceptTouchListener = listener;
597 }
598
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800599 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700600 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800601 }
602
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800603 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700604 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800605 }
606
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800607 public void setIsHotseat(boolean isHotseat) {
608 mIsHotseat = isHotseat;
Winson Chung5f8afe62013-08-12 16:19:28 -0700609 mShortcutsAndWidgets.setIsHotseat(isHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800610 }
611
Sunny Goyale9b651e2015-04-24 11:44:51 -0700612 public boolean isHotseat() {
613 return mIsHotseat;
614 }
615
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800616 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700617 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700618 final LayoutParams lp = params;
619
Andrew Flynnde38e422012-05-08 11:22:15 -0700620 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800621 if (child instanceof BubbleTextView) {
622 BubbleTextView bubbleChild = (BubbleTextView) child;
Winson Chung5f8afe62013-08-12 16:19:28 -0700623 bubbleChild.setTextVisibility(!mIsHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800624 }
625
Adam Cohen307fe232012-08-16 17:55:58 -0700626 child.setScaleX(getChildrenScale());
627 child.setScaleY(getChildrenScale());
628
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629 // Generate an id for each view, this assumes we have at most 256x256 cells
630 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700631 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700632 // If the horizontal or vertical span is set to -1, it is taken to
633 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700634 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
635 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800636
Winson Chungaafa03c2010-06-11 17:34:16 -0700637 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700638 if (LOGD) {
639 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
640 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700641 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700642
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700643 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700644
Winson Chungaafa03c2010-06-11 17:34:16 -0700645 return true;
646 }
647 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800648 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700649
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800650 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700651 public void removeAllViews() {
652 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700653 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700654 }
655
656 @Override
657 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700658 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700659 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700660 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700661 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700662 }
663
664 @Override
665 public void removeView(View view) {
666 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700667 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700668 }
669
670 @Override
671 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700672 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
673 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700674 }
675
676 @Override
677 public void removeViewInLayout(View view) {
678 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700679 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700680 }
681
682 @Override
683 public void removeViews(int start, int count) {
684 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700685 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700686 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700687 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700688 }
689
690 @Override
691 public void removeViewsInLayout(int start, int count) {
692 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700693 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700694 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700695 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800696 }
697
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700698 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700699 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800700 * @param x X coordinate of the point
701 * @param y Y coordinate of the point
702 * @param result Array of 2 ints to hold the x and y coordinate of the cell
703 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700704 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700705 final int hStartPadding = getPaddingLeft();
706 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800707
708 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
709 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
710
Adam Cohend22015c2010-07-26 22:02:18 -0700711 final int xAxis = mCountX;
712 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800713
714 if (result[0] < 0) result[0] = 0;
715 if (result[0] >= xAxis) result[0] = xAxis - 1;
716 if (result[1] < 0) result[1] = 0;
717 if (result[1] >= yAxis) result[1] = yAxis - 1;
718 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700719
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800720 /**
721 * Given a point, return the cell that most closely encloses that point
722 * @param x X coordinate of the point
723 * @param y Y coordinate of the point
724 * @param result Array of 2 ints to hold the x and y coordinate of the cell
725 */
726 void pointToCellRounded(int x, int y, int[] result) {
727 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
728 }
729
730 /**
731 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700732 *
733 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800734 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700735 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800736 * @param result Array of 2 ints to hold the x and y coordinate of the point
737 */
738 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700739 final int hStartPadding = getPaddingLeft();
740 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800741
742 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
743 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
744 }
745
Adam Cohene3e27a82011-04-15 12:07:39 -0700746 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800747 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700748 *
749 * @param cellX X coordinate of the cell
750 * @param cellY Y coordinate of the cell
751 *
752 * @param result Array of 2 ints to hold the x and y coordinate of the point
753 */
754 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700755 regionToCenterPoint(cellX, cellY, 1, 1, result);
756 }
757
758 /**
759 * Given a cell coordinate and span return the point that represents the center of the regio
760 *
761 * @param cellX X coordinate of the cell
762 * @param cellY Y coordinate of the cell
763 *
764 * @param result Array of 2 ints to hold the x and y coordinate of the point
765 */
766 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700767 final int hStartPadding = getPaddingLeft();
768 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700769 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
770 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
771 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
772 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700773 }
774
Adam Cohen19f37922012-03-21 11:59:11 -0700775 /**
776 * Given a cell coordinate and span fills out a corresponding pixel rect
777 *
778 * @param cellX X coordinate of the cell
779 * @param cellY Y coordinate of the cell
780 * @param result Rect in which to write the result
781 */
782 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
783 final int hStartPadding = getPaddingLeft();
784 final int vStartPadding = getPaddingTop();
785 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
786 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
787 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
788 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
789 }
790
Adam Cohen482ed822012-03-02 14:15:13 -0800791 public float getDistanceFromCell(float x, float y, int[] cell) {
792 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700793 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800794 }
795
Adam Cohenf9c184a2016-01-15 16:47:43 -0800796 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800797 return mCellWidth;
798 }
799
800 int getCellHeight() {
801 return mCellHeight;
802 }
803
Adam Cohend4844c32011-02-18 19:25:06 -0800804 int getWidthGap() {
805 return mWidthGap;
806 }
807
808 int getHeightGap() {
809 return mHeightGap;
810 }
811
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700812 public void setFixedSize(int width, int height) {
813 mFixedWidth = width;
814 mFixedHeight = height;
815 }
816
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800817 @Override
818 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800819 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800820 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700821 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
822 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700823 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
824 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Winson Chung11a1a532013-09-13 11:14:45 -0700825 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Sunny Goyalc6205602015-05-21 20:46:33 -0700826 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
827 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700828 if (cw != mCellWidth || ch != mCellHeight) {
829 mCellWidth = cw;
830 mCellHeight = ch;
831 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
832 mHeightGap, mCountX, mCountY);
833 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700834 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700835
Winson Chung2d75f122013-09-23 16:53:31 -0700836 int newWidth = childWidthSize;
837 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700838 if (mFixedWidth > 0 && mFixedHeight > 0) {
839 newWidth = mFixedWidth;
840 newHeight = mFixedHeight;
841 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800842 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
843 }
844
Adam Cohend22015c2010-07-26 22:02:18 -0700845 int numWidthGaps = mCountX - 1;
846 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800847
Adam Cohen234c4cd2011-07-17 21:03:04 -0700848 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -0700849 int hSpace = childWidthSize;
850 int vSpace = childHeightSize;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700851 int hFreeSpace = hSpace - (mCountX * mCellWidth);
852 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700853 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
854 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Winson Chung5f8afe62013-08-12 16:19:28 -0700855 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
856 mHeightGap, mCountX, mCountY);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700857 } else {
858 mWidthGap = mOriginalWidthGap;
859 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700860 }
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700861
862 // Make the feedback view large enough to hold the blur bitmap.
863 mTouchFeedbackView.measure(
864 MeasureSpec.makeMeasureSpec(mCellWidth + mTouchFeedbackView.getExtraSize(),
865 MeasureSpec.EXACTLY),
866 MeasureSpec.makeMeasureSpec(mCellHeight + mTouchFeedbackView.getExtraSize(),
867 MeasureSpec.EXACTLY));
868
869 mShortcutsAndWidgets.measure(
870 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
871 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
872
873 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
874 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700875 if (mFixedWidth > 0 && mFixedHeight > 0) {
876 setMeasuredDimension(maxWidth, maxHeight);
877 } else {
878 setMeasuredDimension(widthSize, heightSize);
879 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800880 }
881
882 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700883 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -0800884 boolean isFullscreen = mShortcutsAndWidgets.getChildCount() > 0 &&
885 ((LayoutParams) mShortcutsAndWidgets.getChildAt(0).getLayoutParams()).isFullscreen;
886 int left = getPaddingLeft();
887 if (!isFullscreen) {
Tony Wickhama501d492015-11-03 18:05:01 -0800888 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Tony Wickham26b01422015-11-10 14:44:32 -0800889 }
Winson Chung38848ca2013-10-08 12:03:44 -0700890 int top = getPaddingTop();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700891
892 mTouchFeedbackView.layout(left, top,
893 left + mTouchFeedbackView.getMeasuredWidth(),
894 top + mTouchFeedbackView.getMeasuredHeight());
895 mShortcutsAndWidgets.layout(left, top,
896 left + r - l,
897 top + b - t);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800898 }
899
Tony Wickhama501d492015-11-03 18:05:01 -0800900 /**
901 * Returns the amount of space left over after subtracting padding and cells. This space will be
902 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
903 * width in {@link DeviceProfile#calculateCellWidth(int, int)}.
904 */
905 public int getUnusedHorizontalSpace() {
906 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
907 }
908
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800909 @Override
Michael Jurkadee05892010-07-27 10:01:56 -0700910 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
911 super.onSizeChanged(w, h, oldw, oldh);
Winson Chung82a9bd22013-10-08 16:02:34 -0700912
913 // Expand the background drawing bounds by the padding baked into the background drawable
Sunny Goyal2805e632015-05-20 15:35:32 -0700914 mBackground.getPadding(mTempRect);
915 mBackground.setBounds(-mTempRect.left, -mTempRect.top,
916 w + mTempRect.right, h + mTempRect.bottom);
Michael Jurkadee05892010-07-27 10:01:56 -0700917 }
918
919 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800920 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700921 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800922 }
923
924 @Override
925 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700926 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800927 }
928
Michael Jurka5f1c5092010-09-03 14:15:02 -0700929 public float getBackgroundAlpha() {
930 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -0700931 }
932
Michael Jurka5f1c5092010-09-03 14:15:02 -0700933 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -0800934 if (mBackgroundAlpha != alpha) {
935 mBackgroundAlpha = alpha;
Sunny Goyal2805e632015-05-20 15:35:32 -0700936 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurkaafaa0502011-12-13 18:22:50 -0800937 }
Michael Jurkadee05892010-07-27 10:01:56 -0700938 }
939
Sunny Goyal2805e632015-05-20 15:35:32 -0700940 @Override
941 protected boolean verifyDrawable(Drawable who) {
942 return super.verifyDrawable(who) || (mIsDragTarget && who == mBackground);
943 }
944
Michael Jurkaa52570f2012-03-20 03:18:20 -0700945 public void setShortcutAndWidgetAlpha(float alpha) {
Sunny Goyal02b50812014-09-10 15:44:42 -0700946 mShortcutsAndWidgets.setAlpha(alpha);
Michael Jurkadee05892010-07-27 10:01:56 -0700947 }
948
Michael Jurkaa52570f2012-03-20 03:18:20 -0700949 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -0700950 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700951 }
952
Patrick Dubroy440c3602010-07-13 17:50:32 -0700953 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700954 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -0700955 }
956
Adam Cohen76fc0852011-06-17 13:26:23 -0700957 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -0800958 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700959 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -0800960 boolean[][] occupied = mOccupied;
961 if (!permanent) {
962 occupied = mTmpOccupied;
963 }
964
Adam Cohen19f37922012-03-21 11:59:11 -0700965 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700966 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
967 final ItemInfo info = (ItemInfo) child.getTag();
968
969 // We cancel any existing animations
970 if (mReorderAnimators.containsKey(lp)) {
971 mReorderAnimators.get(lp).cancel();
972 mReorderAnimators.remove(lp);
973 }
974
Adam Cohen482ed822012-03-02 14:15:13 -0800975 final int oldX = lp.x;
976 final int oldY = lp.y;
977 if (adjustOccupied) {
978 occupied[lp.cellX][lp.cellY] = false;
979 occupied[cellX][cellY] = true;
980 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700981 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -0800982 if (permanent) {
983 lp.cellX = info.cellX = cellX;
984 lp.cellY = info.cellY = cellY;
985 } else {
986 lp.tmpCellX = cellX;
987 lp.tmpCellY = cellY;
988 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700989 clc.setupLp(lp);
990 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800991 final int newX = lp.x;
992 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700993
Adam Cohen76fc0852011-06-17 13:26:23 -0700994 lp.x = oldX;
995 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -0700996
Adam Cohen482ed822012-03-02 14:15:13 -0800997 // Exit early if we're not actually moving the view
998 if (oldX == newX && oldY == newY) {
999 lp.isLockedToGrid = true;
1000 return true;
1001 }
1002
Michael Jurkaf1ad6082013-03-13 12:55:46 +01001003 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001004 va.setDuration(duration);
1005 mReorderAnimators.put(lp, va);
1006
1007 va.addUpdateListener(new AnimatorUpdateListener() {
1008 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001009 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001010 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001011 lp.x = (int) ((1 - r) * oldX + r * newX);
1012 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001013 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001014 }
1015 });
Adam Cohen482ed822012-03-02 14:15:13 -08001016 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001017 boolean cancelled = false;
1018 public void onAnimationEnd(Animator animation) {
1019 // If the animation was cancelled, it means that another animation
1020 // has interrupted this one, and we don't want to lock the item into
1021 // place just yet.
1022 if (!cancelled) {
1023 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001024 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001025 }
1026 if (mReorderAnimators.containsKey(lp)) {
1027 mReorderAnimators.remove(lp);
1028 }
1029 }
1030 public void onAnimationCancel(Animator animation) {
1031 cancelled = true;
1032 }
1033 });
Adam Cohen482ed822012-03-02 14:15:13 -08001034 va.setStartDelay(delay);
1035 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001036 return true;
1037 }
1038 return false;
1039 }
1040
Tony Wickhama501d492015-11-03 18:05:01 -08001041 void visualizeDropLocation(View v, Bitmap dragOutline, int cellX, int cellY, int spanX,
1042 int spanY, boolean resize, DropTarget.DragObject dragObject) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001043 final int oldDragCellX = mDragCell[0];
1044 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001045
Adam Cohen2801caf2011-05-13 20:57:39 -07001046 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001047 return;
1048 }
1049
Adam Cohen482ed822012-03-02 14:15:13 -08001050 if (cellX != oldDragCellX || cellY != oldDragCellY) {
Sunny Goyale78e3d72015-09-24 11:23:31 -07001051 Point dragOffset = dragObject.dragView.getDragVisualizeOffset();
1052 Rect dragRegion = dragObject.dragView.getDragRegion();
1053
Adam Cohen482ed822012-03-02 14:15:13 -08001054 mDragCell[0] = cellX;
1055 mDragCell[1] = cellY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001056
Joe Onorato4be866d2010-10-10 11:26:02 -07001057 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001058 mDragOutlineAnims[oldIndex].animateOut();
1059 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001060 Rect r = mDragOutlines[mDragOutlineCurrent];
Sunny Goyal106bf642015-07-16 12:18:06 -07001061
Adam Cohend41fbf52012-02-16 23:53:59 -08001062 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001063 cellToRect(cellX, cellY, spanX, spanY, r);
Sunny Goyal106bf642015-07-16 12:18:06 -07001064 } else {
1065 // Find the top left corner of the rect the object will occupy
1066 final int[] topLeft = mTmpPoint;
1067 cellToPoint(cellX, cellY, topLeft);
1068
1069 int left = topLeft[0];
1070 int top = topLeft[1];
1071
1072 if (v != null && dragOffset == null) {
1073 // When drawing the drag outline, it did not account for margin offsets
1074 // added by the view's parent.
1075 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1076 left += lp.leftMargin;
1077 top += lp.topMargin;
1078
1079 // Offsets due to the size difference between the View and the dragOutline.
1080 // There is a size difference to account for the outer blur, which may lie
1081 // outside the bounds of the view.
1082 top += (v.getHeight() - dragOutline.getHeight()) / 2;
1083 // We center about the x axis
1084 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1085 - dragOutline.getWidth()) / 2;
1086 } else {
1087 if (dragOffset != null && dragRegion != null) {
1088 // Center the drag region *horizontally* in the cell and apply a drag
1089 // outline offset
1090 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1091 - dragRegion.width()) / 2;
1092 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
1093 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
1094 top += dragOffset.y + cellPaddingY;
1095 } else {
1096 // Center the drag outline in the cell
1097 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1098 - dragOutline.getWidth()) / 2;
1099 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1100 - dragOutline.getHeight()) / 2;
1101 }
1102 }
1103 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
Adam Cohend41fbf52012-02-16 23:53:59 -08001104 }
Winson Chung150fbab2010-09-29 17:14:26 -07001105
Sunny Goyal106bf642015-07-16 12:18:06 -07001106 Utilities.scaleRectAboutCenter(r, getChildrenScale());
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001107 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1108 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001109
1110 if (dragObject.stateAnnouncer != null) {
1111 String msg;
1112 if (isHotseat()) {
1113 msg = getContext().getString(R.string.move_to_hotseat_position,
1114 Math.max(cellX, cellY) + 1);
1115 } else {
1116 msg = getContext().getString(R.string.move_to_empty_cell,
1117 cellY + 1, cellX + 1);
1118 }
1119 dragObject.stateAnnouncer.announce(msg);
1120 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001121 }
1122 }
1123
Adam Cohene0310962011-04-18 16:15:31 -07001124 public void clearDragOutlines() {
1125 final int oldIndex = mDragOutlineCurrent;
1126 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001127 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001128 }
1129
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001130 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001131 * Find a vacant area that will fit the given bounds nearest the requested
1132 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001133 *
Romain Guy51afc022009-05-04 18:03:43 -07001134 * @param pixelX The X location at which you want to search for a vacant area.
1135 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001136 * @param minSpanX The minimum horizontal span required
1137 * @param minSpanY The minimum vertical span required
1138 * @param spanX Horizontal span of the object.
1139 * @param spanY Vertical span of the object.
1140 * @param result Array in which to place the result, or null (in which case a new array will
1141 * be allocated)
1142 * @return The X, Y cell of a vacant area that can contain this object,
1143 * nearest the requested location.
1144 */
1145 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1146 int spanY, int[] result, int[] resultSpan) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001147 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
Adam Cohend41fbf52012-02-16 23:53:59 -08001148 result, resultSpan);
1149 }
1150
Adam Cohend41fbf52012-02-16 23:53:59 -08001151 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1152 private void lazyInitTempRectStack() {
1153 if (mTempRectStack.isEmpty()) {
1154 for (int i = 0; i < mCountX * mCountY; i++) {
1155 mTempRectStack.push(new Rect());
1156 }
1157 }
1158 }
Adam Cohen482ed822012-03-02 14:15:13 -08001159
Adam Cohend41fbf52012-02-16 23:53:59 -08001160 private void recycleTempRects(Stack<Rect> used) {
1161 while (!used.isEmpty()) {
1162 mTempRectStack.push(used.pop());
1163 }
1164 }
1165
1166 /**
1167 * Find a vacant area that will fit the given bounds nearest the requested
1168 * cell location. Uses Euclidean distance to score multiple vacant areas.
1169 *
1170 * @param pixelX The X location at which you want to search for a vacant area.
1171 * @param pixelY The Y location at which you want to search for a vacant area.
1172 * @param minSpanX The minimum horizontal span required
1173 * @param minSpanY The minimum vertical span required
1174 * @param spanX Horizontal span of the object.
1175 * @param spanY Vertical span of the object.
1176 * @param ignoreOccupied If true, the result can be an occupied cell
1177 * @param result Array in which to place the result, or null (in which case a new array will
1178 * be allocated)
1179 * @return The X, Y cell of a vacant area that can contain this object,
1180 * nearest the requested location.
1181 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001182 private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1183 int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001184 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001185
Adam Cohene3e27a82011-04-15 12:07:39 -07001186 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1187 // to the center of the item, but we are searching based on the top-left cell, so
1188 // we translate the point over to correspond to the top-left.
1189 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1190 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1191
Jeff Sharkey70864282009-04-07 21:08:40 -07001192 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001193 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001194 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001195 final Rect bestRect = new Rect(-1, -1, -1, -1);
1196 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001197
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001198 final int countX = mCountX;
1199 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001200
Adam Cohend41fbf52012-02-16 23:53:59 -08001201 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1202 spanX < minSpanX || spanY < minSpanY) {
1203 return bestXY;
1204 }
1205
1206 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001207 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001208 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1209 int ySize = -1;
1210 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001211 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001212 // First, let's see if this thing fits anywhere
1213 for (int i = 0; i < minSpanX; i++) {
1214 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001215 if (mOccupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001216 continue inner;
1217 }
Michael Jurkac28de512010-08-13 11:27:44 -07001218 }
1219 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001220 xSize = minSpanX;
1221 ySize = minSpanY;
1222
1223 // We know that the item will fit at _some_ acceptable size, now let's see
1224 // how big we can make it. We'll alternate between incrementing x and y spans
1225 // until we hit a limit.
1226 boolean incX = true;
1227 boolean hitMaxX = xSize >= spanX;
1228 boolean hitMaxY = ySize >= spanY;
1229 while (!(hitMaxX && hitMaxY)) {
1230 if (incX && !hitMaxX) {
1231 for (int j = 0; j < ySize; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001232 if (x + xSize > countX -1 || mOccupied[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001233 // We can't move out horizontally
1234 hitMaxX = true;
1235 }
1236 }
1237 if (!hitMaxX) {
1238 xSize++;
1239 }
1240 } else if (!hitMaxY) {
1241 for (int i = 0; i < xSize; i++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001242 if (y + ySize > countY - 1 || mOccupied[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001243 // We can't move out vertically
1244 hitMaxY = true;
1245 }
1246 }
1247 if (!hitMaxY) {
1248 ySize++;
1249 }
1250 }
1251 hitMaxX |= xSize >= spanX;
1252 hitMaxY |= ySize >= spanY;
1253 incX = !incX;
1254 }
1255 incX = true;
1256 hitMaxX = xSize >= spanX;
1257 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001258 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001259 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001260 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001261
Adam Cohend41fbf52012-02-16 23:53:59 -08001262 // We verify that the current rect is not a sub-rect of any of our previous
1263 // candidates. In this case, the current rect is disqualified in favour of the
1264 // containing rect.
1265 Rect currentRect = mTempRectStack.pop();
1266 currentRect.set(x, y, x + xSize, y + ySize);
1267 boolean contained = false;
1268 for (Rect r : validRegions) {
1269 if (r.contains(currentRect)) {
1270 contained = true;
1271 break;
1272 }
1273 }
1274 validRegions.push(currentRect);
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001275 double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
Adam Cohen482ed822012-03-02 14:15:13 -08001276
Adam Cohend41fbf52012-02-16 23:53:59 -08001277 if ((distance <= bestDistance && !contained) ||
1278 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001279 bestDistance = distance;
1280 bestXY[0] = x;
1281 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001282 if (resultSpan != null) {
1283 resultSpan[0] = xSize;
1284 resultSpan[1] = ySize;
1285 }
1286 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001287 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001288 }
1289 }
1290
Adam Cohenc0dcf592011-06-01 15:30:43 -07001291 // Return -1, -1 if no suitable location found
1292 if (bestDistance == Double.MAX_VALUE) {
1293 bestXY[0] = -1;
1294 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001295 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001296 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001297 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001298 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001299
Adam Cohen482ed822012-03-02 14:15:13 -08001300 /**
1301 * Find a vacant area that will fit the given bounds nearest the requested
1302 * cell location, and will also weigh in a suggested direction vector of the
1303 * desired location. This method computers distance based on unit grid distances,
1304 * not pixel distances.
1305 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001306 * @param cellX The X cell nearest to which you want to search for a vacant area.
1307 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001308 * @param spanX Horizontal span of the object.
1309 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001310 * @param direction The favored direction in which the views should move from x, y
Sunny Goyal9eba1fd2015-10-16 08:58:57 -07001311 * @param occupied The array which represents which cells in the CellLayout are occupied
Adam Cohen47a876d2012-03-19 13:21:41 -07001312 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001313 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001314 * @param result Array in which to place the result, or null (in which case a new array will
1315 * be allocated)
1316 * @return The X, Y cell of a vacant area that can contain this object,
1317 * nearest the requested location.
1318 */
1319 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001320 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001321 // Keep track of best-scoring drop area
1322 final int[] bestXY = result != null ? result : new int[2];
1323 float bestDistance = Float.MAX_VALUE;
1324 int bestDirectionScore = Integer.MIN_VALUE;
1325
1326 final int countX = mCountX;
1327 final int countY = mCountY;
1328
1329 for (int y = 0; y < countY - (spanY - 1); y++) {
1330 inner:
1331 for (int x = 0; x < countX - (spanX - 1); x++) {
1332 // First, let's see if this thing fits anywhere
1333 for (int i = 0; i < spanX; i++) {
1334 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001335 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001336 continue inner;
1337 }
1338 }
1339 }
1340
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001341 float distance = (float) Math.hypot(x - cellX, y - cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001342 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001343 computeDirectionVector(x - cellX, y - cellY, curDirection);
1344 // The direction score is just the dot product of the two candidate direction
1345 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001346 int curDirectionScore = direction[0] * curDirection[0] +
1347 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001348 boolean exactDirectionOnly = false;
1349 boolean directionMatches = direction[0] == curDirection[0] &&
1350 direction[0] == curDirection[0];
1351 if ((directionMatches || !exactDirectionOnly) &&
1352 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001353 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1354 bestDistance = distance;
1355 bestDirectionScore = curDirectionScore;
1356 bestXY[0] = x;
1357 bestXY[1] = y;
1358 }
1359 }
1360 }
1361
1362 // Return -1, -1 if no suitable location found
1363 if (bestDistance == Float.MAX_VALUE) {
1364 bestXY[0] = -1;
1365 bestXY[1] = -1;
1366 }
1367 return bestXY;
1368 }
1369
1370 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001371 int[] direction, ItemConfiguration currentState) {
1372 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001373 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001374 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001375 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1376
Adam Cohen8baab352012-03-20 17:39:21 -07001377 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001378
1379 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001380 c.x = mTempLocation[0];
1381 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001382 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001383 }
Adam Cohen8baab352012-03-20 17:39:21 -07001384 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001385 return success;
1386 }
1387
Adam Cohenf3900c22012-11-16 18:28:11 -08001388 /**
1389 * This helper class defines a cluster of views. It helps with defining complex edges
1390 * of the cluster and determining how those edges interact with other views. The edges
1391 * essentially define a fine-grained boundary around the cluster of views -- like a more
1392 * precise version of a bounding box.
1393 */
1394 private class ViewCluster {
1395 final static int LEFT = 0;
1396 final static int TOP = 1;
1397 final static int RIGHT = 2;
1398 final static int BOTTOM = 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001399
Adam Cohenf3900c22012-11-16 18:28:11 -08001400 ArrayList<View> views;
1401 ItemConfiguration config;
1402 Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001403
Adam Cohenf3900c22012-11-16 18:28:11 -08001404 int[] leftEdge = new int[mCountY];
1405 int[] rightEdge = new int[mCountY];
1406 int[] topEdge = new int[mCountX];
1407 int[] bottomEdge = new int[mCountX];
1408 boolean leftEdgeDirty, rightEdgeDirty, topEdgeDirty, bottomEdgeDirty, boundingRectDirty;
1409
1410 @SuppressWarnings("unchecked")
1411 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1412 this.views = (ArrayList<View>) views.clone();
1413 this.config = config;
1414 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001415 }
1416
Adam Cohenf3900c22012-11-16 18:28:11 -08001417 void resetEdges() {
1418 for (int i = 0; i < mCountX; i++) {
1419 topEdge[i] = -1;
1420 bottomEdge[i] = -1;
1421 }
1422 for (int i = 0; i < mCountY; i++) {
1423 leftEdge[i] = -1;
1424 rightEdge[i] = -1;
1425 }
1426 leftEdgeDirty = true;
1427 rightEdgeDirty = true;
1428 bottomEdgeDirty = true;
1429 topEdgeDirty = true;
1430 boundingRectDirty = true;
1431 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001432
Adam Cohenf3900c22012-11-16 18:28:11 -08001433 void computeEdge(int which, int[] edge) {
1434 int count = views.size();
1435 for (int i = 0; i < count; i++) {
1436 CellAndSpan cs = config.map.get(views.get(i));
1437 switch (which) {
1438 case LEFT:
1439 int left = cs.x;
1440 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1441 if (left < edge[j] || edge[j] < 0) {
1442 edge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001443 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001444 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001445 break;
1446 case RIGHT:
1447 int right = cs.x + cs.spanX;
1448 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1449 if (right > edge[j]) {
1450 edge[j] = right;
1451 }
1452 }
1453 break;
1454 case TOP:
1455 int top = cs.y;
1456 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1457 if (top < edge[j] || edge[j] < 0) {
1458 edge[j] = top;
1459 }
1460 }
1461 break;
1462 case BOTTOM:
1463 int bottom = cs.y + cs.spanY;
1464 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1465 if (bottom > edge[j]) {
1466 edge[j] = bottom;
1467 }
1468 }
1469 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001470 }
1471 }
1472 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001473
1474 boolean isViewTouchingEdge(View v, int whichEdge) {
1475 CellAndSpan cs = config.map.get(v);
1476
1477 int[] edge = getEdge(whichEdge);
1478
1479 switch (whichEdge) {
1480 case LEFT:
1481 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1482 if (edge[i] == cs.x + cs.spanX) {
1483 return true;
1484 }
1485 }
1486 break;
1487 case RIGHT:
1488 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1489 if (edge[i] == cs.x) {
1490 return true;
1491 }
1492 }
1493 break;
1494 case TOP:
1495 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1496 if (edge[i] == cs.y + cs.spanY) {
1497 return true;
1498 }
1499 }
1500 break;
1501 case BOTTOM:
1502 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1503 if (edge[i] == cs.y) {
1504 return true;
1505 }
1506 }
1507 break;
1508 }
1509 return false;
1510 }
1511
1512 void shift(int whichEdge, int delta) {
1513 for (View v: views) {
1514 CellAndSpan c = config.map.get(v);
1515 switch (whichEdge) {
1516 case LEFT:
1517 c.x -= delta;
1518 break;
1519 case RIGHT:
1520 c.x += delta;
1521 break;
1522 case TOP:
1523 c.y -= delta;
1524 break;
1525 case BOTTOM:
1526 default:
1527 c.y += delta;
1528 break;
1529 }
1530 }
1531 resetEdges();
1532 }
1533
1534 public void addView(View v) {
1535 views.add(v);
1536 resetEdges();
1537 }
1538
1539 public Rect getBoundingRect() {
1540 if (boundingRectDirty) {
1541 boolean first = true;
1542 for (View v: views) {
1543 CellAndSpan c = config.map.get(v);
1544 if (first) {
1545 boundingRect.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1546 first = false;
1547 } else {
1548 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1549 }
1550 }
1551 }
1552 return boundingRect;
1553 }
1554
1555 public int[] getEdge(int which) {
1556 switch (which) {
1557 case LEFT:
1558 return getLeftEdge();
1559 case RIGHT:
1560 return getRightEdge();
1561 case TOP:
1562 return getTopEdge();
1563 case BOTTOM:
1564 default:
1565 return getBottomEdge();
1566 }
1567 }
1568
1569 public int[] getLeftEdge() {
1570 if (leftEdgeDirty) {
1571 computeEdge(LEFT, leftEdge);
1572 }
1573 return leftEdge;
1574 }
1575
1576 public int[] getRightEdge() {
1577 if (rightEdgeDirty) {
1578 computeEdge(RIGHT, rightEdge);
1579 }
1580 return rightEdge;
1581 }
1582
1583 public int[] getTopEdge() {
1584 if (topEdgeDirty) {
1585 computeEdge(TOP, topEdge);
1586 }
1587 return topEdge;
1588 }
1589
1590 public int[] getBottomEdge() {
1591 if (bottomEdgeDirty) {
1592 computeEdge(BOTTOM, bottomEdge);
1593 }
1594 return bottomEdge;
1595 }
1596
1597 PositionComparator comparator = new PositionComparator();
1598 class PositionComparator implements Comparator<View> {
1599 int whichEdge = 0;
1600 public int compare(View left, View right) {
1601 CellAndSpan l = config.map.get(left);
1602 CellAndSpan r = config.map.get(right);
1603 switch (whichEdge) {
1604 case LEFT:
1605 return (r.x + r.spanX) - (l.x + l.spanX);
1606 case RIGHT:
1607 return l.x - r.x;
1608 case TOP:
1609 return (r.y + r.spanY) - (l.y + l.spanY);
1610 case BOTTOM:
1611 default:
1612 return l.y - r.y;
1613 }
1614 }
1615 }
1616
1617 public void sortConfigurationForEdgePush(int edge) {
1618 comparator.whichEdge = edge;
1619 Collections.sort(config.sortedViews, comparator);
1620 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001621 }
1622
Adam Cohenf3900c22012-11-16 18:28:11 -08001623 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1624 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001625
Adam Cohenf3900c22012-11-16 18:28:11 -08001626 ViewCluster cluster = new ViewCluster(views, currentState);
1627 Rect clusterRect = cluster.getBoundingRect();
1628 int whichEdge;
1629 int pushDistance;
1630 boolean fail = false;
1631
1632 // Determine the edge of the cluster that will be leading the push and how far
1633 // the cluster must be shifted.
1634 if (direction[0] < 0) {
1635 whichEdge = ViewCluster.LEFT;
1636 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001637 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001638 whichEdge = ViewCluster.RIGHT;
1639 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1640 } else if (direction[1] < 0) {
1641 whichEdge = ViewCluster.TOP;
1642 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1643 } else {
1644 whichEdge = ViewCluster.BOTTOM;
1645 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07001646 }
1647
Adam Cohenf3900c22012-11-16 18:28:11 -08001648 // Break early for invalid push distance.
1649 if (pushDistance <= 0) {
1650 return false;
Adam Cohene0489502012-08-27 15:18:53 -07001651 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001652
1653 // Mark the occupied state as false for the group of views we want to move.
1654 for (View v: views) {
1655 CellAndSpan c = currentState.map.get(v);
1656 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1657 }
1658
1659 // We save the current configuration -- if we fail to find a solution we will revert
1660 // to the initial state. The process of finding a solution modifies the configuration
1661 // in place, hence the need for revert in the failure case.
1662 currentState.save();
1663
1664 // The pushing algorithm is simplified by considering the views in the order in which
1665 // they would be pushed by the cluster. For example, if the cluster is leading with its
1666 // left edge, we consider sort the views by their right edge, from right to left.
1667 cluster.sortConfigurationForEdgePush(whichEdge);
1668
1669 while (pushDistance > 0 && !fail) {
1670 for (View v: currentState.sortedViews) {
1671 // For each view that isn't in the cluster, we see if the leading edge of the
1672 // cluster is contacting the edge of that view. If so, we add that view to the
1673 // cluster.
1674 if (!cluster.views.contains(v) && v != dragView) {
1675 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1676 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1677 if (!lp.canReorder) {
1678 // The push solution includes the all apps button, this is not viable.
1679 fail = true;
1680 break;
1681 }
1682 cluster.addView(v);
1683 CellAndSpan c = currentState.map.get(v);
1684
1685 // Adding view to cluster, mark it as not occupied.
1686 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1687 }
1688 }
1689 }
1690 pushDistance--;
1691
1692 // The cluster has been completed, now we move the whole thing over in the appropriate
1693 // direction.
1694 cluster.shift(whichEdge, 1);
1695 }
1696
1697 boolean foundSolution = false;
1698 clusterRect = cluster.getBoundingRect();
1699
1700 // Due to the nature of the algorithm, the only check required to verify a valid solution
1701 // is to ensure that completed shifted cluster lies completely within the cell layout.
1702 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1703 clusterRect.bottom <= mCountY) {
1704 foundSolution = true;
1705 } else {
1706 currentState.restore();
1707 }
1708
1709 // In either case, we set the occupied array as marked for the location of the views
1710 for (View v: cluster.views) {
1711 CellAndSpan c = currentState.map.get(v);
1712 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
1713 }
1714
1715 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07001716 }
1717
Adam Cohen482ed822012-03-02 14:15:13 -08001718 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08001719 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001720 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001721
Adam Cohen8baab352012-03-20 17:39:21 -07001722 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001723 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001724 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001725 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001726 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001727 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001728 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001729 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001730 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001731 }
1732 }
Adam Cohen8baab352012-03-20 17:39:21 -07001733
Adam Cohen8baab352012-03-20 17:39:21 -07001734 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08001735 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001736 CellAndSpan c = currentState.map.get(v);
1737 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1738 }
1739
Adam Cohen47a876d2012-03-19 13:21:41 -07001740 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1741 int top = boundingRect.top;
1742 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001743 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001744 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08001745 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001746 CellAndSpan c = currentState.map.get(v);
1747 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001748 }
1749
Adam Cohen482ed822012-03-02 14:15:13 -08001750 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1751
Adam Cohenf3900c22012-11-16 18:28:11 -08001752 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1753 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001754
Adam Cohen8baab352012-03-20 17:39:21 -07001755 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001756 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001757 int deltaX = mTempLocation[0] - boundingRect.left;
1758 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001759 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001760 CellAndSpan c = currentState.map.get(v);
1761 c.x += deltaX;
1762 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001763 }
1764 success = true;
1765 }
Adam Cohen8baab352012-03-20 17:39:21 -07001766
1767 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08001768 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001769 CellAndSpan c = currentState.map.get(v);
1770 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001771 }
1772 return success;
1773 }
1774
1775 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1776 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1777 }
1778
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001779 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1780 // to push items in each of the cardinal directions, in an order based on the direction vector
1781 // passed.
1782 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1783 int[] direction, View ignoreView, ItemConfiguration solution) {
1784 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001785 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001786 // separately in each of the components.
1787 int temp = direction[1];
1788 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001789
1790 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001791 ignoreView, solution)) {
1792 return true;
1793 }
1794 direction[1] = temp;
1795 temp = direction[0];
1796 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001797
1798 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001799 ignoreView, solution)) {
1800 return true;
1801 }
1802 // Revert the direction
1803 direction[0] = temp;
1804
1805 // Now we try pushing in each component of the opposite direction
1806 direction[0] *= -1;
1807 direction[1] *= -1;
1808 temp = direction[1];
1809 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001810 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001811 ignoreView, solution)) {
1812 return true;
1813 }
1814
1815 direction[1] = temp;
1816 temp = direction[0];
1817 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001818 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001819 ignoreView, solution)) {
1820 return true;
1821 }
1822 // revert the direction
1823 direction[0] = temp;
1824 direction[0] *= -1;
1825 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001826
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001827 } else {
1828 // If the direction vector has a single non-zero component, we push first in the
1829 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08001830 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001831 ignoreView, solution)) {
1832 return true;
1833 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001834 // Then we try the opposite direction
1835 direction[0] *= -1;
1836 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001837 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001838 ignoreView, solution)) {
1839 return true;
1840 }
1841 // Switch the direction back
1842 direction[0] *= -1;
1843 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001844
1845 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001846 // to find a solution by pushing along the perpendicular axis.
1847
1848 // Swap the components
1849 int temp = direction[1];
1850 direction[1] = direction[0];
1851 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08001852 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001853 ignoreView, solution)) {
1854 return true;
1855 }
1856
1857 // Then we try the opposite direction
1858 direction[0] *= -1;
1859 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001860 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001861 ignoreView, solution)) {
1862 return true;
1863 }
1864 // Switch the direction back
1865 direction[0] *= -1;
1866 direction[1] *= -1;
1867
1868 // Swap the components back
1869 temp = direction[1];
1870 direction[1] = direction[0];
1871 direction[0] = temp;
1872 }
1873 return false;
1874 }
1875
Adam Cohen482ed822012-03-02 14:15:13 -08001876 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001877 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001878 // Return early if get invalid cell positions
1879 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001880
Adam Cohen8baab352012-03-20 17:39:21 -07001881 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001882 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001883
Adam Cohen8baab352012-03-20 17:39:21 -07001884 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001885 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001886 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001887 if (c != null) {
1888 c.x = cellX;
1889 c.y = cellY;
1890 }
Adam Cohen482ed822012-03-02 14:15:13 -08001891 }
Adam Cohen482ed822012-03-02 14:15:13 -08001892 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1893 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001894 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001895 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001896 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001897 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001898 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001899 if (Rect.intersects(r0, r1)) {
1900 if (!lp.canReorder) {
1901 return false;
1902 }
1903 mIntersectingViews.add(child);
1904 }
1905 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001906
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001907 solution.intersectingViews = new ArrayList<View>(mIntersectingViews);
1908
Winson Chung5f8afe62013-08-12 16:19:28 -07001909 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001910 // we try to find a solution such that no displaced item travels through another item
1911 // without also displacing that item.
1912 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001913 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001914 return true;
1915 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001916
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001917 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08001918 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001919 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001920 return true;
1921 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001922
Adam Cohen482ed822012-03-02 14:15:13 -08001923 // Ok, they couldn't move as a block, let's move them individually
1924 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001925 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001926 return false;
1927 }
1928 }
1929 return true;
1930 }
1931
1932 /*
1933 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1934 * the provided point and the provided cell
1935 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001936 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001937 double angle = Math.atan(((float) deltaY) / deltaX);
1938
1939 result[0] = 0;
1940 result[1] = 0;
1941 if (Math.abs(Math.cos(angle)) > 0.5f) {
1942 result[0] = (int) Math.signum(deltaX);
1943 }
1944 if (Math.abs(Math.sin(angle)) > 0.5f) {
1945 result[1] = (int) Math.signum(deltaY);
1946 }
1947 }
1948
Adam Cohen8baab352012-03-20 17:39:21 -07001949 private void copyOccupiedArray(boolean[][] occupied) {
1950 for (int i = 0; i < mCountX; i++) {
1951 for (int j = 0; j < mCountY; j++) {
1952 occupied[i][j] = mOccupied[i][j];
1953 }
1954 }
1955 }
1956
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001957 private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001958 int spanX, int spanY, int[] direction, View dragView, boolean decX,
1959 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001960 // Copy the current state into the solution. This solution will be manipulated as necessary.
1961 copyCurrentStateToSolution(solution, false);
1962 // Copy the current occupied array into the temporary occupied array. This array will be
1963 // manipulated as necessary to find a solution.
1964 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001965
1966 // We find the nearest cell into which we would place the dragged item, assuming there's
1967 // nothing in its way.
1968 int result[] = new int[2];
1969 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1970
1971 boolean success = false;
1972 // First we try the exact nearest position of the item being dragged,
1973 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001974 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1975 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001976
1977 if (!success) {
1978 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1979 // x, then 1 in y etc.
1980 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001981 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
1982 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001983 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001984 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
1985 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001986 }
1987 solution.isSolution = false;
1988 } else {
1989 solution.isSolution = true;
1990 solution.dragViewX = result[0];
1991 solution.dragViewY = result[1];
1992 solution.dragViewSpanX = spanX;
1993 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001994 }
1995 return solution;
1996 }
1997
1998 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001999 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002000 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002001 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002002 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002003 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08002004 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07002005 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002006 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07002007 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002008 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002009 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08002010 }
2011 }
2012
2013 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
2014 for (int i = 0; i < mCountX; i++) {
2015 for (int j = 0; j < mCountY; j++) {
2016 mTmpOccupied[i][j] = false;
2017 }
2018 }
2019
Michael Jurkaa52570f2012-03-20 03:18:20 -07002020 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002021 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002022 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002023 if (child == dragView) continue;
2024 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002025 CellAndSpan c = solution.map.get(child);
2026 if (c != null) {
2027 lp.tmpCellX = c.x;
2028 lp.tmpCellY = c.y;
2029 lp.cellHSpan = c.spanX;
2030 lp.cellVSpan = c.spanY;
2031 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002032 }
2033 }
2034 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2035 solution.dragViewSpanY, mTmpOccupied, true);
2036 }
2037
2038 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
2039 commitDragView) {
2040
2041 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
2042 for (int i = 0; i < mCountX; i++) {
2043 for (int j = 0; j < mCountY; j++) {
2044 occupied[i][j] = false;
2045 }
2046 }
2047
Michael Jurkaa52570f2012-03-20 03:18:20 -07002048 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002049 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002050 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002051 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002052 CellAndSpan c = solution.map.get(child);
2053 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002054 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2055 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002056 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002057 }
2058 }
2059 if (commitDragView) {
2060 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2061 solution.dragViewSpanY, occupied, true);
2062 }
2063 }
2064
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002065
2066 // This method starts or changes the reorder preview animations
2067 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
2068 View dragView, int delay, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07002069 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002070 for (int i = 0; i < childCount; i++) {
2071 View child = mShortcutsAndWidgets.getChildAt(i);
2072 if (child == dragView) continue;
2073 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002074 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
2075 != null && !solution.intersectingViews.contains(child);
2076
Adam Cohen19f37922012-03-21 11:59:11 -07002077 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002078 if (c != null && !skip) {
2079 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
2080 lp.cellY, c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002081 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002082 }
2083 }
2084 }
2085
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002086 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07002087 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002088 class ReorderPreviewAnimation {
Adam Cohen19f37922012-03-21 11:59:11 -07002089 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002090 float finalDeltaX;
2091 float finalDeltaY;
2092 float initDeltaX;
2093 float initDeltaY;
2094 float finalScale;
2095 float initScale;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002096 int mode;
2097 boolean repeating = false;
2098 private static final int PREVIEW_DURATION = 300;
2099 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
2100
2101 public static final int MODE_HINT = 0;
2102 public static final int MODE_PREVIEW = 1;
2103
Adam Cohene7587d22012-05-24 18:50:02 -07002104 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002105
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002106 public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
2107 int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07002108 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2109 final int x0 = mTmpPoint[0];
2110 final int y0 = mTmpPoint[1];
2111 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2112 final int x1 = mTmpPoint[0];
2113 final int y1 = mTmpPoint[1];
2114 final int dX = x1 - x0;
2115 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002116 finalDeltaX = 0;
2117 finalDeltaY = 0;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002118 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07002119 if (dX == dY && dX == 0) {
2120 } else {
2121 if (dY == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002122 finalDeltaX = - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002123 } else if (dX == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002124 finalDeltaY = - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002125 } else {
2126 double angle = Math.atan( (float) (dY) / dX);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002127 finalDeltaX = (int) (- dir * Math.signum(dX) *
2128 Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
2129 finalDeltaY = (int) (- dir * Math.signum(dY) *
2130 Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002131 }
2132 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002133 this.mode = mode;
Adam Cohend024f982012-05-23 18:26:45 -07002134 initDeltaX = child.getTranslationX();
2135 initDeltaY = child.getTranslationY();
Adam Cohen307fe232012-08-16 17:55:58 -07002136 finalScale = getChildrenScale() - 4.0f / child.getWidth();
Adam Cohend024f982012-05-23 18:26:45 -07002137 initScale = child.getScaleX();
Adam Cohen19f37922012-03-21 11:59:11 -07002138 this.child = child;
2139 }
2140
Adam Cohend024f982012-05-23 18:26:45 -07002141 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002142 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002143 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002144 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002145 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002146 if (finalDeltaX == 0 && finalDeltaY == 0) {
2147 completeAnimationImmediately();
2148 return;
2149 }
Adam Cohen19f37922012-03-21 11:59:11 -07002150 }
Adam Cohend024f982012-05-23 18:26:45 -07002151 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002152 return;
2153 }
Michael Jurkaf1ad6082013-03-13 12:55:46 +01002154 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002155 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07002156
2157 // Animations are disabled in power save mode, causing the repeated animation to jump
2158 // spastically between beginning and end states. Since this looks bad, we don't repeat
2159 // the animation in power save mode.
Tony Wickham112ac952015-11-12 12:31:50 -08002160 if (!Utilities.isPowerSaverOn(getContext())) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07002161 va.setRepeatMode(ValueAnimator.REVERSE);
2162 va.setRepeatCount(ValueAnimator.INFINITE);
2163 }
2164
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002165 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002166 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002167 va.addUpdateListener(new AnimatorUpdateListener() {
2168 @Override
2169 public void onAnimationUpdate(ValueAnimator animation) {
2170 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002171 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : r;
2172 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2173 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002174 child.setTranslationX(x);
2175 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002176 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002177 child.setScaleX(s);
2178 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002179 }
2180 });
2181 va.addListener(new AnimatorListenerAdapter() {
2182 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002183 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002184 initDeltaX = 0;
2185 initDeltaY = 0;
Adam Cohen307fe232012-08-16 17:55:58 -07002186 initScale = getChildrenScale();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002187 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002188 }
2189 });
Adam Cohen19f37922012-03-21 11:59:11 -07002190 mShakeAnimators.put(child, this);
2191 va.start();
2192 }
2193
Adam Cohend024f982012-05-23 18:26:45 -07002194 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002195 if (a != null) {
2196 a.cancel();
2197 }
Adam Cohen19f37922012-03-21 11:59:11 -07002198 }
Adam Cohene7587d22012-05-24 18:50:02 -07002199
Adam Cohen091440a2015-03-18 14:16:05 -07002200 @Thunk void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002201 if (a != null) {
2202 a.cancel();
2203 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002204
Sunny Goyal5d2fc322015-07-06 22:52:49 -07002205 a = new LauncherViewPropertyAnimator(child)
2206 .scaleX(getChildrenScale())
2207 .scaleY(getChildrenScale())
2208 .translationX(0)
2209 .translationY(0)
2210 .setDuration(REORDER_ANIMATION_DURATION);
2211 a.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2212 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07002213 }
Adam Cohen19f37922012-03-21 11:59:11 -07002214 }
2215
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002216 private void completeAndClearReorderPreviewAnimations() {
2217 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002218 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002219 }
2220 mShakeAnimators.clear();
2221 }
2222
Adam Cohen482ed822012-03-02 14:15:13 -08002223 private void commitTempPlacement() {
2224 for (int i = 0; i < mCountX; i++) {
2225 for (int j = 0; j < mCountY; j++) {
2226 mOccupied[i][j] = mTmpOccupied[i][j];
2227 }
2228 }
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002229
2230 long screenId = mLauncher.getWorkspace().getIdForScreen(this);
2231 int container = Favorites.CONTAINER_DESKTOP;
2232
2233 if (mLauncher.isHotseatLayout(this)) {
2234 screenId = -1;
2235 container = Favorites.CONTAINER_HOTSEAT;
2236 }
2237
Michael Jurkaa52570f2012-03-20 03:18:20 -07002238 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002239 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002240 View child = mShortcutsAndWidgets.getChildAt(i);
2241 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2242 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002243 // We do a null check here because the item info can be null in the case of the
2244 // AllApps button in the hotseat.
2245 if (info != null) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002246 final boolean requiresDbUpdate = (info.cellX != lp.tmpCellX
2247 || info.cellY != lp.tmpCellY || info.spanX != lp.cellHSpan
2248 || info.spanY != lp.cellVSpan);
2249
Adam Cohen2acce882012-03-28 19:03:19 -07002250 info.cellX = lp.cellX = lp.tmpCellX;
2251 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002252 info.spanX = lp.cellHSpan;
2253 info.spanY = lp.cellVSpan;
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002254
2255 if (requiresDbUpdate) {
2256 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId,
2257 info.cellX, info.cellY, info.spanX, info.spanY);
2258 }
Adam Cohen2acce882012-03-28 19:03:19 -07002259 }
Adam Cohen482ed822012-03-02 14:15:13 -08002260 }
2261 }
2262
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002263 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002264 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002265 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002266 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002267 lp.useTmpCoords = useTempCoords;
2268 }
2269 }
2270
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002271 private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002272 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2273 int[] result = new int[2];
2274 int[] resultSpan = new int[2];
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002275 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
Adam Cohen482ed822012-03-02 14:15:13 -08002276 resultSpan);
2277 if (result[0] >= 0 && result[1] >= 0) {
2278 copyCurrentStateToSolution(solution, false);
2279 solution.dragViewX = result[0];
2280 solution.dragViewY = result[1];
2281 solution.dragViewSpanX = resultSpan[0];
2282 solution.dragViewSpanY = resultSpan[1];
2283 solution.isSolution = true;
2284 } else {
2285 solution.isSolution = false;
2286 }
2287 return solution;
2288 }
2289
2290 public void prepareChildForDrag(View child) {
2291 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002292 }
2293
Adam Cohen19f37922012-03-21 11:59:11 -07002294 /* This seems like it should be obvious and straight-forward, but when the direction vector
2295 needs to match with the notion of the dragView pushing other views, we have to employ
2296 a slightly more subtle notion of the direction vector. The question is what two points is
2297 the vector between? The center of the dragView and its desired destination? Not quite, as
2298 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2299 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2300 or right, which helps make pushing feel right.
2301 */
2302 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2303 int spanY, View dragView, int[] resultDirection) {
2304 int[] targetDestination = new int[2];
2305
2306 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2307 Rect dragRect = new Rect();
2308 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2309 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2310
2311 Rect dropRegionRect = new Rect();
2312 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2313 dragView, dropRegionRect, mIntersectingViews);
2314
2315 int dropRegionSpanX = dropRegionRect.width();
2316 int dropRegionSpanY = dropRegionRect.height();
2317
2318 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2319 dropRegionRect.height(), dropRegionRect);
2320
2321 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2322 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2323
2324 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2325 deltaX = 0;
2326 }
2327 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2328 deltaY = 0;
2329 }
2330
2331 if (deltaX == 0 && deltaY == 0) {
2332 // No idea what to do, give a random direction.
2333 resultDirection[0] = 1;
2334 resultDirection[1] = 0;
2335 } else {
2336 computeDirectionVector(deltaX, deltaY, resultDirection);
2337 }
2338 }
2339
2340 // For a given cell and span, fetch the set of views intersecting the region.
2341 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2342 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2343 if (boundingRect != null) {
2344 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2345 }
2346 intersectingViews.clear();
2347 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2348 Rect r1 = new Rect();
2349 final int count = mShortcutsAndWidgets.getChildCount();
2350 for (int i = 0; i < count; i++) {
2351 View child = mShortcutsAndWidgets.getChildAt(i);
2352 if (child == dragView) continue;
2353 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2354 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2355 if (Rect.intersects(r0, r1)) {
2356 mIntersectingViews.add(child);
2357 if (boundingRect != null) {
2358 boundingRect.union(r1);
2359 }
2360 }
2361 }
2362 }
2363
2364 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2365 View dragView, int[] result) {
2366 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2367 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2368 mIntersectingViews);
2369 return !mIntersectingViews.isEmpty();
2370 }
2371
2372 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002373 completeAndClearReorderPreviewAnimations();
2374 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2375 final int count = mShortcutsAndWidgets.getChildCount();
2376 for (int i = 0; i < count; i++) {
2377 View child = mShortcutsAndWidgets.getChildAt(i);
2378 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2379 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2380 lp.tmpCellX = lp.cellX;
2381 lp.tmpCellY = lp.cellY;
2382 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2383 0, false, false);
2384 }
Adam Cohen19f37922012-03-21 11:59:11 -07002385 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002386 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002387 }
Adam Cohen19f37922012-03-21 11:59:11 -07002388 }
2389
Adam Cohenbebf0422012-04-11 18:06:28 -07002390 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2391 View dragView, int[] direction, boolean commit) {
2392 int[] pixelXY = new int[2];
2393 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2394
2395 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002396 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002397 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2398
2399 setUseTempCoords(true);
2400 if (swapSolution != null && swapSolution.isSolution) {
2401 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2402 // committing anything or animating anything as we just want to determine if a solution
2403 // exists
2404 copySolutionToTempState(swapSolution, dragView);
2405 setItemPlacementDirty(true);
2406 animateItemsToSolution(swapSolution, dragView, commit);
2407
2408 if (commit) {
2409 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002410 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002411 setItemPlacementDirty(false);
2412 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002413 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
2414 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002415 }
2416 mShortcutsAndWidgets.requestLayout();
2417 }
2418 return swapSolution.isSolution;
2419 }
2420
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002421 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002422 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002423 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002424 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002425
2426 if (resultSpan == null) {
2427 resultSpan = new int[2];
2428 }
2429
Adam Cohen19f37922012-03-21 11:59:11 -07002430 // When we are checking drop validity or actually dropping, we don't recompute the
2431 // direction vector, since we want the solution to match the preview, and it's possible
2432 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002433 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2434 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002435 mDirectionVector[0] = mPreviousReorderDirection[0];
2436 mDirectionVector[1] = mPreviousReorderDirection[1];
2437 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002438 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2439 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2440 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002441 }
2442 } else {
2443 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2444 mPreviousReorderDirection[0] = mDirectionVector[0];
2445 mPreviousReorderDirection[1] = mDirectionVector[1];
2446 }
2447
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002448 // Find a solution involving pushing / displacing any items in the way
2449 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002450 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2451
2452 // We attempt the approach which doesn't shuffle views at all
2453 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2454 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2455
2456 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002457
2458 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2459 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002460 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2461 finalSolution = swapSolution;
2462 } else if (noShuffleSolution.isSolution) {
2463 finalSolution = noShuffleSolution;
2464 }
2465
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002466 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002467 if (finalSolution != null) {
Adam Cohenfe692872013-12-11 14:47:23 -08002468 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
2469 ReorderPreviewAnimation.MODE_HINT);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002470 result[0] = finalSolution.dragViewX;
2471 result[1] = finalSolution.dragViewY;
2472 resultSpan[0] = finalSolution.dragViewSpanX;
2473 resultSpan[1] = finalSolution.dragViewSpanY;
2474 } else {
2475 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2476 }
2477 return result;
2478 }
2479
Adam Cohen482ed822012-03-02 14:15:13 -08002480 boolean foundSolution = true;
2481 if (!DESTRUCTIVE_REORDER) {
2482 setUseTempCoords(true);
2483 }
2484
2485 if (finalSolution != null) {
2486 result[0] = finalSolution.dragViewX;
2487 result[1] = finalSolution.dragViewY;
2488 resultSpan[0] = finalSolution.dragViewSpanX;
2489 resultSpan[1] = finalSolution.dragViewSpanY;
2490
2491 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2492 // committing anything or animating anything as we just want to determine if a solution
2493 // exists
2494 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2495 if (!DESTRUCTIVE_REORDER) {
2496 copySolutionToTempState(finalSolution, dragView);
2497 }
2498 setItemPlacementDirty(true);
2499 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2500
Adam Cohen19f37922012-03-21 11:59:11 -07002501 if (!DESTRUCTIVE_REORDER &&
2502 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002503 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002504 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002505 setItemPlacementDirty(false);
2506 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002507 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
2508 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002509 }
2510 }
2511 } else {
2512 foundSolution = false;
2513 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2514 }
2515
2516 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2517 setUseTempCoords(false);
2518 }
Adam Cohen482ed822012-03-02 14:15:13 -08002519
Michael Jurkaa52570f2012-03-20 03:18:20 -07002520 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002521 return result;
2522 }
2523
Adam Cohen19f37922012-03-21 11:59:11 -07002524 void setItemPlacementDirty(boolean dirty) {
2525 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002526 }
Adam Cohen19f37922012-03-21 11:59:11 -07002527 boolean isItemPlacementDirty() {
2528 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002529 }
2530
Adam Cohen091440a2015-03-18 14:16:05 -07002531 @Thunk class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002532 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohenf3900c22012-11-16 18:28:11 -08002533 private HashMap<View, CellAndSpan> savedMap = new HashMap<View, CellAndSpan>();
2534 ArrayList<View> sortedViews = new ArrayList<View>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002535 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002536 boolean isSolution = false;
2537 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2538
Adam Cohenf3900c22012-11-16 18:28:11 -08002539 void save() {
2540 // Copy current state into savedMap
2541 for (View v: map.keySet()) {
2542 map.get(v).copy(savedMap.get(v));
2543 }
2544 }
2545
2546 void restore() {
2547 // Restore current state from savedMap
2548 for (View v: savedMap.keySet()) {
2549 savedMap.get(v).copy(map.get(v));
2550 }
2551 }
2552
2553 void add(View v, CellAndSpan cs) {
2554 map.put(v, cs);
2555 savedMap.put(v, new CellAndSpan());
2556 sortedViews.add(v);
2557 }
2558
Adam Cohen482ed822012-03-02 14:15:13 -08002559 int area() {
2560 return dragViewSpanX * dragViewSpanY;
2561 }
Adam Cohen8baab352012-03-20 17:39:21 -07002562 }
2563
2564 private class CellAndSpan {
2565 int x, y;
2566 int spanX, spanY;
2567
Adam Cohenf3900c22012-11-16 18:28:11 -08002568 public CellAndSpan() {
2569 }
2570
2571 public void copy(CellAndSpan copy) {
2572 copy.x = x;
2573 copy.y = y;
2574 copy.spanX = spanX;
2575 copy.spanY = spanY;
2576 }
2577
Adam Cohen8baab352012-03-20 17:39:21 -07002578 public CellAndSpan(int x, int y, int spanX, int spanY) {
2579 this.x = x;
2580 this.y = y;
2581 this.spanX = spanX;
2582 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002583 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002584
2585 public String toString() {
2586 return "(" + x + ", " + y + ": " + spanX + ", " + spanY + ")";
2587 }
2588
Adam Cohen482ed822012-03-02 14:15:13 -08002589 }
2590
Adam Cohendf035382011-04-11 17:22:04 -07002591 /**
Adam Cohendf035382011-04-11 17:22:04 -07002592 * Find a starting cell position that will fit the given bounds nearest the requested
2593 * cell location. Uses Euclidean distance to score multiple vacant areas.
2594 *
2595 * @param pixelX The X location at which you want to search for a vacant area.
2596 * @param pixelY The Y location at which you want to search for a vacant area.
2597 * @param spanX Horizontal span of the object.
2598 * @param spanY Vertical span of the object.
2599 * @param ignoreView Considers space occupied by this view as unoccupied
2600 * @param result Previously returned value to possibly recycle.
2601 * @return The X, Y cell of a vacant area that can contain this object,
2602 * nearest the requested location.
2603 */
Adam Cohenf9c184a2016-01-15 16:47:43 -08002604 public int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002605 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002606 }
2607
Michael Jurka0280c3b2010-09-17 15:00:07 -07002608 boolean existsEmptyCell() {
2609 return findCellForSpan(null, 1, 1);
2610 }
2611
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002612 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002613 * Finds the upper-left coordinate of the first rectangle in the grid that can
2614 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2615 * then this method will only return coordinates for rectangles that contain the cell
2616 * (intersectX, intersectY)
2617 *
2618 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2619 * can be found.
2620 * @param spanX The horizontal span of the cell we want to find.
2621 * @param spanY The vertical span of the cell we want to find.
2622 *
2623 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002624 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002625 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Michael Jurka28750fb2010-09-24 17:43:49 -07002626 boolean foundCell = false;
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002627 final int endX = mCountX - (spanX - 1);
2628 final int endY = mCountY - (spanY - 1);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002629
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002630 for (int y = 0; y < endY && !foundCell; y++) {
2631 inner:
2632 for (int x = 0; x < endX; x++) {
2633 for (int i = 0; i < spanX; i++) {
2634 for (int j = 0; j < spanY; j++) {
2635 if (mOccupied[x + i][y + j]) {
2636 // small optimization: we can skip to after the column we just found
2637 // an occupied cell
2638 x += i;
2639 continue inner;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002640 }
2641 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002642 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002643 if (cellXY != null) {
2644 cellXY[0] = x;
2645 cellXY[1] = y;
2646 }
2647 foundCell = true;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002648 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002649 }
2650 }
2651
Michael Jurka28750fb2010-09-24 17:43:49 -07002652 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002653 }
2654
2655 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002656 * A drag event has begun over this layout.
2657 * It may have begun over this layout (in which case onDragChild is called first),
2658 * or it may have begun on another layout.
2659 */
2660 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002661 mDragging = true;
2662 }
2663
2664 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002665 * Called when drag has left this CellLayout or has been completed (successfully or not)
2666 */
2667 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002668 // This can actually be called when we aren't in a drag, e.g. when adding a new
2669 // item to this layout via the customize drawer.
2670 // Guard against that case.
2671 if (mDragging) {
2672 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002673 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002674
2675 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002676 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002677 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2678 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002679 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002680 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002681 }
2682
2683 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002684 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002685 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002686 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002687 *
2688 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002689 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002690 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002691 if (child != null) {
2692 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002693 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002694 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002695 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002696 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002697 }
2698
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002699 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002700 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002701 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002702 * @param cellX X coordinate of upper left corner expressed as a cell position
2703 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002704 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002705 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002706 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002707 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002708 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002709 final int cellWidth = mCellWidth;
2710 final int cellHeight = mCellHeight;
2711 final int widthGap = mWidthGap;
2712 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002713
Winson Chung4b825dcd2011-06-19 12:41:22 -07002714 final int hStartPadding = getPaddingLeft();
2715 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002716
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002717 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2718 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2719
2720 int x = hStartPadding + cellX * (cellWidth + widthGap);
2721 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002722
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002723 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002724 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002725
Michael Jurka0280c3b2010-09-17 15:00:07 -07002726 private void clearOccupiedCells() {
2727 for (int x = 0; x < mCountX; x++) {
2728 for (int y = 0; y < mCountY; y++) {
2729 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002730 }
2731 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002732 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002733
Adam Cohend4844c32011-02-18 19:25:06 -08002734 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002735 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002736 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002737 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002738 }
2739
Adam Cohend4844c32011-02-18 19:25:06 -08002740 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002741 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002742 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002743 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002744 }
2745
Adam Cohen482ed822012-03-02 14:15:13 -08002746 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2747 boolean value) {
2748 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002749 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2750 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002751 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002752 }
2753 }
2754 }
2755
Adam Cohen2801caf2011-05-13 20:57:39 -07002756 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002757 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002758 (Math.max((mCountX - 1), 0) * mWidthGap);
2759 }
2760
2761 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002762 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002763 (Math.max((mCountY - 1), 0) * mHeightGap);
2764 }
2765
Michael Jurka66d72172011-04-12 16:29:25 -07002766 public boolean isOccupied(int x, int y) {
2767 if (x < mCountX && y < mCountY) {
2768 return mOccupied[x][y];
2769 } else {
2770 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2771 }
2772 }
2773
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002774 @Override
2775 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2776 return new CellLayout.LayoutParams(getContext(), attrs);
2777 }
2778
2779 @Override
2780 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2781 return p instanceof CellLayout.LayoutParams;
2782 }
2783
2784 @Override
2785 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2786 return new CellLayout.LayoutParams(p);
2787 }
2788
2789 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2790 /**
2791 * Horizontal location of the item in the grid.
2792 */
2793 @ViewDebug.ExportedProperty
2794 public int cellX;
2795
2796 /**
2797 * Vertical location of the item in the grid.
2798 */
2799 @ViewDebug.ExportedProperty
2800 public int cellY;
2801
2802 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002803 * Temporary horizontal location of the item in the grid during reorder
2804 */
2805 public int tmpCellX;
2806
2807 /**
2808 * Temporary vertical location of the item in the grid during reorder
2809 */
2810 public int tmpCellY;
2811
2812 /**
2813 * Indicates that the temporary coordinates should be used to layout the items
2814 */
2815 public boolean useTmpCoords;
2816
2817 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002818 * Number of cells spanned horizontally by the item.
2819 */
2820 @ViewDebug.ExportedProperty
2821 public int cellHSpan;
2822
2823 /**
2824 * Number of cells spanned vertically by the item.
2825 */
2826 @ViewDebug.ExportedProperty
2827 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002828
Adam Cohen1b607ed2011-03-03 17:26:50 -08002829 /**
2830 * Indicates whether the item will set its x, y, width and height parameters freely,
2831 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2832 */
Adam Cohend4844c32011-02-18 19:25:06 -08002833 public boolean isLockedToGrid = true;
2834
Adam Cohen482ed822012-03-02 14:15:13 -08002835 /**
Adam Cohenec40b2b2013-07-23 15:52:40 -07002836 * Indicates that this item should use the full extents of its parent.
2837 */
2838 public boolean isFullscreen = false;
2839
2840 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002841 * Indicates whether this item can be reordered. Always true except in the case of the
2842 * the AllApps button.
2843 */
2844 public boolean canReorder = true;
2845
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002846 // X coordinate of the view in the layout.
2847 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002848 public int x;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002849 // Y coordinate of the view in the layout.
2850 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002851 public int y;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002852
Romain Guy84f296c2009-11-04 15:00:44 -08002853 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002854
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002855 public LayoutParams(Context c, AttributeSet attrs) {
2856 super(c, attrs);
2857 cellHSpan = 1;
2858 cellVSpan = 1;
2859 }
2860
2861 public LayoutParams(ViewGroup.LayoutParams source) {
2862 super(source);
2863 cellHSpan = 1;
2864 cellVSpan = 1;
2865 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002866
2867 public LayoutParams(LayoutParams source) {
2868 super(source);
2869 this.cellX = source.cellX;
2870 this.cellY = source.cellY;
2871 this.cellHSpan = source.cellHSpan;
2872 this.cellVSpan = source.cellVSpan;
2873 }
2874
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002875 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002876 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002877 this.cellX = cellX;
2878 this.cellY = cellY;
2879 this.cellHSpan = cellHSpan;
2880 this.cellVSpan = cellVSpan;
2881 }
2882
Adam Cohen2374abf2013-04-16 14:56:57 -07002883 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap,
2884 boolean invertHorizontally, int colCount) {
Adam Cohend4844c32011-02-18 19:25:06 -08002885 if (isLockedToGrid) {
2886 final int myCellHSpan = cellHSpan;
2887 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002888 int myCellX = useTmpCoords ? tmpCellX : cellX;
2889 int myCellY = useTmpCoords ? tmpCellY : cellY;
2890
2891 if (invertHorizontally) {
2892 myCellX = colCount - myCellX - cellHSpan;
2893 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002894
Adam Cohend4844c32011-02-18 19:25:06 -08002895 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2896 leftMargin - rightMargin;
2897 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2898 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002899 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2900 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002901 }
2902 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002903
Winson Chungaafa03c2010-06-11 17:34:16 -07002904 public String toString() {
2905 return "(" + this.cellX + ", " + this.cellY + ")";
2906 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002907
2908 public void setWidth(int width) {
2909 this.width = width;
2910 }
2911
2912 public int getWidth() {
2913 return width;
2914 }
2915
2916 public void setHeight(int height) {
2917 this.height = height;
2918 }
2919
2920 public int getHeight() {
2921 return height;
2922 }
2923
2924 public void setX(int x) {
2925 this.x = x;
2926 }
2927
2928 public int getX() {
2929 return x;
2930 }
2931
2932 public void setY(int y) {
2933 this.y = y;
2934 }
2935
2936 public int getY() {
2937 return y;
2938 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002939 }
2940
Michael Jurka0280c3b2010-09-17 15:00:07 -07002941 // This class stores info for two purposes:
2942 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2943 // its spanX, spanY, and the screen it is on
2944 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2945 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2946 // the CellLayout that was long clicked
Sunny Goyal83a8f042015-05-19 12:52:12 -07002947 public static final class CellInfo {
Adam Cohenf9c184a2016-01-15 16:47:43 -08002948 public View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002949 int cellX = -1;
2950 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002951 int spanX;
2952 int spanY;
Adam Cohendcd297f2013-06-18 13:13:40 -07002953 long screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07002954 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002955
Sunny Goyal83a8f042015-05-19 12:52:12 -07002956 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002957 cell = v;
2958 cellX = info.cellX;
2959 cellY = info.cellY;
2960 spanX = info.spanX;
2961 spanY = info.spanY;
2962 screenId = info.screenId;
2963 container = info.container;
2964 }
2965
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002966 @Override
2967 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002968 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2969 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002970 }
2971 }
Michael Jurkad771c962011-08-09 15:00:48 -07002972
Sunny Goyala9116722015-04-29 13:55:58 -07002973 public boolean findVacantCell(int spanX, int spanY, int[] outXY) {
2974 return Utilities.findVacantCell(outXY, spanX, spanY, mCountX, mCountY, mOccupied);
2975 }
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002976
Tony Wickham86930612015-09-09 13:50:40 -07002977 /**
2978 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2979 * if necessary).
2980 */
2981 public boolean hasReorderSolution(ItemInfo itemInfo) {
2982 int[] cellPoint = new int[2];
2983 // Check for a solution starting at every cell.
2984 for (int cellX = 0; cellX < getCountX(); cellX++) {
2985 for (int cellY = 0; cellY < getCountY(); cellY++) {
2986 cellToPoint(cellX, cellY, cellPoint);
2987 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2988 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2989 true, new ItemConfiguration()).isSolution) {
2990 return true;
2991 }
2992 }
2993 }
2994 return false;
2995 }
2996
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002997 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
2998 int x2 = x + spanX - 1;
2999 int y2 = y + spanY - 1;
3000 if (x < 0 || y < 0 || x2 >= mCountX || y2 >= mCountY) {
3001 return false;
3002 }
3003 for (int i = x; i <= x2; i++) {
3004 for (int j = y; j <= y2; j++) {
3005 if (mOccupied[i][j]) {
3006 return false;
3007 }
3008 }
3009 }
3010
3011 return true;
3012 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003013}