blob: a20a08093552b4f0310b4c122c213b54124a1bfe [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;
Tony Wickhame0c33232016-02-08 11:37:04 -080035import 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;
Daniel Sandler325dc232013-06-05 22:57:57 -040051import com.android.launcher3.FolderIcon.FolderRingAnimator;
Sunny Goyalaa8ef112015-06-12 20:04:41 -070052import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyale9b651e2015-04-24 11:44:51 -070053import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
54import com.android.launcher3.accessibility.FolderAccessibilityHelper;
55import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
Tony Wickhame0c33232016-02-08 11:37:04 -080056import com.android.launcher3.config.FeatureFlags;
Sunny Goyal6c56c682015-07-16 14:09:05 -070057import com.android.launcher3.config.ProviderConfig;
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 Cohen69ce2e52011-07-03 19:25:21 -0700110 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -0700111 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -0700112
Michael Jurka5f1c5092010-09-03 14:15:02 -0700113 private float mBackgroundAlpha;
Adam Cohenf34bab52010-09-30 14:11:56 -0700114
Sunny Goyal2805e632015-05-20 15:35:32 -0700115 private static final int BACKGROUND_ACTIVATE_DURATION = 120;
116 private final TransitionDrawable mBackground;
117
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700118 // These values allow a fixed measurement to be set on the CellLayout.
119 private int mFixedWidth = -1;
120 private int mFixedHeight = -1;
121
Michael Jurka33945b22010-12-21 18:19:38 -0800122 // If we're actively dragging something over this screen, mIsDragOverlapping is true
123 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700124
Winson Chung150fbab2010-09-29 17:14:26 -0700125 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700126 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohen091440a2015-03-18 14:16:05 -0700127 @Thunk Rect[] mDragOutlines = new Rect[4];
128 @Thunk float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700129 private InterruptibleInOutAnimator[] mDragOutlineAnims =
130 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700131
132 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700133 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700134 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700135
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700136 private final ClickShadowView mTouchFeedbackView;
Patrick Dubroy96864c32011-03-10 17:17:23 -0800137
Sunny Goyal316490e2015-06-02 09:38:28 -0700138 @Thunk HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new HashMap<>();
139 @Thunk HashMap<View, ReorderPreviewAnimation> mShakeAnimators = new HashMap<>();
Adam Cohen19f37922012-03-21 11:59:11 -0700140
141 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700142
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700143 // When a drag operation is in progress, holds the nearest cell to the touch point
144 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800145
Joe Onorato4be866d2010-10-10 11:26:02 -0700146 private boolean mDragging = false;
147
Patrick Dubroyce34a972010-10-19 10:34:32 -0700148 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700149 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700150
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800151 private boolean mIsHotseat = false;
Adam Cohen307fe232012-08-16 17:55:58 -0700152 private float mHotseatScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800153
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800154 public static final int MODE_SHOW_REORDER_HINT = 0;
155 public static final int MODE_DRAG_OVER = 1;
156 public static final int MODE_ON_DROP = 2;
157 public static final int MODE_ON_DROP_EXTERNAL = 3;
158 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700159 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800160 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
161
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800162 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700163 private static final int REORDER_ANIMATION_DURATION = 150;
Adam Cohen091440a2015-03-18 14:16:05 -0700164 @Thunk float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700165
Adam Cohen482ed822012-03-02 14:15:13 -0800166 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
167 private Rect mOccupiedRect = new Rect();
168 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700169 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700170 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800171
Sunny Goyal2805e632015-05-20 15:35:32 -0700172 private final Rect mTempRect = new Rect();
Winson Chung3a6e7f32013-10-09 15:50:52 -0700173
Michael Jurkaca993832012-06-29 15:17:04 -0700174 private final static Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700175
Adam Cohenc9735cf2015-01-23 16:11:55 -0800176 // Related to accessible drag and drop
Sunny Goyale9b651e2015-04-24 11:44:51 -0700177 private DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800178 private boolean mUseTouchHelper = false;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800179
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180 public CellLayout(Context context) {
181 this(context, null);
182 }
183
184 public CellLayout(Context context, AttributeSet attrs) {
185 this(context, attrs, 0);
186 }
187
188 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
189 super(context, attrs, defStyle);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700190
191 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
192 // the user where a dragged item will land when dropped.
193 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800194 setClipToPadding(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700195 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700196
Adam Cohen2e6da152015-05-06 11:42:25 -0700197 DeviceProfile grid = mLauncher.getDeviceProfile();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800198
Winson Chung11a1a532013-09-13 11:14:45 -0700199 mCellWidth = mCellHeight = -1;
Nilesh Agrawal5f7099a2014-01-02 15:54:57 -0800200 mFixedCellWidth = mFixedCellHeight = -1;
Winson Chung5f8afe62013-08-12 16:19:28 -0700201 mWidthGap = mOriginalWidthGap = 0;
202 mHeightGap = mOriginalHeightGap = 0;
203 mMaxGap = Integer.MAX_VALUE;
Adam Cohen2e6da152015-05-06 11:42:25 -0700204 mCountX = (int) grid.inv.numColumns;
205 mCountY = (int) grid.inv.numRows;
Michael Jurka0280c3b2010-09-17 15:00:07 -0700206 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800207 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700208 mPreviousReorderDirection[0] = INVALID_DIRECTION;
209 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800210
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800211 setAlwaysDrawnWithCacheEnabled(false);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700212 final Resources res = getResources();
Winson Chung6e1c0d32013-10-25 15:24:24 -0700213 mHotseatScale = (float) grid.hotseatIconSizePx / grid.iconSizePx;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700214
Tony Wickhame0c33232016-02-08 11:37:04 -0800215 mBackground = (TransitionDrawable) res.getDrawable(
216 FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND ? R.drawable.bg_screenpanel
217 : R.drawable.bg_celllayout);
Sunny Goyal2805e632015-05-20 15:35:32 -0700218 mBackground.setCallback(this);
Winson Chunge8f1d042015-07-31 12:39:57 -0700219 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurka33945b22010-12-21 18:19:38 -0800220
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800221 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE *
Winson Chung5f8afe62013-08-12 16:19:28 -0700222 grid.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700223
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700224 // Initialize the data structures used for the drag visualization.
Patrick Dubroyce34a972010-10-19 10:34:32 -0700225 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700226 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700227 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800228 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700229 }
230
231 // When dragging things around the home screens, we show a green outline of
232 // where the item will land. The outlines gradually fade out, leaving a trail
233 // behind the drag path.
234 // Set up all the animations that are used to implement this fading.
235 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700236 final float fromAlphaValue = 0;
237 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700238
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700239 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700240
241 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700242 final InterruptibleInOutAnimator anim =
Michael Jurkaf1ad6082013-03-13 12:55:46 +0100243 new InterruptibleInOutAnimator(this, duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700244 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700245 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700246 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700247 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700248 final Bitmap outline = (Bitmap)anim.getTag();
249
250 // If an animation is started and then stopped very quickly, we can still
251 // get spurious updates we've cleared the tag. Guard against this.
252 if (outline == null) {
Tony Wickhama0628cc2015-10-14 15:23:04 -0700253 if (LOGD) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700254 Object val = animation.getAnimatedValue();
255 Log.d(TAG, "anim " + thisIndex + " update: " + val +
256 ", isStopped " + anim.isStopped());
257 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700258 // Try to prevent it from continuing to run
259 animation.cancel();
260 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700261 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800262 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700263 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700264 }
265 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700266 // The animation holds a reference to the drag outline bitmap as long is it's
267 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700268 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700269 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700270 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700271 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700272 anim.setTag(null);
273 }
274 }
275 });
276 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700277 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700278
Michael Jurkaa52570f2012-03-20 03:18:20 -0700279 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
Adam Cohen2374abf2013-04-16 14:56:57 -0700280 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700281 mCountX, mCountY);
Adam Cohen2374abf2013-04-16 14:56:57 -0700282
Mady Mellorbb835202015-07-15 16:34:34 -0700283 mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
Mady Melloref044dd2015-06-02 15:35:07 -0700284
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700285 mTouchFeedbackView = new ClickShadowView(context);
286 addView(mTouchFeedbackView);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700287 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700288 }
289
Adam Cohenc9735cf2015-01-23 16:11:55 -0800290 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
Sunny Goyale9b651e2015-04-24 11:44:51 -0700291 public void enableAccessibleDrag(boolean enable, int dragType) {
Adam Cohenc9735cf2015-01-23 16:11:55 -0800292 mUseTouchHelper = enable;
293 if (!enable) {
294 ViewCompat.setAccessibilityDelegate(this, null);
295 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
296 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
297 setOnClickListener(mLauncher);
298 } else {
Sunny Goyale9b651e2015-04-24 11:44:51 -0700299 if (dragType == WORKSPACE_ACCESSIBILITY_DRAG &&
300 !(mTouchHelper instanceof WorkspaceAccessibilityHelper)) {
301 mTouchHelper = new WorkspaceAccessibilityHelper(this);
302 } else if (dragType == FOLDER_ACCESSIBILITY_DRAG &&
303 !(mTouchHelper instanceof FolderAccessibilityHelper)) {
304 mTouchHelper = new FolderAccessibilityHelper(this);
305 }
Adam Cohenc9735cf2015-01-23 16:11:55 -0800306 ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
307 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
308 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
309 setOnClickListener(mTouchHelper);
310 }
311
312 // Invalidate the accessibility hierarchy
313 if (getParent() != null) {
314 getParent().notifySubtreeAccessibilityStateChanged(
315 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
316 }
317 }
318
319 @Override
320 public boolean dispatchHoverEvent(MotionEvent event) {
321 // Always attempt to dispatch hover events to accessibility first.
322 if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
323 return true;
324 }
325 return super.dispatchHoverEvent(event);
326 }
327
328 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800329 public boolean onInterceptTouchEvent(MotionEvent ev) {
330 if (mUseTouchHelper ||
331 (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
332 return true;
333 }
334 return false;
335 }
336
Mady Melloref044dd2015-06-02 15:35:07 -0700337 @Override
338 public boolean onTouchEvent(MotionEvent ev) {
339 boolean handled = super.onTouchEvent(ev);
340 // Stylus button press on a home screen should not switch between overview mode and
341 // the home screen mode, however, once in overview mode stylus button press should be
342 // enabled to allow rearranging the different home screens. So check what mode
343 // the workspace is in, and only perform stylus button presses while in overview mode.
344 if (mLauncher.mWorkspace.isInOverviewMode()
Mady Mellorbb835202015-07-15 16:34:34 -0700345 && mStylusEventHelper.onMotionEvent(ev)) {
Mady Melloref044dd2015-06-02 15:35:07 -0700346 return true;
347 }
348 return handled;
349 }
350
Chris Craik01f2d7f2013-10-01 14:41:56 -0700351 public void enableHardwareLayer(boolean hasLayer) {
352 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700353 }
354
355 public void buildHardwareLayer() {
356 mShortcutsAndWidgets.buildLayer();
Adam Cohen2801caf2011-05-13 20:57:39 -0700357 }
358
Adam Cohen307fe232012-08-16 17:55:58 -0700359 public float getChildrenScale() {
360 return mIsHotseat ? mHotseatScale : 1.0f;
361 }
362
Winson Chung5f8afe62013-08-12 16:19:28 -0700363 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700364 mFixedCellWidth = mCellWidth = width;
365 mFixedCellHeight = mCellHeight = height;
Winson Chung5f8afe62013-08-12 16:19:28 -0700366 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
367 mCountX, mCountY);
368 }
369
Adam Cohen2801caf2011-05-13 20:57:39 -0700370 public void setGridSize(int x, int y) {
371 mCountX = x;
372 mCountY = y;
373 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800374 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700375 mTempRectStack.clear();
Adam Cohen2374abf2013-04-16 14:56:57 -0700376 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700377 mCountX, mCountY);
Adam Cohen76fc0852011-06-17 13:26:23 -0700378 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700379 }
380
Adam Cohen2374abf2013-04-16 14:56:57 -0700381 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
382 public void setInvertIfRtl(boolean invert) {
383 mShortcutsAndWidgets.setInvertIfRtl(invert);
384 }
385
Adam Cohen917e3882013-10-31 15:03:35 -0700386 public void setDropPending(boolean pending) {
387 mDropPending = pending;
388 }
389
390 public boolean isDropPending() {
391 return mDropPending;
392 }
393
Sunny Goyal4b6eb262015-05-14 19:24:40 -0700394 @Override
395 public void setPressedIcon(BubbleTextView icon, Bitmap background) {
Sunny Goyal508da152014-08-14 10:53:27 -0700396 if (icon == null || background == null) {
397 mTouchFeedbackView.setBitmap(null);
398 mTouchFeedbackView.animate().cancel();
399 } else {
Sunny Goyal508da152014-08-14 10:53:27 -0700400 if (mTouchFeedbackView.setBitmap(background)) {
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700401 mTouchFeedbackView.alignWithIconView(icon, mShortcutsAndWidgets);
402 mTouchFeedbackView.animateShadow();
Sunny Goyal508da152014-08-14 10:53:27 -0700403 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800404 }
405 }
406
Adam Cohenc50438c2014-08-19 17:43:05 -0700407 void disableDragTarget() {
408 mIsDragTarget = false;
409 }
410
Tony Wickham0f97b782015-12-02 17:55:07 -0800411 public boolean isDragTarget() {
412 return mIsDragTarget;
413 }
414
Adam Cohenc50438c2014-08-19 17:43:05 -0700415 void setIsDragOverlapping(boolean isDragOverlapping) {
416 if (mIsDragOverlapping != isDragOverlapping) {
417 mIsDragOverlapping = isDragOverlapping;
Sunny Goyal2805e632015-05-20 15:35:32 -0700418 if (mIsDragOverlapping) {
419 mBackground.startTransition(BACKGROUND_ACTIVATE_DURATION);
420 } else {
Winson Chunge8f1d042015-07-31 12:39:57 -0700421 if (mBackgroundAlpha > 0f) {
422 mBackground.reverseTransition(BACKGROUND_ACTIVATE_DURATION);
423 } else {
424 mBackground.resetTransition();
425 }
Sunny Goyal2805e632015-05-20 15:35:32 -0700426 }
Adam Cohenc50438c2014-08-19 17:43:05 -0700427 invalidate();
428 }
429 }
430
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700431 public void disableJailContent() {
432 mJailContent = false;
433 }
434
435 @Override
436 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
437 if (mJailContent) {
438 ParcelableSparseArray jail = getJailedArray(container);
439 super.dispatchSaveInstanceState(jail);
440 container.put(R.id.cell_layout_jail_id, jail);
441 } else {
442 super.dispatchSaveInstanceState(container);
443 }
444 }
445
446 @Override
447 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
448 super.dispatchRestoreInstanceState(mJailContent ? getJailedArray(container) : container);
449 }
450
451 private ParcelableSparseArray getJailedArray(SparseArray<Parcelable> container) {
452 final Parcelable parcelable = container.get(R.id.cell_layout_jail_id);
453 return parcelable instanceof ParcelableSparseArray ?
454 (ParcelableSparseArray) parcelable : new ParcelableSparseArray();
455 }
456
Tony Wickham0f97b782015-12-02 17:55:07 -0800457 public boolean getIsDragOverlapping() {
458 return mIsDragOverlapping;
459 }
460
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700461 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700462 protected void onDraw(Canvas canvas) {
Sunny Goyal05739772015-05-19 19:59:09 -0700463 if (!mIsDragTarget) {
464 return;
465 }
466
Michael Jurka3e7c7632010-10-02 16:01:03 -0700467 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
468 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
469 // When we're small, we are either drawn normally or in the "accepts drops" state (during
470 // a drag). However, we also drag the mini hover background *over* one of those two
471 // backgrounds
Sunny Goyal05739772015-05-19 19:59:09 -0700472 if (mBackgroundAlpha > 0.0f) {
Sunny Goyal2805e632015-05-20 15:35:32 -0700473 mBackground.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700474 }
Romain Guya6abce82009-11-10 02:54:41 -0800475
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700476 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700477 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700478 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700479 if (alpha > 0) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700480 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700481 paint.setAlpha((int)(alpha + .5f));
Sunny Goyal106bf642015-07-16 12:18:06 -0700482 canvas.drawBitmap(b, null, mDragOutlines[i], paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700483 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700484 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800485
Adam Cohen482ed822012-03-02 14:15:13 -0800486 if (DEBUG_VISUALIZE_OCCUPIED) {
487 int[] pt = new int[2];
488 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700489 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800490 for (int i = 0; i < mCountX; i++) {
491 for (int j = 0; j < mCountY; j++) {
492 if (mOccupied[i][j]) {
493 cellToPoint(i, j, pt);
494 canvas.save();
495 canvas.translate(pt[0], pt[1]);
496 cd.draw(canvas);
497 canvas.restore();
498 }
499 }
500 }
501 }
502
Andrew Flynn850d2e72012-04-26 16:51:20 -0700503 int previewOffset = FolderRingAnimator.sPreviewSize;
504
Adam Cohen69ce2e52011-07-03 19:25:21 -0700505 // The folder outer / inner ring image(s)
Adam Cohen2e6da152015-05-06 11:42:25 -0700506 DeviceProfile grid = mLauncher.getDeviceProfile();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700507 for (int i = 0; i < mFolderOuterRings.size(); i++) {
508 FolderRingAnimator fra = mFolderOuterRings.get(i);
509
Adam Cohen5108bc02013-09-20 17:04:51 -0700510 Drawable d;
511 int width, height;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700512 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
Winson Chung5f8afe62013-08-12 16:19:28 -0700513 View child = getChildAt(fra.mCellX, fra.mCellY);
Adam Cohen558f1c22013-10-09 15:15:24 -0700514
Winson Chung89f97052013-09-20 11:32:26 -0700515 if (child != null) {
Adam Cohen558f1c22013-10-09 15:15:24 -0700516 int centerX = mTempLocation[0] + mCellWidth / 2;
517 int centerY = mTempLocation[1] + previewOffset / 2 +
518 child.getPaddingTop() + grid.folderBackgroundOffset;
519
Adam Cohen5108bc02013-09-20 17:04:51 -0700520 // Draw outer ring, if it exists
521 if (FolderIcon.HAS_OUTER_RING) {
522 d = FolderRingAnimator.sSharedOuterRingDrawable;
523 width = (int) (fra.getOuterRingSize() * getChildrenScale());
524 height = width;
525 canvas.save();
526 canvas.translate(centerX - width / 2, centerY - height / 2);
527 d.setBounds(0, 0, width, height);
528 d.draw(canvas);
529 canvas.restore();
530 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700531
Winson Chung89f97052013-09-20 11:32:26 -0700532 // Draw inner ring
533 d = FolderRingAnimator.sSharedInnerRingDrawable;
534 width = (int) (fra.getInnerRingSize() * getChildrenScale());
535 height = width;
Winson Chung89f97052013-09-20 11:32:26 -0700536 canvas.save();
537 canvas.translate(centerX - width / 2, centerY - width / 2);
538 d.setBounds(0, 0, width, height);
539 d.draw(canvas);
540 canvas.restore();
541 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700542 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700543
544 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
545 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
546 int width = d.getIntrinsicWidth();
547 int height = d.getIntrinsicHeight();
548
549 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
Winson Chung5f8afe62013-08-12 16:19:28 -0700550 View child = getChildAt(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1]);
Winson Chung89f97052013-09-20 11:32:26 -0700551 if (child != null) {
552 int centerX = mTempLocation[0] + mCellWidth / 2;
553 int centerY = mTempLocation[1] + previewOffset / 2 +
554 child.getPaddingTop() + grid.folderBackgroundOffset;
Adam Cohenc51934b2011-07-26 21:07:43 -0700555
Winson Chung89f97052013-09-20 11:32:26 -0700556 canvas.save();
557 canvas.translate(centerX - width / 2, centerY - width / 2);
558 d.setBounds(0, 0, width, height);
559 d.draw(canvas);
560 canvas.restore();
561 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700562 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700563 }
564
565 public void showFolderAccept(FolderRingAnimator fra) {
566 mFolderOuterRings.add(fra);
567 }
568
569 public void hideFolderAccept(FolderRingAnimator fra) {
570 if (mFolderOuterRings.contains(fra)) {
571 mFolderOuterRings.remove(fra);
572 }
573 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700574 }
575
Adam Cohenc51934b2011-07-26 21:07:43 -0700576 public void setFolderLeaveBehindCell(int x, int y) {
577 mFolderLeaveBehindCell[0] = x;
578 mFolderLeaveBehindCell[1] = y;
579 invalidate();
580 }
581
582 public void clearFolderLeaveBehind() {
583 mFolderLeaveBehindCell[0] = -1;
584 mFolderLeaveBehindCell[1] = -1;
585 invalidate();
586 }
587
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700588 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700589 public boolean shouldDelayChildPressedState() {
590 return false;
591 }
592
Adam Cohen1462de32012-07-24 22:34:36 -0700593 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700594 try {
595 dispatchRestoreInstanceState(states);
596 } catch (IllegalArgumentException ex) {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700597 if (ProviderConfig.IS_DOGFOOD_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700598 throw ex;
599 }
600 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
601 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
602 }
Adam Cohen1462de32012-07-24 22:34:36 -0700603 }
604
Michael Jurkae6235dd2011-10-04 15:02:05 -0700605 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700606 public void cancelLongPress() {
607 super.cancelLongPress();
608
609 // Cancel long press for all children
610 final int count = getChildCount();
611 for (int i = 0; i < count; i++) {
612 final View child = getChildAt(i);
613 child.cancelLongPress();
614 }
615 }
616
Michael Jurkadee05892010-07-27 10:01:56 -0700617 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
618 mInterceptTouchListener = listener;
619 }
620
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800621 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700622 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800623 }
624
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800625 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700626 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627 }
628
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800629 public void setIsHotseat(boolean isHotseat) {
630 mIsHotseat = isHotseat;
Winson Chung5f8afe62013-08-12 16:19:28 -0700631 mShortcutsAndWidgets.setIsHotseat(isHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800632 }
633
Sunny Goyale9b651e2015-04-24 11:44:51 -0700634 public boolean isHotseat() {
635 return mIsHotseat;
636 }
637
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800638 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700639 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700640 final LayoutParams lp = params;
641
Andrew Flynnde38e422012-05-08 11:22:15 -0700642 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800643 if (child instanceof BubbleTextView) {
644 BubbleTextView bubbleChild = (BubbleTextView) child;
Winson Chung5f8afe62013-08-12 16:19:28 -0700645 bubbleChild.setTextVisibility(!mIsHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800646 }
647
Adam Cohen307fe232012-08-16 17:55:58 -0700648 child.setScaleX(getChildrenScale());
649 child.setScaleY(getChildrenScale());
650
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800651 // Generate an id for each view, this assumes we have at most 256x256 cells
652 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700653 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700654 // If the horizontal or vertical span is set to -1, it is taken to
655 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700656 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
657 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800658
Winson Chungaafa03c2010-06-11 17:34:16 -0700659 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700660 if (LOGD) {
661 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
662 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700663 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700664
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700665 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700666
Winson Chungaafa03c2010-06-11 17:34:16 -0700667 return true;
668 }
669 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800670 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700671
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800672 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700673 public void removeAllViews() {
674 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700675 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700676 }
677
678 @Override
679 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700680 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700681 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700682 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700683 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700684 }
685
686 @Override
687 public void removeView(View view) {
688 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700689 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700690 }
691
692 @Override
693 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700694 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
695 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700696 }
697
698 @Override
699 public void removeViewInLayout(View view) {
700 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700701 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700702 }
703
704 @Override
705 public void removeViews(int start, int count) {
706 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700707 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700708 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700709 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700710 }
711
712 @Override
713 public void removeViewsInLayout(int start, int count) {
714 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700715 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700716 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700717 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800718 }
719
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700720 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700721 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800722 * @param x X coordinate of the point
723 * @param y Y coordinate of the point
724 * @param result Array of 2 ints to hold the x and y coordinate of the cell
725 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700726 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700727 final int hStartPadding = getPaddingLeft();
728 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800729
730 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
731 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
732
Adam Cohend22015c2010-07-26 22:02:18 -0700733 final int xAxis = mCountX;
734 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800735
736 if (result[0] < 0) result[0] = 0;
737 if (result[0] >= xAxis) result[0] = xAxis - 1;
738 if (result[1] < 0) result[1] = 0;
739 if (result[1] >= yAxis) result[1] = yAxis - 1;
740 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700741
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800742 /**
743 * Given a point, return the cell that most closely encloses that point
744 * @param x X coordinate of the point
745 * @param y Y coordinate of the point
746 * @param result Array of 2 ints to hold the x and y coordinate of the cell
747 */
748 void pointToCellRounded(int x, int y, int[] result) {
749 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
750 }
751
752 /**
753 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700754 *
755 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800756 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700757 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800758 * @param result Array of 2 ints to hold the x and y coordinate of the point
759 */
760 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700761 final int hStartPadding = getPaddingLeft();
762 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800763
764 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
765 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
766 }
767
Adam Cohene3e27a82011-04-15 12:07:39 -0700768 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800769 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700770 *
771 * @param cellX X coordinate of the cell
772 * @param cellY Y coordinate of the cell
773 *
774 * @param result Array of 2 ints to hold the x and y coordinate of the point
775 */
776 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700777 regionToCenterPoint(cellX, cellY, 1, 1, result);
778 }
779
780 /**
781 * Given a cell coordinate and span return the point that represents the center of the regio
782 *
783 * @param cellX X coordinate of the cell
784 * @param cellY Y coordinate of the cell
785 *
786 * @param result Array of 2 ints to hold the x and y coordinate of the point
787 */
788 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700789 final int hStartPadding = getPaddingLeft();
790 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700791 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
792 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
793 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
794 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700795 }
796
Adam Cohen19f37922012-03-21 11:59:11 -0700797 /**
798 * Given a cell coordinate and span fills out a corresponding pixel rect
799 *
800 * @param cellX X coordinate of the cell
801 * @param cellY Y coordinate of the cell
802 * @param result Rect in which to write the result
803 */
804 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
805 final int hStartPadding = getPaddingLeft();
806 final int vStartPadding = getPaddingTop();
807 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
808 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
809 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
810 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
811 }
812
Adam Cohen482ed822012-03-02 14:15:13 -0800813 public float getDistanceFromCell(float x, float y, int[] cell) {
814 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700815 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800816 }
817
Romain Guy84f296c2009-11-04 15:00:44 -0800818 int getCellWidth() {
819 return mCellWidth;
820 }
821
822 int getCellHeight() {
823 return mCellHeight;
824 }
825
Adam Cohend4844c32011-02-18 19:25:06 -0800826 int getWidthGap() {
827 return mWidthGap;
828 }
829
830 int getHeightGap() {
831 return mHeightGap;
832 }
833
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700834 public void setFixedSize(int width, int height) {
835 mFixedWidth = width;
836 mFixedHeight = height;
837 }
838
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800839 @Override
840 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800841 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800842 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700843 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
844 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700845 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
846 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Winson Chung11a1a532013-09-13 11:14:45 -0700847 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Sunny Goyalc6205602015-05-21 20:46:33 -0700848 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
849 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700850 if (cw != mCellWidth || ch != mCellHeight) {
851 mCellWidth = cw;
852 mCellHeight = ch;
853 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
854 mHeightGap, mCountX, mCountY);
855 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700856 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700857
Winson Chung2d75f122013-09-23 16:53:31 -0700858 int newWidth = childWidthSize;
859 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700860 if (mFixedWidth > 0 && mFixedHeight > 0) {
861 newWidth = mFixedWidth;
862 newHeight = mFixedHeight;
863 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800864 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
865 }
866
Adam Cohend22015c2010-07-26 22:02:18 -0700867 int numWidthGaps = mCountX - 1;
868 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800869
Adam Cohen234c4cd2011-07-17 21:03:04 -0700870 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -0700871 int hSpace = childWidthSize;
872 int vSpace = childHeightSize;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700873 int hFreeSpace = hSpace - (mCountX * mCellWidth);
874 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700875 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
876 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Winson Chung5f8afe62013-08-12 16:19:28 -0700877 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
878 mHeightGap, mCountX, mCountY);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700879 } else {
880 mWidthGap = mOriginalWidthGap;
881 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700882 }
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700883
884 // Make the feedback view large enough to hold the blur bitmap.
885 mTouchFeedbackView.measure(
886 MeasureSpec.makeMeasureSpec(mCellWidth + mTouchFeedbackView.getExtraSize(),
887 MeasureSpec.EXACTLY),
888 MeasureSpec.makeMeasureSpec(mCellHeight + mTouchFeedbackView.getExtraSize(),
889 MeasureSpec.EXACTLY));
890
891 mShortcutsAndWidgets.measure(
892 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
893 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
894
895 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
896 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700897 if (mFixedWidth > 0 && mFixedHeight > 0) {
898 setMeasuredDimension(maxWidth, maxHeight);
899 } else {
900 setMeasuredDimension(widthSize, heightSize);
901 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800902 }
903
904 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700905 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -0800906 boolean isFullscreen = mShortcutsAndWidgets.getChildCount() > 0 &&
907 ((LayoutParams) mShortcutsAndWidgets.getChildAt(0).getLayoutParams()).isFullscreen;
908 int left = getPaddingLeft();
909 if (!isFullscreen) {
Tony Wickhama501d492015-11-03 18:05:01 -0800910 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Tony Wickham26b01422015-11-10 14:44:32 -0800911 }
Winson Chung38848ca2013-10-08 12:03:44 -0700912 int top = getPaddingTop();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700913
914 mTouchFeedbackView.layout(left, top,
915 left + mTouchFeedbackView.getMeasuredWidth(),
916 top + mTouchFeedbackView.getMeasuredHeight());
917 mShortcutsAndWidgets.layout(left, top,
918 left + r - l,
919 top + b - t);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800920 }
921
Tony Wickhama501d492015-11-03 18:05:01 -0800922 /**
923 * Returns the amount of space left over after subtracting padding and cells. This space will be
924 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
925 * width in {@link DeviceProfile#calculateCellWidth(int, int)}.
926 */
927 public int getUnusedHorizontalSpace() {
928 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
929 }
930
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800931 @Override
Michael Jurkadee05892010-07-27 10:01:56 -0700932 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
933 super.onSizeChanged(w, h, oldw, oldh);
Winson Chung82a9bd22013-10-08 16:02:34 -0700934
935 // Expand the background drawing bounds by the padding baked into the background drawable
Sunny Goyal2805e632015-05-20 15:35:32 -0700936 mBackground.getPadding(mTempRect);
937 mBackground.setBounds(-mTempRect.left, -mTempRect.top,
938 w + mTempRect.right, h + mTempRect.bottom);
Michael Jurkadee05892010-07-27 10:01:56 -0700939 }
940
941 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800942 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700943 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800944 }
945
946 @Override
947 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700948 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800949 }
950
Michael Jurka5f1c5092010-09-03 14:15:02 -0700951 public float getBackgroundAlpha() {
952 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -0700953 }
954
Michael Jurka5f1c5092010-09-03 14:15:02 -0700955 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -0800956 if (mBackgroundAlpha != alpha) {
957 mBackgroundAlpha = alpha;
Sunny Goyal2805e632015-05-20 15:35:32 -0700958 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurkaafaa0502011-12-13 18:22:50 -0800959 }
Michael Jurkadee05892010-07-27 10:01:56 -0700960 }
961
Sunny Goyal2805e632015-05-20 15:35:32 -0700962 @Override
963 protected boolean verifyDrawable(Drawable who) {
964 return super.verifyDrawable(who) || (mIsDragTarget && who == mBackground);
965 }
966
Michael Jurkaa52570f2012-03-20 03:18:20 -0700967 public void setShortcutAndWidgetAlpha(float alpha) {
Sunny Goyal02b50812014-09-10 15:44:42 -0700968 mShortcutsAndWidgets.setAlpha(alpha);
Michael Jurkadee05892010-07-27 10:01:56 -0700969 }
970
Michael Jurkaa52570f2012-03-20 03:18:20 -0700971 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -0700972 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700973 }
974
Patrick Dubroy440c3602010-07-13 17:50:32 -0700975 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700976 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -0700977 }
978
Adam Cohen76fc0852011-06-17 13:26:23 -0700979 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -0800980 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700981 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -0800982 boolean[][] occupied = mOccupied;
983 if (!permanent) {
984 occupied = mTmpOccupied;
985 }
986
Adam Cohen19f37922012-03-21 11:59:11 -0700987 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700988 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
989 final ItemInfo info = (ItemInfo) child.getTag();
990
991 // We cancel any existing animations
992 if (mReorderAnimators.containsKey(lp)) {
993 mReorderAnimators.get(lp).cancel();
994 mReorderAnimators.remove(lp);
995 }
996
Adam Cohen482ed822012-03-02 14:15:13 -0800997 final int oldX = lp.x;
998 final int oldY = lp.y;
999 if (adjustOccupied) {
1000 occupied[lp.cellX][lp.cellY] = false;
1001 occupied[cellX][cellY] = true;
1002 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001003 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001004 if (permanent) {
1005 lp.cellX = info.cellX = cellX;
1006 lp.cellY = info.cellY = cellY;
1007 } else {
1008 lp.tmpCellX = cellX;
1009 lp.tmpCellY = cellY;
1010 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001011 clc.setupLp(lp);
1012 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001013 final int newX = lp.x;
1014 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001015
Adam Cohen76fc0852011-06-17 13:26:23 -07001016 lp.x = oldX;
1017 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001018
Adam Cohen482ed822012-03-02 14:15:13 -08001019 // Exit early if we're not actually moving the view
1020 if (oldX == newX && oldY == newY) {
1021 lp.isLockedToGrid = true;
1022 return true;
1023 }
1024
Michael Jurkaf1ad6082013-03-13 12:55:46 +01001025 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001026 va.setDuration(duration);
1027 mReorderAnimators.put(lp, va);
1028
1029 va.addUpdateListener(new AnimatorUpdateListener() {
1030 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001031 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001032 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001033 lp.x = (int) ((1 - r) * oldX + r * newX);
1034 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001035 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001036 }
1037 });
Adam Cohen482ed822012-03-02 14:15:13 -08001038 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001039 boolean cancelled = false;
1040 public void onAnimationEnd(Animator animation) {
1041 // If the animation was cancelled, it means that another animation
1042 // has interrupted this one, and we don't want to lock the item into
1043 // place just yet.
1044 if (!cancelled) {
1045 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001046 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001047 }
1048 if (mReorderAnimators.containsKey(lp)) {
1049 mReorderAnimators.remove(lp);
1050 }
1051 }
1052 public void onAnimationCancel(Animator animation) {
1053 cancelled = true;
1054 }
1055 });
Adam Cohen482ed822012-03-02 14:15:13 -08001056 va.setStartDelay(delay);
1057 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001058 return true;
1059 }
1060 return false;
1061 }
1062
Tony Wickhama501d492015-11-03 18:05:01 -08001063 void visualizeDropLocation(View v, Bitmap dragOutline, int cellX, int cellY, int spanX,
1064 int spanY, boolean resize, DropTarget.DragObject dragObject) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001065 final int oldDragCellX = mDragCell[0];
1066 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001067
Adam Cohen2801caf2011-05-13 20:57:39 -07001068 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001069 return;
1070 }
1071
Adam Cohen482ed822012-03-02 14:15:13 -08001072 if (cellX != oldDragCellX || cellY != oldDragCellY) {
Sunny Goyale78e3d72015-09-24 11:23:31 -07001073 Point dragOffset = dragObject.dragView.getDragVisualizeOffset();
1074 Rect dragRegion = dragObject.dragView.getDragRegion();
1075
Adam Cohen482ed822012-03-02 14:15:13 -08001076 mDragCell[0] = cellX;
1077 mDragCell[1] = cellY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001078
Joe Onorato4be866d2010-10-10 11:26:02 -07001079 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001080 mDragOutlineAnims[oldIndex].animateOut();
1081 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001082 Rect r = mDragOutlines[mDragOutlineCurrent];
Sunny Goyal106bf642015-07-16 12:18:06 -07001083
Adam Cohend41fbf52012-02-16 23:53:59 -08001084 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001085 cellToRect(cellX, cellY, spanX, spanY, r);
Sunny Goyal106bf642015-07-16 12:18:06 -07001086 } else {
1087 // Find the top left corner of the rect the object will occupy
1088 final int[] topLeft = mTmpPoint;
1089 cellToPoint(cellX, cellY, topLeft);
1090
1091 int left = topLeft[0];
1092 int top = topLeft[1];
1093
1094 if (v != null && dragOffset == null) {
1095 // When drawing the drag outline, it did not account for margin offsets
1096 // added by the view's parent.
1097 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1098 left += lp.leftMargin;
1099 top += lp.topMargin;
1100
1101 // Offsets due to the size difference between the View and the dragOutline.
1102 // There is a size difference to account for the outer blur, which may lie
1103 // outside the bounds of the view.
1104 top += (v.getHeight() - dragOutline.getHeight()) / 2;
1105 // We center about the x axis
1106 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1107 - dragOutline.getWidth()) / 2;
1108 } else {
1109 if (dragOffset != null && dragRegion != null) {
1110 // Center the drag region *horizontally* in the cell and apply a drag
1111 // outline offset
1112 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1113 - dragRegion.width()) / 2;
1114 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
1115 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
1116 top += dragOffset.y + cellPaddingY;
1117 } else {
1118 // Center the drag outline in the cell
1119 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1120 - dragOutline.getWidth()) / 2;
1121 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1122 - dragOutline.getHeight()) / 2;
1123 }
1124 }
1125 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
Adam Cohend41fbf52012-02-16 23:53:59 -08001126 }
Winson Chung150fbab2010-09-29 17:14:26 -07001127
Sunny Goyal106bf642015-07-16 12:18:06 -07001128 Utilities.scaleRectAboutCenter(r, getChildrenScale());
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001129 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1130 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001131
1132 if (dragObject.stateAnnouncer != null) {
1133 String msg;
1134 if (isHotseat()) {
1135 msg = getContext().getString(R.string.move_to_hotseat_position,
1136 Math.max(cellX, cellY) + 1);
1137 } else {
1138 msg = getContext().getString(R.string.move_to_empty_cell,
1139 cellY + 1, cellX + 1);
1140 }
1141 dragObject.stateAnnouncer.announce(msg);
1142 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001143 }
1144 }
1145
Adam Cohene0310962011-04-18 16:15:31 -07001146 public void clearDragOutlines() {
1147 final int oldIndex = mDragOutlineCurrent;
1148 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001149 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001150 }
1151
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001152 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001153 * Find a vacant area that will fit the given bounds nearest the requested
1154 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001155 *
Romain Guy51afc022009-05-04 18:03:43 -07001156 * @param pixelX The X location at which you want to search for a vacant area.
1157 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001158 * @param minSpanX The minimum horizontal span required
1159 * @param minSpanY The minimum vertical span required
1160 * @param spanX Horizontal span of the object.
1161 * @param spanY Vertical span of the object.
1162 * @param result Array in which to place the result, or null (in which case a new array will
1163 * be allocated)
1164 * @return The X, Y cell of a vacant area that can contain this object,
1165 * nearest the requested location.
1166 */
1167 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1168 int spanY, int[] result, int[] resultSpan) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001169 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
Adam Cohend41fbf52012-02-16 23:53:59 -08001170 result, resultSpan);
1171 }
1172
Adam Cohend41fbf52012-02-16 23:53:59 -08001173 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1174 private void lazyInitTempRectStack() {
1175 if (mTempRectStack.isEmpty()) {
1176 for (int i = 0; i < mCountX * mCountY; i++) {
1177 mTempRectStack.push(new Rect());
1178 }
1179 }
1180 }
Adam Cohen482ed822012-03-02 14:15:13 -08001181
Adam Cohend41fbf52012-02-16 23:53:59 -08001182 private void recycleTempRects(Stack<Rect> used) {
1183 while (!used.isEmpty()) {
1184 mTempRectStack.push(used.pop());
1185 }
1186 }
1187
1188 /**
1189 * Find a vacant area that will fit the given bounds nearest the requested
1190 * cell location. Uses Euclidean distance to score multiple vacant areas.
1191 *
1192 * @param pixelX The X location at which you want to search for a vacant area.
1193 * @param pixelY The Y location at which you want to search for a vacant area.
1194 * @param minSpanX The minimum horizontal span required
1195 * @param minSpanY The minimum vertical span required
1196 * @param spanX Horizontal span of the object.
1197 * @param spanY Vertical span of the object.
1198 * @param ignoreOccupied If true, the result can be an occupied cell
1199 * @param result Array in which to place the result, or null (in which case a new array will
1200 * be allocated)
1201 * @return The X, Y cell of a vacant area that can contain this object,
1202 * nearest the requested location.
1203 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001204 private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1205 int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001206 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001207
Adam Cohene3e27a82011-04-15 12:07:39 -07001208 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1209 // to the center of the item, but we are searching based on the top-left cell, so
1210 // we translate the point over to correspond to the top-left.
1211 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1212 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1213
Jeff Sharkey70864282009-04-07 21:08:40 -07001214 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001215 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001216 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001217 final Rect bestRect = new Rect(-1, -1, -1, -1);
1218 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001219
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001220 final int countX = mCountX;
1221 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001222
Adam Cohend41fbf52012-02-16 23:53:59 -08001223 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1224 spanX < minSpanX || spanY < minSpanY) {
1225 return bestXY;
1226 }
1227
1228 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001229 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001230 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1231 int ySize = -1;
1232 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001233 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001234 // First, let's see if this thing fits anywhere
1235 for (int i = 0; i < minSpanX; i++) {
1236 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001237 if (mOccupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001238 continue inner;
1239 }
Michael Jurkac28de512010-08-13 11:27:44 -07001240 }
1241 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001242 xSize = minSpanX;
1243 ySize = minSpanY;
1244
1245 // We know that the item will fit at _some_ acceptable size, now let's see
1246 // how big we can make it. We'll alternate between incrementing x and y spans
1247 // until we hit a limit.
1248 boolean incX = true;
1249 boolean hitMaxX = xSize >= spanX;
1250 boolean hitMaxY = ySize >= spanY;
1251 while (!(hitMaxX && hitMaxY)) {
1252 if (incX && !hitMaxX) {
1253 for (int j = 0; j < ySize; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001254 if (x + xSize > countX -1 || mOccupied[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001255 // We can't move out horizontally
1256 hitMaxX = true;
1257 }
1258 }
1259 if (!hitMaxX) {
1260 xSize++;
1261 }
1262 } else if (!hitMaxY) {
1263 for (int i = 0; i < xSize; i++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001264 if (y + ySize > countY - 1 || mOccupied[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001265 // We can't move out vertically
1266 hitMaxY = true;
1267 }
1268 }
1269 if (!hitMaxY) {
1270 ySize++;
1271 }
1272 }
1273 hitMaxX |= xSize >= spanX;
1274 hitMaxY |= ySize >= spanY;
1275 incX = !incX;
1276 }
1277 incX = true;
1278 hitMaxX = xSize >= spanX;
1279 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001280 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001281 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001282 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001283
Adam Cohend41fbf52012-02-16 23:53:59 -08001284 // We verify that the current rect is not a sub-rect of any of our previous
1285 // candidates. In this case, the current rect is disqualified in favour of the
1286 // containing rect.
1287 Rect currentRect = mTempRectStack.pop();
1288 currentRect.set(x, y, x + xSize, y + ySize);
1289 boolean contained = false;
1290 for (Rect r : validRegions) {
1291 if (r.contains(currentRect)) {
1292 contained = true;
1293 break;
1294 }
1295 }
1296 validRegions.push(currentRect);
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001297 double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
Adam Cohen482ed822012-03-02 14:15:13 -08001298
Adam Cohend41fbf52012-02-16 23:53:59 -08001299 if ((distance <= bestDistance && !contained) ||
1300 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001301 bestDistance = distance;
1302 bestXY[0] = x;
1303 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001304 if (resultSpan != null) {
1305 resultSpan[0] = xSize;
1306 resultSpan[1] = ySize;
1307 }
1308 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001309 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001310 }
1311 }
1312
Adam Cohenc0dcf592011-06-01 15:30:43 -07001313 // Return -1, -1 if no suitable location found
1314 if (bestDistance == Double.MAX_VALUE) {
1315 bestXY[0] = -1;
1316 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001317 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001318 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001319 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001320 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001321
Adam Cohen482ed822012-03-02 14:15:13 -08001322 /**
1323 * Find a vacant area that will fit the given bounds nearest the requested
1324 * cell location, and will also weigh in a suggested direction vector of the
1325 * desired location. This method computers distance based on unit grid distances,
1326 * not pixel distances.
1327 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001328 * @param cellX The X cell nearest to which you want to search for a vacant area.
1329 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001330 * @param spanX Horizontal span of the object.
1331 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001332 * @param direction The favored direction in which the views should move from x, y
Sunny Goyal9eba1fd2015-10-16 08:58:57 -07001333 * @param occupied The array which represents which cells in the CellLayout are occupied
Adam Cohen47a876d2012-03-19 13:21:41 -07001334 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001335 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001336 * @param result Array in which to place the result, or null (in which case a new array will
1337 * be allocated)
1338 * @return The X, Y cell of a vacant area that can contain this object,
1339 * nearest the requested location.
1340 */
1341 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001342 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001343 // Keep track of best-scoring drop area
1344 final int[] bestXY = result != null ? result : new int[2];
1345 float bestDistance = Float.MAX_VALUE;
1346 int bestDirectionScore = Integer.MIN_VALUE;
1347
1348 final int countX = mCountX;
1349 final int countY = mCountY;
1350
1351 for (int y = 0; y < countY - (spanY - 1); y++) {
1352 inner:
1353 for (int x = 0; x < countX - (spanX - 1); x++) {
1354 // First, let's see if this thing fits anywhere
1355 for (int i = 0; i < spanX; i++) {
1356 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001357 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001358 continue inner;
1359 }
1360 }
1361 }
1362
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001363 float distance = (float) Math.hypot(x - cellX, y - cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001364 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001365 computeDirectionVector(x - cellX, y - cellY, curDirection);
1366 // The direction score is just the dot product of the two candidate direction
1367 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001368 int curDirectionScore = direction[0] * curDirection[0] +
1369 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001370 boolean exactDirectionOnly = false;
1371 boolean directionMatches = direction[0] == curDirection[0] &&
1372 direction[0] == curDirection[0];
1373 if ((directionMatches || !exactDirectionOnly) &&
1374 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001375 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1376 bestDistance = distance;
1377 bestDirectionScore = curDirectionScore;
1378 bestXY[0] = x;
1379 bestXY[1] = y;
1380 }
1381 }
1382 }
1383
1384 // Return -1, -1 if no suitable location found
1385 if (bestDistance == Float.MAX_VALUE) {
1386 bestXY[0] = -1;
1387 bestXY[1] = -1;
1388 }
1389 return bestXY;
1390 }
1391
1392 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001393 int[] direction, ItemConfiguration currentState) {
1394 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001395 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001396 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001397 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1398
Adam Cohen8baab352012-03-20 17:39:21 -07001399 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001400
1401 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001402 c.x = mTempLocation[0];
1403 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001404 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001405 }
Adam Cohen8baab352012-03-20 17:39:21 -07001406 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001407 return success;
1408 }
1409
Adam Cohenf3900c22012-11-16 18:28:11 -08001410 /**
1411 * This helper class defines a cluster of views. It helps with defining complex edges
1412 * of the cluster and determining how those edges interact with other views. The edges
1413 * essentially define a fine-grained boundary around the cluster of views -- like a more
1414 * precise version of a bounding box.
1415 */
1416 private class ViewCluster {
1417 final static int LEFT = 0;
1418 final static int TOP = 1;
1419 final static int RIGHT = 2;
1420 final static int BOTTOM = 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001421
Adam Cohenf3900c22012-11-16 18:28:11 -08001422 ArrayList<View> views;
1423 ItemConfiguration config;
1424 Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001425
Adam Cohenf3900c22012-11-16 18:28:11 -08001426 int[] leftEdge = new int[mCountY];
1427 int[] rightEdge = new int[mCountY];
1428 int[] topEdge = new int[mCountX];
1429 int[] bottomEdge = new int[mCountX];
1430 boolean leftEdgeDirty, rightEdgeDirty, topEdgeDirty, bottomEdgeDirty, boundingRectDirty;
1431
1432 @SuppressWarnings("unchecked")
1433 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1434 this.views = (ArrayList<View>) views.clone();
1435 this.config = config;
1436 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001437 }
1438
Adam Cohenf3900c22012-11-16 18:28:11 -08001439 void resetEdges() {
1440 for (int i = 0; i < mCountX; i++) {
1441 topEdge[i] = -1;
1442 bottomEdge[i] = -1;
1443 }
1444 for (int i = 0; i < mCountY; i++) {
1445 leftEdge[i] = -1;
1446 rightEdge[i] = -1;
1447 }
1448 leftEdgeDirty = true;
1449 rightEdgeDirty = true;
1450 bottomEdgeDirty = true;
1451 topEdgeDirty = true;
1452 boundingRectDirty = true;
1453 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001454
Adam Cohenf3900c22012-11-16 18:28:11 -08001455 void computeEdge(int which, int[] edge) {
1456 int count = views.size();
1457 for (int i = 0; i < count; i++) {
1458 CellAndSpan cs = config.map.get(views.get(i));
1459 switch (which) {
1460 case LEFT:
1461 int left = cs.x;
1462 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1463 if (left < edge[j] || edge[j] < 0) {
1464 edge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001465 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001466 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001467 break;
1468 case RIGHT:
1469 int right = cs.x + cs.spanX;
1470 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1471 if (right > edge[j]) {
1472 edge[j] = right;
1473 }
1474 }
1475 break;
1476 case TOP:
1477 int top = cs.y;
1478 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1479 if (top < edge[j] || edge[j] < 0) {
1480 edge[j] = top;
1481 }
1482 }
1483 break;
1484 case BOTTOM:
1485 int bottom = cs.y + cs.spanY;
1486 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1487 if (bottom > edge[j]) {
1488 edge[j] = bottom;
1489 }
1490 }
1491 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001492 }
1493 }
1494 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001495
1496 boolean isViewTouchingEdge(View v, int whichEdge) {
1497 CellAndSpan cs = config.map.get(v);
1498
1499 int[] edge = getEdge(whichEdge);
1500
1501 switch (whichEdge) {
1502 case LEFT:
1503 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1504 if (edge[i] == cs.x + cs.spanX) {
1505 return true;
1506 }
1507 }
1508 break;
1509 case RIGHT:
1510 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1511 if (edge[i] == cs.x) {
1512 return true;
1513 }
1514 }
1515 break;
1516 case TOP:
1517 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1518 if (edge[i] == cs.y + cs.spanY) {
1519 return true;
1520 }
1521 }
1522 break;
1523 case BOTTOM:
1524 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1525 if (edge[i] == cs.y) {
1526 return true;
1527 }
1528 }
1529 break;
1530 }
1531 return false;
1532 }
1533
1534 void shift(int whichEdge, int delta) {
1535 for (View v: views) {
1536 CellAndSpan c = config.map.get(v);
1537 switch (whichEdge) {
1538 case LEFT:
1539 c.x -= delta;
1540 break;
1541 case RIGHT:
1542 c.x += delta;
1543 break;
1544 case TOP:
1545 c.y -= delta;
1546 break;
1547 case BOTTOM:
1548 default:
1549 c.y += delta;
1550 break;
1551 }
1552 }
1553 resetEdges();
1554 }
1555
1556 public void addView(View v) {
1557 views.add(v);
1558 resetEdges();
1559 }
1560
1561 public Rect getBoundingRect() {
1562 if (boundingRectDirty) {
1563 boolean first = true;
1564 for (View v: views) {
1565 CellAndSpan c = config.map.get(v);
1566 if (first) {
1567 boundingRect.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1568 first = false;
1569 } else {
1570 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1571 }
1572 }
1573 }
1574 return boundingRect;
1575 }
1576
1577 public int[] getEdge(int which) {
1578 switch (which) {
1579 case LEFT:
1580 return getLeftEdge();
1581 case RIGHT:
1582 return getRightEdge();
1583 case TOP:
1584 return getTopEdge();
1585 case BOTTOM:
1586 default:
1587 return getBottomEdge();
1588 }
1589 }
1590
1591 public int[] getLeftEdge() {
1592 if (leftEdgeDirty) {
1593 computeEdge(LEFT, leftEdge);
1594 }
1595 return leftEdge;
1596 }
1597
1598 public int[] getRightEdge() {
1599 if (rightEdgeDirty) {
1600 computeEdge(RIGHT, rightEdge);
1601 }
1602 return rightEdge;
1603 }
1604
1605 public int[] getTopEdge() {
1606 if (topEdgeDirty) {
1607 computeEdge(TOP, topEdge);
1608 }
1609 return topEdge;
1610 }
1611
1612 public int[] getBottomEdge() {
1613 if (bottomEdgeDirty) {
1614 computeEdge(BOTTOM, bottomEdge);
1615 }
1616 return bottomEdge;
1617 }
1618
1619 PositionComparator comparator = new PositionComparator();
1620 class PositionComparator implements Comparator<View> {
1621 int whichEdge = 0;
1622 public int compare(View left, View right) {
1623 CellAndSpan l = config.map.get(left);
1624 CellAndSpan r = config.map.get(right);
1625 switch (whichEdge) {
1626 case LEFT:
1627 return (r.x + r.spanX) - (l.x + l.spanX);
1628 case RIGHT:
1629 return l.x - r.x;
1630 case TOP:
1631 return (r.y + r.spanY) - (l.y + l.spanY);
1632 case BOTTOM:
1633 default:
1634 return l.y - r.y;
1635 }
1636 }
1637 }
1638
1639 public void sortConfigurationForEdgePush(int edge) {
1640 comparator.whichEdge = edge;
1641 Collections.sort(config.sortedViews, comparator);
1642 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001643 }
1644
Adam Cohenf3900c22012-11-16 18:28:11 -08001645 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1646 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001647
Adam Cohenf3900c22012-11-16 18:28:11 -08001648 ViewCluster cluster = new ViewCluster(views, currentState);
1649 Rect clusterRect = cluster.getBoundingRect();
1650 int whichEdge;
1651 int pushDistance;
1652 boolean fail = false;
1653
1654 // Determine the edge of the cluster that will be leading the push and how far
1655 // the cluster must be shifted.
1656 if (direction[0] < 0) {
1657 whichEdge = ViewCluster.LEFT;
1658 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001659 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001660 whichEdge = ViewCluster.RIGHT;
1661 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1662 } else if (direction[1] < 0) {
1663 whichEdge = ViewCluster.TOP;
1664 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1665 } else {
1666 whichEdge = ViewCluster.BOTTOM;
1667 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07001668 }
1669
Adam Cohenf3900c22012-11-16 18:28:11 -08001670 // Break early for invalid push distance.
1671 if (pushDistance <= 0) {
1672 return false;
Adam Cohene0489502012-08-27 15:18:53 -07001673 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001674
1675 // Mark the occupied state as false for the group of views we want to move.
1676 for (View v: views) {
1677 CellAndSpan c = currentState.map.get(v);
1678 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1679 }
1680
1681 // We save the current configuration -- if we fail to find a solution we will revert
1682 // to the initial state. The process of finding a solution modifies the configuration
1683 // in place, hence the need for revert in the failure case.
1684 currentState.save();
1685
1686 // The pushing algorithm is simplified by considering the views in the order in which
1687 // they would be pushed by the cluster. For example, if the cluster is leading with its
1688 // left edge, we consider sort the views by their right edge, from right to left.
1689 cluster.sortConfigurationForEdgePush(whichEdge);
1690
1691 while (pushDistance > 0 && !fail) {
1692 for (View v: currentState.sortedViews) {
1693 // For each view that isn't in the cluster, we see if the leading edge of the
1694 // cluster is contacting the edge of that view. If so, we add that view to the
1695 // cluster.
1696 if (!cluster.views.contains(v) && v != dragView) {
1697 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1698 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1699 if (!lp.canReorder) {
1700 // The push solution includes the all apps button, this is not viable.
1701 fail = true;
1702 break;
1703 }
1704 cluster.addView(v);
1705 CellAndSpan c = currentState.map.get(v);
1706
1707 // Adding view to cluster, mark it as not occupied.
1708 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1709 }
1710 }
1711 }
1712 pushDistance--;
1713
1714 // The cluster has been completed, now we move the whole thing over in the appropriate
1715 // direction.
1716 cluster.shift(whichEdge, 1);
1717 }
1718
1719 boolean foundSolution = false;
1720 clusterRect = cluster.getBoundingRect();
1721
1722 // Due to the nature of the algorithm, the only check required to verify a valid solution
1723 // is to ensure that completed shifted cluster lies completely within the cell layout.
1724 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1725 clusterRect.bottom <= mCountY) {
1726 foundSolution = true;
1727 } else {
1728 currentState.restore();
1729 }
1730
1731 // In either case, we set the occupied array as marked for the location of the views
1732 for (View v: cluster.views) {
1733 CellAndSpan c = currentState.map.get(v);
1734 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
1735 }
1736
1737 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07001738 }
1739
Adam Cohen482ed822012-03-02 14:15:13 -08001740 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08001741 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001742 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001743
Adam Cohen8baab352012-03-20 17:39:21 -07001744 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001745 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001746 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001747 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001748 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001749 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001750 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001751 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001752 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001753 }
1754 }
Adam Cohen8baab352012-03-20 17:39:21 -07001755
Adam Cohen8baab352012-03-20 17:39:21 -07001756 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08001757 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001758 CellAndSpan c = currentState.map.get(v);
1759 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1760 }
1761
Adam Cohen47a876d2012-03-19 13:21:41 -07001762 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1763 int top = boundingRect.top;
1764 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001765 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001766 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08001767 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001768 CellAndSpan c = currentState.map.get(v);
1769 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001770 }
1771
Adam Cohen482ed822012-03-02 14:15:13 -08001772 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1773
Adam Cohenf3900c22012-11-16 18:28:11 -08001774 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1775 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001776
Adam Cohen8baab352012-03-20 17:39:21 -07001777 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001778 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001779 int deltaX = mTempLocation[0] - boundingRect.left;
1780 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001781 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001782 CellAndSpan c = currentState.map.get(v);
1783 c.x += deltaX;
1784 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001785 }
1786 success = true;
1787 }
Adam Cohen8baab352012-03-20 17:39:21 -07001788
1789 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08001790 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001791 CellAndSpan c = currentState.map.get(v);
1792 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001793 }
1794 return success;
1795 }
1796
1797 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1798 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1799 }
1800
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001801 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1802 // to push items in each of the cardinal directions, in an order based on the direction vector
1803 // passed.
1804 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1805 int[] direction, View ignoreView, ItemConfiguration solution) {
1806 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001807 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001808 // separately in each of the components.
1809 int temp = direction[1];
1810 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001811
1812 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001813 ignoreView, solution)) {
1814 return true;
1815 }
1816 direction[1] = temp;
1817 temp = direction[0];
1818 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001819
1820 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001821 ignoreView, solution)) {
1822 return true;
1823 }
1824 // Revert the direction
1825 direction[0] = temp;
1826
1827 // Now we try pushing in each component of the opposite direction
1828 direction[0] *= -1;
1829 direction[1] *= -1;
1830 temp = direction[1];
1831 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001832 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001833 ignoreView, solution)) {
1834 return true;
1835 }
1836
1837 direction[1] = temp;
1838 temp = direction[0];
1839 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001840 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001841 ignoreView, solution)) {
1842 return true;
1843 }
1844 // revert the direction
1845 direction[0] = temp;
1846 direction[0] *= -1;
1847 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001848
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001849 } else {
1850 // If the direction vector has a single non-zero component, we push first in the
1851 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08001852 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001853 ignoreView, solution)) {
1854 return true;
1855 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001856 // Then we try the opposite direction
1857 direction[0] *= -1;
1858 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001859 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001860 ignoreView, solution)) {
1861 return true;
1862 }
1863 // Switch the direction back
1864 direction[0] *= -1;
1865 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001866
1867 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001868 // to find a solution by pushing along the perpendicular axis.
1869
1870 // Swap the components
1871 int temp = direction[1];
1872 direction[1] = direction[0];
1873 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08001874 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001875 ignoreView, solution)) {
1876 return true;
1877 }
1878
1879 // Then we try the opposite direction
1880 direction[0] *= -1;
1881 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001882 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001883 ignoreView, solution)) {
1884 return true;
1885 }
1886 // Switch the direction back
1887 direction[0] *= -1;
1888 direction[1] *= -1;
1889
1890 // Swap the components back
1891 temp = direction[1];
1892 direction[1] = direction[0];
1893 direction[0] = temp;
1894 }
1895 return false;
1896 }
1897
Adam Cohen482ed822012-03-02 14:15:13 -08001898 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001899 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001900 // Return early if get invalid cell positions
1901 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001902
Adam Cohen8baab352012-03-20 17:39:21 -07001903 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001904 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001905
Adam Cohen8baab352012-03-20 17:39:21 -07001906 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001907 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001908 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001909 if (c != null) {
1910 c.x = cellX;
1911 c.y = cellY;
1912 }
Adam Cohen482ed822012-03-02 14:15:13 -08001913 }
Adam Cohen482ed822012-03-02 14:15:13 -08001914 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1915 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001916 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001917 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001918 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001919 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001920 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001921 if (Rect.intersects(r0, r1)) {
1922 if (!lp.canReorder) {
1923 return false;
1924 }
1925 mIntersectingViews.add(child);
1926 }
1927 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001928
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001929 solution.intersectingViews = new ArrayList<View>(mIntersectingViews);
1930
Winson Chung5f8afe62013-08-12 16:19:28 -07001931 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001932 // we try to find a solution such that no displaced item travels through another item
1933 // without also displacing that item.
1934 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001935 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001936 return true;
1937 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001938
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001939 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08001940 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001941 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001942 return true;
1943 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001944
Adam Cohen482ed822012-03-02 14:15:13 -08001945 // Ok, they couldn't move as a block, let's move them individually
1946 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001947 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001948 return false;
1949 }
1950 }
1951 return true;
1952 }
1953
1954 /*
1955 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1956 * the provided point and the provided cell
1957 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001958 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001959 double angle = Math.atan(((float) deltaY) / deltaX);
1960
1961 result[0] = 0;
1962 result[1] = 0;
1963 if (Math.abs(Math.cos(angle)) > 0.5f) {
1964 result[0] = (int) Math.signum(deltaX);
1965 }
1966 if (Math.abs(Math.sin(angle)) > 0.5f) {
1967 result[1] = (int) Math.signum(deltaY);
1968 }
1969 }
1970
Adam Cohen8baab352012-03-20 17:39:21 -07001971 private void copyOccupiedArray(boolean[][] occupied) {
1972 for (int i = 0; i < mCountX; i++) {
1973 for (int j = 0; j < mCountY; j++) {
1974 occupied[i][j] = mOccupied[i][j];
1975 }
1976 }
1977 }
1978
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001979 private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001980 int spanX, int spanY, int[] direction, View dragView, boolean decX,
1981 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001982 // Copy the current state into the solution. This solution will be manipulated as necessary.
1983 copyCurrentStateToSolution(solution, false);
1984 // Copy the current occupied array into the temporary occupied array. This array will be
1985 // manipulated as necessary to find a solution.
1986 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001987
1988 // We find the nearest cell into which we would place the dragged item, assuming there's
1989 // nothing in its way.
1990 int result[] = new int[2];
1991 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1992
1993 boolean success = false;
1994 // First we try the exact nearest position of the item being dragged,
1995 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001996 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1997 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001998
1999 if (!success) {
2000 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
2001 // x, then 1 in y etc.
2002 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002003 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
2004 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08002005 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002006 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
2007 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08002008 }
2009 solution.isSolution = false;
2010 } else {
2011 solution.isSolution = true;
2012 solution.dragViewX = result[0];
2013 solution.dragViewY = result[1];
2014 solution.dragViewSpanX = spanX;
2015 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002016 }
2017 return solution;
2018 }
2019
2020 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002021 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002022 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002023 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002024 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002025 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08002026 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07002027 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002028 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07002029 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002030 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002031 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08002032 }
2033 }
2034
2035 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
2036 for (int i = 0; i < mCountX; i++) {
2037 for (int j = 0; j < mCountY; j++) {
2038 mTmpOccupied[i][j] = false;
2039 }
2040 }
2041
Michael Jurkaa52570f2012-03-20 03:18:20 -07002042 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002043 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002044 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002045 if (child == dragView) continue;
2046 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002047 CellAndSpan c = solution.map.get(child);
2048 if (c != null) {
2049 lp.tmpCellX = c.x;
2050 lp.tmpCellY = c.y;
2051 lp.cellHSpan = c.spanX;
2052 lp.cellVSpan = c.spanY;
2053 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002054 }
2055 }
2056 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2057 solution.dragViewSpanY, mTmpOccupied, true);
2058 }
2059
2060 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
2061 commitDragView) {
2062
2063 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
2064 for (int i = 0; i < mCountX; i++) {
2065 for (int j = 0; j < mCountY; j++) {
2066 occupied[i][j] = false;
2067 }
2068 }
2069
Michael Jurkaa52570f2012-03-20 03:18:20 -07002070 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002071 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002072 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002073 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002074 CellAndSpan c = solution.map.get(child);
2075 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002076 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2077 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002078 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002079 }
2080 }
2081 if (commitDragView) {
2082 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2083 solution.dragViewSpanY, occupied, true);
2084 }
2085 }
2086
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002087
2088 // This method starts or changes the reorder preview animations
2089 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
2090 View dragView, int delay, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07002091 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002092 for (int i = 0; i < childCount; i++) {
2093 View child = mShortcutsAndWidgets.getChildAt(i);
2094 if (child == dragView) continue;
2095 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002096 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
2097 != null && !solution.intersectingViews.contains(child);
2098
Adam Cohen19f37922012-03-21 11:59:11 -07002099 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002100 if (c != null && !skip) {
2101 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
2102 lp.cellY, c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002103 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002104 }
2105 }
2106 }
2107
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002108 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07002109 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002110 class ReorderPreviewAnimation {
Adam Cohen19f37922012-03-21 11:59:11 -07002111 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002112 float finalDeltaX;
2113 float finalDeltaY;
2114 float initDeltaX;
2115 float initDeltaY;
2116 float finalScale;
2117 float initScale;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002118 int mode;
2119 boolean repeating = false;
2120 private static final int PREVIEW_DURATION = 300;
2121 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
2122
2123 public static final int MODE_HINT = 0;
2124 public static final int MODE_PREVIEW = 1;
2125
Adam Cohene7587d22012-05-24 18:50:02 -07002126 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002127
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002128 public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
2129 int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07002130 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2131 final int x0 = mTmpPoint[0];
2132 final int y0 = mTmpPoint[1];
2133 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2134 final int x1 = mTmpPoint[0];
2135 final int y1 = mTmpPoint[1];
2136 final int dX = x1 - x0;
2137 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002138 finalDeltaX = 0;
2139 finalDeltaY = 0;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002140 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07002141 if (dX == dY && dX == 0) {
2142 } else {
2143 if (dY == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002144 finalDeltaX = - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002145 } else if (dX == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002146 finalDeltaY = - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002147 } else {
2148 double angle = Math.atan( (float) (dY) / dX);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002149 finalDeltaX = (int) (- dir * Math.signum(dX) *
2150 Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
2151 finalDeltaY = (int) (- dir * Math.signum(dY) *
2152 Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002153 }
2154 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002155 this.mode = mode;
Adam Cohend024f982012-05-23 18:26:45 -07002156 initDeltaX = child.getTranslationX();
2157 initDeltaY = child.getTranslationY();
Adam Cohen307fe232012-08-16 17:55:58 -07002158 finalScale = getChildrenScale() - 4.0f / child.getWidth();
Adam Cohend024f982012-05-23 18:26:45 -07002159 initScale = child.getScaleX();
Adam Cohen19f37922012-03-21 11:59:11 -07002160 this.child = child;
2161 }
2162
Adam Cohend024f982012-05-23 18:26:45 -07002163 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002164 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002165 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002166 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002167 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002168 if (finalDeltaX == 0 && finalDeltaY == 0) {
2169 completeAnimationImmediately();
2170 return;
2171 }
Adam Cohen19f37922012-03-21 11:59:11 -07002172 }
Adam Cohend024f982012-05-23 18:26:45 -07002173 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002174 return;
2175 }
Michael Jurkaf1ad6082013-03-13 12:55:46 +01002176 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002177 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07002178
2179 // Animations are disabled in power save mode, causing the repeated animation to jump
2180 // spastically between beginning and end states. Since this looks bad, we don't repeat
2181 // the animation in power save mode.
Tony Wickham112ac952015-11-12 12:31:50 -08002182 if (!Utilities.isPowerSaverOn(getContext())) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07002183 va.setRepeatMode(ValueAnimator.REVERSE);
2184 va.setRepeatCount(ValueAnimator.INFINITE);
2185 }
2186
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002187 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002188 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002189 va.addUpdateListener(new AnimatorUpdateListener() {
2190 @Override
2191 public void onAnimationUpdate(ValueAnimator animation) {
2192 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002193 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : r;
2194 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2195 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002196 child.setTranslationX(x);
2197 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002198 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002199 child.setScaleX(s);
2200 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002201 }
2202 });
2203 va.addListener(new AnimatorListenerAdapter() {
2204 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002205 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002206 initDeltaX = 0;
2207 initDeltaY = 0;
Adam Cohen307fe232012-08-16 17:55:58 -07002208 initScale = getChildrenScale();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002209 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002210 }
2211 });
Adam Cohen19f37922012-03-21 11:59:11 -07002212 mShakeAnimators.put(child, this);
2213 va.start();
2214 }
2215
Adam Cohend024f982012-05-23 18:26:45 -07002216 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002217 if (a != null) {
2218 a.cancel();
2219 }
Adam Cohen19f37922012-03-21 11:59:11 -07002220 }
Adam Cohene7587d22012-05-24 18:50:02 -07002221
Adam Cohen091440a2015-03-18 14:16:05 -07002222 @Thunk void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002223 if (a != null) {
2224 a.cancel();
2225 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002226
Sunny Goyal5d2fc322015-07-06 22:52:49 -07002227 a = new LauncherViewPropertyAnimator(child)
2228 .scaleX(getChildrenScale())
2229 .scaleY(getChildrenScale())
2230 .translationX(0)
2231 .translationY(0)
2232 .setDuration(REORDER_ANIMATION_DURATION);
2233 a.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2234 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07002235 }
Adam Cohen19f37922012-03-21 11:59:11 -07002236 }
2237
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002238 private void completeAndClearReorderPreviewAnimations() {
2239 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002240 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002241 }
2242 mShakeAnimators.clear();
2243 }
2244
Adam Cohen482ed822012-03-02 14:15:13 -08002245 private void commitTempPlacement() {
2246 for (int i = 0; i < mCountX; i++) {
2247 for (int j = 0; j < mCountY; j++) {
2248 mOccupied[i][j] = mTmpOccupied[i][j];
2249 }
2250 }
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002251
2252 long screenId = mLauncher.getWorkspace().getIdForScreen(this);
2253 int container = Favorites.CONTAINER_DESKTOP;
2254
2255 if (mLauncher.isHotseatLayout(this)) {
2256 screenId = -1;
2257 container = Favorites.CONTAINER_HOTSEAT;
2258 }
2259
Michael Jurkaa52570f2012-03-20 03:18:20 -07002260 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002261 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002262 View child = mShortcutsAndWidgets.getChildAt(i);
2263 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2264 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002265 // We do a null check here because the item info can be null in the case of the
2266 // AllApps button in the hotseat.
2267 if (info != null) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002268 final boolean requiresDbUpdate = (info.cellX != lp.tmpCellX
2269 || info.cellY != lp.tmpCellY || info.spanX != lp.cellHSpan
2270 || info.spanY != lp.cellVSpan);
2271
Adam Cohen2acce882012-03-28 19:03:19 -07002272 info.cellX = lp.cellX = lp.tmpCellX;
2273 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002274 info.spanX = lp.cellHSpan;
2275 info.spanY = lp.cellVSpan;
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002276
2277 if (requiresDbUpdate) {
2278 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId,
2279 info.cellX, info.cellY, info.spanX, info.spanY);
2280 }
Adam Cohen2acce882012-03-28 19:03:19 -07002281 }
Adam Cohen482ed822012-03-02 14:15:13 -08002282 }
2283 }
2284
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002285 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002286 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002287 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002288 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002289 lp.useTmpCoords = useTempCoords;
2290 }
2291 }
2292
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002293 private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002294 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2295 int[] result = new int[2];
2296 int[] resultSpan = new int[2];
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002297 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
Adam Cohen482ed822012-03-02 14:15:13 -08002298 resultSpan);
2299 if (result[0] >= 0 && result[1] >= 0) {
2300 copyCurrentStateToSolution(solution, false);
2301 solution.dragViewX = result[0];
2302 solution.dragViewY = result[1];
2303 solution.dragViewSpanX = resultSpan[0];
2304 solution.dragViewSpanY = resultSpan[1];
2305 solution.isSolution = true;
2306 } else {
2307 solution.isSolution = false;
2308 }
2309 return solution;
2310 }
2311
2312 public void prepareChildForDrag(View child) {
2313 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002314 }
2315
Adam Cohen19f37922012-03-21 11:59:11 -07002316 /* This seems like it should be obvious and straight-forward, but when the direction vector
2317 needs to match with the notion of the dragView pushing other views, we have to employ
2318 a slightly more subtle notion of the direction vector. The question is what two points is
2319 the vector between? The center of the dragView and its desired destination? Not quite, as
2320 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2321 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2322 or right, which helps make pushing feel right.
2323 */
2324 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2325 int spanY, View dragView, int[] resultDirection) {
2326 int[] targetDestination = new int[2];
2327
2328 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2329 Rect dragRect = new Rect();
2330 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2331 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2332
2333 Rect dropRegionRect = new Rect();
2334 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2335 dragView, dropRegionRect, mIntersectingViews);
2336
2337 int dropRegionSpanX = dropRegionRect.width();
2338 int dropRegionSpanY = dropRegionRect.height();
2339
2340 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2341 dropRegionRect.height(), dropRegionRect);
2342
2343 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2344 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2345
2346 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2347 deltaX = 0;
2348 }
2349 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2350 deltaY = 0;
2351 }
2352
2353 if (deltaX == 0 && deltaY == 0) {
2354 // No idea what to do, give a random direction.
2355 resultDirection[0] = 1;
2356 resultDirection[1] = 0;
2357 } else {
2358 computeDirectionVector(deltaX, deltaY, resultDirection);
2359 }
2360 }
2361
2362 // For a given cell and span, fetch the set of views intersecting the region.
2363 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2364 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2365 if (boundingRect != null) {
2366 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2367 }
2368 intersectingViews.clear();
2369 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2370 Rect r1 = new Rect();
2371 final int count = mShortcutsAndWidgets.getChildCount();
2372 for (int i = 0; i < count; i++) {
2373 View child = mShortcutsAndWidgets.getChildAt(i);
2374 if (child == dragView) continue;
2375 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2376 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2377 if (Rect.intersects(r0, r1)) {
2378 mIntersectingViews.add(child);
2379 if (boundingRect != null) {
2380 boundingRect.union(r1);
2381 }
2382 }
2383 }
2384 }
2385
2386 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2387 View dragView, int[] result) {
2388 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2389 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2390 mIntersectingViews);
2391 return !mIntersectingViews.isEmpty();
2392 }
2393
2394 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002395 completeAndClearReorderPreviewAnimations();
2396 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2397 final int count = mShortcutsAndWidgets.getChildCount();
2398 for (int i = 0; i < count; i++) {
2399 View child = mShortcutsAndWidgets.getChildAt(i);
2400 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2401 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2402 lp.tmpCellX = lp.cellX;
2403 lp.tmpCellY = lp.cellY;
2404 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2405 0, false, false);
2406 }
Adam Cohen19f37922012-03-21 11:59:11 -07002407 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002408 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002409 }
Adam Cohen19f37922012-03-21 11:59:11 -07002410 }
2411
Adam Cohenbebf0422012-04-11 18:06:28 -07002412 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2413 View dragView, int[] direction, boolean commit) {
2414 int[] pixelXY = new int[2];
2415 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2416
2417 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002418 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002419 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2420
2421 setUseTempCoords(true);
2422 if (swapSolution != null && swapSolution.isSolution) {
2423 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2424 // committing anything or animating anything as we just want to determine if a solution
2425 // exists
2426 copySolutionToTempState(swapSolution, dragView);
2427 setItemPlacementDirty(true);
2428 animateItemsToSolution(swapSolution, dragView, commit);
2429
2430 if (commit) {
2431 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002432 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002433 setItemPlacementDirty(false);
2434 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002435 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
2436 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002437 }
2438 mShortcutsAndWidgets.requestLayout();
2439 }
2440 return swapSolution.isSolution;
2441 }
2442
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002443 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002444 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002445 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002446 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002447
2448 if (resultSpan == null) {
2449 resultSpan = new int[2];
2450 }
2451
Adam Cohen19f37922012-03-21 11:59:11 -07002452 // When we are checking drop validity or actually dropping, we don't recompute the
2453 // direction vector, since we want the solution to match the preview, and it's possible
2454 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002455 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2456 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002457 mDirectionVector[0] = mPreviousReorderDirection[0];
2458 mDirectionVector[1] = mPreviousReorderDirection[1];
2459 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002460 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2461 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2462 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002463 }
2464 } else {
2465 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2466 mPreviousReorderDirection[0] = mDirectionVector[0];
2467 mPreviousReorderDirection[1] = mDirectionVector[1];
2468 }
2469
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002470 // Find a solution involving pushing / displacing any items in the way
2471 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002472 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2473
2474 // We attempt the approach which doesn't shuffle views at all
2475 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2476 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2477
2478 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002479
2480 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2481 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002482 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2483 finalSolution = swapSolution;
2484 } else if (noShuffleSolution.isSolution) {
2485 finalSolution = noShuffleSolution;
2486 }
2487
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002488 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002489 if (finalSolution != null) {
Adam Cohenfe692872013-12-11 14:47:23 -08002490 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
2491 ReorderPreviewAnimation.MODE_HINT);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002492 result[0] = finalSolution.dragViewX;
2493 result[1] = finalSolution.dragViewY;
2494 resultSpan[0] = finalSolution.dragViewSpanX;
2495 resultSpan[1] = finalSolution.dragViewSpanY;
2496 } else {
2497 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2498 }
2499 return result;
2500 }
2501
Adam Cohen482ed822012-03-02 14:15:13 -08002502 boolean foundSolution = true;
2503 if (!DESTRUCTIVE_REORDER) {
2504 setUseTempCoords(true);
2505 }
2506
2507 if (finalSolution != null) {
2508 result[0] = finalSolution.dragViewX;
2509 result[1] = finalSolution.dragViewY;
2510 resultSpan[0] = finalSolution.dragViewSpanX;
2511 resultSpan[1] = finalSolution.dragViewSpanY;
2512
2513 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2514 // committing anything or animating anything as we just want to determine if a solution
2515 // exists
2516 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2517 if (!DESTRUCTIVE_REORDER) {
2518 copySolutionToTempState(finalSolution, dragView);
2519 }
2520 setItemPlacementDirty(true);
2521 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2522
Adam Cohen19f37922012-03-21 11:59:11 -07002523 if (!DESTRUCTIVE_REORDER &&
2524 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002525 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002526 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002527 setItemPlacementDirty(false);
2528 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002529 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
2530 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002531 }
2532 }
2533 } else {
2534 foundSolution = false;
2535 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2536 }
2537
2538 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2539 setUseTempCoords(false);
2540 }
Adam Cohen482ed822012-03-02 14:15:13 -08002541
Michael Jurkaa52570f2012-03-20 03:18:20 -07002542 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002543 return result;
2544 }
2545
Adam Cohen19f37922012-03-21 11:59:11 -07002546 void setItemPlacementDirty(boolean dirty) {
2547 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002548 }
Adam Cohen19f37922012-03-21 11:59:11 -07002549 boolean isItemPlacementDirty() {
2550 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002551 }
2552
Adam Cohen091440a2015-03-18 14:16:05 -07002553 @Thunk class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002554 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohenf3900c22012-11-16 18:28:11 -08002555 private HashMap<View, CellAndSpan> savedMap = new HashMap<View, CellAndSpan>();
2556 ArrayList<View> sortedViews = new ArrayList<View>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002557 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002558 boolean isSolution = false;
2559 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2560
Adam Cohenf3900c22012-11-16 18:28:11 -08002561 void save() {
2562 // Copy current state into savedMap
2563 for (View v: map.keySet()) {
2564 map.get(v).copy(savedMap.get(v));
2565 }
2566 }
2567
2568 void restore() {
2569 // Restore current state from savedMap
2570 for (View v: savedMap.keySet()) {
2571 savedMap.get(v).copy(map.get(v));
2572 }
2573 }
2574
2575 void add(View v, CellAndSpan cs) {
2576 map.put(v, cs);
2577 savedMap.put(v, new CellAndSpan());
2578 sortedViews.add(v);
2579 }
2580
Adam Cohen482ed822012-03-02 14:15:13 -08002581 int area() {
2582 return dragViewSpanX * dragViewSpanY;
2583 }
Adam Cohen8baab352012-03-20 17:39:21 -07002584 }
2585
2586 private class CellAndSpan {
2587 int x, y;
2588 int spanX, spanY;
2589
Adam Cohenf3900c22012-11-16 18:28:11 -08002590 public CellAndSpan() {
2591 }
2592
2593 public void copy(CellAndSpan copy) {
2594 copy.x = x;
2595 copy.y = y;
2596 copy.spanX = spanX;
2597 copy.spanY = spanY;
2598 }
2599
Adam Cohen8baab352012-03-20 17:39:21 -07002600 public CellAndSpan(int x, int y, int spanX, int spanY) {
2601 this.x = x;
2602 this.y = y;
2603 this.spanX = spanX;
2604 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002605 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002606
2607 public String toString() {
2608 return "(" + x + ", " + y + ": " + spanX + ", " + spanY + ")";
2609 }
2610
Adam Cohen482ed822012-03-02 14:15:13 -08002611 }
2612
Adam Cohendf035382011-04-11 17:22:04 -07002613 /**
Adam Cohendf035382011-04-11 17:22:04 -07002614 * Find a starting cell position that will fit the given bounds nearest the requested
2615 * cell location. Uses Euclidean distance to score multiple vacant areas.
2616 *
2617 * @param pixelX The X location at which you want to search for a vacant area.
2618 * @param pixelY The Y location at which you want to search for a vacant area.
2619 * @param spanX Horizontal span of the object.
2620 * @param spanY Vertical span of the object.
2621 * @param ignoreView Considers space occupied by this view as unoccupied
2622 * @param result Previously returned value to possibly recycle.
2623 * @return The X, Y cell of a vacant area that can contain this object,
2624 * nearest the requested location.
2625 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002626 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2627 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002628 }
2629
Michael Jurka0280c3b2010-09-17 15:00:07 -07002630 boolean existsEmptyCell() {
2631 return findCellForSpan(null, 1, 1);
2632 }
2633
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002634 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002635 * Finds the upper-left coordinate of the first rectangle in the grid that can
2636 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2637 * then this method will only return coordinates for rectangles that contain the cell
2638 * (intersectX, intersectY)
2639 *
2640 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2641 * can be found.
2642 * @param spanX The horizontal span of the cell we want to find.
2643 * @param spanY The vertical span of the cell we want to find.
2644 *
2645 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002646 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002647 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Michael Jurka28750fb2010-09-24 17:43:49 -07002648 boolean foundCell = false;
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002649 final int endX = mCountX - (spanX - 1);
2650 final int endY = mCountY - (spanY - 1);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002651
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002652 for (int y = 0; y < endY && !foundCell; y++) {
2653 inner:
2654 for (int x = 0; x < endX; x++) {
2655 for (int i = 0; i < spanX; i++) {
2656 for (int j = 0; j < spanY; j++) {
2657 if (mOccupied[x + i][y + j]) {
2658 // small optimization: we can skip to after the column we just found
2659 // an occupied cell
2660 x += i;
2661 continue inner;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002662 }
2663 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002664 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002665 if (cellXY != null) {
2666 cellXY[0] = x;
2667 cellXY[1] = y;
2668 }
2669 foundCell = true;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002670 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002671 }
2672 }
2673
Michael Jurka28750fb2010-09-24 17:43:49 -07002674 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002675 }
2676
2677 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002678 * A drag event has begun over this layout.
2679 * It may have begun over this layout (in which case onDragChild is called first),
2680 * or it may have begun on another layout.
2681 */
2682 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002683 mDragging = true;
2684 }
2685
2686 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002687 * Called when drag has left this CellLayout or has been completed (successfully or not)
2688 */
2689 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002690 // This can actually be called when we aren't in a drag, e.g. when adding a new
2691 // item to this layout via the customize drawer.
2692 // Guard against that case.
2693 if (mDragging) {
2694 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002695 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002696
2697 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002698 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002699 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2700 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002701 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002702 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002703 }
2704
2705 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002706 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002707 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002708 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002709 *
2710 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002711 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002712 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002713 if (child != null) {
2714 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002715 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002716 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002717 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002718 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002719 }
2720
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002721 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002722 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002723 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002724 * @param cellX X coordinate of upper left corner expressed as a cell position
2725 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002726 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002727 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002728 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002729 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002730 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002731 final int cellWidth = mCellWidth;
2732 final int cellHeight = mCellHeight;
2733 final int widthGap = mWidthGap;
2734 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002735
Winson Chung4b825dcd2011-06-19 12:41:22 -07002736 final int hStartPadding = getPaddingLeft();
2737 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002738
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002739 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2740 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2741
2742 int x = hStartPadding + cellX * (cellWidth + widthGap);
2743 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002744
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002745 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002746 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002747
Michael Jurka0280c3b2010-09-17 15:00:07 -07002748 private void clearOccupiedCells() {
2749 for (int x = 0; x < mCountX; x++) {
2750 for (int y = 0; y < mCountY; y++) {
2751 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002752 }
2753 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002754 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002755
Adam Cohend4844c32011-02-18 19:25:06 -08002756 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002757 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002758 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002759 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002760 }
2761
Adam Cohend4844c32011-02-18 19:25:06 -08002762 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002763 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002764 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002765 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002766 }
2767
Adam Cohen482ed822012-03-02 14:15:13 -08002768 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2769 boolean value) {
2770 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002771 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2772 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002773 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002774 }
2775 }
2776 }
2777
Adam Cohen2801caf2011-05-13 20:57:39 -07002778 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002779 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002780 (Math.max((mCountX - 1), 0) * mWidthGap);
2781 }
2782
2783 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002784 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002785 (Math.max((mCountY - 1), 0) * mHeightGap);
2786 }
2787
Michael Jurka66d72172011-04-12 16:29:25 -07002788 public boolean isOccupied(int x, int y) {
2789 if (x < mCountX && y < mCountY) {
2790 return mOccupied[x][y];
2791 } else {
2792 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2793 }
2794 }
2795
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002796 @Override
2797 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2798 return new CellLayout.LayoutParams(getContext(), attrs);
2799 }
2800
2801 @Override
2802 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2803 return p instanceof CellLayout.LayoutParams;
2804 }
2805
2806 @Override
2807 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2808 return new CellLayout.LayoutParams(p);
2809 }
2810
2811 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2812 /**
2813 * Horizontal location of the item in the grid.
2814 */
2815 @ViewDebug.ExportedProperty
2816 public int cellX;
2817
2818 /**
2819 * Vertical location of the item in the grid.
2820 */
2821 @ViewDebug.ExportedProperty
2822 public int cellY;
2823
2824 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002825 * Temporary horizontal location of the item in the grid during reorder
2826 */
2827 public int tmpCellX;
2828
2829 /**
2830 * Temporary vertical location of the item in the grid during reorder
2831 */
2832 public int tmpCellY;
2833
2834 /**
2835 * Indicates that the temporary coordinates should be used to layout the items
2836 */
2837 public boolean useTmpCoords;
2838
2839 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002840 * Number of cells spanned horizontally by the item.
2841 */
2842 @ViewDebug.ExportedProperty
2843 public int cellHSpan;
2844
2845 /**
2846 * Number of cells spanned vertically by the item.
2847 */
2848 @ViewDebug.ExportedProperty
2849 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002850
Adam Cohen1b607ed2011-03-03 17:26:50 -08002851 /**
2852 * Indicates whether the item will set its x, y, width and height parameters freely,
2853 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2854 */
Adam Cohend4844c32011-02-18 19:25:06 -08002855 public boolean isLockedToGrid = true;
2856
Adam Cohen482ed822012-03-02 14:15:13 -08002857 /**
Adam Cohenec40b2b2013-07-23 15:52:40 -07002858 * Indicates that this item should use the full extents of its parent.
2859 */
2860 public boolean isFullscreen = false;
2861
2862 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002863 * Indicates whether this item can be reordered. Always true except in the case of the
2864 * the AllApps button.
2865 */
2866 public boolean canReorder = true;
2867
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002868 // X coordinate of the view in the layout.
2869 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002870 public int x;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002871 // Y coordinate of the view in the layout.
2872 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002873 public int y;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002874
Romain Guy84f296c2009-11-04 15:00:44 -08002875 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002876
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002877 public LayoutParams(Context c, AttributeSet attrs) {
2878 super(c, attrs);
2879 cellHSpan = 1;
2880 cellVSpan = 1;
2881 }
2882
2883 public LayoutParams(ViewGroup.LayoutParams source) {
2884 super(source);
2885 cellHSpan = 1;
2886 cellVSpan = 1;
2887 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002888
2889 public LayoutParams(LayoutParams source) {
2890 super(source);
2891 this.cellX = source.cellX;
2892 this.cellY = source.cellY;
2893 this.cellHSpan = source.cellHSpan;
2894 this.cellVSpan = source.cellVSpan;
2895 }
2896
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002897 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002898 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002899 this.cellX = cellX;
2900 this.cellY = cellY;
2901 this.cellHSpan = cellHSpan;
2902 this.cellVSpan = cellVSpan;
2903 }
2904
Adam Cohen2374abf2013-04-16 14:56:57 -07002905 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap,
2906 boolean invertHorizontally, int colCount) {
Adam Cohend4844c32011-02-18 19:25:06 -08002907 if (isLockedToGrid) {
2908 final int myCellHSpan = cellHSpan;
2909 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002910 int myCellX = useTmpCoords ? tmpCellX : cellX;
2911 int myCellY = useTmpCoords ? tmpCellY : cellY;
2912
2913 if (invertHorizontally) {
2914 myCellX = colCount - myCellX - cellHSpan;
2915 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002916
Adam Cohend4844c32011-02-18 19:25:06 -08002917 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2918 leftMargin - rightMargin;
2919 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2920 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002921 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2922 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002923 }
2924 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002925
Winson Chungaafa03c2010-06-11 17:34:16 -07002926 public String toString() {
2927 return "(" + this.cellX + ", " + this.cellY + ")";
2928 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002929
2930 public void setWidth(int width) {
2931 this.width = width;
2932 }
2933
2934 public int getWidth() {
2935 return width;
2936 }
2937
2938 public void setHeight(int height) {
2939 this.height = height;
2940 }
2941
2942 public int getHeight() {
2943 return height;
2944 }
2945
2946 public void setX(int x) {
2947 this.x = x;
2948 }
2949
2950 public int getX() {
2951 return x;
2952 }
2953
2954 public void setY(int y) {
2955 this.y = y;
2956 }
2957
2958 public int getY() {
2959 return y;
2960 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002961 }
2962
Michael Jurka0280c3b2010-09-17 15:00:07 -07002963 // This class stores info for two purposes:
2964 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2965 // its spanX, spanY, and the screen it is on
2966 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2967 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2968 // the CellLayout that was long clicked
Sunny Goyal83a8f042015-05-19 12:52:12 -07002969 public static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002970 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002971 int cellX = -1;
2972 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002973 int spanX;
2974 int spanY;
Adam Cohendcd297f2013-06-18 13:13:40 -07002975 long screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07002976 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002977
Sunny Goyal83a8f042015-05-19 12:52:12 -07002978 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002979 cell = v;
2980 cellX = info.cellX;
2981 cellY = info.cellY;
2982 spanX = info.spanX;
2983 spanY = info.spanY;
2984 screenId = info.screenId;
2985 container = info.container;
2986 }
2987
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002988 @Override
2989 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002990 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2991 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002992 }
2993 }
Michael Jurkad771c962011-08-09 15:00:48 -07002994
Sunny Goyala9116722015-04-29 13:55:58 -07002995 public boolean findVacantCell(int spanX, int spanY, int[] outXY) {
2996 return Utilities.findVacantCell(outXY, spanX, spanY, mCountX, mCountY, mOccupied);
2997 }
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002998
Tony Wickham86930612015-09-09 13:50:40 -07002999 /**
3000 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
3001 * if necessary).
3002 */
3003 public boolean hasReorderSolution(ItemInfo itemInfo) {
3004 int[] cellPoint = new int[2];
3005 // Check for a solution starting at every cell.
3006 for (int cellX = 0; cellX < getCountX(); cellX++) {
3007 for (int cellY = 0; cellY < getCountY(); cellY++) {
3008 cellToPoint(cellX, cellY, cellPoint);
3009 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
3010 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
3011 true, new ItemConfiguration()).isSolution) {
3012 return true;
3013 }
3014 }
3015 }
3016 return false;
3017 }
3018
Sunny Goyal9ca9c132015-04-29 14:57:22 -07003019 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
3020 int x2 = x + spanX - 1;
3021 int y2 = y + spanY - 1;
3022 if (x < 0 || y < 0 || x2 >= mCountX || y2 >= mCountY) {
3023 return false;
3024 }
3025 for (int i = x; i <= x2; i++) {
3026 for (int j = y; j <= y2; j++) {
3027 if (mOccupied[i][j]) {
3028 return false;
3029 }
3030 }
3031 }
3032
3033 return true;
3034 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003035}