blob: 51ee47aeedbdd3c150e776c6d997b1b331100635 [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);
Adam Cohenf172b742016-03-30 19:28:34 -0700513 if (!bg.isClipping) {
514 bg.drawBackgroundStroke(canvas, mFolderBgPaint);
515 }
Adam Cohenefca0272016-02-24 19:19:06 -0800516 canvas.restore();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700517 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700518
Adam Cohenefca0272016-02-24 19:19:06 -0800519 if (mFolderLeaveBehind.delegateCellX >= 0 && mFolderLeaveBehind.delegateCellY >= 0) {
520 cellToPoint(mFolderLeaveBehind.delegateCellX,
521 mFolderLeaveBehind.delegateCellY, mTempLocation);
522 canvas.save();
523 canvas.translate(mTempLocation[0], mTempLocation[1]);
524 mFolderLeaveBehind.drawLeaveBehind(canvas, mFolderBgPaint);
525 canvas.restore();
Adam Cohenc51934b2011-07-26 21:07:43 -0700526 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700527 }
528
Adam Cohenefca0272016-02-24 19:19:06 -0800529 @Override
530 protected void dispatchDraw(Canvas canvas) {
531 super.dispatchDraw(canvas);
532
533 for (int i = 0; i < mFolderBackgrounds.size(); i++) {
534 FolderIcon.PreviewBackground bg = mFolderBackgrounds.get(i);
Adam Cohenf172b742016-03-30 19:28:34 -0700535 if (bg.isClipping) {
536 cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
537 canvas.save();
538 canvas.translate(mTempLocation[0], mTempLocation[1]);
539 bg.drawBackgroundStroke(canvas, mFolderBgPaint);
540 canvas.restore();
541 }
Adam Cohenefca0272016-02-24 19:19:06 -0800542 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700543 }
544
Adam Cohenefca0272016-02-24 19:19:06 -0800545 public void addFolderBackground(FolderIcon.PreviewBackground bg) {
546 mFolderBackgrounds.add(bg);
547 }
548 public void removeFolderBackground(FolderIcon.PreviewBackground bg) {
549 mFolderBackgrounds.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700550 }
551
Adam Cohenc51934b2011-07-26 21:07:43 -0700552 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800553
554 DeviceProfile grid = mLauncher.getDeviceProfile();
555 View child = getChildAt(x, y);
556
557 mFolderLeaveBehind.setup(getResources().getDisplayMetrics(), grid, null,
558 child.getMeasuredWidth(), child.getPaddingTop());
559
560 mFolderLeaveBehind.delegateCellX = x;
561 mFolderLeaveBehind.delegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700562 invalidate();
563 }
564
565 public void clearFolderLeaveBehind() {
Adam Cohenefca0272016-02-24 19:19:06 -0800566 mFolderLeaveBehind.delegateCellX = -1;
567 mFolderLeaveBehind.delegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700568 invalidate();
569 }
570
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700571 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700572 public boolean shouldDelayChildPressedState() {
573 return false;
574 }
575
Adam Cohen1462de32012-07-24 22:34:36 -0700576 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700577 try {
578 dispatchRestoreInstanceState(states);
579 } catch (IllegalArgumentException ex) {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700580 if (ProviderConfig.IS_DOGFOOD_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700581 throw ex;
582 }
583 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
584 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
585 }
Adam Cohen1462de32012-07-24 22:34:36 -0700586 }
587
Michael Jurkae6235dd2011-10-04 15:02:05 -0700588 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700589 public void cancelLongPress() {
590 super.cancelLongPress();
591
592 // Cancel long press for all children
593 final int count = getChildCount();
594 for (int i = 0; i < count; i++) {
595 final View child = getChildAt(i);
596 child.cancelLongPress();
597 }
598 }
599
Michael Jurkadee05892010-07-27 10:01:56 -0700600 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
601 mInterceptTouchListener = listener;
602 }
603
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800604 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700605 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800606 }
607
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800608 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700609 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800610 }
611
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800612 public void setIsHotseat(boolean isHotseat) {
613 mIsHotseat = isHotseat;
Winson Chung5f8afe62013-08-12 16:19:28 -0700614 mShortcutsAndWidgets.setIsHotseat(isHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800615 }
616
Sunny Goyale9b651e2015-04-24 11:44:51 -0700617 public boolean isHotseat() {
618 return mIsHotseat;
619 }
620
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800621 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700622 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700623 final LayoutParams lp = params;
624
Andrew Flynnde38e422012-05-08 11:22:15 -0700625 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800626 if (child instanceof BubbleTextView) {
627 BubbleTextView bubbleChild = (BubbleTextView) child;
Winson Chung5f8afe62013-08-12 16:19:28 -0700628 bubbleChild.setTextVisibility(!mIsHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800629 }
630
Adam Cohen307fe232012-08-16 17:55:58 -0700631 child.setScaleX(getChildrenScale());
632 child.setScaleY(getChildrenScale());
633
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800634 // Generate an id for each view, this assumes we have at most 256x256 cells
635 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700636 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700637 // If the horizontal or vertical span is set to -1, it is taken to
638 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700639 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
640 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800641
Winson Chungaafa03c2010-06-11 17:34:16 -0700642 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700643 if (LOGD) {
644 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
645 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700646 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700647
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700648 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700649
Winson Chungaafa03c2010-06-11 17:34:16 -0700650 return true;
651 }
652 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800653 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700654
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800655 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700656 public void removeAllViews() {
657 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700658 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700659 }
660
661 @Override
662 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700663 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700664 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700665 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700666 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700667 }
668
669 @Override
670 public void removeView(View view) {
671 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700672 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700673 }
674
675 @Override
676 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700677 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
678 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700679 }
680
681 @Override
682 public void removeViewInLayout(View view) {
683 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700684 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700685 }
686
687 @Override
688 public void removeViews(int start, int count) {
689 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700690 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700691 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700692 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700693 }
694
695 @Override
696 public void removeViewsInLayout(int start, int count) {
697 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700698 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700699 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700700 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800701 }
702
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700703 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700704 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800705 * @param x X coordinate of the point
706 * @param y Y coordinate of the point
707 * @param result Array of 2 ints to hold the x and y coordinate of the cell
708 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700709 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700710 final int hStartPadding = getPaddingLeft();
711 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800712
713 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
714 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
715
Adam Cohend22015c2010-07-26 22:02:18 -0700716 final int xAxis = mCountX;
717 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800718
719 if (result[0] < 0) result[0] = 0;
720 if (result[0] >= xAxis) result[0] = xAxis - 1;
721 if (result[1] < 0) result[1] = 0;
722 if (result[1] >= yAxis) result[1] = yAxis - 1;
723 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700724
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800725 /**
726 * Given a point, return the cell that most closely encloses that point
727 * @param x X coordinate of the point
728 * @param y Y coordinate of the point
729 * @param result Array of 2 ints to hold the x and y coordinate of the cell
730 */
731 void pointToCellRounded(int x, int y, int[] result) {
732 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
733 }
734
735 /**
736 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700737 *
738 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800739 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700740 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800741 * @param result Array of 2 ints to hold the x and y coordinate of the point
742 */
743 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700744 final int hStartPadding = getPaddingLeft();
745 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800746
747 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
748 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
749 }
750
Adam Cohene3e27a82011-04-15 12:07:39 -0700751 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800752 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700753 *
754 * @param cellX X coordinate of the cell
755 * @param cellY Y coordinate of the cell
756 *
757 * @param result Array of 2 ints to hold the x and y coordinate of the point
758 */
759 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700760 regionToCenterPoint(cellX, cellY, 1, 1, result);
761 }
762
763 /**
764 * Given a cell coordinate and span return the point that represents the center of the regio
765 *
766 * @param cellX X coordinate of the cell
767 * @param cellY Y coordinate of the cell
768 *
769 * @param result Array of 2 ints to hold the x and y coordinate of the point
770 */
771 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700772 final int hStartPadding = getPaddingLeft();
773 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700774 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
775 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
776 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
777 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700778 }
779
Adam Cohen19f37922012-03-21 11:59:11 -0700780 /**
781 * Given a cell coordinate and span fills out a corresponding pixel rect
782 *
783 * @param cellX X coordinate of the cell
784 * @param cellY Y coordinate of the cell
785 * @param result Rect in which to write the result
786 */
787 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
788 final int hStartPadding = getPaddingLeft();
789 final int vStartPadding = getPaddingTop();
790 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
791 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
792 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
793 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
794 }
795
Adam Cohen482ed822012-03-02 14:15:13 -0800796 public float getDistanceFromCell(float x, float y, int[] cell) {
797 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700798 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800799 }
800
Adam Cohenf9c184a2016-01-15 16:47:43 -0800801 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800802 return mCellWidth;
803 }
804
805 int getCellHeight() {
806 return mCellHeight;
807 }
808
Adam Cohend4844c32011-02-18 19:25:06 -0800809 int getWidthGap() {
810 return mWidthGap;
811 }
812
813 int getHeightGap() {
814 return mHeightGap;
815 }
816
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700817 public void setFixedSize(int width, int height) {
818 mFixedWidth = width;
819 mFixedHeight = height;
820 }
821
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800822 @Override
823 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800824 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800825 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700826 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
827 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700828 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
829 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Winson Chung11a1a532013-09-13 11:14:45 -0700830 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Sunny Goyalc6205602015-05-21 20:46:33 -0700831 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
832 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700833 if (cw != mCellWidth || ch != mCellHeight) {
834 mCellWidth = cw;
835 mCellHeight = ch;
836 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
837 mHeightGap, mCountX, mCountY);
838 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700839 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700840
Winson Chung2d75f122013-09-23 16:53:31 -0700841 int newWidth = childWidthSize;
842 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700843 if (mFixedWidth > 0 && mFixedHeight > 0) {
844 newWidth = mFixedWidth;
845 newHeight = mFixedHeight;
846 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800847 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
848 }
849
Adam Cohend22015c2010-07-26 22:02:18 -0700850 int numWidthGaps = mCountX - 1;
851 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800852
Adam Cohen234c4cd2011-07-17 21:03:04 -0700853 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -0700854 int hSpace = childWidthSize;
855 int vSpace = childHeightSize;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700856 int hFreeSpace = hSpace - (mCountX * mCellWidth);
857 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700858 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
859 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Winson Chung5f8afe62013-08-12 16:19:28 -0700860 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
861 mHeightGap, mCountX, mCountY);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700862 } else {
863 mWidthGap = mOriginalWidthGap;
864 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700865 }
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700866
867 // Make the feedback view large enough to hold the blur bitmap.
868 mTouchFeedbackView.measure(
869 MeasureSpec.makeMeasureSpec(mCellWidth + mTouchFeedbackView.getExtraSize(),
870 MeasureSpec.EXACTLY),
871 MeasureSpec.makeMeasureSpec(mCellHeight + mTouchFeedbackView.getExtraSize(),
872 MeasureSpec.EXACTLY));
873
874 mShortcutsAndWidgets.measure(
875 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
876 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
877
878 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
879 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700880 if (mFixedWidth > 0 && mFixedHeight > 0) {
881 setMeasuredDimension(maxWidth, maxHeight);
882 } else {
883 setMeasuredDimension(widthSize, heightSize);
884 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800885 }
886
887 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700888 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -0800889 boolean isFullscreen = mShortcutsAndWidgets.getChildCount() > 0 &&
890 ((LayoutParams) mShortcutsAndWidgets.getChildAt(0).getLayoutParams()).isFullscreen;
891 int left = getPaddingLeft();
892 if (!isFullscreen) {
Tony Wickhama501d492015-11-03 18:05:01 -0800893 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Tony Wickham26b01422015-11-10 14:44:32 -0800894 }
Winson Chung38848ca2013-10-08 12:03:44 -0700895 int top = getPaddingTop();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700896
897 mTouchFeedbackView.layout(left, top,
898 left + mTouchFeedbackView.getMeasuredWidth(),
899 top + mTouchFeedbackView.getMeasuredHeight());
900 mShortcutsAndWidgets.layout(left, top,
901 left + r - l,
902 top + b - t);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800903 }
904
Tony Wickhama501d492015-11-03 18:05:01 -0800905 /**
906 * Returns the amount of space left over after subtracting padding and cells. This space will be
907 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
908 * width in {@link DeviceProfile#calculateCellWidth(int, int)}.
909 */
910 public int getUnusedHorizontalSpace() {
911 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
912 }
913
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800914 @Override
Michael Jurkadee05892010-07-27 10:01:56 -0700915 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
916 super.onSizeChanged(w, h, oldw, oldh);
Winson Chung82a9bd22013-10-08 16:02:34 -0700917
918 // Expand the background drawing bounds by the padding baked into the background drawable
Sunny Goyal2805e632015-05-20 15:35:32 -0700919 mBackground.getPadding(mTempRect);
920 mBackground.setBounds(-mTempRect.left, -mTempRect.top,
921 w + mTempRect.right, h + mTempRect.bottom);
Michael Jurkadee05892010-07-27 10:01:56 -0700922 }
923
924 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800925 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700926 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800927 }
928
929 @Override
930 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700931 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800932 }
933
Michael Jurka5f1c5092010-09-03 14:15:02 -0700934 public float getBackgroundAlpha() {
935 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -0700936 }
937
Michael Jurka5f1c5092010-09-03 14:15:02 -0700938 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -0800939 if (mBackgroundAlpha != alpha) {
940 mBackgroundAlpha = alpha;
Sunny Goyal2805e632015-05-20 15:35:32 -0700941 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurkaafaa0502011-12-13 18:22:50 -0800942 }
Michael Jurkadee05892010-07-27 10:01:56 -0700943 }
944
Sunny Goyal2805e632015-05-20 15:35:32 -0700945 @Override
946 protected boolean verifyDrawable(Drawable who) {
947 return super.verifyDrawable(who) || (mIsDragTarget && who == mBackground);
948 }
949
Michael Jurkaa52570f2012-03-20 03:18:20 -0700950 public void setShortcutAndWidgetAlpha(float alpha) {
Sunny Goyal02b50812014-09-10 15:44:42 -0700951 mShortcutsAndWidgets.setAlpha(alpha);
Michael Jurkadee05892010-07-27 10:01:56 -0700952 }
953
Michael Jurkaa52570f2012-03-20 03:18:20 -0700954 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -0700955 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700956 }
957
Patrick Dubroy440c3602010-07-13 17:50:32 -0700958 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700959 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -0700960 }
961
Adam Cohen76fc0852011-06-17 13:26:23 -0700962 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -0800963 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700964 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -0800965 boolean[][] occupied = mOccupied;
966 if (!permanent) {
967 occupied = mTmpOccupied;
968 }
969
Adam Cohen19f37922012-03-21 11:59:11 -0700970 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700971 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
972 final ItemInfo info = (ItemInfo) child.getTag();
973
974 // We cancel any existing animations
975 if (mReorderAnimators.containsKey(lp)) {
976 mReorderAnimators.get(lp).cancel();
977 mReorderAnimators.remove(lp);
978 }
979
Adam Cohen482ed822012-03-02 14:15:13 -0800980 final int oldX = lp.x;
981 final int oldY = lp.y;
982 if (adjustOccupied) {
983 occupied[lp.cellX][lp.cellY] = false;
984 occupied[cellX][cellY] = true;
985 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700986 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -0800987 if (permanent) {
988 lp.cellX = info.cellX = cellX;
989 lp.cellY = info.cellY = cellY;
990 } else {
991 lp.tmpCellX = cellX;
992 lp.tmpCellY = cellY;
993 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700994 clc.setupLp(lp);
995 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800996 final int newX = lp.x;
997 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700998
Adam Cohen76fc0852011-06-17 13:26:23 -0700999 lp.x = oldX;
1000 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001001
Adam Cohen482ed822012-03-02 14:15:13 -08001002 // Exit early if we're not actually moving the view
1003 if (oldX == newX && oldY == newY) {
1004 lp.isLockedToGrid = true;
1005 return true;
1006 }
1007
Michael Jurkaf1ad6082013-03-13 12:55:46 +01001008 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001009 va.setDuration(duration);
1010 mReorderAnimators.put(lp, va);
1011
1012 va.addUpdateListener(new AnimatorUpdateListener() {
1013 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001014 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001015 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001016 lp.x = (int) ((1 - r) * oldX + r * newX);
1017 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001018 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001019 }
1020 });
Adam Cohen482ed822012-03-02 14:15:13 -08001021 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001022 boolean cancelled = false;
1023 public void onAnimationEnd(Animator animation) {
1024 // If the animation was cancelled, it means that another animation
1025 // has interrupted this one, and we don't want to lock the item into
1026 // place just yet.
1027 if (!cancelled) {
1028 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001029 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001030 }
1031 if (mReorderAnimators.containsKey(lp)) {
1032 mReorderAnimators.remove(lp);
1033 }
1034 }
1035 public void onAnimationCancel(Animator animation) {
1036 cancelled = true;
1037 }
1038 });
Adam Cohen482ed822012-03-02 14:15:13 -08001039 va.setStartDelay(delay);
1040 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001041 return true;
1042 }
1043 return false;
1044 }
1045
Tony Wickhama501d492015-11-03 18:05:01 -08001046 void visualizeDropLocation(View v, Bitmap dragOutline, int cellX, int cellY, int spanX,
1047 int spanY, boolean resize, DropTarget.DragObject dragObject) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001048 final int oldDragCellX = mDragCell[0];
1049 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001050
Adam Cohen2801caf2011-05-13 20:57:39 -07001051 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001052 return;
1053 }
1054
Adam Cohen482ed822012-03-02 14:15:13 -08001055 if (cellX != oldDragCellX || cellY != oldDragCellY) {
Sunny Goyale78e3d72015-09-24 11:23:31 -07001056 Point dragOffset = dragObject.dragView.getDragVisualizeOffset();
1057 Rect dragRegion = dragObject.dragView.getDragRegion();
1058
Adam Cohen482ed822012-03-02 14:15:13 -08001059 mDragCell[0] = cellX;
1060 mDragCell[1] = cellY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001061
Joe Onorato4be866d2010-10-10 11:26:02 -07001062 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001063 mDragOutlineAnims[oldIndex].animateOut();
1064 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001065 Rect r = mDragOutlines[mDragOutlineCurrent];
Sunny Goyal106bf642015-07-16 12:18:06 -07001066
Adam Cohend41fbf52012-02-16 23:53:59 -08001067 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001068 cellToRect(cellX, cellY, spanX, spanY, r);
Sunny Goyal106bf642015-07-16 12:18:06 -07001069 } else {
1070 // Find the top left corner of the rect the object will occupy
1071 final int[] topLeft = mTmpPoint;
1072 cellToPoint(cellX, cellY, topLeft);
1073
1074 int left = topLeft[0];
1075 int top = topLeft[1];
1076
1077 if (v != null && dragOffset == null) {
1078 // When drawing the drag outline, it did not account for margin offsets
1079 // added by the view's parent.
1080 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1081 left += lp.leftMargin;
1082 top += lp.topMargin;
1083
1084 // Offsets due to the size difference between the View and the dragOutline.
1085 // There is a size difference to account for the outer blur, which may lie
1086 // outside the bounds of the view.
1087 top += (v.getHeight() - dragOutline.getHeight()) / 2;
1088 // We center about the x axis
1089 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1090 - dragOutline.getWidth()) / 2;
1091 } else {
1092 if (dragOffset != null && dragRegion != null) {
1093 // Center the drag region *horizontally* in the cell and apply a drag
1094 // outline offset
1095 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1096 - dragRegion.width()) / 2;
1097 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
1098 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
1099 top += dragOffset.y + cellPaddingY;
1100 } else {
1101 // Center the drag outline in the cell
1102 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1103 - dragOutline.getWidth()) / 2;
1104 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1105 - dragOutline.getHeight()) / 2;
1106 }
1107 }
1108 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
Adam Cohend41fbf52012-02-16 23:53:59 -08001109 }
Winson Chung150fbab2010-09-29 17:14:26 -07001110
Sunny Goyal106bf642015-07-16 12:18:06 -07001111 Utilities.scaleRectAboutCenter(r, getChildrenScale());
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001112 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1113 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001114
1115 if (dragObject.stateAnnouncer != null) {
1116 String msg;
1117 if (isHotseat()) {
1118 msg = getContext().getString(R.string.move_to_hotseat_position,
1119 Math.max(cellX, cellY) + 1);
1120 } else {
1121 msg = getContext().getString(R.string.move_to_empty_cell,
1122 cellY + 1, cellX + 1);
1123 }
1124 dragObject.stateAnnouncer.announce(msg);
1125 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001126 }
1127 }
1128
Adam Cohene0310962011-04-18 16:15:31 -07001129 public void clearDragOutlines() {
1130 final int oldIndex = mDragOutlineCurrent;
1131 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001132 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001133 }
1134
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001135 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001136 * Find a vacant area that will fit the given bounds nearest the requested
1137 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001138 *
Romain Guy51afc022009-05-04 18:03:43 -07001139 * @param pixelX The X location at which you want to search for a vacant area.
1140 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001141 * @param minSpanX The minimum horizontal span required
1142 * @param minSpanY The minimum vertical span required
1143 * @param spanX Horizontal span of the object.
1144 * @param spanY Vertical span of the object.
1145 * @param result Array in which to place the result, or null (in which case a new array will
1146 * be allocated)
1147 * @return The X, Y cell of a vacant area that can contain this object,
1148 * nearest the requested location.
1149 */
1150 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1151 int spanY, int[] result, int[] resultSpan) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001152 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
Adam Cohend41fbf52012-02-16 23:53:59 -08001153 result, resultSpan);
1154 }
1155
Adam Cohend41fbf52012-02-16 23:53:59 -08001156 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1157 private void lazyInitTempRectStack() {
1158 if (mTempRectStack.isEmpty()) {
1159 for (int i = 0; i < mCountX * mCountY; i++) {
1160 mTempRectStack.push(new Rect());
1161 }
1162 }
1163 }
Adam Cohen482ed822012-03-02 14:15:13 -08001164
Adam Cohend41fbf52012-02-16 23:53:59 -08001165 private void recycleTempRects(Stack<Rect> used) {
1166 while (!used.isEmpty()) {
1167 mTempRectStack.push(used.pop());
1168 }
1169 }
1170
1171 /**
1172 * Find a vacant area that will fit the given bounds nearest the requested
1173 * cell location. Uses Euclidean distance to score multiple vacant areas.
1174 *
1175 * @param pixelX The X location at which you want to search for a vacant area.
1176 * @param pixelY The Y location at which you want to search for a vacant area.
1177 * @param minSpanX The minimum horizontal span required
1178 * @param minSpanY The minimum vertical span required
1179 * @param spanX Horizontal span of the object.
1180 * @param spanY Vertical span of the object.
1181 * @param ignoreOccupied If true, the result can be an occupied cell
1182 * @param result Array in which to place the result, or null (in which case a new array will
1183 * be allocated)
1184 * @return The X, Y cell of a vacant area that can contain this object,
1185 * nearest the requested location.
1186 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001187 private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1188 int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001189 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001190
Adam Cohene3e27a82011-04-15 12:07:39 -07001191 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1192 // to the center of the item, but we are searching based on the top-left cell, so
1193 // we translate the point over to correspond to the top-left.
1194 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1195 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1196
Jeff Sharkey70864282009-04-07 21:08:40 -07001197 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001198 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001199 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001200 final Rect bestRect = new Rect(-1, -1, -1, -1);
1201 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001202
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001203 final int countX = mCountX;
1204 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001205
Adam Cohend41fbf52012-02-16 23:53:59 -08001206 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1207 spanX < minSpanX || spanY < minSpanY) {
1208 return bestXY;
1209 }
1210
1211 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001212 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001213 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1214 int ySize = -1;
1215 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001216 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001217 // First, let's see if this thing fits anywhere
1218 for (int i = 0; i < minSpanX; i++) {
1219 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001220 if (mOccupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001221 continue inner;
1222 }
Michael Jurkac28de512010-08-13 11:27:44 -07001223 }
1224 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001225 xSize = minSpanX;
1226 ySize = minSpanY;
1227
1228 // We know that the item will fit at _some_ acceptable size, now let's see
1229 // how big we can make it. We'll alternate between incrementing x and y spans
1230 // until we hit a limit.
1231 boolean incX = true;
1232 boolean hitMaxX = xSize >= spanX;
1233 boolean hitMaxY = ySize >= spanY;
1234 while (!(hitMaxX && hitMaxY)) {
1235 if (incX && !hitMaxX) {
1236 for (int j = 0; j < ySize; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001237 if (x + xSize > countX -1 || mOccupied[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001238 // We can't move out horizontally
1239 hitMaxX = true;
1240 }
1241 }
1242 if (!hitMaxX) {
1243 xSize++;
1244 }
1245 } else if (!hitMaxY) {
1246 for (int i = 0; i < xSize; i++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001247 if (y + ySize > countY - 1 || mOccupied[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001248 // We can't move out vertically
1249 hitMaxY = true;
1250 }
1251 }
1252 if (!hitMaxY) {
1253 ySize++;
1254 }
1255 }
1256 hitMaxX |= xSize >= spanX;
1257 hitMaxY |= ySize >= spanY;
1258 incX = !incX;
1259 }
1260 incX = true;
1261 hitMaxX = xSize >= spanX;
1262 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001263 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001264 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001265 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001266
Adam Cohend41fbf52012-02-16 23:53:59 -08001267 // We verify that the current rect is not a sub-rect of any of our previous
1268 // candidates. In this case, the current rect is disqualified in favour of the
1269 // containing rect.
1270 Rect currentRect = mTempRectStack.pop();
1271 currentRect.set(x, y, x + xSize, y + ySize);
1272 boolean contained = false;
1273 for (Rect r : validRegions) {
1274 if (r.contains(currentRect)) {
1275 contained = true;
1276 break;
1277 }
1278 }
1279 validRegions.push(currentRect);
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001280 double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
Adam Cohen482ed822012-03-02 14:15:13 -08001281
Adam Cohend41fbf52012-02-16 23:53:59 -08001282 if ((distance <= bestDistance && !contained) ||
1283 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001284 bestDistance = distance;
1285 bestXY[0] = x;
1286 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001287 if (resultSpan != null) {
1288 resultSpan[0] = xSize;
1289 resultSpan[1] = ySize;
1290 }
1291 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001292 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001293 }
1294 }
1295
Adam Cohenc0dcf592011-06-01 15:30:43 -07001296 // Return -1, -1 if no suitable location found
1297 if (bestDistance == Double.MAX_VALUE) {
1298 bestXY[0] = -1;
1299 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001300 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001301 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001302 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001303 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001304
Adam Cohen482ed822012-03-02 14:15:13 -08001305 /**
1306 * Find a vacant area that will fit the given bounds nearest the requested
1307 * cell location, and will also weigh in a suggested direction vector of the
1308 * desired location. This method computers distance based on unit grid distances,
1309 * not pixel distances.
1310 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001311 * @param cellX The X cell nearest to which you want to search for a vacant area.
1312 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001313 * @param spanX Horizontal span of the object.
1314 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001315 * @param direction The favored direction in which the views should move from x, y
Sunny Goyal9eba1fd2015-10-16 08:58:57 -07001316 * @param occupied The array which represents which cells in the CellLayout are occupied
Adam Cohen47a876d2012-03-19 13:21:41 -07001317 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001318 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001319 * @param result Array in which to place the result, or null (in which case a new array will
1320 * be allocated)
1321 * @return The X, Y cell of a vacant area that can contain this object,
1322 * nearest the requested location.
1323 */
1324 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001325 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001326 // Keep track of best-scoring drop area
1327 final int[] bestXY = result != null ? result : new int[2];
1328 float bestDistance = Float.MAX_VALUE;
1329 int bestDirectionScore = Integer.MIN_VALUE;
1330
1331 final int countX = mCountX;
1332 final int countY = mCountY;
1333
1334 for (int y = 0; y < countY - (spanY - 1); y++) {
1335 inner:
1336 for (int x = 0; x < countX - (spanX - 1); x++) {
1337 // First, let's see if this thing fits anywhere
1338 for (int i = 0; i < spanX; i++) {
1339 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001340 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001341 continue inner;
1342 }
1343 }
1344 }
1345
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001346 float distance = (float) Math.hypot(x - cellX, y - cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001347 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001348 computeDirectionVector(x - cellX, y - cellY, curDirection);
1349 // The direction score is just the dot product of the two candidate direction
1350 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001351 int curDirectionScore = direction[0] * curDirection[0] +
1352 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001353 boolean exactDirectionOnly = false;
1354 boolean directionMatches = direction[0] == curDirection[0] &&
1355 direction[0] == curDirection[0];
1356 if ((directionMatches || !exactDirectionOnly) &&
1357 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001358 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1359 bestDistance = distance;
1360 bestDirectionScore = curDirectionScore;
1361 bestXY[0] = x;
1362 bestXY[1] = y;
1363 }
1364 }
1365 }
1366
1367 // Return -1, -1 if no suitable location found
1368 if (bestDistance == Float.MAX_VALUE) {
1369 bestXY[0] = -1;
1370 bestXY[1] = -1;
1371 }
1372 return bestXY;
1373 }
1374
1375 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001376 int[] direction, ItemConfiguration currentState) {
1377 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001378 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001379 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001380 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1381
Adam Cohen8baab352012-03-20 17:39:21 -07001382 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001383
1384 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001385 c.x = mTempLocation[0];
1386 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001387 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001388 }
Adam Cohen8baab352012-03-20 17:39:21 -07001389 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001390 return success;
1391 }
1392
Adam Cohenf3900c22012-11-16 18:28:11 -08001393 /**
1394 * This helper class defines a cluster of views. It helps with defining complex edges
1395 * of the cluster and determining how those edges interact with other views. The edges
1396 * essentially define a fine-grained boundary around the cluster of views -- like a more
1397 * precise version of a bounding box.
1398 */
1399 private class ViewCluster {
1400 final static int LEFT = 0;
1401 final static int TOP = 1;
1402 final static int RIGHT = 2;
1403 final static int BOTTOM = 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001404
Adam Cohenf3900c22012-11-16 18:28:11 -08001405 ArrayList<View> views;
1406 ItemConfiguration config;
1407 Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001408
Adam Cohenf3900c22012-11-16 18:28:11 -08001409 int[] leftEdge = new int[mCountY];
1410 int[] rightEdge = new int[mCountY];
1411 int[] topEdge = new int[mCountX];
1412 int[] bottomEdge = new int[mCountX];
1413 boolean leftEdgeDirty, rightEdgeDirty, topEdgeDirty, bottomEdgeDirty, boundingRectDirty;
1414
1415 @SuppressWarnings("unchecked")
1416 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1417 this.views = (ArrayList<View>) views.clone();
1418 this.config = config;
1419 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001420 }
1421
Adam Cohenf3900c22012-11-16 18:28:11 -08001422 void resetEdges() {
1423 for (int i = 0; i < mCountX; i++) {
1424 topEdge[i] = -1;
1425 bottomEdge[i] = -1;
1426 }
1427 for (int i = 0; i < mCountY; i++) {
1428 leftEdge[i] = -1;
1429 rightEdge[i] = -1;
1430 }
1431 leftEdgeDirty = true;
1432 rightEdgeDirty = true;
1433 bottomEdgeDirty = true;
1434 topEdgeDirty = true;
1435 boundingRectDirty = true;
1436 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001437
Adam Cohenf3900c22012-11-16 18:28:11 -08001438 void computeEdge(int which, int[] edge) {
1439 int count = views.size();
1440 for (int i = 0; i < count; i++) {
1441 CellAndSpan cs = config.map.get(views.get(i));
1442 switch (which) {
1443 case LEFT:
1444 int left = cs.x;
1445 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1446 if (left < edge[j] || edge[j] < 0) {
1447 edge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001448 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001449 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001450 break;
1451 case RIGHT:
1452 int right = cs.x + cs.spanX;
1453 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1454 if (right > edge[j]) {
1455 edge[j] = right;
1456 }
1457 }
1458 break;
1459 case TOP:
1460 int top = cs.y;
1461 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1462 if (top < edge[j] || edge[j] < 0) {
1463 edge[j] = top;
1464 }
1465 }
1466 break;
1467 case BOTTOM:
1468 int bottom = cs.y + cs.spanY;
1469 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1470 if (bottom > edge[j]) {
1471 edge[j] = bottom;
1472 }
1473 }
1474 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001475 }
1476 }
1477 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001478
1479 boolean isViewTouchingEdge(View v, int whichEdge) {
1480 CellAndSpan cs = config.map.get(v);
1481
1482 int[] edge = getEdge(whichEdge);
1483
1484 switch (whichEdge) {
1485 case LEFT:
1486 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1487 if (edge[i] == cs.x + cs.spanX) {
1488 return true;
1489 }
1490 }
1491 break;
1492 case RIGHT:
1493 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1494 if (edge[i] == cs.x) {
1495 return true;
1496 }
1497 }
1498 break;
1499 case TOP:
1500 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1501 if (edge[i] == cs.y + cs.spanY) {
1502 return true;
1503 }
1504 }
1505 break;
1506 case BOTTOM:
1507 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1508 if (edge[i] == cs.y) {
1509 return true;
1510 }
1511 }
1512 break;
1513 }
1514 return false;
1515 }
1516
1517 void shift(int whichEdge, int delta) {
1518 for (View v: views) {
1519 CellAndSpan c = config.map.get(v);
1520 switch (whichEdge) {
1521 case LEFT:
1522 c.x -= delta;
1523 break;
1524 case RIGHT:
1525 c.x += delta;
1526 break;
1527 case TOP:
1528 c.y -= delta;
1529 break;
1530 case BOTTOM:
1531 default:
1532 c.y += delta;
1533 break;
1534 }
1535 }
1536 resetEdges();
1537 }
1538
1539 public void addView(View v) {
1540 views.add(v);
1541 resetEdges();
1542 }
1543
1544 public Rect getBoundingRect() {
1545 if (boundingRectDirty) {
1546 boolean first = true;
1547 for (View v: views) {
1548 CellAndSpan c = config.map.get(v);
1549 if (first) {
1550 boundingRect.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1551 first = false;
1552 } else {
1553 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1554 }
1555 }
1556 }
1557 return boundingRect;
1558 }
1559
1560 public int[] getEdge(int which) {
1561 switch (which) {
1562 case LEFT:
1563 return getLeftEdge();
1564 case RIGHT:
1565 return getRightEdge();
1566 case TOP:
1567 return getTopEdge();
1568 case BOTTOM:
1569 default:
1570 return getBottomEdge();
1571 }
1572 }
1573
1574 public int[] getLeftEdge() {
1575 if (leftEdgeDirty) {
1576 computeEdge(LEFT, leftEdge);
1577 }
1578 return leftEdge;
1579 }
1580
1581 public int[] getRightEdge() {
1582 if (rightEdgeDirty) {
1583 computeEdge(RIGHT, rightEdge);
1584 }
1585 return rightEdge;
1586 }
1587
1588 public int[] getTopEdge() {
1589 if (topEdgeDirty) {
1590 computeEdge(TOP, topEdge);
1591 }
1592 return topEdge;
1593 }
1594
1595 public int[] getBottomEdge() {
1596 if (bottomEdgeDirty) {
1597 computeEdge(BOTTOM, bottomEdge);
1598 }
1599 return bottomEdge;
1600 }
1601
1602 PositionComparator comparator = new PositionComparator();
1603 class PositionComparator implements Comparator<View> {
1604 int whichEdge = 0;
1605 public int compare(View left, View right) {
1606 CellAndSpan l = config.map.get(left);
1607 CellAndSpan r = config.map.get(right);
1608 switch (whichEdge) {
1609 case LEFT:
1610 return (r.x + r.spanX) - (l.x + l.spanX);
1611 case RIGHT:
1612 return l.x - r.x;
1613 case TOP:
1614 return (r.y + r.spanY) - (l.y + l.spanY);
1615 case BOTTOM:
1616 default:
1617 return l.y - r.y;
1618 }
1619 }
1620 }
1621
1622 public void sortConfigurationForEdgePush(int edge) {
1623 comparator.whichEdge = edge;
1624 Collections.sort(config.sortedViews, comparator);
1625 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001626 }
1627
Adam Cohenf3900c22012-11-16 18:28:11 -08001628 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1629 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001630
Adam Cohenf3900c22012-11-16 18:28:11 -08001631 ViewCluster cluster = new ViewCluster(views, currentState);
1632 Rect clusterRect = cluster.getBoundingRect();
1633 int whichEdge;
1634 int pushDistance;
1635 boolean fail = false;
1636
1637 // Determine the edge of the cluster that will be leading the push and how far
1638 // the cluster must be shifted.
1639 if (direction[0] < 0) {
1640 whichEdge = ViewCluster.LEFT;
1641 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001642 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001643 whichEdge = ViewCluster.RIGHT;
1644 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1645 } else if (direction[1] < 0) {
1646 whichEdge = ViewCluster.TOP;
1647 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1648 } else {
1649 whichEdge = ViewCluster.BOTTOM;
1650 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07001651 }
1652
Adam Cohenf3900c22012-11-16 18:28:11 -08001653 // Break early for invalid push distance.
1654 if (pushDistance <= 0) {
1655 return false;
Adam Cohene0489502012-08-27 15:18:53 -07001656 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001657
1658 // Mark the occupied state as false for the group of views we want to move.
1659 for (View v: views) {
1660 CellAndSpan c = currentState.map.get(v);
1661 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1662 }
1663
1664 // We save the current configuration -- if we fail to find a solution we will revert
1665 // to the initial state. The process of finding a solution modifies the configuration
1666 // in place, hence the need for revert in the failure case.
1667 currentState.save();
1668
1669 // The pushing algorithm is simplified by considering the views in the order in which
1670 // they would be pushed by the cluster. For example, if the cluster is leading with its
1671 // left edge, we consider sort the views by their right edge, from right to left.
1672 cluster.sortConfigurationForEdgePush(whichEdge);
1673
1674 while (pushDistance > 0 && !fail) {
1675 for (View v: currentState.sortedViews) {
1676 // For each view that isn't in the cluster, we see if the leading edge of the
1677 // cluster is contacting the edge of that view. If so, we add that view to the
1678 // cluster.
1679 if (!cluster.views.contains(v) && v != dragView) {
1680 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1681 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1682 if (!lp.canReorder) {
1683 // The push solution includes the all apps button, this is not viable.
1684 fail = true;
1685 break;
1686 }
1687 cluster.addView(v);
1688 CellAndSpan c = currentState.map.get(v);
1689
1690 // Adding view to cluster, mark it as not occupied.
1691 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1692 }
1693 }
1694 }
1695 pushDistance--;
1696
1697 // The cluster has been completed, now we move the whole thing over in the appropriate
1698 // direction.
1699 cluster.shift(whichEdge, 1);
1700 }
1701
1702 boolean foundSolution = false;
1703 clusterRect = cluster.getBoundingRect();
1704
1705 // Due to the nature of the algorithm, the only check required to verify a valid solution
1706 // is to ensure that completed shifted cluster lies completely within the cell layout.
1707 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1708 clusterRect.bottom <= mCountY) {
1709 foundSolution = true;
1710 } else {
1711 currentState.restore();
1712 }
1713
1714 // In either case, we set the occupied array as marked for the location of the views
1715 for (View v: cluster.views) {
1716 CellAndSpan c = currentState.map.get(v);
1717 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
1718 }
1719
1720 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07001721 }
1722
Adam Cohen482ed822012-03-02 14:15:13 -08001723 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08001724 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001725 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001726
Adam Cohen8baab352012-03-20 17:39:21 -07001727 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001728 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001729 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001730 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001731 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001732 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001733 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001734 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001735 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001736 }
1737 }
Adam Cohen8baab352012-03-20 17:39:21 -07001738
Adam Cohen8baab352012-03-20 17:39:21 -07001739 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08001740 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001741 CellAndSpan c = currentState.map.get(v);
1742 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1743 }
1744
Adam Cohen47a876d2012-03-19 13:21:41 -07001745 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1746 int top = boundingRect.top;
1747 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001748 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001749 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08001750 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001751 CellAndSpan c = currentState.map.get(v);
1752 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001753 }
1754
Adam Cohen482ed822012-03-02 14:15:13 -08001755 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1756
Adam Cohenf3900c22012-11-16 18:28:11 -08001757 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1758 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001759
Adam Cohen8baab352012-03-20 17:39:21 -07001760 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001761 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001762 int deltaX = mTempLocation[0] - boundingRect.left;
1763 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001764 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001765 CellAndSpan c = currentState.map.get(v);
1766 c.x += deltaX;
1767 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001768 }
1769 success = true;
1770 }
Adam Cohen8baab352012-03-20 17:39:21 -07001771
1772 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08001773 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001774 CellAndSpan c = currentState.map.get(v);
1775 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001776 }
1777 return success;
1778 }
1779
1780 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1781 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1782 }
1783
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001784 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1785 // to push items in each of the cardinal directions, in an order based on the direction vector
1786 // passed.
1787 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1788 int[] direction, View ignoreView, ItemConfiguration solution) {
1789 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001790 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001791 // separately in each of the components.
1792 int temp = direction[1];
1793 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001794
1795 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001796 ignoreView, solution)) {
1797 return true;
1798 }
1799 direction[1] = temp;
1800 temp = direction[0];
1801 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001802
1803 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001804 ignoreView, solution)) {
1805 return true;
1806 }
1807 // Revert the direction
1808 direction[0] = temp;
1809
1810 // Now we try pushing in each component of the opposite direction
1811 direction[0] *= -1;
1812 direction[1] *= -1;
1813 temp = direction[1];
1814 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001815 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001816 ignoreView, solution)) {
1817 return true;
1818 }
1819
1820 direction[1] = temp;
1821 temp = direction[0];
1822 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001823 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001824 ignoreView, solution)) {
1825 return true;
1826 }
1827 // revert the direction
1828 direction[0] = temp;
1829 direction[0] *= -1;
1830 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001831
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001832 } else {
1833 // If the direction vector has a single non-zero component, we push first in the
1834 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08001835 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001836 ignoreView, solution)) {
1837 return true;
1838 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001839 // Then we try the opposite direction
1840 direction[0] *= -1;
1841 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001842 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001843 ignoreView, solution)) {
1844 return true;
1845 }
1846 // Switch the direction back
1847 direction[0] *= -1;
1848 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001849
1850 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001851 // to find a solution by pushing along the perpendicular axis.
1852
1853 // Swap the components
1854 int temp = direction[1];
1855 direction[1] = direction[0];
1856 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08001857 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001858 ignoreView, solution)) {
1859 return true;
1860 }
1861
1862 // Then we try the opposite direction
1863 direction[0] *= -1;
1864 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001865 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001866 ignoreView, solution)) {
1867 return true;
1868 }
1869 // Switch the direction back
1870 direction[0] *= -1;
1871 direction[1] *= -1;
1872
1873 // Swap the components back
1874 temp = direction[1];
1875 direction[1] = direction[0];
1876 direction[0] = temp;
1877 }
1878 return false;
1879 }
1880
Adam Cohen482ed822012-03-02 14:15:13 -08001881 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001882 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001883 // Return early if get invalid cell positions
1884 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001885
Adam Cohen8baab352012-03-20 17:39:21 -07001886 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001887 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001888
Adam Cohen8baab352012-03-20 17:39:21 -07001889 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001890 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001891 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001892 if (c != null) {
1893 c.x = cellX;
1894 c.y = cellY;
1895 }
Adam Cohen482ed822012-03-02 14:15:13 -08001896 }
Adam Cohen482ed822012-03-02 14:15:13 -08001897 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1898 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001899 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001900 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001901 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001902 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001903 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001904 if (Rect.intersects(r0, r1)) {
1905 if (!lp.canReorder) {
1906 return false;
1907 }
1908 mIntersectingViews.add(child);
1909 }
1910 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001911
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001912 solution.intersectingViews = new ArrayList<View>(mIntersectingViews);
1913
Winson Chung5f8afe62013-08-12 16:19:28 -07001914 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001915 // we try to find a solution such that no displaced item travels through another item
1916 // without also displacing that item.
1917 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001918 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001919 return true;
1920 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001921
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001922 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08001923 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001924 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001925 return true;
1926 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001927
Adam Cohen482ed822012-03-02 14:15:13 -08001928 // Ok, they couldn't move as a block, let's move them individually
1929 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001930 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001931 return false;
1932 }
1933 }
1934 return true;
1935 }
1936
1937 /*
1938 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1939 * the provided point and the provided cell
1940 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001941 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001942 double angle = Math.atan(((float) deltaY) / deltaX);
1943
1944 result[0] = 0;
1945 result[1] = 0;
1946 if (Math.abs(Math.cos(angle)) > 0.5f) {
1947 result[0] = (int) Math.signum(deltaX);
1948 }
1949 if (Math.abs(Math.sin(angle)) > 0.5f) {
1950 result[1] = (int) Math.signum(deltaY);
1951 }
1952 }
1953
Adam Cohen8baab352012-03-20 17:39:21 -07001954 private void copyOccupiedArray(boolean[][] occupied) {
1955 for (int i = 0; i < mCountX; i++) {
1956 for (int j = 0; j < mCountY; j++) {
1957 occupied[i][j] = mOccupied[i][j];
1958 }
1959 }
1960 }
1961
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001962 private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001963 int spanX, int spanY, int[] direction, View dragView, boolean decX,
1964 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001965 // Copy the current state into the solution. This solution will be manipulated as necessary.
1966 copyCurrentStateToSolution(solution, false);
1967 // Copy the current occupied array into the temporary occupied array. This array will be
1968 // manipulated as necessary to find a solution.
1969 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001970
1971 // We find the nearest cell into which we would place the dragged item, assuming there's
1972 // nothing in its way.
1973 int result[] = new int[2];
1974 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1975
1976 boolean success = false;
1977 // First we try the exact nearest position of the item being dragged,
1978 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001979 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1980 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001981
1982 if (!success) {
1983 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1984 // x, then 1 in y etc.
1985 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001986 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
1987 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001988 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001989 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
1990 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001991 }
1992 solution.isSolution = false;
1993 } else {
1994 solution.isSolution = true;
1995 solution.dragViewX = result[0];
1996 solution.dragViewY = result[1];
1997 solution.dragViewSpanX = spanX;
1998 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001999 }
2000 return solution;
2001 }
2002
2003 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002004 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002005 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002006 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002007 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002008 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08002009 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07002010 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002011 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07002012 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002013 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002014 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08002015 }
2016 }
2017
2018 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
2019 for (int i = 0; i < mCountX; i++) {
2020 for (int j = 0; j < mCountY; j++) {
2021 mTmpOccupied[i][j] = false;
2022 }
2023 }
2024
Michael Jurkaa52570f2012-03-20 03:18:20 -07002025 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002026 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002027 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002028 if (child == dragView) continue;
2029 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002030 CellAndSpan c = solution.map.get(child);
2031 if (c != null) {
2032 lp.tmpCellX = c.x;
2033 lp.tmpCellY = c.y;
2034 lp.cellHSpan = c.spanX;
2035 lp.cellVSpan = c.spanY;
2036 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002037 }
2038 }
2039 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2040 solution.dragViewSpanY, mTmpOccupied, true);
2041 }
2042
2043 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
2044 commitDragView) {
2045
2046 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
2047 for (int i = 0; i < mCountX; i++) {
2048 for (int j = 0; j < mCountY; j++) {
2049 occupied[i][j] = false;
2050 }
2051 }
2052
Michael Jurkaa52570f2012-03-20 03:18:20 -07002053 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002054 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002055 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002056 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002057 CellAndSpan c = solution.map.get(child);
2058 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002059 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2060 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002061 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002062 }
2063 }
2064 if (commitDragView) {
2065 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2066 solution.dragViewSpanY, occupied, true);
2067 }
2068 }
2069
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002070
2071 // This method starts or changes the reorder preview animations
2072 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
2073 View dragView, int delay, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07002074 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002075 for (int i = 0; i < childCount; i++) {
2076 View child = mShortcutsAndWidgets.getChildAt(i);
2077 if (child == dragView) continue;
2078 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002079 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
2080 != null && !solution.intersectingViews.contains(child);
2081
Adam Cohen19f37922012-03-21 11:59:11 -07002082 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002083 if (c != null && !skip) {
2084 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
2085 lp.cellY, c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002086 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002087 }
2088 }
2089 }
2090
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002091 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07002092 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002093 class ReorderPreviewAnimation {
Adam Cohen19f37922012-03-21 11:59:11 -07002094 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002095 float finalDeltaX;
2096 float finalDeltaY;
2097 float initDeltaX;
2098 float initDeltaY;
2099 float finalScale;
2100 float initScale;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002101 int mode;
2102 boolean repeating = false;
2103 private static final int PREVIEW_DURATION = 300;
2104 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
2105
2106 public static final int MODE_HINT = 0;
2107 public static final int MODE_PREVIEW = 1;
2108
Adam Cohene7587d22012-05-24 18:50:02 -07002109 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002110
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002111 public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
2112 int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07002113 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2114 final int x0 = mTmpPoint[0];
2115 final int y0 = mTmpPoint[1];
2116 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2117 final int x1 = mTmpPoint[0];
2118 final int y1 = mTmpPoint[1];
2119 final int dX = x1 - x0;
2120 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002121 finalDeltaX = 0;
2122 finalDeltaY = 0;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002123 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07002124 if (dX == dY && dX == 0) {
2125 } else {
2126 if (dY == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002127 finalDeltaX = - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002128 } else if (dX == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002129 finalDeltaY = - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002130 } else {
2131 double angle = Math.atan( (float) (dY) / dX);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002132 finalDeltaX = (int) (- dir * Math.signum(dX) *
2133 Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
2134 finalDeltaY = (int) (- dir * Math.signum(dY) *
2135 Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002136 }
2137 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002138 this.mode = mode;
Adam Cohend024f982012-05-23 18:26:45 -07002139 initDeltaX = child.getTranslationX();
2140 initDeltaY = child.getTranslationY();
Adam Cohen307fe232012-08-16 17:55:58 -07002141 finalScale = getChildrenScale() - 4.0f / child.getWidth();
Adam Cohend024f982012-05-23 18:26:45 -07002142 initScale = child.getScaleX();
Adam Cohen19f37922012-03-21 11:59:11 -07002143 this.child = child;
2144 }
2145
Adam Cohend024f982012-05-23 18:26:45 -07002146 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002147 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002148 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002149 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002150 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002151 if (finalDeltaX == 0 && finalDeltaY == 0) {
2152 completeAnimationImmediately();
2153 return;
2154 }
Adam Cohen19f37922012-03-21 11:59:11 -07002155 }
Adam Cohend024f982012-05-23 18:26:45 -07002156 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002157 return;
2158 }
Michael Jurkaf1ad6082013-03-13 12:55:46 +01002159 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002160 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07002161
2162 // Animations are disabled in power save mode, causing the repeated animation to jump
2163 // spastically between beginning and end states. Since this looks bad, we don't repeat
2164 // the animation in power save mode.
Tony Wickham112ac952015-11-12 12:31:50 -08002165 if (!Utilities.isPowerSaverOn(getContext())) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07002166 va.setRepeatMode(ValueAnimator.REVERSE);
2167 va.setRepeatCount(ValueAnimator.INFINITE);
2168 }
2169
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002170 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002171 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002172 va.addUpdateListener(new AnimatorUpdateListener() {
2173 @Override
2174 public void onAnimationUpdate(ValueAnimator animation) {
2175 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002176 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : r;
2177 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2178 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002179 child.setTranslationX(x);
2180 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002181 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002182 child.setScaleX(s);
2183 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002184 }
2185 });
2186 va.addListener(new AnimatorListenerAdapter() {
2187 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002188 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002189 initDeltaX = 0;
2190 initDeltaY = 0;
Adam Cohen307fe232012-08-16 17:55:58 -07002191 initScale = getChildrenScale();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002192 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002193 }
2194 });
Adam Cohen19f37922012-03-21 11:59:11 -07002195 mShakeAnimators.put(child, this);
2196 va.start();
2197 }
2198
Adam Cohend024f982012-05-23 18:26:45 -07002199 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002200 if (a != null) {
2201 a.cancel();
2202 }
Adam Cohen19f37922012-03-21 11:59:11 -07002203 }
Adam Cohene7587d22012-05-24 18:50:02 -07002204
Adam Cohen091440a2015-03-18 14:16:05 -07002205 @Thunk void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002206 if (a != null) {
2207 a.cancel();
2208 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002209
Sunny Goyal5d2fc322015-07-06 22:52:49 -07002210 a = new LauncherViewPropertyAnimator(child)
2211 .scaleX(getChildrenScale())
2212 .scaleY(getChildrenScale())
2213 .translationX(0)
2214 .translationY(0)
2215 .setDuration(REORDER_ANIMATION_DURATION);
2216 a.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2217 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07002218 }
Adam Cohen19f37922012-03-21 11:59:11 -07002219 }
2220
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002221 private void completeAndClearReorderPreviewAnimations() {
2222 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002223 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002224 }
2225 mShakeAnimators.clear();
2226 }
2227
Adam Cohen482ed822012-03-02 14:15:13 -08002228 private void commitTempPlacement() {
2229 for (int i = 0; i < mCountX; i++) {
2230 for (int j = 0; j < mCountY; j++) {
2231 mOccupied[i][j] = mTmpOccupied[i][j];
2232 }
2233 }
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002234
2235 long screenId = mLauncher.getWorkspace().getIdForScreen(this);
2236 int container = Favorites.CONTAINER_DESKTOP;
2237
2238 if (mLauncher.isHotseatLayout(this)) {
2239 screenId = -1;
2240 container = Favorites.CONTAINER_HOTSEAT;
2241 }
2242
Michael Jurkaa52570f2012-03-20 03:18:20 -07002243 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002244 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002245 View child = mShortcutsAndWidgets.getChildAt(i);
2246 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2247 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002248 // We do a null check here because the item info can be null in the case of the
2249 // AllApps button in the hotseat.
2250 if (info != null) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002251 final boolean requiresDbUpdate = (info.cellX != lp.tmpCellX
2252 || info.cellY != lp.tmpCellY || info.spanX != lp.cellHSpan
2253 || info.spanY != lp.cellVSpan);
2254
Adam Cohen2acce882012-03-28 19:03:19 -07002255 info.cellX = lp.cellX = lp.tmpCellX;
2256 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002257 info.spanX = lp.cellHSpan;
2258 info.spanY = lp.cellVSpan;
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002259
2260 if (requiresDbUpdate) {
2261 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId,
2262 info.cellX, info.cellY, info.spanX, info.spanY);
2263 }
Adam Cohen2acce882012-03-28 19:03:19 -07002264 }
Adam Cohen482ed822012-03-02 14:15:13 -08002265 }
2266 }
2267
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002268 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002269 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002270 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002271 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002272 lp.useTmpCoords = useTempCoords;
2273 }
2274 }
2275
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002276 private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002277 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2278 int[] result = new int[2];
2279 int[] resultSpan = new int[2];
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002280 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
Adam Cohen482ed822012-03-02 14:15:13 -08002281 resultSpan);
2282 if (result[0] >= 0 && result[1] >= 0) {
2283 copyCurrentStateToSolution(solution, false);
2284 solution.dragViewX = result[0];
2285 solution.dragViewY = result[1];
2286 solution.dragViewSpanX = resultSpan[0];
2287 solution.dragViewSpanY = resultSpan[1];
2288 solution.isSolution = true;
2289 } else {
2290 solution.isSolution = false;
2291 }
2292 return solution;
2293 }
2294
2295 public void prepareChildForDrag(View child) {
2296 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002297 }
2298
Adam Cohen19f37922012-03-21 11:59:11 -07002299 /* This seems like it should be obvious and straight-forward, but when the direction vector
2300 needs to match with the notion of the dragView pushing other views, we have to employ
2301 a slightly more subtle notion of the direction vector. The question is what two points is
2302 the vector between? The center of the dragView and its desired destination? Not quite, as
2303 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2304 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2305 or right, which helps make pushing feel right.
2306 */
2307 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2308 int spanY, View dragView, int[] resultDirection) {
2309 int[] targetDestination = new int[2];
2310
2311 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2312 Rect dragRect = new Rect();
2313 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2314 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2315
2316 Rect dropRegionRect = new Rect();
2317 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2318 dragView, dropRegionRect, mIntersectingViews);
2319
2320 int dropRegionSpanX = dropRegionRect.width();
2321 int dropRegionSpanY = dropRegionRect.height();
2322
2323 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2324 dropRegionRect.height(), dropRegionRect);
2325
2326 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2327 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2328
2329 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2330 deltaX = 0;
2331 }
2332 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2333 deltaY = 0;
2334 }
2335
2336 if (deltaX == 0 && deltaY == 0) {
2337 // No idea what to do, give a random direction.
2338 resultDirection[0] = 1;
2339 resultDirection[1] = 0;
2340 } else {
2341 computeDirectionVector(deltaX, deltaY, resultDirection);
2342 }
2343 }
2344
2345 // For a given cell and span, fetch the set of views intersecting the region.
2346 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2347 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2348 if (boundingRect != null) {
2349 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2350 }
2351 intersectingViews.clear();
2352 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2353 Rect r1 = new Rect();
2354 final int count = mShortcutsAndWidgets.getChildCount();
2355 for (int i = 0; i < count; i++) {
2356 View child = mShortcutsAndWidgets.getChildAt(i);
2357 if (child == dragView) continue;
2358 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2359 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2360 if (Rect.intersects(r0, r1)) {
2361 mIntersectingViews.add(child);
2362 if (boundingRect != null) {
2363 boundingRect.union(r1);
2364 }
2365 }
2366 }
2367 }
2368
2369 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2370 View dragView, int[] result) {
2371 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2372 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2373 mIntersectingViews);
2374 return !mIntersectingViews.isEmpty();
2375 }
2376
2377 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002378 completeAndClearReorderPreviewAnimations();
2379 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2380 final int count = mShortcutsAndWidgets.getChildCount();
2381 for (int i = 0; i < count; i++) {
2382 View child = mShortcutsAndWidgets.getChildAt(i);
2383 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2384 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2385 lp.tmpCellX = lp.cellX;
2386 lp.tmpCellY = lp.cellY;
2387 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2388 0, false, false);
2389 }
Adam Cohen19f37922012-03-21 11:59:11 -07002390 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002391 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002392 }
Adam Cohen19f37922012-03-21 11:59:11 -07002393 }
2394
Adam Cohenbebf0422012-04-11 18:06:28 -07002395 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2396 View dragView, int[] direction, boolean commit) {
2397 int[] pixelXY = new int[2];
2398 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2399
2400 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002401 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002402 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2403
2404 setUseTempCoords(true);
2405 if (swapSolution != null && swapSolution.isSolution) {
2406 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2407 // committing anything or animating anything as we just want to determine if a solution
2408 // exists
2409 copySolutionToTempState(swapSolution, dragView);
2410 setItemPlacementDirty(true);
2411 animateItemsToSolution(swapSolution, dragView, commit);
2412
2413 if (commit) {
2414 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002415 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002416 setItemPlacementDirty(false);
2417 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002418 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
2419 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002420 }
2421 mShortcutsAndWidgets.requestLayout();
2422 }
2423 return swapSolution.isSolution;
2424 }
2425
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002426 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002427 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002428 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002429 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002430
2431 if (resultSpan == null) {
2432 resultSpan = new int[2];
2433 }
2434
Adam Cohen19f37922012-03-21 11:59:11 -07002435 // When we are checking drop validity or actually dropping, we don't recompute the
2436 // direction vector, since we want the solution to match the preview, and it's possible
2437 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002438 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2439 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002440 mDirectionVector[0] = mPreviousReorderDirection[0];
2441 mDirectionVector[1] = mPreviousReorderDirection[1];
2442 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002443 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2444 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2445 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002446 }
2447 } else {
2448 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2449 mPreviousReorderDirection[0] = mDirectionVector[0];
2450 mPreviousReorderDirection[1] = mDirectionVector[1];
2451 }
2452
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002453 // Find a solution involving pushing / displacing any items in the way
2454 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002455 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2456
2457 // We attempt the approach which doesn't shuffle views at all
2458 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2459 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2460
2461 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002462
2463 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2464 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002465 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2466 finalSolution = swapSolution;
2467 } else if (noShuffleSolution.isSolution) {
2468 finalSolution = noShuffleSolution;
2469 }
2470
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002471 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002472 if (finalSolution != null) {
Adam Cohenfe692872013-12-11 14:47:23 -08002473 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
2474 ReorderPreviewAnimation.MODE_HINT);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002475 result[0] = finalSolution.dragViewX;
2476 result[1] = finalSolution.dragViewY;
2477 resultSpan[0] = finalSolution.dragViewSpanX;
2478 resultSpan[1] = finalSolution.dragViewSpanY;
2479 } else {
2480 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2481 }
2482 return result;
2483 }
2484
Adam Cohen482ed822012-03-02 14:15:13 -08002485 boolean foundSolution = true;
2486 if (!DESTRUCTIVE_REORDER) {
2487 setUseTempCoords(true);
2488 }
2489
2490 if (finalSolution != null) {
2491 result[0] = finalSolution.dragViewX;
2492 result[1] = finalSolution.dragViewY;
2493 resultSpan[0] = finalSolution.dragViewSpanX;
2494 resultSpan[1] = finalSolution.dragViewSpanY;
2495
2496 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2497 // committing anything or animating anything as we just want to determine if a solution
2498 // exists
2499 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2500 if (!DESTRUCTIVE_REORDER) {
2501 copySolutionToTempState(finalSolution, dragView);
2502 }
2503 setItemPlacementDirty(true);
2504 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2505
Adam Cohen19f37922012-03-21 11:59:11 -07002506 if (!DESTRUCTIVE_REORDER &&
2507 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002508 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002509 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002510 setItemPlacementDirty(false);
2511 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002512 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
2513 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002514 }
2515 }
2516 } else {
2517 foundSolution = false;
2518 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2519 }
2520
2521 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2522 setUseTempCoords(false);
2523 }
Adam Cohen482ed822012-03-02 14:15:13 -08002524
Michael Jurkaa52570f2012-03-20 03:18:20 -07002525 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002526 return result;
2527 }
2528
Adam Cohen19f37922012-03-21 11:59:11 -07002529 void setItemPlacementDirty(boolean dirty) {
2530 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002531 }
Adam Cohen19f37922012-03-21 11:59:11 -07002532 boolean isItemPlacementDirty() {
2533 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002534 }
2535
Adam Cohen091440a2015-03-18 14:16:05 -07002536 @Thunk class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002537 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohenf3900c22012-11-16 18:28:11 -08002538 private HashMap<View, CellAndSpan> savedMap = new HashMap<View, CellAndSpan>();
2539 ArrayList<View> sortedViews = new ArrayList<View>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002540 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002541 boolean isSolution = false;
2542 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2543
Adam Cohenf3900c22012-11-16 18:28:11 -08002544 void save() {
2545 // Copy current state into savedMap
2546 for (View v: map.keySet()) {
2547 map.get(v).copy(savedMap.get(v));
2548 }
2549 }
2550
2551 void restore() {
2552 // Restore current state from savedMap
2553 for (View v: savedMap.keySet()) {
2554 savedMap.get(v).copy(map.get(v));
2555 }
2556 }
2557
2558 void add(View v, CellAndSpan cs) {
2559 map.put(v, cs);
2560 savedMap.put(v, new CellAndSpan());
2561 sortedViews.add(v);
2562 }
2563
Adam Cohen482ed822012-03-02 14:15:13 -08002564 int area() {
2565 return dragViewSpanX * dragViewSpanY;
2566 }
Adam Cohen8baab352012-03-20 17:39:21 -07002567 }
2568
2569 private class CellAndSpan {
2570 int x, y;
2571 int spanX, spanY;
2572
Adam Cohenf3900c22012-11-16 18:28:11 -08002573 public CellAndSpan() {
2574 }
2575
2576 public void copy(CellAndSpan copy) {
2577 copy.x = x;
2578 copy.y = y;
2579 copy.spanX = spanX;
2580 copy.spanY = spanY;
2581 }
2582
Adam Cohen8baab352012-03-20 17:39:21 -07002583 public CellAndSpan(int x, int y, int spanX, int spanY) {
2584 this.x = x;
2585 this.y = y;
2586 this.spanX = spanX;
2587 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002588 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002589
2590 public String toString() {
2591 return "(" + x + ", " + y + ": " + spanX + ", " + spanY + ")";
2592 }
2593
Adam Cohen482ed822012-03-02 14:15:13 -08002594 }
2595
Adam Cohendf035382011-04-11 17:22:04 -07002596 /**
Adam Cohendf035382011-04-11 17:22:04 -07002597 * Find a starting cell position that will fit the given bounds nearest the requested
2598 * cell location. Uses Euclidean distance to score multiple vacant areas.
2599 *
2600 * @param pixelX The X location at which you want to search for a vacant area.
2601 * @param pixelY The Y location at which you want to search for a vacant area.
2602 * @param spanX Horizontal span of the object.
2603 * @param spanY Vertical span of the object.
2604 * @param ignoreView Considers space occupied by this view as unoccupied
2605 * @param result Previously returned value to possibly recycle.
2606 * @return The X, Y cell of a vacant area that can contain this object,
2607 * nearest the requested location.
2608 */
Adam Cohenf9c184a2016-01-15 16:47:43 -08002609 public int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002610 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002611 }
2612
Michael Jurka0280c3b2010-09-17 15:00:07 -07002613 boolean existsEmptyCell() {
2614 return findCellForSpan(null, 1, 1);
2615 }
2616
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002617 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002618 * Finds the upper-left coordinate of the first rectangle in the grid that can
2619 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2620 * then this method will only return coordinates for rectangles that contain the cell
2621 * (intersectX, intersectY)
2622 *
2623 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2624 * can be found.
2625 * @param spanX The horizontal span of the cell we want to find.
2626 * @param spanY The vertical span of the cell we want to find.
2627 *
2628 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002629 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002630 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Michael Jurka28750fb2010-09-24 17:43:49 -07002631 boolean foundCell = false;
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002632 final int endX = mCountX - (spanX - 1);
2633 final int endY = mCountY - (spanY - 1);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002634
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002635 for (int y = 0; y < endY && !foundCell; y++) {
2636 inner:
2637 for (int x = 0; x < endX; x++) {
2638 for (int i = 0; i < spanX; i++) {
2639 for (int j = 0; j < spanY; j++) {
2640 if (mOccupied[x + i][y + j]) {
2641 // small optimization: we can skip to after the column we just found
2642 // an occupied cell
2643 x += i;
2644 continue inner;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002645 }
2646 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002647 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002648 if (cellXY != null) {
2649 cellXY[0] = x;
2650 cellXY[1] = y;
2651 }
2652 foundCell = true;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002653 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002654 }
2655 }
2656
Michael Jurka28750fb2010-09-24 17:43:49 -07002657 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002658 }
2659
2660 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002661 * A drag event has begun over this layout.
2662 * It may have begun over this layout (in which case onDragChild is called first),
2663 * or it may have begun on another layout.
2664 */
2665 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002666 mDragging = true;
2667 }
2668
2669 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002670 * Called when drag has left this CellLayout or has been completed (successfully or not)
2671 */
2672 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002673 // This can actually be called when we aren't in a drag, e.g. when adding a new
2674 // item to this layout via the customize drawer.
2675 // Guard against that case.
2676 if (mDragging) {
2677 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002678 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002679
2680 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002681 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002682 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2683 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002684 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002685 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002686 }
2687
2688 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002689 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002690 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002691 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002692 *
2693 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002694 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002695 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002696 if (child != null) {
2697 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002698 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002699 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002700 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002701 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002702 }
2703
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002704 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002705 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002706 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002707 * @param cellX X coordinate of upper left corner expressed as a cell position
2708 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002709 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002710 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002711 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002712 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002713 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002714 final int cellWidth = mCellWidth;
2715 final int cellHeight = mCellHeight;
2716 final int widthGap = mWidthGap;
2717 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002718
Winson Chung4b825dcd2011-06-19 12:41:22 -07002719 final int hStartPadding = getPaddingLeft();
2720 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002721
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002722 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2723 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2724
2725 int x = hStartPadding + cellX * (cellWidth + widthGap);
2726 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002727
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002728 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002729 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002730
Michael Jurka0280c3b2010-09-17 15:00:07 -07002731 private void clearOccupiedCells() {
2732 for (int x = 0; x < mCountX; x++) {
2733 for (int y = 0; y < mCountY; y++) {
2734 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002735 }
2736 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002737 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002738
Adam Cohend4844c32011-02-18 19:25:06 -08002739 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002740 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002741 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002742 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002743 }
2744
Adam Cohend4844c32011-02-18 19:25:06 -08002745 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002746 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002747 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002748 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002749 }
2750
Adam Cohen482ed822012-03-02 14:15:13 -08002751 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2752 boolean value) {
2753 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002754 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2755 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002756 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002757 }
2758 }
2759 }
2760
Adam Cohen2801caf2011-05-13 20:57:39 -07002761 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002762 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002763 (Math.max((mCountX - 1), 0) * mWidthGap);
2764 }
2765
2766 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002767 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002768 (Math.max((mCountY - 1), 0) * mHeightGap);
2769 }
2770
Michael Jurka66d72172011-04-12 16:29:25 -07002771 public boolean isOccupied(int x, int y) {
2772 if (x < mCountX && y < mCountY) {
2773 return mOccupied[x][y];
2774 } else {
2775 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2776 }
2777 }
2778
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002779 @Override
2780 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2781 return new CellLayout.LayoutParams(getContext(), attrs);
2782 }
2783
2784 @Override
2785 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2786 return p instanceof CellLayout.LayoutParams;
2787 }
2788
2789 @Override
2790 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2791 return new CellLayout.LayoutParams(p);
2792 }
2793
2794 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2795 /**
2796 * Horizontal location of the item in the grid.
2797 */
2798 @ViewDebug.ExportedProperty
2799 public int cellX;
2800
2801 /**
2802 * Vertical location of the item in the grid.
2803 */
2804 @ViewDebug.ExportedProperty
2805 public int cellY;
2806
2807 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002808 * Temporary horizontal location of the item in the grid during reorder
2809 */
2810 public int tmpCellX;
2811
2812 /**
2813 * Temporary vertical location of the item in the grid during reorder
2814 */
2815 public int tmpCellY;
2816
2817 /**
2818 * Indicates that the temporary coordinates should be used to layout the items
2819 */
2820 public boolean useTmpCoords;
2821
2822 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002823 * Number of cells spanned horizontally by the item.
2824 */
2825 @ViewDebug.ExportedProperty
2826 public int cellHSpan;
2827
2828 /**
2829 * Number of cells spanned vertically by the item.
2830 */
2831 @ViewDebug.ExportedProperty
2832 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002833
Adam Cohen1b607ed2011-03-03 17:26:50 -08002834 /**
2835 * Indicates whether the item will set its x, y, width and height parameters freely,
2836 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2837 */
Adam Cohend4844c32011-02-18 19:25:06 -08002838 public boolean isLockedToGrid = true;
2839
Adam Cohen482ed822012-03-02 14:15:13 -08002840 /**
Adam Cohenec40b2b2013-07-23 15:52:40 -07002841 * Indicates that this item should use the full extents of its parent.
2842 */
2843 public boolean isFullscreen = false;
2844
2845 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002846 * Indicates whether this item can be reordered. Always true except in the case of the
2847 * the AllApps button.
2848 */
2849 public boolean canReorder = true;
2850
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002851 // X coordinate of the view in the layout.
2852 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002853 public int x;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002854 // Y coordinate of the view in the layout.
2855 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002856 public int y;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002857
Romain Guy84f296c2009-11-04 15:00:44 -08002858 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002859
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002860 public LayoutParams(Context c, AttributeSet attrs) {
2861 super(c, attrs);
2862 cellHSpan = 1;
2863 cellVSpan = 1;
2864 }
2865
2866 public LayoutParams(ViewGroup.LayoutParams source) {
2867 super(source);
2868 cellHSpan = 1;
2869 cellVSpan = 1;
2870 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002871
2872 public LayoutParams(LayoutParams source) {
2873 super(source);
2874 this.cellX = source.cellX;
2875 this.cellY = source.cellY;
2876 this.cellHSpan = source.cellHSpan;
2877 this.cellVSpan = source.cellVSpan;
2878 }
2879
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002880 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002881 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002882 this.cellX = cellX;
2883 this.cellY = cellY;
2884 this.cellHSpan = cellHSpan;
2885 this.cellVSpan = cellVSpan;
2886 }
2887
Adam Cohen2374abf2013-04-16 14:56:57 -07002888 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap,
2889 boolean invertHorizontally, int colCount) {
Adam Cohend4844c32011-02-18 19:25:06 -08002890 if (isLockedToGrid) {
2891 final int myCellHSpan = cellHSpan;
2892 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002893 int myCellX = useTmpCoords ? tmpCellX : cellX;
2894 int myCellY = useTmpCoords ? tmpCellY : cellY;
2895
2896 if (invertHorizontally) {
2897 myCellX = colCount - myCellX - cellHSpan;
2898 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002899
Adam Cohend4844c32011-02-18 19:25:06 -08002900 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2901 leftMargin - rightMargin;
2902 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2903 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002904 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2905 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002906 }
2907 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002908
Winson Chungaafa03c2010-06-11 17:34:16 -07002909 public String toString() {
2910 return "(" + this.cellX + ", " + this.cellY + ")";
2911 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002912
2913 public void setWidth(int width) {
2914 this.width = width;
2915 }
2916
2917 public int getWidth() {
2918 return width;
2919 }
2920
2921 public void setHeight(int height) {
2922 this.height = height;
2923 }
2924
2925 public int getHeight() {
2926 return height;
2927 }
2928
2929 public void setX(int x) {
2930 this.x = x;
2931 }
2932
2933 public int getX() {
2934 return x;
2935 }
2936
2937 public void setY(int y) {
2938 this.y = y;
2939 }
2940
2941 public int getY() {
2942 return y;
2943 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002944 }
2945
Michael Jurka0280c3b2010-09-17 15:00:07 -07002946 // This class stores info for two purposes:
2947 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2948 // its spanX, spanY, and the screen it is on
2949 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2950 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2951 // the CellLayout that was long clicked
Sunny Goyal83a8f042015-05-19 12:52:12 -07002952 public static final class CellInfo {
Adam Cohenf9c184a2016-01-15 16:47:43 -08002953 public View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002954 int cellX = -1;
2955 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002956 int spanX;
2957 int spanY;
Adam Cohendcd297f2013-06-18 13:13:40 -07002958 long screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07002959 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002960
Sunny Goyal83a8f042015-05-19 12:52:12 -07002961 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002962 cell = v;
2963 cellX = info.cellX;
2964 cellY = info.cellY;
2965 spanX = info.spanX;
2966 spanY = info.spanY;
2967 screenId = info.screenId;
2968 container = info.container;
2969 }
2970
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002971 @Override
2972 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002973 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2974 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002975 }
2976 }
Michael Jurkad771c962011-08-09 15:00:48 -07002977
Sunny Goyala9116722015-04-29 13:55:58 -07002978 public boolean findVacantCell(int spanX, int spanY, int[] outXY) {
2979 return Utilities.findVacantCell(outXY, spanX, spanY, mCountX, mCountY, mOccupied);
2980 }
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002981
Tony Wickham86930612015-09-09 13:50:40 -07002982 /**
2983 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2984 * if necessary).
2985 */
2986 public boolean hasReorderSolution(ItemInfo itemInfo) {
2987 int[] cellPoint = new int[2];
2988 // Check for a solution starting at every cell.
2989 for (int cellX = 0; cellX < getCountX(); cellX++) {
2990 for (int cellY = 0; cellY < getCountY(); cellY++) {
2991 cellToPoint(cellX, cellY, cellPoint);
2992 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2993 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2994 true, new ItemConfiguration()).isSolution) {
2995 return true;
2996 }
2997 }
2998 }
2999 return false;
3000 }
3001
Sunny Goyal9ca9c132015-04-29 14:57:22 -07003002 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
3003 int x2 = x + spanX - 1;
3004 int y2 = y + spanY - 1;
3005 if (x < 0 || y < 0 || x2 >= mCountX || y2 >= mCountY) {
3006 return false;
3007 }
3008 for (int i = x; i <= x2; i++) {
3009 for (int j = y; j <= y2; j++) {
3010 if (mOccupied[i][j]) {
3011 return false;
3012 }
3013 }
3014 }
3015
3016 return true;
3017 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003018}