blob: 6426ec287ab85451582b68da7c6ac720efa563f5 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Joe Onorato4be866d2010-10-10 11:26:02 -070019import android.animation.Animator;
Michael Jurka629758f2012-06-14 16:18:21 -070020import android.animation.AnimatorListenerAdapter;
Chet Haase00397b12010-10-07 11:13:10 -070021import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070022import android.animation.ValueAnimator;
23import android.animation.ValueAnimator.AnimatorUpdateListener;
Adam Cohenc9735cf2015-01-23 16:11:55 -080024import android.annotation.TargetApi;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040026import android.content.res.Resources;
Joe Onorato4be866d2010-10-10 11:26:02 -070027import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070028import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080029import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070030import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070031import android.graphics.Point;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080033import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070034import android.graphics.drawable.Drawable;
Sunny Goyal26119432016-02-18 22:09:23 +000035import android.graphics.drawable.GradientDrawable;
Sunny Goyal2805e632015-05-20 15:35:32 -070036import android.graphics.drawable.TransitionDrawable;
Adam Cohenc9735cf2015-01-23 16:11:55 -080037import android.os.Build;
Adam Cohen1462de32012-07-24 22:34:36 -070038import android.os.Parcelable;
Adam Cohenc9735cf2015-01-23 16:11:55 -080039import android.support.v4.view.ViewCompat;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070041import android.util.Log;
Adam Cohen1462de32012-07-24 22:34:36 -070042import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.view.MotionEvent;
44import android.view.View;
45import android.view.ViewDebug;
46import android.view.ViewGroup;
Adam Cohenc9735cf2015-01-23 16:11:55 -080047import android.view.accessibility.AccessibilityEvent;
Winson Chung150fbab2010-09-29 17:14:26 -070048import android.view.animation.DecelerateInterpolator;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049
Sunny Goyal4b6eb262015-05-14 19:24:40 -070050import com.android.launcher3.BubbleTextView.BubbleTextShadowHandler;
Sunny Goyalaa8ef112015-06-12 20:04:41 -070051import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyale9b651e2015-04-24 11:44:51 -070052import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
53import com.android.launcher3.accessibility.FolderAccessibilityHelper;
54import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
Tony Wickhame0c33232016-02-08 11:37:04 -080055import com.android.launcher3.config.FeatureFlags;
Sunny Goyal6c56c682015-07-16 14:09:05 -070056import com.android.launcher3.config.ProviderConfig;
Sunny Goyal26119432016-02-18 22:09:23 +000057import com.android.launcher3.folder.FolderIcon;
Sunny Goyale2fd14b2015-08-27 17:45:46 -070058import com.android.launcher3.util.ParcelableSparseArray;
Adam Cohen091440a2015-03-18 14:16:05 -070059import com.android.launcher3.util.Thunk;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070060
Adam Cohen69ce2e52011-07-03 19:25:21 -070061import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070062import java.util.Arrays;
Adam Cohenf3900c22012-11-16 18:28:11 -080063import java.util.Collections;
64import java.util.Comparator;
Adam Cohenbfbfd262011-06-13 16:55:12 -070065import java.util.HashMap;
Adam Cohend41fbf52012-02-16 23:53:59 -080066import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070067
Sunny Goyal4b6eb262015-05-14 19:24:40 -070068public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
Sunny Goyale9b651e2015-04-24 11:44:51 -070069 public static final int WORKSPACE_ACCESSIBILITY_DRAG = 2;
70 public static final int FOLDER_ACCESSIBILITY_DRAG = 1;
71
Tony Wickhama0628cc2015-10-14 15:23:04 -070072 private static final String TAG = "CellLayout";
73 private static final boolean LOGD = false;
Winson Chungaafa03c2010-06-11 17:34:16 -070074
Adam Cohen2acce882012-03-28 19:03:19 -070075 private Launcher mLauncher;
Sunny Goyal4ffec482016-02-09 11:28:52 -080076 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070077 @Thunk int mCellWidth;
Sunny Goyal4ffec482016-02-09 11:28:52 -080078 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070079 @Thunk int mCellHeight;
Winson Chung11a1a532013-09-13 11:14:45 -070080 private int mFixedCellWidth;
81 private int mFixedCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070082
Sunny Goyal4ffec482016-02-09 11:28:52 -080083 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070084 @Thunk int mCountX;
Sunny Goyal4ffec482016-02-09 11:28:52 -080085 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070086 @Thunk int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Adam Cohen234c4cd2011-07-17 21:03:04 -070088 private int mOriginalWidthGap;
89 private int mOriginalHeightGap;
Sunny Goyal4ffec482016-02-09 11:28:52 -080090 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070091 @Thunk int mWidthGap;
Sunny Goyal4ffec482016-02-09 11:28:52 -080092 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070093 @Thunk int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070094 private int mMaxGap;
Adam Cohen917e3882013-10-31 15:03:35 -070095 private boolean mDropPending = false;
Adam Cohenc50438c2014-08-19 17:43:05 -070096 private boolean mIsDragTarget = true;
Sunny Goyale2fd14b2015-08-27 17:45:46 -070097 private boolean mJailContent = true;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098
Patrick Dubroyde7658b2010-09-27 11:15:43 -070099 // These are temporary variables to prevent having to allocate a new object just to
100 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Adam Cohen091440a2015-03-18 14:16:05 -0700101 @Thunk final int[] mTmpPoint = new int[2];
Sunny Goyal2805e632015-05-20 15:35:32 -0700102 @Thunk final int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700103
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800104 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -0800105 boolean[][] mTmpOccupied;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800106
Michael Jurkadee05892010-07-27 10:01:56 -0700107 private OnTouchListener mInterceptTouchListener;
Mady Melloref044dd2015-06-02 15:35:07 -0700108 private StylusEventHelper mStylusEventHelper;
Michael Jurkadee05892010-07-27 10:01:56 -0700109
Adam Cohenefca0272016-02-24 19:19:06 -0800110 private ArrayList<FolderIcon.PreviewBackground> mFolderBackgrounds = new ArrayList<FolderIcon.PreviewBackground>();
111 FolderIcon.PreviewBackground mFolderLeaveBehind = new FolderIcon.PreviewBackground();
112 Paint mFolderBgPaint = new Paint();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700113
Michael Jurka5f1c5092010-09-03 14:15:02 -0700114 private float mBackgroundAlpha;
Adam Cohenf34bab52010-09-30 14:11:56 -0700115
Tony Wickham33326072016-04-04 15:05:49 -0700116 private static final int BACKGROUND_ACTIVATE_DURATION =
117 FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND ? 120 : 0;
Sunny Goyal2805e632015-05-20 15:35:32 -0700118 private final TransitionDrawable mBackground;
119
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700120 // These values allow a fixed measurement to be set on the CellLayout.
121 private int mFixedWidth = -1;
122 private int mFixedHeight = -1;
123
Michael Jurka33945b22010-12-21 18:19:38 -0800124 // If we're actively dragging something over this screen, mIsDragOverlapping is true
125 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700126
Winson Chung150fbab2010-09-29 17:14:26 -0700127 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700128 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohen091440a2015-03-18 14:16:05 -0700129 @Thunk Rect[] mDragOutlines = new Rect[4];
130 @Thunk float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700131 private InterruptibleInOutAnimator[] mDragOutlineAnims =
132 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700133
134 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700135 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700136 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700137
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700138 private final ClickShadowView mTouchFeedbackView;
Patrick Dubroy96864c32011-03-10 17:17:23 -0800139
Sunny Goyal316490e2015-06-02 09:38:28 -0700140 @Thunk HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new HashMap<>();
141 @Thunk HashMap<View, ReorderPreviewAnimation> mShakeAnimators = new HashMap<>();
Adam Cohen19f37922012-03-21 11:59:11 -0700142
143 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700144
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700145 // When a drag operation is in progress, holds the nearest cell to the touch point
146 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800147
Joe Onorato4be866d2010-10-10 11:26:02 -0700148 private boolean mDragging = false;
149
Patrick Dubroyce34a972010-10-19 10:34:32 -0700150 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700151 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700152
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800153 private boolean mIsHotseat = false;
Adam Cohen307fe232012-08-16 17:55:58 -0700154 private float mHotseatScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800155
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800156 public static final int MODE_SHOW_REORDER_HINT = 0;
157 public static final int MODE_DRAG_OVER = 1;
158 public static final int MODE_ON_DROP = 2;
159 public static final int MODE_ON_DROP_EXTERNAL = 3;
160 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700161 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800162 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
163
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800164 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700165 private static final int REORDER_ANIMATION_DURATION = 150;
Adam Cohen091440a2015-03-18 14:16:05 -0700166 @Thunk float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700167
Adam Cohen482ed822012-03-02 14:15:13 -0800168 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
169 private Rect mOccupiedRect = new Rect();
170 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700171 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700172 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800173
Sunny Goyal2805e632015-05-20 15:35:32 -0700174 private final Rect mTempRect = new Rect();
Winson Chung3a6e7f32013-10-09 15:50:52 -0700175
Michael Jurkaca993832012-06-29 15:17:04 -0700176 private final static Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700177
Adam Cohenc9735cf2015-01-23 16:11:55 -0800178 // Related to accessible drag and drop
Sunny Goyale9b651e2015-04-24 11:44:51 -0700179 private DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800180 private boolean mUseTouchHelper = false;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800181
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182 public CellLayout(Context context) {
183 this(context, null);
184 }
185
186 public CellLayout(Context context, AttributeSet attrs) {
187 this(context, attrs, 0);
188 }
189
190 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
191 super(context, attrs, defStyle);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700192
193 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
194 // the user where a dragged item will land when dropped.
195 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800196 setClipToPadding(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700197 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700198
Adam Cohen2e6da152015-05-06 11:42:25 -0700199 DeviceProfile grid = mLauncher.getDeviceProfile();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800200
Winson Chung11a1a532013-09-13 11:14:45 -0700201 mCellWidth = mCellHeight = -1;
Nilesh Agrawal5f7099a2014-01-02 15:54:57 -0800202 mFixedCellWidth = mFixedCellHeight = -1;
Winson Chung5f8afe62013-08-12 16:19:28 -0700203 mWidthGap = mOriginalWidthGap = 0;
204 mHeightGap = mOriginalHeightGap = 0;
205 mMaxGap = Integer.MAX_VALUE;
Adam Cohen2e6da152015-05-06 11:42:25 -0700206 mCountX = (int) grid.inv.numColumns;
207 mCountY = (int) grid.inv.numRows;
Michael Jurka0280c3b2010-09-17 15:00:07 -0700208 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800209 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700210 mPreviousReorderDirection[0] = INVALID_DIRECTION;
211 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212
Adam Cohenefca0272016-02-24 19:19:06 -0800213 mFolderLeaveBehind.delegateCellX = -1;
214 mFolderLeaveBehind.delegateCellY = -1;
215
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216 setAlwaysDrawnWithCacheEnabled(false);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700217 final Resources res = getResources();
Winson Chung6e1c0d32013-10-25 15:24:24 -0700218 mHotseatScale = (float) grid.hotseatIconSizePx / grid.iconSizePx;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700219
Tony Wickhame0c33232016-02-08 11:37:04 -0800220 mBackground = (TransitionDrawable) res.getDrawable(
221 FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND ? R.drawable.bg_screenpanel
222 : R.drawable.bg_celllayout);
Sunny Goyal2805e632015-05-20 15:35:32 -0700223 mBackground.setCallback(this);
Winson Chunge8f1d042015-07-31 12:39:57 -0700224 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurka33945b22010-12-21 18:19:38 -0800225
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800226 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE *
Winson Chung5f8afe62013-08-12 16:19:28 -0700227 grid.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700228
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700229 // Initialize the data structures used for the drag visualization.
Patrick Dubroyce34a972010-10-19 10:34:32 -0700230 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700231 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700232 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800233 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700234 }
235
236 // When dragging things around the home screens, we show a green outline of
237 // where the item will land. The outlines gradually fade out, leaving a trail
238 // behind the drag path.
239 // Set up all the animations that are used to implement this fading.
240 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700241 final float fromAlphaValue = 0;
242 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700243
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700244 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700245
246 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700247 final InterruptibleInOutAnimator anim =
Michael Jurkaf1ad6082013-03-13 12:55:46 +0100248 new InterruptibleInOutAnimator(this, duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700249 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700250 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700251 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700252 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700253 final Bitmap outline = (Bitmap)anim.getTag();
254
255 // If an animation is started and then stopped very quickly, we can still
256 // get spurious updates we've cleared the tag. Guard against this.
257 if (outline == null) {
Tony Wickhama0628cc2015-10-14 15:23:04 -0700258 if (LOGD) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700259 Object val = animation.getAnimatedValue();
260 Log.d(TAG, "anim " + thisIndex + " update: " + val +
261 ", isStopped " + anim.isStopped());
262 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700263 // Try to prevent it from continuing to run
264 animation.cancel();
265 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700266 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800267 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700268 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700269 }
270 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700271 // The animation holds a reference to the drag outline bitmap as long is it's
272 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700273 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700274 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700275 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700276 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700277 anim.setTag(null);
278 }
279 }
280 });
281 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700282 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700283
Michael Jurkaa52570f2012-03-20 03:18:20 -0700284 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
Adam Cohen2374abf2013-04-16 14:56:57 -0700285 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700286 mCountX, mCountY);
Adam Cohen2374abf2013-04-16 14:56:57 -0700287
Mady Mellorbb835202015-07-15 16:34:34 -0700288 mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
Mady Melloref044dd2015-06-02 15:35:07 -0700289
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700290 mTouchFeedbackView = new ClickShadowView(context);
291 addView(mTouchFeedbackView);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700292 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700293 }
294
Adam Cohenc9735cf2015-01-23 16:11:55 -0800295 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
Sunny Goyale9b651e2015-04-24 11:44:51 -0700296 public void enableAccessibleDrag(boolean enable, int dragType) {
Adam Cohenc9735cf2015-01-23 16:11:55 -0800297 mUseTouchHelper = enable;
298 if (!enable) {
299 ViewCompat.setAccessibilityDelegate(this, null);
300 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
301 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
302 setOnClickListener(mLauncher);
303 } else {
Sunny Goyale9b651e2015-04-24 11:44:51 -0700304 if (dragType == WORKSPACE_ACCESSIBILITY_DRAG &&
305 !(mTouchHelper instanceof WorkspaceAccessibilityHelper)) {
306 mTouchHelper = new WorkspaceAccessibilityHelper(this);
307 } else if (dragType == FOLDER_ACCESSIBILITY_DRAG &&
308 !(mTouchHelper instanceof FolderAccessibilityHelper)) {
309 mTouchHelper = new FolderAccessibilityHelper(this);
310 }
Adam Cohenc9735cf2015-01-23 16:11:55 -0800311 ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
312 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
313 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
314 setOnClickListener(mTouchHelper);
315 }
316
317 // Invalidate the accessibility hierarchy
318 if (getParent() != null) {
319 getParent().notifySubtreeAccessibilityStateChanged(
320 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
321 }
322 }
323
324 @Override
325 public boolean dispatchHoverEvent(MotionEvent event) {
326 // Always attempt to dispatch hover events to accessibility first.
327 if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
328 return true;
329 }
330 return super.dispatchHoverEvent(event);
331 }
332
333 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800334 public boolean onInterceptTouchEvent(MotionEvent ev) {
335 if (mUseTouchHelper ||
336 (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
337 return true;
338 }
339 return false;
340 }
341
Mady Melloref044dd2015-06-02 15:35:07 -0700342 @Override
343 public boolean onTouchEvent(MotionEvent ev) {
344 boolean handled = super.onTouchEvent(ev);
345 // Stylus button press on a home screen should not switch between overview mode and
346 // the home screen mode, however, once in overview mode stylus button press should be
347 // enabled to allow rearranging the different home screens. So check what mode
348 // the workspace is in, and only perform stylus button presses while in overview mode.
349 if (mLauncher.mWorkspace.isInOverviewMode()
Mady Mellorbb835202015-07-15 16:34:34 -0700350 && mStylusEventHelper.onMotionEvent(ev)) {
Mady Melloref044dd2015-06-02 15:35:07 -0700351 return true;
352 }
353 return handled;
354 }
355
Chris Craik01f2d7f2013-10-01 14:41:56 -0700356 public void enableHardwareLayer(boolean hasLayer) {
357 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700358 }
359
360 public void buildHardwareLayer() {
361 mShortcutsAndWidgets.buildLayer();
Adam Cohen2801caf2011-05-13 20:57:39 -0700362 }
363
Adam Cohen307fe232012-08-16 17:55:58 -0700364 public float getChildrenScale() {
365 return mIsHotseat ? mHotseatScale : 1.0f;
366 }
367
Winson Chung5f8afe62013-08-12 16:19:28 -0700368 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700369 mFixedCellWidth = mCellWidth = width;
370 mFixedCellHeight = mCellHeight = height;
Winson Chung5f8afe62013-08-12 16:19:28 -0700371 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
372 mCountX, mCountY);
373 }
374
Adam Cohen2801caf2011-05-13 20:57:39 -0700375 public void setGridSize(int x, int y) {
376 mCountX = x;
377 mCountY = y;
378 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800379 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700380 mTempRectStack.clear();
Adam Cohen2374abf2013-04-16 14:56:57 -0700381 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700382 mCountX, mCountY);
Adam Cohen76fc0852011-06-17 13:26:23 -0700383 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700384 }
385
Adam Cohen2374abf2013-04-16 14:56:57 -0700386 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
387 public void setInvertIfRtl(boolean invert) {
388 mShortcutsAndWidgets.setInvertIfRtl(invert);
389 }
390
Adam Cohen917e3882013-10-31 15:03:35 -0700391 public void setDropPending(boolean pending) {
392 mDropPending = pending;
393 }
394
395 public boolean isDropPending() {
396 return mDropPending;
397 }
398
Sunny Goyal4b6eb262015-05-14 19:24:40 -0700399 @Override
400 public void setPressedIcon(BubbleTextView icon, Bitmap background) {
Sunny Goyal508da152014-08-14 10:53:27 -0700401 if (icon == null || background == null) {
402 mTouchFeedbackView.setBitmap(null);
403 mTouchFeedbackView.animate().cancel();
404 } else {
Sunny Goyal508da152014-08-14 10:53:27 -0700405 if (mTouchFeedbackView.setBitmap(background)) {
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700406 mTouchFeedbackView.alignWithIconView(icon, mShortcutsAndWidgets);
407 mTouchFeedbackView.animateShadow();
Sunny Goyal508da152014-08-14 10:53:27 -0700408 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800409 }
410 }
411
Adam Cohenc50438c2014-08-19 17:43:05 -0700412 void disableDragTarget() {
413 mIsDragTarget = false;
414 }
415
Tony Wickham0f97b782015-12-02 17:55:07 -0800416 public boolean isDragTarget() {
417 return mIsDragTarget;
418 }
419
Adam Cohenc50438c2014-08-19 17:43:05 -0700420 void setIsDragOverlapping(boolean isDragOverlapping) {
421 if (mIsDragOverlapping != isDragOverlapping) {
422 mIsDragOverlapping = isDragOverlapping;
Sunny Goyal2805e632015-05-20 15:35:32 -0700423 if (mIsDragOverlapping) {
424 mBackground.startTransition(BACKGROUND_ACTIVATE_DURATION);
425 } else {
Winson Chunge8f1d042015-07-31 12:39:57 -0700426 if (mBackgroundAlpha > 0f) {
427 mBackground.reverseTransition(BACKGROUND_ACTIVATE_DURATION);
428 } else {
429 mBackground.resetTransition();
430 }
Sunny Goyal2805e632015-05-20 15:35:32 -0700431 }
Adam Cohenc50438c2014-08-19 17:43:05 -0700432 invalidate();
433 }
434 }
435
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700436 public void disableJailContent() {
437 mJailContent = false;
438 }
439
440 @Override
441 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
442 if (mJailContent) {
443 ParcelableSparseArray jail = getJailedArray(container);
444 super.dispatchSaveInstanceState(jail);
445 container.put(R.id.cell_layout_jail_id, jail);
446 } else {
447 super.dispatchSaveInstanceState(container);
448 }
449 }
450
451 @Override
452 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
453 super.dispatchRestoreInstanceState(mJailContent ? getJailedArray(container) : container);
454 }
455
456 private ParcelableSparseArray getJailedArray(SparseArray<Parcelable> container) {
457 final Parcelable parcelable = container.get(R.id.cell_layout_jail_id);
458 return parcelable instanceof ParcelableSparseArray ?
459 (ParcelableSparseArray) parcelable : new ParcelableSparseArray();
460 }
461
Tony Wickham0f97b782015-12-02 17:55:07 -0800462 public boolean getIsDragOverlapping() {
463 return mIsDragOverlapping;
464 }
465
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700466 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700467 protected void onDraw(Canvas canvas) {
Sunny Goyal05739772015-05-19 19:59:09 -0700468 if (!mIsDragTarget) {
469 return;
470 }
471
Michael Jurka3e7c7632010-10-02 16:01:03 -0700472 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
473 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
474 // When we're small, we are either drawn normally or in the "accepts drops" state (during
475 // a drag). However, we also drag the mini hover background *over* one of those two
476 // backgrounds
Sunny Goyal05739772015-05-19 19:59:09 -0700477 if (mBackgroundAlpha > 0.0f) {
Sunny Goyal2805e632015-05-20 15:35:32 -0700478 mBackground.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700479 }
Romain Guya6abce82009-11-10 02:54:41 -0800480
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700481 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700482 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700483 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700484 if (alpha > 0) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700485 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700486 paint.setAlpha((int)(alpha + .5f));
Sunny Goyal106bf642015-07-16 12:18:06 -0700487 canvas.drawBitmap(b, null, mDragOutlines[i], paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700488 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700489 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800490
Adam Cohen482ed822012-03-02 14:15:13 -0800491 if (DEBUG_VISUALIZE_OCCUPIED) {
492 int[] pt = new int[2];
493 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700494 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800495 for (int i = 0; i < mCountX; i++) {
496 for (int j = 0; j < mCountY; j++) {
497 if (mOccupied[i][j]) {
498 cellToPoint(i, j, pt);
499 canvas.save();
500 canvas.translate(pt[0], pt[1]);
501 cd.draw(canvas);
502 canvas.restore();
503 }
504 }
505 }
506 }
507
Adam Cohenefca0272016-02-24 19:19:06 -0800508 for (int i = 0; i < mFolderBackgrounds.size(); i++) {
509 FolderIcon.PreviewBackground bg = mFolderBackgrounds.get(i);
510 cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
511 canvas.save();
512 canvas.translate(mTempLocation[0], mTempLocation[1]);
513 bg.drawBackground(canvas, mFolderBgPaint);
514 canvas.restore();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700515 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700516
Adam Cohenefca0272016-02-24 19:19:06 -0800517 if (mFolderLeaveBehind.delegateCellX >= 0 && mFolderLeaveBehind.delegateCellY >= 0) {
518 cellToPoint(mFolderLeaveBehind.delegateCellX,
519 mFolderLeaveBehind.delegateCellY, mTempLocation);
520 canvas.save();
521 canvas.translate(mTempLocation[0], mTempLocation[1]);
522 mFolderLeaveBehind.drawLeaveBehind(canvas, mFolderBgPaint);
523 canvas.restore();
Adam Cohenc51934b2011-07-26 21:07:43 -0700524 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700525 }
526
Adam Cohenefca0272016-02-24 19:19:06 -0800527 @Override
528 protected void dispatchDraw(Canvas canvas) {
529 super.dispatchDraw(canvas);
530
531 for (int i = 0; i < mFolderBackgrounds.size(); i++) {
532 FolderIcon.PreviewBackground bg = mFolderBackgrounds.get(i);
533 cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
534 canvas.save();
535 canvas.translate(mTempLocation[0], mTempLocation[1]);
536 bg.drawBackgroundStroke(canvas, mFolderBgPaint);
537 canvas.restore();
538 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700539 }
540
Adam Cohenefca0272016-02-24 19:19:06 -0800541 public void addFolderBackground(FolderIcon.PreviewBackground bg) {
542 mFolderBackgrounds.add(bg);
543 }
544 public void removeFolderBackground(FolderIcon.PreviewBackground bg) {
545 mFolderBackgrounds.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700546 }
547
Adam Cohenc51934b2011-07-26 21:07:43 -0700548 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800549
550 DeviceProfile grid = mLauncher.getDeviceProfile();
551 View child = getChildAt(x, y);
552
553 mFolderLeaveBehind.setup(getResources().getDisplayMetrics(), grid, null,
554 child.getMeasuredWidth(), child.getPaddingTop());
555
556 mFolderLeaveBehind.delegateCellX = x;
557 mFolderLeaveBehind.delegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700558 invalidate();
559 }
560
561 public void clearFolderLeaveBehind() {
Adam Cohenefca0272016-02-24 19:19:06 -0800562 mFolderLeaveBehind.delegateCellX = -1;
563 mFolderLeaveBehind.delegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700564 invalidate();
565 }
566
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700567 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700568 public boolean shouldDelayChildPressedState() {
569 return false;
570 }
571
Adam Cohen1462de32012-07-24 22:34:36 -0700572 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700573 try {
574 dispatchRestoreInstanceState(states);
575 } catch (IllegalArgumentException ex) {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700576 if (ProviderConfig.IS_DOGFOOD_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700577 throw ex;
578 }
579 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
580 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
581 }
Adam Cohen1462de32012-07-24 22:34:36 -0700582 }
583
Michael Jurkae6235dd2011-10-04 15:02:05 -0700584 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700585 public void cancelLongPress() {
586 super.cancelLongPress();
587
588 // Cancel long press for all children
589 final int count = getChildCount();
590 for (int i = 0; i < count; i++) {
591 final View child = getChildAt(i);
592 child.cancelLongPress();
593 }
594 }
595
Michael Jurkadee05892010-07-27 10:01:56 -0700596 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
597 mInterceptTouchListener = listener;
598 }
599
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800600 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700601 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800602 }
603
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800604 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700605 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800606 }
607
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800608 public void setIsHotseat(boolean isHotseat) {
609 mIsHotseat = isHotseat;
Winson Chung5f8afe62013-08-12 16:19:28 -0700610 mShortcutsAndWidgets.setIsHotseat(isHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800611 }
612
Sunny Goyale9b651e2015-04-24 11:44:51 -0700613 public boolean isHotseat() {
614 return mIsHotseat;
615 }
616
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800617 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700618 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700619 final LayoutParams lp = params;
620
Andrew Flynnde38e422012-05-08 11:22:15 -0700621 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800622 if (child instanceof BubbleTextView) {
623 BubbleTextView bubbleChild = (BubbleTextView) child;
Winson Chung5f8afe62013-08-12 16:19:28 -0700624 bubbleChild.setTextVisibility(!mIsHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800625 }
626
Adam Cohen307fe232012-08-16 17:55:58 -0700627 child.setScaleX(getChildrenScale());
628 child.setScaleY(getChildrenScale());
629
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800630 // Generate an id for each view, this assumes we have at most 256x256 cells
631 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700632 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700633 // If the horizontal or vertical span is set to -1, it is taken to
634 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700635 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
636 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800637
Winson Chungaafa03c2010-06-11 17:34:16 -0700638 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700639 if (LOGD) {
640 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
641 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700642 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700643
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700644 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700645
Winson Chungaafa03c2010-06-11 17:34:16 -0700646 return true;
647 }
648 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800649 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700650
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800651 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700652 public void removeAllViews() {
653 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700654 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700655 }
656
657 @Override
658 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700659 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700660 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700661 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700662 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700663 }
664
665 @Override
666 public void removeView(View view) {
667 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700668 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700669 }
670
671 @Override
672 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700673 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
674 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700675 }
676
677 @Override
678 public void removeViewInLayout(View view) {
679 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700680 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700681 }
682
683 @Override
684 public void removeViews(int start, int count) {
685 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700686 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700687 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700688 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700689 }
690
691 @Override
692 public void removeViewsInLayout(int start, int count) {
693 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700694 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700695 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700696 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800697 }
698
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700699 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700700 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800701 * @param x X coordinate of the point
702 * @param y Y coordinate of the point
703 * @param result Array of 2 ints to hold the x and y coordinate of the cell
704 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700705 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700706 final int hStartPadding = getPaddingLeft();
707 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800708
709 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
710 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
711
Adam Cohend22015c2010-07-26 22:02:18 -0700712 final int xAxis = mCountX;
713 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800714
715 if (result[0] < 0) result[0] = 0;
716 if (result[0] >= xAxis) result[0] = xAxis - 1;
717 if (result[1] < 0) result[1] = 0;
718 if (result[1] >= yAxis) result[1] = yAxis - 1;
719 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700720
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800721 /**
722 * Given a point, return the cell that most closely encloses that point
723 * @param x X coordinate of the point
724 * @param y Y coordinate of the point
725 * @param result Array of 2 ints to hold the x and y coordinate of the cell
726 */
727 void pointToCellRounded(int x, int y, int[] result) {
728 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
729 }
730
731 /**
732 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700733 *
734 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800735 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700736 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800737 * @param result Array of 2 ints to hold the x and y coordinate of the point
738 */
739 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700740 final int hStartPadding = getPaddingLeft();
741 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800742
743 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
744 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
745 }
746
Adam Cohene3e27a82011-04-15 12:07:39 -0700747 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800748 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700749 *
750 * @param cellX X coordinate of the cell
751 * @param cellY Y coordinate of the cell
752 *
753 * @param result Array of 2 ints to hold the x and y coordinate of the point
754 */
755 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700756 regionToCenterPoint(cellX, cellY, 1, 1, result);
757 }
758
759 /**
760 * Given a cell coordinate and span return the point that represents the center of the regio
761 *
762 * @param cellX X coordinate of the cell
763 * @param cellY Y coordinate of the cell
764 *
765 * @param result Array of 2 ints to hold the x and y coordinate of the point
766 */
767 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700768 final int hStartPadding = getPaddingLeft();
769 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700770 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
771 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
772 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
773 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700774 }
775
Adam Cohen19f37922012-03-21 11:59:11 -0700776 /**
777 * Given a cell coordinate and span fills out a corresponding pixel rect
778 *
779 * @param cellX X coordinate of the cell
780 * @param cellY Y coordinate of the cell
781 * @param result Rect in which to write the result
782 */
783 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
784 final int hStartPadding = getPaddingLeft();
785 final int vStartPadding = getPaddingTop();
786 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
787 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
788 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
789 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
790 }
791
Adam Cohen482ed822012-03-02 14:15:13 -0800792 public float getDistanceFromCell(float x, float y, int[] cell) {
793 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700794 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800795 }
796
Adam Cohenf9c184a2016-01-15 16:47:43 -0800797 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800798 return mCellWidth;
799 }
800
801 int getCellHeight() {
802 return mCellHeight;
803 }
804
Adam Cohend4844c32011-02-18 19:25:06 -0800805 int getWidthGap() {
806 return mWidthGap;
807 }
808
809 int getHeightGap() {
810 return mHeightGap;
811 }
812
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700813 public void setFixedSize(int width, int height) {
814 mFixedWidth = width;
815 mFixedHeight = height;
816 }
817
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800818 @Override
819 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800820 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800821 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700822 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
823 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700824 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
825 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Winson Chung11a1a532013-09-13 11:14:45 -0700826 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Sunny Goyalc6205602015-05-21 20:46:33 -0700827 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
828 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700829 if (cw != mCellWidth || ch != mCellHeight) {
830 mCellWidth = cw;
831 mCellHeight = ch;
832 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
833 mHeightGap, mCountX, mCountY);
834 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700835 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700836
Winson Chung2d75f122013-09-23 16:53:31 -0700837 int newWidth = childWidthSize;
838 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700839 if (mFixedWidth > 0 && mFixedHeight > 0) {
840 newWidth = mFixedWidth;
841 newHeight = mFixedHeight;
842 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800843 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
844 }
845
Adam Cohend22015c2010-07-26 22:02:18 -0700846 int numWidthGaps = mCountX - 1;
847 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800848
Adam Cohen234c4cd2011-07-17 21:03:04 -0700849 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -0700850 int hSpace = childWidthSize;
851 int vSpace = childHeightSize;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700852 int hFreeSpace = hSpace - (mCountX * mCellWidth);
853 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700854 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
855 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Winson Chung5f8afe62013-08-12 16:19:28 -0700856 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
857 mHeightGap, mCountX, mCountY);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700858 } else {
859 mWidthGap = mOriginalWidthGap;
860 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700861 }
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700862
863 // Make the feedback view large enough to hold the blur bitmap.
864 mTouchFeedbackView.measure(
865 MeasureSpec.makeMeasureSpec(mCellWidth + mTouchFeedbackView.getExtraSize(),
866 MeasureSpec.EXACTLY),
867 MeasureSpec.makeMeasureSpec(mCellHeight + mTouchFeedbackView.getExtraSize(),
868 MeasureSpec.EXACTLY));
869
870 mShortcutsAndWidgets.measure(
871 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
872 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
873
874 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
875 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700876 if (mFixedWidth > 0 && mFixedHeight > 0) {
877 setMeasuredDimension(maxWidth, maxHeight);
878 } else {
879 setMeasuredDimension(widthSize, heightSize);
880 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800881 }
882
883 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700884 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -0800885 boolean isFullscreen = mShortcutsAndWidgets.getChildCount() > 0 &&
886 ((LayoutParams) mShortcutsAndWidgets.getChildAt(0).getLayoutParams()).isFullscreen;
887 int left = getPaddingLeft();
888 if (!isFullscreen) {
Tony Wickhama501d492015-11-03 18:05:01 -0800889 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Tony Wickham26b01422015-11-10 14:44:32 -0800890 }
Winson Chung38848ca2013-10-08 12:03:44 -0700891 int top = getPaddingTop();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700892
893 mTouchFeedbackView.layout(left, top,
894 left + mTouchFeedbackView.getMeasuredWidth(),
895 top + mTouchFeedbackView.getMeasuredHeight());
896 mShortcutsAndWidgets.layout(left, top,
897 left + r - l,
898 top + b - t);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800899 }
900
Tony Wickhama501d492015-11-03 18:05:01 -0800901 /**
902 * Returns the amount of space left over after subtracting padding and cells. This space will be
903 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
904 * width in {@link DeviceProfile#calculateCellWidth(int, int)}.
905 */
906 public int getUnusedHorizontalSpace() {
907 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
908 }
909
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800910 @Override
Michael Jurkadee05892010-07-27 10:01:56 -0700911 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
912 super.onSizeChanged(w, h, oldw, oldh);
Winson Chung82a9bd22013-10-08 16:02:34 -0700913
914 // Expand the background drawing bounds by the padding baked into the background drawable
Sunny Goyal2805e632015-05-20 15:35:32 -0700915 mBackground.getPadding(mTempRect);
916 mBackground.setBounds(-mTempRect.left, -mTempRect.top,
917 w + mTempRect.right, h + mTempRect.bottom);
Michael Jurkadee05892010-07-27 10:01:56 -0700918 }
919
920 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800921 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700922 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800923 }
924
925 @Override
926 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700927 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800928 }
929
Michael Jurka5f1c5092010-09-03 14:15:02 -0700930 public float getBackgroundAlpha() {
931 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -0700932 }
933
Michael Jurka5f1c5092010-09-03 14:15:02 -0700934 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -0800935 if (mBackgroundAlpha != alpha) {
936 mBackgroundAlpha = alpha;
Sunny Goyal2805e632015-05-20 15:35:32 -0700937 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurkaafaa0502011-12-13 18:22:50 -0800938 }
Michael Jurkadee05892010-07-27 10:01:56 -0700939 }
940
Sunny Goyal2805e632015-05-20 15:35:32 -0700941 @Override
942 protected boolean verifyDrawable(Drawable who) {
943 return super.verifyDrawable(who) || (mIsDragTarget && who == mBackground);
944 }
945
Michael Jurkaa52570f2012-03-20 03:18:20 -0700946 public void setShortcutAndWidgetAlpha(float alpha) {
Sunny Goyal02b50812014-09-10 15:44:42 -0700947 mShortcutsAndWidgets.setAlpha(alpha);
Michael Jurkadee05892010-07-27 10:01:56 -0700948 }
949
Michael Jurkaa52570f2012-03-20 03:18:20 -0700950 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -0700951 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700952 }
953
Patrick Dubroy440c3602010-07-13 17:50:32 -0700954 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700955 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -0700956 }
957
Adam Cohen76fc0852011-06-17 13:26:23 -0700958 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -0800959 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700960 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -0800961 boolean[][] occupied = mOccupied;
962 if (!permanent) {
963 occupied = mTmpOccupied;
964 }
965
Adam Cohen19f37922012-03-21 11:59:11 -0700966 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700967 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
968 final ItemInfo info = (ItemInfo) child.getTag();
969
970 // We cancel any existing animations
971 if (mReorderAnimators.containsKey(lp)) {
972 mReorderAnimators.get(lp).cancel();
973 mReorderAnimators.remove(lp);
974 }
975
Adam Cohen482ed822012-03-02 14:15:13 -0800976 final int oldX = lp.x;
977 final int oldY = lp.y;
978 if (adjustOccupied) {
979 occupied[lp.cellX][lp.cellY] = false;
980 occupied[cellX][cellY] = true;
981 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700982 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -0800983 if (permanent) {
984 lp.cellX = info.cellX = cellX;
985 lp.cellY = info.cellY = cellY;
986 } else {
987 lp.tmpCellX = cellX;
988 lp.tmpCellY = cellY;
989 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700990 clc.setupLp(lp);
991 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800992 final int newX = lp.x;
993 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700994
Adam Cohen76fc0852011-06-17 13:26:23 -0700995 lp.x = oldX;
996 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -0700997
Adam Cohen482ed822012-03-02 14:15:13 -0800998 // Exit early if we're not actually moving the view
999 if (oldX == newX && oldY == newY) {
1000 lp.isLockedToGrid = true;
1001 return true;
1002 }
1003
Michael Jurkaf1ad6082013-03-13 12:55:46 +01001004 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001005 va.setDuration(duration);
1006 mReorderAnimators.put(lp, va);
1007
1008 va.addUpdateListener(new AnimatorUpdateListener() {
1009 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001010 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001011 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001012 lp.x = (int) ((1 - r) * oldX + r * newX);
1013 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001014 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001015 }
1016 });
Adam Cohen482ed822012-03-02 14:15:13 -08001017 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001018 boolean cancelled = false;
1019 public void onAnimationEnd(Animator animation) {
1020 // If the animation was cancelled, it means that another animation
1021 // has interrupted this one, and we don't want to lock the item into
1022 // place just yet.
1023 if (!cancelled) {
1024 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001025 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001026 }
1027 if (mReorderAnimators.containsKey(lp)) {
1028 mReorderAnimators.remove(lp);
1029 }
1030 }
1031 public void onAnimationCancel(Animator animation) {
1032 cancelled = true;
1033 }
1034 });
Adam Cohen482ed822012-03-02 14:15:13 -08001035 va.setStartDelay(delay);
1036 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001037 return true;
1038 }
1039 return false;
1040 }
1041
Tony Wickhama501d492015-11-03 18:05:01 -08001042 void visualizeDropLocation(View v, Bitmap dragOutline, int cellX, int cellY, int spanX,
1043 int spanY, boolean resize, DropTarget.DragObject dragObject) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001044 final int oldDragCellX = mDragCell[0];
1045 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001046
Adam Cohen2801caf2011-05-13 20:57:39 -07001047 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001048 return;
1049 }
1050
Adam Cohen482ed822012-03-02 14:15:13 -08001051 if (cellX != oldDragCellX || cellY != oldDragCellY) {
Sunny Goyale78e3d72015-09-24 11:23:31 -07001052 Point dragOffset = dragObject.dragView.getDragVisualizeOffset();
1053 Rect dragRegion = dragObject.dragView.getDragRegion();
1054
Adam Cohen482ed822012-03-02 14:15:13 -08001055 mDragCell[0] = cellX;
1056 mDragCell[1] = cellY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001057
Joe Onorato4be866d2010-10-10 11:26:02 -07001058 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001059 mDragOutlineAnims[oldIndex].animateOut();
1060 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001061 Rect r = mDragOutlines[mDragOutlineCurrent];
Sunny Goyal106bf642015-07-16 12:18:06 -07001062
Adam Cohend41fbf52012-02-16 23:53:59 -08001063 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001064 cellToRect(cellX, cellY, spanX, spanY, r);
Sunny Goyal106bf642015-07-16 12:18:06 -07001065 } else {
1066 // Find the top left corner of the rect the object will occupy
1067 final int[] topLeft = mTmpPoint;
1068 cellToPoint(cellX, cellY, topLeft);
1069
1070 int left = topLeft[0];
1071 int top = topLeft[1];
1072
1073 if (v != null && dragOffset == null) {
1074 // When drawing the drag outline, it did not account for margin offsets
1075 // added by the view's parent.
1076 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1077 left += lp.leftMargin;
1078 top += lp.topMargin;
1079
1080 // Offsets due to the size difference between the View and the dragOutline.
1081 // There is a size difference to account for the outer blur, which may lie
1082 // outside the bounds of the view.
1083 top += (v.getHeight() - dragOutline.getHeight()) / 2;
1084 // We center about the x axis
1085 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1086 - dragOutline.getWidth()) / 2;
1087 } else {
1088 if (dragOffset != null && dragRegion != null) {
1089 // Center the drag region *horizontally* in the cell and apply a drag
1090 // outline offset
1091 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1092 - dragRegion.width()) / 2;
1093 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
1094 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
1095 top += dragOffset.y + cellPaddingY;
1096 } else {
1097 // Center the drag outline in the cell
1098 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1099 - dragOutline.getWidth()) / 2;
1100 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1101 - dragOutline.getHeight()) / 2;
1102 }
1103 }
1104 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
Adam Cohend41fbf52012-02-16 23:53:59 -08001105 }
Winson Chung150fbab2010-09-29 17:14:26 -07001106
Sunny Goyal106bf642015-07-16 12:18:06 -07001107 Utilities.scaleRectAboutCenter(r, getChildrenScale());
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001108 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1109 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001110
1111 if (dragObject.stateAnnouncer != null) {
1112 String msg;
1113 if (isHotseat()) {
1114 msg = getContext().getString(R.string.move_to_hotseat_position,
1115 Math.max(cellX, cellY) + 1);
1116 } else {
1117 msg = getContext().getString(R.string.move_to_empty_cell,
1118 cellY + 1, cellX + 1);
1119 }
1120 dragObject.stateAnnouncer.announce(msg);
1121 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001122 }
1123 }
1124
Adam Cohene0310962011-04-18 16:15:31 -07001125 public void clearDragOutlines() {
1126 final int oldIndex = mDragOutlineCurrent;
1127 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001128 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001129 }
1130
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001131 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001132 * Find a vacant area that will fit the given bounds nearest the requested
1133 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001134 *
Romain Guy51afc022009-05-04 18:03:43 -07001135 * @param pixelX The X location at which you want to search for a vacant area.
1136 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001137 * @param minSpanX The minimum horizontal span required
1138 * @param minSpanY The minimum vertical span required
1139 * @param spanX Horizontal span of the object.
1140 * @param spanY Vertical span of the object.
1141 * @param result Array in which to place the result, or null (in which case a new array will
1142 * be allocated)
1143 * @return The X, Y cell of a vacant area that can contain this object,
1144 * nearest the requested location.
1145 */
1146 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1147 int spanY, int[] result, int[] resultSpan) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001148 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
Adam Cohend41fbf52012-02-16 23:53:59 -08001149 result, resultSpan);
1150 }
1151
Adam Cohend41fbf52012-02-16 23:53:59 -08001152 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1153 private void lazyInitTempRectStack() {
1154 if (mTempRectStack.isEmpty()) {
1155 for (int i = 0; i < mCountX * mCountY; i++) {
1156 mTempRectStack.push(new Rect());
1157 }
1158 }
1159 }
Adam Cohen482ed822012-03-02 14:15:13 -08001160
Adam Cohend41fbf52012-02-16 23:53:59 -08001161 private void recycleTempRects(Stack<Rect> used) {
1162 while (!used.isEmpty()) {
1163 mTempRectStack.push(used.pop());
1164 }
1165 }
1166
1167 /**
1168 * Find a vacant area that will fit the given bounds nearest the requested
1169 * cell location. Uses Euclidean distance to score multiple vacant areas.
1170 *
1171 * @param pixelX The X location at which you want to search for a vacant area.
1172 * @param pixelY The Y location at which you want to search for a vacant area.
1173 * @param minSpanX The minimum horizontal span required
1174 * @param minSpanY The minimum vertical span required
1175 * @param spanX Horizontal span of the object.
1176 * @param spanY Vertical span of the object.
1177 * @param ignoreOccupied If true, the result can be an occupied cell
1178 * @param result Array in which to place the result, or null (in which case a new array will
1179 * be allocated)
1180 * @return The X, Y cell of a vacant area that can contain this object,
1181 * nearest the requested location.
1182 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001183 private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1184 int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001185 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001186
Adam Cohene3e27a82011-04-15 12:07:39 -07001187 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1188 // to the center of the item, but we are searching based on the top-left cell, so
1189 // we translate the point over to correspond to the top-left.
1190 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1191 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1192
Jeff Sharkey70864282009-04-07 21:08:40 -07001193 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001194 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001195 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001196 final Rect bestRect = new Rect(-1, -1, -1, -1);
1197 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001198
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001199 final int countX = mCountX;
1200 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001201
Adam Cohend41fbf52012-02-16 23:53:59 -08001202 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1203 spanX < minSpanX || spanY < minSpanY) {
1204 return bestXY;
1205 }
1206
1207 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001208 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001209 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1210 int ySize = -1;
1211 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001212 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001213 // First, let's see if this thing fits anywhere
1214 for (int i = 0; i < minSpanX; i++) {
1215 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001216 if (mOccupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001217 continue inner;
1218 }
Michael Jurkac28de512010-08-13 11:27:44 -07001219 }
1220 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001221 xSize = minSpanX;
1222 ySize = minSpanY;
1223
1224 // We know that the item will fit at _some_ acceptable size, now let's see
1225 // how big we can make it. We'll alternate between incrementing x and y spans
1226 // until we hit a limit.
1227 boolean incX = true;
1228 boolean hitMaxX = xSize >= spanX;
1229 boolean hitMaxY = ySize >= spanY;
1230 while (!(hitMaxX && hitMaxY)) {
1231 if (incX && !hitMaxX) {
1232 for (int j = 0; j < ySize; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001233 if (x + xSize > countX -1 || mOccupied[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001234 // We can't move out horizontally
1235 hitMaxX = true;
1236 }
1237 }
1238 if (!hitMaxX) {
1239 xSize++;
1240 }
1241 } else if (!hitMaxY) {
1242 for (int i = 0; i < xSize; i++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001243 if (y + ySize > countY - 1 || mOccupied[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001244 // We can't move out vertically
1245 hitMaxY = true;
1246 }
1247 }
1248 if (!hitMaxY) {
1249 ySize++;
1250 }
1251 }
1252 hitMaxX |= xSize >= spanX;
1253 hitMaxY |= ySize >= spanY;
1254 incX = !incX;
1255 }
1256 incX = true;
1257 hitMaxX = xSize >= spanX;
1258 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001259 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001260 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001261 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001262
Adam Cohend41fbf52012-02-16 23:53:59 -08001263 // We verify that the current rect is not a sub-rect of any of our previous
1264 // candidates. In this case, the current rect is disqualified in favour of the
1265 // containing rect.
1266 Rect currentRect = mTempRectStack.pop();
1267 currentRect.set(x, y, x + xSize, y + ySize);
1268 boolean contained = false;
1269 for (Rect r : validRegions) {
1270 if (r.contains(currentRect)) {
1271 contained = true;
1272 break;
1273 }
1274 }
1275 validRegions.push(currentRect);
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001276 double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
Adam Cohen482ed822012-03-02 14:15:13 -08001277
Adam Cohend41fbf52012-02-16 23:53:59 -08001278 if ((distance <= bestDistance && !contained) ||
1279 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001280 bestDistance = distance;
1281 bestXY[0] = x;
1282 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001283 if (resultSpan != null) {
1284 resultSpan[0] = xSize;
1285 resultSpan[1] = ySize;
1286 }
1287 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001288 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001289 }
1290 }
1291
Adam Cohenc0dcf592011-06-01 15:30:43 -07001292 // Return -1, -1 if no suitable location found
1293 if (bestDistance == Double.MAX_VALUE) {
1294 bestXY[0] = -1;
1295 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001296 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001297 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001298 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001299 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001300
Adam Cohen482ed822012-03-02 14:15:13 -08001301 /**
1302 * Find a vacant area that will fit the given bounds nearest the requested
1303 * cell location, and will also weigh in a suggested direction vector of the
1304 * desired location. This method computers distance based on unit grid distances,
1305 * not pixel distances.
1306 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001307 * @param cellX The X cell nearest to which you want to search for a vacant area.
1308 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001309 * @param spanX Horizontal span of the object.
1310 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001311 * @param direction The favored direction in which the views should move from x, y
Sunny Goyal9eba1fd2015-10-16 08:58:57 -07001312 * @param occupied The array which represents which cells in the CellLayout are occupied
Adam Cohen47a876d2012-03-19 13:21:41 -07001313 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001314 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001315 * @param result Array in which to place the result, or null (in which case a new array will
1316 * be allocated)
1317 * @return The X, Y cell of a vacant area that can contain this object,
1318 * nearest the requested location.
1319 */
1320 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001321 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001322 // Keep track of best-scoring drop area
1323 final int[] bestXY = result != null ? result : new int[2];
1324 float bestDistance = Float.MAX_VALUE;
1325 int bestDirectionScore = Integer.MIN_VALUE;
1326
1327 final int countX = mCountX;
1328 final int countY = mCountY;
1329
1330 for (int y = 0; y < countY - (spanY - 1); y++) {
1331 inner:
1332 for (int x = 0; x < countX - (spanX - 1); x++) {
1333 // First, let's see if this thing fits anywhere
1334 for (int i = 0; i < spanX; i++) {
1335 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001336 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001337 continue inner;
1338 }
1339 }
1340 }
1341
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001342 float distance = (float) Math.hypot(x - cellX, y - cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001343 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001344 computeDirectionVector(x - cellX, y - cellY, curDirection);
1345 // The direction score is just the dot product of the two candidate direction
1346 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001347 int curDirectionScore = direction[0] * curDirection[0] +
1348 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001349 boolean exactDirectionOnly = false;
1350 boolean directionMatches = direction[0] == curDirection[0] &&
1351 direction[0] == curDirection[0];
1352 if ((directionMatches || !exactDirectionOnly) &&
1353 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001354 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1355 bestDistance = distance;
1356 bestDirectionScore = curDirectionScore;
1357 bestXY[0] = x;
1358 bestXY[1] = y;
1359 }
1360 }
1361 }
1362
1363 // Return -1, -1 if no suitable location found
1364 if (bestDistance == Float.MAX_VALUE) {
1365 bestXY[0] = -1;
1366 bestXY[1] = -1;
1367 }
1368 return bestXY;
1369 }
1370
1371 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001372 int[] direction, ItemConfiguration currentState) {
1373 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001374 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001375 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001376 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1377
Adam Cohen8baab352012-03-20 17:39:21 -07001378 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001379
1380 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001381 c.x = mTempLocation[0];
1382 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001383 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001384 }
Adam Cohen8baab352012-03-20 17:39:21 -07001385 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001386 return success;
1387 }
1388
Adam Cohenf3900c22012-11-16 18:28:11 -08001389 /**
1390 * This helper class defines a cluster of views. It helps with defining complex edges
1391 * of the cluster and determining how those edges interact with other views. The edges
1392 * essentially define a fine-grained boundary around the cluster of views -- like a more
1393 * precise version of a bounding box.
1394 */
1395 private class ViewCluster {
1396 final static int LEFT = 0;
1397 final static int TOP = 1;
1398 final static int RIGHT = 2;
1399 final static int BOTTOM = 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001400
Adam Cohenf3900c22012-11-16 18:28:11 -08001401 ArrayList<View> views;
1402 ItemConfiguration config;
1403 Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001404
Adam Cohenf3900c22012-11-16 18:28:11 -08001405 int[] leftEdge = new int[mCountY];
1406 int[] rightEdge = new int[mCountY];
1407 int[] topEdge = new int[mCountX];
1408 int[] bottomEdge = new int[mCountX];
1409 boolean leftEdgeDirty, rightEdgeDirty, topEdgeDirty, bottomEdgeDirty, boundingRectDirty;
1410
1411 @SuppressWarnings("unchecked")
1412 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1413 this.views = (ArrayList<View>) views.clone();
1414 this.config = config;
1415 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001416 }
1417
Adam Cohenf3900c22012-11-16 18:28:11 -08001418 void resetEdges() {
1419 for (int i = 0; i < mCountX; i++) {
1420 topEdge[i] = -1;
1421 bottomEdge[i] = -1;
1422 }
1423 for (int i = 0; i < mCountY; i++) {
1424 leftEdge[i] = -1;
1425 rightEdge[i] = -1;
1426 }
1427 leftEdgeDirty = true;
1428 rightEdgeDirty = true;
1429 bottomEdgeDirty = true;
1430 topEdgeDirty = true;
1431 boundingRectDirty = true;
1432 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001433
Adam Cohenf3900c22012-11-16 18:28:11 -08001434 void computeEdge(int which, int[] edge) {
1435 int count = views.size();
1436 for (int i = 0; i < count; i++) {
1437 CellAndSpan cs = config.map.get(views.get(i));
1438 switch (which) {
1439 case LEFT:
1440 int left = cs.x;
1441 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1442 if (left < edge[j] || edge[j] < 0) {
1443 edge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001444 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001445 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001446 break;
1447 case RIGHT:
1448 int right = cs.x + cs.spanX;
1449 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1450 if (right > edge[j]) {
1451 edge[j] = right;
1452 }
1453 }
1454 break;
1455 case TOP:
1456 int top = cs.y;
1457 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1458 if (top < edge[j] || edge[j] < 0) {
1459 edge[j] = top;
1460 }
1461 }
1462 break;
1463 case BOTTOM:
1464 int bottom = cs.y + cs.spanY;
1465 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1466 if (bottom > edge[j]) {
1467 edge[j] = bottom;
1468 }
1469 }
1470 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001471 }
1472 }
1473 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001474
1475 boolean isViewTouchingEdge(View v, int whichEdge) {
1476 CellAndSpan cs = config.map.get(v);
1477
1478 int[] edge = getEdge(whichEdge);
1479
1480 switch (whichEdge) {
1481 case LEFT:
1482 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1483 if (edge[i] == cs.x + cs.spanX) {
1484 return true;
1485 }
1486 }
1487 break;
1488 case RIGHT:
1489 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1490 if (edge[i] == cs.x) {
1491 return true;
1492 }
1493 }
1494 break;
1495 case TOP:
1496 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1497 if (edge[i] == cs.y + cs.spanY) {
1498 return true;
1499 }
1500 }
1501 break;
1502 case BOTTOM:
1503 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1504 if (edge[i] == cs.y) {
1505 return true;
1506 }
1507 }
1508 break;
1509 }
1510 return false;
1511 }
1512
1513 void shift(int whichEdge, int delta) {
1514 for (View v: views) {
1515 CellAndSpan c = config.map.get(v);
1516 switch (whichEdge) {
1517 case LEFT:
1518 c.x -= delta;
1519 break;
1520 case RIGHT:
1521 c.x += delta;
1522 break;
1523 case TOP:
1524 c.y -= delta;
1525 break;
1526 case BOTTOM:
1527 default:
1528 c.y += delta;
1529 break;
1530 }
1531 }
1532 resetEdges();
1533 }
1534
1535 public void addView(View v) {
1536 views.add(v);
1537 resetEdges();
1538 }
1539
1540 public Rect getBoundingRect() {
1541 if (boundingRectDirty) {
1542 boolean first = true;
1543 for (View v: views) {
1544 CellAndSpan c = config.map.get(v);
1545 if (first) {
1546 boundingRect.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1547 first = false;
1548 } else {
1549 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1550 }
1551 }
1552 }
1553 return boundingRect;
1554 }
1555
1556 public int[] getEdge(int which) {
1557 switch (which) {
1558 case LEFT:
1559 return getLeftEdge();
1560 case RIGHT:
1561 return getRightEdge();
1562 case TOP:
1563 return getTopEdge();
1564 case BOTTOM:
1565 default:
1566 return getBottomEdge();
1567 }
1568 }
1569
1570 public int[] getLeftEdge() {
1571 if (leftEdgeDirty) {
1572 computeEdge(LEFT, leftEdge);
1573 }
1574 return leftEdge;
1575 }
1576
1577 public int[] getRightEdge() {
1578 if (rightEdgeDirty) {
1579 computeEdge(RIGHT, rightEdge);
1580 }
1581 return rightEdge;
1582 }
1583
1584 public int[] getTopEdge() {
1585 if (topEdgeDirty) {
1586 computeEdge(TOP, topEdge);
1587 }
1588 return topEdge;
1589 }
1590
1591 public int[] getBottomEdge() {
1592 if (bottomEdgeDirty) {
1593 computeEdge(BOTTOM, bottomEdge);
1594 }
1595 return bottomEdge;
1596 }
1597
1598 PositionComparator comparator = new PositionComparator();
1599 class PositionComparator implements Comparator<View> {
1600 int whichEdge = 0;
1601 public int compare(View left, View right) {
1602 CellAndSpan l = config.map.get(left);
1603 CellAndSpan r = config.map.get(right);
1604 switch (whichEdge) {
1605 case LEFT:
1606 return (r.x + r.spanX) - (l.x + l.spanX);
1607 case RIGHT:
1608 return l.x - r.x;
1609 case TOP:
1610 return (r.y + r.spanY) - (l.y + l.spanY);
1611 case BOTTOM:
1612 default:
1613 return l.y - r.y;
1614 }
1615 }
1616 }
1617
1618 public void sortConfigurationForEdgePush(int edge) {
1619 comparator.whichEdge = edge;
1620 Collections.sort(config.sortedViews, comparator);
1621 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001622 }
1623
Adam Cohenf3900c22012-11-16 18:28:11 -08001624 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1625 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001626
Adam Cohenf3900c22012-11-16 18:28:11 -08001627 ViewCluster cluster = new ViewCluster(views, currentState);
1628 Rect clusterRect = cluster.getBoundingRect();
1629 int whichEdge;
1630 int pushDistance;
1631 boolean fail = false;
1632
1633 // Determine the edge of the cluster that will be leading the push and how far
1634 // the cluster must be shifted.
1635 if (direction[0] < 0) {
1636 whichEdge = ViewCluster.LEFT;
1637 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001638 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001639 whichEdge = ViewCluster.RIGHT;
1640 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1641 } else if (direction[1] < 0) {
1642 whichEdge = ViewCluster.TOP;
1643 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1644 } else {
1645 whichEdge = ViewCluster.BOTTOM;
1646 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07001647 }
1648
Adam Cohenf3900c22012-11-16 18:28:11 -08001649 // Break early for invalid push distance.
1650 if (pushDistance <= 0) {
1651 return false;
Adam Cohene0489502012-08-27 15:18:53 -07001652 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001653
1654 // Mark the occupied state as false for the group of views we want to move.
1655 for (View v: views) {
1656 CellAndSpan c = currentState.map.get(v);
1657 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1658 }
1659
1660 // We save the current configuration -- if we fail to find a solution we will revert
1661 // to the initial state. The process of finding a solution modifies the configuration
1662 // in place, hence the need for revert in the failure case.
1663 currentState.save();
1664
1665 // The pushing algorithm is simplified by considering the views in the order in which
1666 // they would be pushed by the cluster. For example, if the cluster is leading with its
1667 // left edge, we consider sort the views by their right edge, from right to left.
1668 cluster.sortConfigurationForEdgePush(whichEdge);
1669
1670 while (pushDistance > 0 && !fail) {
1671 for (View v: currentState.sortedViews) {
1672 // For each view that isn't in the cluster, we see if the leading edge of the
1673 // cluster is contacting the edge of that view. If so, we add that view to the
1674 // cluster.
1675 if (!cluster.views.contains(v) && v != dragView) {
1676 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1677 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1678 if (!lp.canReorder) {
1679 // The push solution includes the all apps button, this is not viable.
1680 fail = true;
1681 break;
1682 }
1683 cluster.addView(v);
1684 CellAndSpan c = currentState.map.get(v);
1685
1686 // Adding view to cluster, mark it as not occupied.
1687 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1688 }
1689 }
1690 }
1691 pushDistance--;
1692
1693 // The cluster has been completed, now we move the whole thing over in the appropriate
1694 // direction.
1695 cluster.shift(whichEdge, 1);
1696 }
1697
1698 boolean foundSolution = false;
1699 clusterRect = cluster.getBoundingRect();
1700
1701 // Due to the nature of the algorithm, the only check required to verify a valid solution
1702 // is to ensure that completed shifted cluster lies completely within the cell layout.
1703 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1704 clusterRect.bottom <= mCountY) {
1705 foundSolution = true;
1706 } else {
1707 currentState.restore();
1708 }
1709
1710 // In either case, we set the occupied array as marked for the location of the views
1711 for (View v: cluster.views) {
1712 CellAndSpan c = currentState.map.get(v);
1713 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
1714 }
1715
1716 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07001717 }
1718
Adam Cohen482ed822012-03-02 14:15:13 -08001719 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08001720 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001721 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001722
Adam Cohen8baab352012-03-20 17:39:21 -07001723 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001724 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001725 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001726 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001727 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001728 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001729 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001730 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001731 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001732 }
1733 }
Adam Cohen8baab352012-03-20 17:39:21 -07001734
Adam Cohen8baab352012-03-20 17:39:21 -07001735 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08001736 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001737 CellAndSpan c = currentState.map.get(v);
1738 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1739 }
1740
Adam Cohen47a876d2012-03-19 13:21:41 -07001741 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1742 int top = boundingRect.top;
1743 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001744 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001745 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08001746 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001747 CellAndSpan c = currentState.map.get(v);
1748 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001749 }
1750
Adam Cohen482ed822012-03-02 14:15:13 -08001751 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1752
Adam Cohenf3900c22012-11-16 18:28:11 -08001753 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1754 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001755
Adam Cohen8baab352012-03-20 17:39:21 -07001756 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001757 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001758 int deltaX = mTempLocation[0] - boundingRect.left;
1759 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001760 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001761 CellAndSpan c = currentState.map.get(v);
1762 c.x += deltaX;
1763 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001764 }
1765 success = true;
1766 }
Adam Cohen8baab352012-03-20 17:39:21 -07001767
1768 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08001769 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001770 CellAndSpan c = currentState.map.get(v);
1771 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001772 }
1773 return success;
1774 }
1775
1776 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1777 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1778 }
1779
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001780 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1781 // to push items in each of the cardinal directions, in an order based on the direction vector
1782 // passed.
1783 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1784 int[] direction, View ignoreView, ItemConfiguration solution) {
1785 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001786 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001787 // separately in each of the components.
1788 int temp = direction[1];
1789 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001790
1791 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001792 ignoreView, solution)) {
1793 return true;
1794 }
1795 direction[1] = temp;
1796 temp = direction[0];
1797 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001798
1799 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001800 ignoreView, solution)) {
1801 return true;
1802 }
1803 // Revert the direction
1804 direction[0] = temp;
1805
1806 // Now we try pushing in each component of the opposite direction
1807 direction[0] *= -1;
1808 direction[1] *= -1;
1809 temp = direction[1];
1810 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001811 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001812 ignoreView, solution)) {
1813 return true;
1814 }
1815
1816 direction[1] = temp;
1817 temp = direction[0];
1818 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001819 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001820 ignoreView, solution)) {
1821 return true;
1822 }
1823 // revert the direction
1824 direction[0] = temp;
1825 direction[0] *= -1;
1826 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001827
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001828 } else {
1829 // If the direction vector has a single non-zero component, we push first in the
1830 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08001831 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001832 ignoreView, solution)) {
1833 return true;
1834 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001835 // Then we try the opposite direction
1836 direction[0] *= -1;
1837 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001838 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001839 ignoreView, solution)) {
1840 return true;
1841 }
1842 // Switch the direction back
1843 direction[0] *= -1;
1844 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001845
1846 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001847 // to find a solution by pushing along the perpendicular axis.
1848
1849 // Swap the components
1850 int temp = direction[1];
1851 direction[1] = direction[0];
1852 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08001853 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001854 ignoreView, solution)) {
1855 return true;
1856 }
1857
1858 // Then we try the opposite direction
1859 direction[0] *= -1;
1860 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001861 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001862 ignoreView, solution)) {
1863 return true;
1864 }
1865 // Switch the direction back
1866 direction[0] *= -1;
1867 direction[1] *= -1;
1868
1869 // Swap the components back
1870 temp = direction[1];
1871 direction[1] = direction[0];
1872 direction[0] = temp;
1873 }
1874 return false;
1875 }
1876
Adam Cohen482ed822012-03-02 14:15:13 -08001877 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001878 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001879 // Return early if get invalid cell positions
1880 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001881
Adam Cohen8baab352012-03-20 17:39:21 -07001882 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001883 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001884
Adam Cohen8baab352012-03-20 17:39:21 -07001885 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001886 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001887 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001888 if (c != null) {
1889 c.x = cellX;
1890 c.y = cellY;
1891 }
Adam Cohen482ed822012-03-02 14:15:13 -08001892 }
Adam Cohen482ed822012-03-02 14:15:13 -08001893 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1894 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001895 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001896 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001897 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001898 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001899 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001900 if (Rect.intersects(r0, r1)) {
1901 if (!lp.canReorder) {
1902 return false;
1903 }
1904 mIntersectingViews.add(child);
1905 }
1906 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001907
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001908 solution.intersectingViews = new ArrayList<View>(mIntersectingViews);
1909
Winson Chung5f8afe62013-08-12 16:19:28 -07001910 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001911 // we try to find a solution such that no displaced item travels through another item
1912 // without also displacing that item.
1913 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001914 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001915 return true;
1916 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001917
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001918 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08001919 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001920 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001921 return true;
1922 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001923
Adam Cohen482ed822012-03-02 14:15:13 -08001924 // Ok, they couldn't move as a block, let's move them individually
1925 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001926 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001927 return false;
1928 }
1929 }
1930 return true;
1931 }
1932
1933 /*
1934 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1935 * the provided point and the provided cell
1936 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001937 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001938 double angle = Math.atan(((float) deltaY) / deltaX);
1939
1940 result[0] = 0;
1941 result[1] = 0;
1942 if (Math.abs(Math.cos(angle)) > 0.5f) {
1943 result[0] = (int) Math.signum(deltaX);
1944 }
1945 if (Math.abs(Math.sin(angle)) > 0.5f) {
1946 result[1] = (int) Math.signum(deltaY);
1947 }
1948 }
1949
Adam Cohen8baab352012-03-20 17:39:21 -07001950 private void copyOccupiedArray(boolean[][] occupied) {
1951 for (int i = 0; i < mCountX; i++) {
1952 for (int j = 0; j < mCountY; j++) {
1953 occupied[i][j] = mOccupied[i][j];
1954 }
1955 }
1956 }
1957
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001958 private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001959 int spanX, int spanY, int[] direction, View dragView, boolean decX,
1960 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001961 // Copy the current state into the solution. This solution will be manipulated as necessary.
1962 copyCurrentStateToSolution(solution, false);
1963 // Copy the current occupied array into the temporary occupied array. This array will be
1964 // manipulated as necessary to find a solution.
1965 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001966
1967 // We find the nearest cell into which we would place the dragged item, assuming there's
1968 // nothing in its way.
1969 int result[] = new int[2];
1970 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1971
1972 boolean success = false;
1973 // First we try the exact nearest position of the item being dragged,
1974 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001975 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1976 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001977
1978 if (!success) {
1979 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1980 // x, then 1 in y etc.
1981 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001982 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
1983 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001984 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001985 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
1986 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001987 }
1988 solution.isSolution = false;
1989 } else {
1990 solution.isSolution = true;
1991 solution.dragViewX = result[0];
1992 solution.dragViewY = result[1];
1993 solution.dragViewSpanX = spanX;
1994 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001995 }
1996 return solution;
1997 }
1998
1999 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002000 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002001 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002002 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002003 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002004 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08002005 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07002006 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002007 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07002008 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002009 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002010 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08002011 }
2012 }
2013
2014 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
2015 for (int i = 0; i < mCountX; i++) {
2016 for (int j = 0; j < mCountY; j++) {
2017 mTmpOccupied[i][j] = false;
2018 }
2019 }
2020
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 if (child == dragView) continue;
2025 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002026 CellAndSpan c = solution.map.get(child);
2027 if (c != null) {
2028 lp.tmpCellX = c.x;
2029 lp.tmpCellY = c.y;
2030 lp.cellHSpan = c.spanX;
2031 lp.cellVSpan = c.spanY;
2032 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002033 }
2034 }
2035 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2036 solution.dragViewSpanY, mTmpOccupied, true);
2037 }
2038
2039 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
2040 commitDragView) {
2041
2042 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
2043 for (int i = 0; i < mCountX; i++) {
2044 for (int j = 0; j < mCountY; j++) {
2045 occupied[i][j] = false;
2046 }
2047 }
2048
Michael Jurkaa52570f2012-03-20 03:18:20 -07002049 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002050 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002051 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002052 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002053 CellAndSpan c = solution.map.get(child);
2054 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002055 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2056 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002057 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002058 }
2059 }
2060 if (commitDragView) {
2061 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2062 solution.dragViewSpanY, occupied, true);
2063 }
2064 }
2065
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002066
2067 // This method starts or changes the reorder preview animations
2068 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
2069 View dragView, int delay, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07002070 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002071 for (int i = 0; i < childCount; i++) {
2072 View child = mShortcutsAndWidgets.getChildAt(i);
2073 if (child == dragView) continue;
2074 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002075 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
2076 != null && !solution.intersectingViews.contains(child);
2077
Adam Cohen19f37922012-03-21 11:59:11 -07002078 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002079 if (c != null && !skip) {
2080 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
2081 lp.cellY, c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002082 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002083 }
2084 }
2085 }
2086
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002087 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07002088 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002089 class ReorderPreviewAnimation {
Adam Cohen19f37922012-03-21 11:59:11 -07002090 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002091 float finalDeltaX;
2092 float finalDeltaY;
2093 float initDeltaX;
2094 float initDeltaY;
2095 float finalScale;
2096 float initScale;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002097 int mode;
2098 boolean repeating = false;
2099 private static final int PREVIEW_DURATION = 300;
2100 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
2101
2102 public static final int MODE_HINT = 0;
2103 public static final int MODE_PREVIEW = 1;
2104
Adam Cohene7587d22012-05-24 18:50:02 -07002105 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002106
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002107 public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
2108 int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07002109 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2110 final int x0 = mTmpPoint[0];
2111 final int y0 = mTmpPoint[1];
2112 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2113 final int x1 = mTmpPoint[0];
2114 final int y1 = mTmpPoint[1];
2115 final int dX = x1 - x0;
2116 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002117 finalDeltaX = 0;
2118 finalDeltaY = 0;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002119 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07002120 if (dX == dY && dX == 0) {
2121 } else {
2122 if (dY == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002123 finalDeltaX = - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002124 } else if (dX == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002125 finalDeltaY = - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002126 } else {
2127 double angle = Math.atan( (float) (dY) / dX);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002128 finalDeltaX = (int) (- dir * Math.signum(dX) *
2129 Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
2130 finalDeltaY = (int) (- dir * Math.signum(dY) *
2131 Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002132 }
2133 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002134 this.mode = mode;
Adam Cohend024f982012-05-23 18:26:45 -07002135 initDeltaX = child.getTranslationX();
2136 initDeltaY = child.getTranslationY();
Adam Cohen307fe232012-08-16 17:55:58 -07002137 finalScale = getChildrenScale() - 4.0f / child.getWidth();
Adam Cohend024f982012-05-23 18:26:45 -07002138 initScale = child.getScaleX();
Adam Cohen19f37922012-03-21 11:59:11 -07002139 this.child = child;
2140 }
2141
Adam Cohend024f982012-05-23 18:26:45 -07002142 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002143 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002144 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002145 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002146 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002147 if (finalDeltaX == 0 && finalDeltaY == 0) {
2148 completeAnimationImmediately();
2149 return;
2150 }
Adam Cohen19f37922012-03-21 11:59:11 -07002151 }
Adam Cohend024f982012-05-23 18:26:45 -07002152 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002153 return;
2154 }
Michael Jurkaf1ad6082013-03-13 12:55:46 +01002155 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002156 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07002157
2158 // Animations are disabled in power save mode, causing the repeated animation to jump
2159 // spastically between beginning and end states. Since this looks bad, we don't repeat
2160 // the animation in power save mode.
Tony Wickham112ac952015-11-12 12:31:50 -08002161 if (!Utilities.isPowerSaverOn(getContext())) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07002162 va.setRepeatMode(ValueAnimator.REVERSE);
2163 va.setRepeatCount(ValueAnimator.INFINITE);
2164 }
2165
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002166 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002167 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002168 va.addUpdateListener(new AnimatorUpdateListener() {
2169 @Override
2170 public void onAnimationUpdate(ValueAnimator animation) {
2171 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002172 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : r;
2173 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2174 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002175 child.setTranslationX(x);
2176 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002177 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002178 child.setScaleX(s);
2179 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002180 }
2181 });
2182 va.addListener(new AnimatorListenerAdapter() {
2183 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002184 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002185 initDeltaX = 0;
2186 initDeltaY = 0;
Adam Cohen307fe232012-08-16 17:55:58 -07002187 initScale = getChildrenScale();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002188 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002189 }
2190 });
Adam Cohen19f37922012-03-21 11:59:11 -07002191 mShakeAnimators.put(child, this);
2192 va.start();
2193 }
2194
Adam Cohend024f982012-05-23 18:26:45 -07002195 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002196 if (a != null) {
2197 a.cancel();
2198 }
Adam Cohen19f37922012-03-21 11:59:11 -07002199 }
Adam Cohene7587d22012-05-24 18:50:02 -07002200
Adam Cohen091440a2015-03-18 14:16:05 -07002201 @Thunk void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002202 if (a != null) {
2203 a.cancel();
2204 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002205
Sunny Goyal5d2fc322015-07-06 22:52:49 -07002206 a = new LauncherViewPropertyAnimator(child)
2207 .scaleX(getChildrenScale())
2208 .scaleY(getChildrenScale())
2209 .translationX(0)
2210 .translationY(0)
2211 .setDuration(REORDER_ANIMATION_DURATION);
2212 a.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2213 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07002214 }
Adam Cohen19f37922012-03-21 11:59:11 -07002215 }
2216
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002217 private void completeAndClearReorderPreviewAnimations() {
2218 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002219 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002220 }
2221 mShakeAnimators.clear();
2222 }
2223
Adam Cohen482ed822012-03-02 14:15:13 -08002224 private void commitTempPlacement() {
2225 for (int i = 0; i < mCountX; i++) {
2226 for (int j = 0; j < mCountY; j++) {
2227 mOccupied[i][j] = mTmpOccupied[i][j];
2228 }
2229 }
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002230
2231 long screenId = mLauncher.getWorkspace().getIdForScreen(this);
2232 int container = Favorites.CONTAINER_DESKTOP;
2233
2234 if (mLauncher.isHotseatLayout(this)) {
2235 screenId = -1;
2236 container = Favorites.CONTAINER_HOTSEAT;
2237 }
2238
Michael Jurkaa52570f2012-03-20 03:18:20 -07002239 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002240 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002241 View child = mShortcutsAndWidgets.getChildAt(i);
2242 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2243 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002244 // We do a null check here because the item info can be null in the case of the
2245 // AllApps button in the hotseat.
2246 if (info != null) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002247 final boolean requiresDbUpdate = (info.cellX != lp.tmpCellX
2248 || info.cellY != lp.tmpCellY || info.spanX != lp.cellHSpan
2249 || info.spanY != lp.cellVSpan);
2250
Adam Cohen2acce882012-03-28 19:03:19 -07002251 info.cellX = lp.cellX = lp.tmpCellX;
2252 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002253 info.spanX = lp.cellHSpan;
2254 info.spanY = lp.cellVSpan;
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002255
2256 if (requiresDbUpdate) {
2257 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId,
2258 info.cellX, info.cellY, info.spanX, info.spanY);
2259 }
Adam Cohen2acce882012-03-28 19:03:19 -07002260 }
Adam Cohen482ed822012-03-02 14:15:13 -08002261 }
2262 }
2263
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002264 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002265 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002266 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002267 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002268 lp.useTmpCoords = useTempCoords;
2269 }
2270 }
2271
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002272 private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002273 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2274 int[] result = new int[2];
2275 int[] resultSpan = new int[2];
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002276 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
Adam Cohen482ed822012-03-02 14:15:13 -08002277 resultSpan);
2278 if (result[0] >= 0 && result[1] >= 0) {
2279 copyCurrentStateToSolution(solution, false);
2280 solution.dragViewX = result[0];
2281 solution.dragViewY = result[1];
2282 solution.dragViewSpanX = resultSpan[0];
2283 solution.dragViewSpanY = resultSpan[1];
2284 solution.isSolution = true;
2285 } else {
2286 solution.isSolution = false;
2287 }
2288 return solution;
2289 }
2290
2291 public void prepareChildForDrag(View child) {
2292 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002293 }
2294
Adam Cohen19f37922012-03-21 11:59:11 -07002295 /* This seems like it should be obvious and straight-forward, but when the direction vector
2296 needs to match with the notion of the dragView pushing other views, we have to employ
2297 a slightly more subtle notion of the direction vector. The question is what two points is
2298 the vector between? The center of the dragView and its desired destination? Not quite, as
2299 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2300 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2301 or right, which helps make pushing feel right.
2302 */
2303 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2304 int spanY, View dragView, int[] resultDirection) {
2305 int[] targetDestination = new int[2];
2306
2307 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2308 Rect dragRect = new Rect();
2309 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2310 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2311
2312 Rect dropRegionRect = new Rect();
2313 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2314 dragView, dropRegionRect, mIntersectingViews);
2315
2316 int dropRegionSpanX = dropRegionRect.width();
2317 int dropRegionSpanY = dropRegionRect.height();
2318
2319 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2320 dropRegionRect.height(), dropRegionRect);
2321
2322 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2323 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2324
2325 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2326 deltaX = 0;
2327 }
2328 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2329 deltaY = 0;
2330 }
2331
2332 if (deltaX == 0 && deltaY == 0) {
2333 // No idea what to do, give a random direction.
2334 resultDirection[0] = 1;
2335 resultDirection[1] = 0;
2336 } else {
2337 computeDirectionVector(deltaX, deltaY, resultDirection);
2338 }
2339 }
2340
2341 // For a given cell and span, fetch the set of views intersecting the region.
2342 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2343 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2344 if (boundingRect != null) {
2345 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2346 }
2347 intersectingViews.clear();
2348 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2349 Rect r1 = new Rect();
2350 final int count = mShortcutsAndWidgets.getChildCount();
2351 for (int i = 0; i < count; i++) {
2352 View child = mShortcutsAndWidgets.getChildAt(i);
2353 if (child == dragView) continue;
2354 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2355 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2356 if (Rect.intersects(r0, r1)) {
2357 mIntersectingViews.add(child);
2358 if (boundingRect != null) {
2359 boundingRect.union(r1);
2360 }
2361 }
2362 }
2363 }
2364
2365 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2366 View dragView, int[] result) {
2367 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2368 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2369 mIntersectingViews);
2370 return !mIntersectingViews.isEmpty();
2371 }
2372
2373 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002374 completeAndClearReorderPreviewAnimations();
2375 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2376 final int count = mShortcutsAndWidgets.getChildCount();
2377 for (int i = 0; i < count; i++) {
2378 View child = mShortcutsAndWidgets.getChildAt(i);
2379 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2380 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2381 lp.tmpCellX = lp.cellX;
2382 lp.tmpCellY = lp.cellY;
2383 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2384 0, false, false);
2385 }
Adam Cohen19f37922012-03-21 11:59:11 -07002386 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002387 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002388 }
Adam Cohen19f37922012-03-21 11:59:11 -07002389 }
2390
Adam Cohenbebf0422012-04-11 18:06:28 -07002391 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2392 View dragView, int[] direction, boolean commit) {
2393 int[] pixelXY = new int[2];
2394 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2395
2396 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002397 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002398 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2399
2400 setUseTempCoords(true);
2401 if (swapSolution != null && swapSolution.isSolution) {
2402 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2403 // committing anything or animating anything as we just want to determine if a solution
2404 // exists
2405 copySolutionToTempState(swapSolution, dragView);
2406 setItemPlacementDirty(true);
2407 animateItemsToSolution(swapSolution, dragView, commit);
2408
2409 if (commit) {
2410 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002411 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002412 setItemPlacementDirty(false);
2413 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002414 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
2415 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002416 }
2417 mShortcutsAndWidgets.requestLayout();
2418 }
2419 return swapSolution.isSolution;
2420 }
2421
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002422 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002423 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002424 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002425 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002426
2427 if (resultSpan == null) {
2428 resultSpan = new int[2];
2429 }
2430
Adam Cohen19f37922012-03-21 11:59:11 -07002431 // When we are checking drop validity or actually dropping, we don't recompute the
2432 // direction vector, since we want the solution to match the preview, and it's possible
2433 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002434 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2435 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002436 mDirectionVector[0] = mPreviousReorderDirection[0];
2437 mDirectionVector[1] = mPreviousReorderDirection[1];
2438 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002439 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2440 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2441 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002442 }
2443 } else {
2444 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2445 mPreviousReorderDirection[0] = mDirectionVector[0];
2446 mPreviousReorderDirection[1] = mDirectionVector[1];
2447 }
2448
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002449 // Find a solution involving pushing / displacing any items in the way
2450 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002451 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2452
2453 // We attempt the approach which doesn't shuffle views at all
2454 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2455 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2456
2457 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002458
2459 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2460 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002461 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2462 finalSolution = swapSolution;
2463 } else if (noShuffleSolution.isSolution) {
2464 finalSolution = noShuffleSolution;
2465 }
2466
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002467 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002468 if (finalSolution != null) {
Adam Cohenfe692872013-12-11 14:47:23 -08002469 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
2470 ReorderPreviewAnimation.MODE_HINT);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002471 result[0] = finalSolution.dragViewX;
2472 result[1] = finalSolution.dragViewY;
2473 resultSpan[0] = finalSolution.dragViewSpanX;
2474 resultSpan[1] = finalSolution.dragViewSpanY;
2475 } else {
2476 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2477 }
2478 return result;
2479 }
2480
Adam Cohen482ed822012-03-02 14:15:13 -08002481 boolean foundSolution = true;
2482 if (!DESTRUCTIVE_REORDER) {
2483 setUseTempCoords(true);
2484 }
2485
2486 if (finalSolution != null) {
2487 result[0] = finalSolution.dragViewX;
2488 result[1] = finalSolution.dragViewY;
2489 resultSpan[0] = finalSolution.dragViewSpanX;
2490 resultSpan[1] = finalSolution.dragViewSpanY;
2491
2492 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2493 // committing anything or animating anything as we just want to determine if a solution
2494 // exists
2495 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2496 if (!DESTRUCTIVE_REORDER) {
2497 copySolutionToTempState(finalSolution, dragView);
2498 }
2499 setItemPlacementDirty(true);
2500 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2501
Adam Cohen19f37922012-03-21 11:59:11 -07002502 if (!DESTRUCTIVE_REORDER &&
2503 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002504 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002505 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002506 setItemPlacementDirty(false);
2507 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002508 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
2509 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002510 }
2511 }
2512 } else {
2513 foundSolution = false;
2514 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2515 }
2516
2517 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2518 setUseTempCoords(false);
2519 }
Adam Cohen482ed822012-03-02 14:15:13 -08002520
Michael Jurkaa52570f2012-03-20 03:18:20 -07002521 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002522 return result;
2523 }
2524
Adam Cohen19f37922012-03-21 11:59:11 -07002525 void setItemPlacementDirty(boolean dirty) {
2526 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002527 }
Adam Cohen19f37922012-03-21 11:59:11 -07002528 boolean isItemPlacementDirty() {
2529 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002530 }
2531
Adam Cohen091440a2015-03-18 14:16:05 -07002532 @Thunk class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002533 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohenf3900c22012-11-16 18:28:11 -08002534 private HashMap<View, CellAndSpan> savedMap = new HashMap<View, CellAndSpan>();
2535 ArrayList<View> sortedViews = new ArrayList<View>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002536 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002537 boolean isSolution = false;
2538 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2539
Adam Cohenf3900c22012-11-16 18:28:11 -08002540 void save() {
2541 // Copy current state into savedMap
2542 for (View v: map.keySet()) {
2543 map.get(v).copy(savedMap.get(v));
2544 }
2545 }
2546
2547 void restore() {
2548 // Restore current state from savedMap
2549 for (View v: savedMap.keySet()) {
2550 savedMap.get(v).copy(map.get(v));
2551 }
2552 }
2553
2554 void add(View v, CellAndSpan cs) {
2555 map.put(v, cs);
2556 savedMap.put(v, new CellAndSpan());
2557 sortedViews.add(v);
2558 }
2559
Adam Cohen482ed822012-03-02 14:15:13 -08002560 int area() {
2561 return dragViewSpanX * dragViewSpanY;
2562 }
Adam Cohen8baab352012-03-20 17:39:21 -07002563 }
2564
2565 private class CellAndSpan {
2566 int x, y;
2567 int spanX, spanY;
2568
Adam Cohenf3900c22012-11-16 18:28:11 -08002569 public CellAndSpan() {
2570 }
2571
2572 public void copy(CellAndSpan copy) {
2573 copy.x = x;
2574 copy.y = y;
2575 copy.spanX = spanX;
2576 copy.spanY = spanY;
2577 }
2578
Adam Cohen8baab352012-03-20 17:39:21 -07002579 public CellAndSpan(int x, int y, int spanX, int spanY) {
2580 this.x = x;
2581 this.y = y;
2582 this.spanX = spanX;
2583 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002584 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002585
2586 public String toString() {
2587 return "(" + x + ", " + y + ": " + spanX + ", " + spanY + ")";
2588 }
2589
Adam Cohen482ed822012-03-02 14:15:13 -08002590 }
2591
Adam Cohendf035382011-04-11 17:22:04 -07002592 /**
Adam Cohendf035382011-04-11 17:22:04 -07002593 * Find a starting cell position that will fit the given bounds nearest the requested
2594 * cell location. Uses Euclidean distance to score multiple vacant areas.
2595 *
2596 * @param pixelX The X location at which you want to search for a vacant area.
2597 * @param pixelY The Y location at which you want to search for a vacant area.
2598 * @param spanX Horizontal span of the object.
2599 * @param spanY Vertical span of the object.
2600 * @param ignoreView Considers space occupied by this view as unoccupied
2601 * @param result Previously returned value to possibly recycle.
2602 * @return The X, Y cell of a vacant area that can contain this object,
2603 * nearest the requested location.
2604 */
Adam Cohenf9c184a2016-01-15 16:47:43 -08002605 public int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002606 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002607 }
2608
Michael Jurka0280c3b2010-09-17 15:00:07 -07002609 boolean existsEmptyCell() {
2610 return findCellForSpan(null, 1, 1);
2611 }
2612
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002613 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002614 * Finds the upper-left coordinate of the first rectangle in the grid that can
2615 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2616 * then this method will only return coordinates for rectangles that contain the cell
2617 * (intersectX, intersectY)
2618 *
2619 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2620 * can be found.
2621 * @param spanX The horizontal span of the cell we want to find.
2622 * @param spanY The vertical span of the cell we want to find.
2623 *
2624 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002625 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002626 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Michael Jurka28750fb2010-09-24 17:43:49 -07002627 boolean foundCell = false;
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002628 final int endX = mCountX - (spanX - 1);
2629 final int endY = mCountY - (spanY - 1);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002630
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002631 for (int y = 0; y < endY && !foundCell; y++) {
2632 inner:
2633 for (int x = 0; x < endX; x++) {
2634 for (int i = 0; i < spanX; i++) {
2635 for (int j = 0; j < spanY; j++) {
2636 if (mOccupied[x + i][y + j]) {
2637 // small optimization: we can skip to after the column we just found
2638 // an occupied cell
2639 x += i;
2640 continue inner;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002641 }
2642 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002643 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002644 if (cellXY != null) {
2645 cellXY[0] = x;
2646 cellXY[1] = y;
2647 }
2648 foundCell = true;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002649 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002650 }
2651 }
2652
Michael Jurka28750fb2010-09-24 17:43:49 -07002653 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002654 }
2655
2656 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002657 * A drag event has begun over this layout.
2658 * It may have begun over this layout (in which case onDragChild is called first),
2659 * or it may have begun on another layout.
2660 */
2661 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002662 mDragging = true;
2663 }
2664
2665 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002666 * Called when drag has left this CellLayout or has been completed (successfully or not)
2667 */
2668 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002669 // This can actually be called when we aren't in a drag, e.g. when adding a new
2670 // item to this layout via the customize drawer.
2671 // Guard against that case.
2672 if (mDragging) {
2673 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002674 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002675
2676 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002677 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002678 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2679 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002680 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002681 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002682 }
2683
2684 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002685 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002686 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002687 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002688 *
2689 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002690 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002691 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002692 if (child != null) {
2693 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002694 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002695 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002696 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002697 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002698 }
2699
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002700 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002701 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002702 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002703 * @param cellX X coordinate of upper left corner expressed as a cell position
2704 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002705 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002706 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002707 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002708 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002709 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002710 final int cellWidth = mCellWidth;
2711 final int cellHeight = mCellHeight;
2712 final int widthGap = mWidthGap;
2713 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002714
Winson Chung4b825dcd2011-06-19 12:41:22 -07002715 final int hStartPadding = getPaddingLeft();
2716 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002717
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002718 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2719 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2720
2721 int x = hStartPadding + cellX * (cellWidth + widthGap);
2722 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002723
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002724 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002725 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002726
Michael Jurka0280c3b2010-09-17 15:00:07 -07002727 private void clearOccupiedCells() {
2728 for (int x = 0; x < mCountX; x++) {
2729 for (int y = 0; y < mCountY; y++) {
2730 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002731 }
2732 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002733 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002734
Adam Cohend4844c32011-02-18 19:25:06 -08002735 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002736 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002737 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002738 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002739 }
2740
Adam Cohend4844c32011-02-18 19:25:06 -08002741 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002742 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002743 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002744 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002745 }
2746
Adam Cohen482ed822012-03-02 14:15:13 -08002747 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2748 boolean value) {
2749 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002750 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2751 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002752 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002753 }
2754 }
2755 }
2756
Adam Cohen2801caf2011-05-13 20:57:39 -07002757 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002758 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002759 (Math.max((mCountX - 1), 0) * mWidthGap);
2760 }
2761
2762 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002763 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002764 (Math.max((mCountY - 1), 0) * mHeightGap);
2765 }
2766
Michael Jurka66d72172011-04-12 16:29:25 -07002767 public boolean isOccupied(int x, int y) {
2768 if (x < mCountX && y < mCountY) {
2769 return mOccupied[x][y];
2770 } else {
2771 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2772 }
2773 }
2774
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002775 @Override
2776 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2777 return new CellLayout.LayoutParams(getContext(), attrs);
2778 }
2779
2780 @Override
2781 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2782 return p instanceof CellLayout.LayoutParams;
2783 }
2784
2785 @Override
2786 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2787 return new CellLayout.LayoutParams(p);
2788 }
2789
2790 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2791 /**
2792 * Horizontal location of the item in the grid.
2793 */
2794 @ViewDebug.ExportedProperty
2795 public int cellX;
2796
2797 /**
2798 * Vertical location of the item in the grid.
2799 */
2800 @ViewDebug.ExportedProperty
2801 public int cellY;
2802
2803 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002804 * Temporary horizontal location of the item in the grid during reorder
2805 */
2806 public int tmpCellX;
2807
2808 /**
2809 * Temporary vertical location of the item in the grid during reorder
2810 */
2811 public int tmpCellY;
2812
2813 /**
2814 * Indicates that the temporary coordinates should be used to layout the items
2815 */
2816 public boolean useTmpCoords;
2817
2818 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002819 * Number of cells spanned horizontally by the item.
2820 */
2821 @ViewDebug.ExportedProperty
2822 public int cellHSpan;
2823
2824 /**
2825 * Number of cells spanned vertically by the item.
2826 */
2827 @ViewDebug.ExportedProperty
2828 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002829
Adam Cohen1b607ed2011-03-03 17:26:50 -08002830 /**
2831 * Indicates whether the item will set its x, y, width and height parameters freely,
2832 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2833 */
Adam Cohend4844c32011-02-18 19:25:06 -08002834 public boolean isLockedToGrid = true;
2835
Adam Cohen482ed822012-03-02 14:15:13 -08002836 /**
Adam Cohenec40b2b2013-07-23 15:52:40 -07002837 * Indicates that this item should use the full extents of its parent.
2838 */
2839 public boolean isFullscreen = false;
2840
2841 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002842 * Indicates whether this item can be reordered. Always true except in the case of the
2843 * the AllApps button.
2844 */
2845 public boolean canReorder = true;
2846
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002847 // X coordinate of the view in the layout.
2848 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002849 public int x;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002850 // Y coordinate of the view in the layout.
2851 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002852 public int y;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002853
Romain Guy84f296c2009-11-04 15:00:44 -08002854 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002855
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002856 public LayoutParams(Context c, AttributeSet attrs) {
2857 super(c, attrs);
2858 cellHSpan = 1;
2859 cellVSpan = 1;
2860 }
2861
2862 public LayoutParams(ViewGroup.LayoutParams source) {
2863 super(source);
2864 cellHSpan = 1;
2865 cellVSpan = 1;
2866 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002867
2868 public LayoutParams(LayoutParams source) {
2869 super(source);
2870 this.cellX = source.cellX;
2871 this.cellY = source.cellY;
2872 this.cellHSpan = source.cellHSpan;
2873 this.cellVSpan = source.cellVSpan;
2874 }
2875
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002876 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002877 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002878 this.cellX = cellX;
2879 this.cellY = cellY;
2880 this.cellHSpan = cellHSpan;
2881 this.cellVSpan = cellVSpan;
2882 }
2883
Adam Cohen2374abf2013-04-16 14:56:57 -07002884 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap,
2885 boolean invertHorizontally, int colCount) {
Adam Cohend4844c32011-02-18 19:25:06 -08002886 if (isLockedToGrid) {
2887 final int myCellHSpan = cellHSpan;
2888 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002889 int myCellX = useTmpCoords ? tmpCellX : cellX;
2890 int myCellY = useTmpCoords ? tmpCellY : cellY;
2891
2892 if (invertHorizontally) {
2893 myCellX = colCount - myCellX - cellHSpan;
2894 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002895
Adam Cohend4844c32011-02-18 19:25:06 -08002896 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2897 leftMargin - rightMargin;
2898 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2899 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002900 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2901 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002902 }
2903 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002904
Winson Chungaafa03c2010-06-11 17:34:16 -07002905 public String toString() {
2906 return "(" + this.cellX + ", " + this.cellY + ")";
2907 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002908
2909 public void setWidth(int width) {
2910 this.width = width;
2911 }
2912
2913 public int getWidth() {
2914 return width;
2915 }
2916
2917 public void setHeight(int height) {
2918 this.height = height;
2919 }
2920
2921 public int getHeight() {
2922 return height;
2923 }
2924
2925 public void setX(int x) {
2926 this.x = x;
2927 }
2928
2929 public int getX() {
2930 return x;
2931 }
2932
2933 public void setY(int y) {
2934 this.y = y;
2935 }
2936
2937 public int getY() {
2938 return y;
2939 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002940 }
2941
Michael Jurka0280c3b2010-09-17 15:00:07 -07002942 // This class stores info for two purposes:
2943 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2944 // its spanX, spanY, and the screen it is on
2945 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2946 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2947 // the CellLayout that was long clicked
Sunny Goyal83a8f042015-05-19 12:52:12 -07002948 public static final class CellInfo {
Adam Cohenf9c184a2016-01-15 16:47:43 -08002949 public View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002950 int cellX = -1;
2951 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002952 int spanX;
2953 int spanY;
Adam Cohendcd297f2013-06-18 13:13:40 -07002954 long screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07002955 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002956
Sunny Goyal83a8f042015-05-19 12:52:12 -07002957 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002958 cell = v;
2959 cellX = info.cellX;
2960 cellY = info.cellY;
2961 spanX = info.spanX;
2962 spanY = info.spanY;
2963 screenId = info.screenId;
2964 container = info.container;
2965 }
2966
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002967 @Override
2968 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002969 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2970 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002971 }
2972 }
Michael Jurkad771c962011-08-09 15:00:48 -07002973
Sunny Goyala9116722015-04-29 13:55:58 -07002974 public boolean findVacantCell(int spanX, int spanY, int[] outXY) {
2975 return Utilities.findVacantCell(outXY, spanX, spanY, mCountX, mCountY, mOccupied);
2976 }
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002977
Tony Wickham86930612015-09-09 13:50:40 -07002978 /**
2979 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2980 * if necessary).
2981 */
2982 public boolean hasReorderSolution(ItemInfo itemInfo) {
2983 int[] cellPoint = new int[2];
2984 // Check for a solution starting at every cell.
2985 for (int cellX = 0; cellX < getCountX(); cellX++) {
2986 for (int cellY = 0; cellY < getCountY(); cellY++) {
2987 cellToPoint(cellX, cellY, cellPoint);
2988 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2989 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2990 true, new ItemConfiguration()).isSolution) {
2991 return true;
2992 }
2993 }
2994 }
2995 return false;
2996 }
2997
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002998 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
2999 int x2 = x + spanX - 1;
3000 int y2 = y + spanY - 1;
3001 if (x < 0 || y < 0 || x2 >= mCountX || y2 >= mCountY) {
3002 return false;
3003 }
3004 for (int i = x; i <= x2; i++) {
3005 for (int j = y; j <= y2; j++) {
3006 if (mOccupied[i][j]) {
3007 return false;
3008 }
3009 }
3010 }
3011
3012 return true;
3013 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003014}