blob: eaa96c93610228f8c9ba6c98e1f97a2fa2ba7119 [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);
Adam Cohenf172b742016-03-30 19:28:34 -0700514 if (!bg.isClipping) {
515 bg.drawBackgroundStroke(canvas, mFolderBgPaint);
516 }
Adam Cohenefca0272016-02-24 19:19:06 -0800517 canvas.restore();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700518 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700519
Adam Cohenefca0272016-02-24 19:19:06 -0800520 if (mFolderLeaveBehind.delegateCellX >= 0 && mFolderLeaveBehind.delegateCellY >= 0) {
521 cellToPoint(mFolderLeaveBehind.delegateCellX,
522 mFolderLeaveBehind.delegateCellY, mTempLocation);
523 canvas.save();
524 canvas.translate(mTempLocation[0], mTempLocation[1]);
525 mFolderLeaveBehind.drawLeaveBehind(canvas, mFolderBgPaint);
526 canvas.restore();
Adam Cohenc51934b2011-07-26 21:07:43 -0700527 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700528 }
529
Adam Cohenefca0272016-02-24 19:19:06 -0800530 @Override
531 protected void dispatchDraw(Canvas canvas) {
532 super.dispatchDraw(canvas);
533
534 for (int i = 0; i < mFolderBackgrounds.size(); i++) {
535 FolderIcon.PreviewBackground bg = mFolderBackgrounds.get(i);
Adam Cohenf172b742016-03-30 19:28:34 -0700536 if (bg.isClipping) {
537 cellToPoint(bg.delegateCellX, bg.delegateCellY, mTempLocation);
538 canvas.save();
539 canvas.translate(mTempLocation[0], mTempLocation[1]);
540 bg.drawBackgroundStroke(canvas, mFolderBgPaint);
541 canvas.restore();
542 }
Adam Cohenefca0272016-02-24 19:19:06 -0800543 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700544 }
545
Adam Cohenefca0272016-02-24 19:19:06 -0800546 public void addFolderBackground(FolderIcon.PreviewBackground bg) {
547 mFolderBackgrounds.add(bg);
548 }
549 public void removeFolderBackground(FolderIcon.PreviewBackground bg) {
550 mFolderBackgrounds.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700551 }
552
Adam Cohenc51934b2011-07-26 21:07:43 -0700553 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800554
555 DeviceProfile grid = mLauncher.getDeviceProfile();
556 View child = getChildAt(x, y);
557
558 mFolderLeaveBehind.setup(getResources().getDisplayMetrics(), grid, null,
559 child.getMeasuredWidth(), child.getPaddingTop());
560
561 mFolderLeaveBehind.delegateCellX = x;
562 mFolderLeaveBehind.delegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700563 invalidate();
564 }
565
566 public void clearFolderLeaveBehind() {
Adam Cohenefca0272016-02-24 19:19:06 -0800567 mFolderLeaveBehind.delegateCellX = -1;
568 mFolderLeaveBehind.delegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700569 invalidate();
570 }
571
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700572 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700573 public boolean shouldDelayChildPressedState() {
574 return false;
575 }
576
Adam Cohen1462de32012-07-24 22:34:36 -0700577 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700578 try {
579 dispatchRestoreInstanceState(states);
580 } catch (IllegalArgumentException ex) {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700581 if (ProviderConfig.IS_DOGFOOD_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700582 throw ex;
583 }
584 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
585 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
586 }
Adam Cohen1462de32012-07-24 22:34:36 -0700587 }
588
Michael Jurkae6235dd2011-10-04 15:02:05 -0700589 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700590 public void cancelLongPress() {
591 super.cancelLongPress();
592
593 // Cancel long press for all children
594 final int count = getChildCount();
595 for (int i = 0; i < count; i++) {
596 final View child = getChildAt(i);
597 child.cancelLongPress();
598 }
599 }
600
Michael Jurkadee05892010-07-27 10:01:56 -0700601 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
602 mInterceptTouchListener = listener;
603 }
604
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800605 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700606 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607 }
608
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800609 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700610 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 }
612
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800613 public void setIsHotseat(boolean isHotseat) {
614 mIsHotseat = isHotseat;
Winson Chung5f8afe62013-08-12 16:19:28 -0700615 mShortcutsAndWidgets.setIsHotseat(isHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800616 }
617
Sunny Goyale9b651e2015-04-24 11:44:51 -0700618 public boolean isHotseat() {
619 return mIsHotseat;
620 }
621
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800622 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700623 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700624 final LayoutParams lp = params;
625
Andrew Flynnde38e422012-05-08 11:22:15 -0700626 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800627 if (child instanceof BubbleTextView) {
628 BubbleTextView bubbleChild = (BubbleTextView) child;
Winson Chung5f8afe62013-08-12 16:19:28 -0700629 bubbleChild.setTextVisibility(!mIsHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800630 }
631
Adam Cohen307fe232012-08-16 17:55:58 -0700632 child.setScaleX(getChildrenScale());
633 child.setScaleY(getChildrenScale());
634
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800635 // Generate an id for each view, this assumes we have at most 256x256 cells
636 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700637 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700638 // If the horizontal or vertical span is set to -1, it is taken to
639 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700640 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
641 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800642
Winson Chungaafa03c2010-06-11 17:34:16 -0700643 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700644 if (LOGD) {
645 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
646 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700647 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700648
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700649 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700650
Winson Chungaafa03c2010-06-11 17:34:16 -0700651 return true;
652 }
653 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800654 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700655
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800656 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700657 public void removeAllViews() {
658 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700659 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700660 }
661
662 @Override
663 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700664 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700665 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700666 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700667 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700668 }
669
670 @Override
671 public void removeView(View view) {
672 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700673 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700674 }
675
676 @Override
677 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700678 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
679 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700680 }
681
682 @Override
683 public void removeViewInLayout(View view) {
684 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700685 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700686 }
687
688 @Override
689 public void removeViews(int start, int count) {
690 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700691 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700692 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700693 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700694 }
695
696 @Override
697 public void removeViewsInLayout(int start, int count) {
698 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700699 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700700 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700701 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800702 }
703
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700704 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700705 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800706 * @param x X coordinate of the point
707 * @param y Y coordinate of the point
708 * @param result Array of 2 ints to hold the x and y coordinate of the cell
709 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700710 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700711 final int hStartPadding = getPaddingLeft();
712 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800713
714 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
715 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
716
Adam Cohend22015c2010-07-26 22:02:18 -0700717 final int xAxis = mCountX;
718 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800719
720 if (result[0] < 0) result[0] = 0;
721 if (result[0] >= xAxis) result[0] = xAxis - 1;
722 if (result[1] < 0) result[1] = 0;
723 if (result[1] >= yAxis) result[1] = yAxis - 1;
724 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700725
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800726 /**
727 * Given a point, return the cell that most closely encloses that point
728 * @param x X coordinate of the point
729 * @param y Y coordinate of the point
730 * @param result Array of 2 ints to hold the x and y coordinate of the cell
731 */
732 void pointToCellRounded(int x, int y, int[] result) {
733 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
734 }
735
736 /**
737 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700738 *
739 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800740 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700741 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800742 * @param result Array of 2 ints to hold the x and y coordinate of the point
743 */
744 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700745 final int hStartPadding = getPaddingLeft();
746 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800747
748 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
749 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
750 }
751
Adam Cohene3e27a82011-04-15 12:07:39 -0700752 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800753 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700754 *
755 * @param cellX X coordinate of the cell
756 * @param cellY Y coordinate of the cell
757 *
758 * @param result Array of 2 ints to hold the x and y coordinate of the point
759 */
760 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700761 regionToCenterPoint(cellX, cellY, 1, 1, result);
762 }
763
764 /**
765 * Given a cell coordinate and span return the point that represents the center of the regio
766 *
767 * @param cellX X coordinate of the cell
768 * @param cellY Y coordinate of the cell
769 *
770 * @param result Array of 2 ints to hold the x and y coordinate of the point
771 */
772 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700773 final int hStartPadding = getPaddingLeft();
774 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700775 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
776 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
777 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
778 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700779 }
780
Adam Cohen19f37922012-03-21 11:59:11 -0700781 /**
782 * Given a cell coordinate and span fills out a corresponding pixel rect
783 *
784 * @param cellX X coordinate of the cell
785 * @param cellY Y coordinate of the cell
786 * @param result Rect in which to write the result
787 */
788 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
789 final int hStartPadding = getPaddingLeft();
790 final int vStartPadding = getPaddingTop();
791 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
792 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
793 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
794 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
795 }
796
Adam Cohen482ed822012-03-02 14:15:13 -0800797 public float getDistanceFromCell(float x, float y, int[] cell) {
798 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700799 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800800 }
801
Adam Cohenf9c184a2016-01-15 16:47:43 -0800802 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800803 return mCellWidth;
804 }
805
806 int getCellHeight() {
807 return mCellHeight;
808 }
809
Adam Cohend4844c32011-02-18 19:25:06 -0800810 int getWidthGap() {
811 return mWidthGap;
812 }
813
814 int getHeightGap() {
815 return mHeightGap;
816 }
817
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700818 public void setFixedSize(int width, int height) {
819 mFixedWidth = width;
820 mFixedHeight = height;
821 }
822
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800823 @Override
824 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800825 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800826 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700827 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
828 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700829 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
830 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Winson Chung11a1a532013-09-13 11:14:45 -0700831 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Sunny Goyalc6205602015-05-21 20:46:33 -0700832 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
833 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700834 if (cw != mCellWidth || ch != mCellHeight) {
835 mCellWidth = cw;
836 mCellHeight = ch;
837 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
838 mHeightGap, mCountX, mCountY);
839 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700840 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700841
Winson Chung2d75f122013-09-23 16:53:31 -0700842 int newWidth = childWidthSize;
843 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700844 if (mFixedWidth > 0 && mFixedHeight > 0) {
845 newWidth = mFixedWidth;
846 newHeight = mFixedHeight;
847 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800848 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
849 }
850
Adam Cohend22015c2010-07-26 22:02:18 -0700851 int numWidthGaps = mCountX - 1;
852 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800853
Adam Cohen234c4cd2011-07-17 21:03:04 -0700854 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -0700855 int hSpace = childWidthSize;
856 int vSpace = childHeightSize;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700857 int hFreeSpace = hSpace - (mCountX * mCellWidth);
858 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700859 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
860 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Winson Chung5f8afe62013-08-12 16:19:28 -0700861 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
862 mHeightGap, mCountX, mCountY);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700863 } else {
864 mWidthGap = mOriginalWidthGap;
865 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700866 }
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700867
868 // Make the feedback view large enough to hold the blur bitmap.
869 mTouchFeedbackView.measure(
870 MeasureSpec.makeMeasureSpec(mCellWidth + mTouchFeedbackView.getExtraSize(),
871 MeasureSpec.EXACTLY),
872 MeasureSpec.makeMeasureSpec(mCellHeight + mTouchFeedbackView.getExtraSize(),
873 MeasureSpec.EXACTLY));
874
875 mShortcutsAndWidgets.measure(
876 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
877 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
878
879 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
880 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700881 if (mFixedWidth > 0 && mFixedHeight > 0) {
882 setMeasuredDimension(maxWidth, maxHeight);
883 } else {
884 setMeasuredDimension(widthSize, heightSize);
885 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800886 }
887
888 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700889 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -0800890 boolean isFullscreen = mShortcutsAndWidgets.getChildCount() > 0 &&
891 ((LayoutParams) mShortcutsAndWidgets.getChildAt(0).getLayoutParams()).isFullscreen;
892 int left = getPaddingLeft();
893 if (!isFullscreen) {
Tony Wickhama501d492015-11-03 18:05:01 -0800894 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Tony Wickham26b01422015-11-10 14:44:32 -0800895 }
Winson Chung38848ca2013-10-08 12:03:44 -0700896 int top = getPaddingTop();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700897
898 mTouchFeedbackView.layout(left, top,
899 left + mTouchFeedbackView.getMeasuredWidth(),
900 top + mTouchFeedbackView.getMeasuredHeight());
901 mShortcutsAndWidgets.layout(left, top,
902 left + r - l,
903 top + b - t);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800904 }
905
Tony Wickhama501d492015-11-03 18:05:01 -0800906 /**
907 * Returns the amount of space left over after subtracting padding and cells. This space will be
908 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
909 * width in {@link DeviceProfile#calculateCellWidth(int, int)}.
910 */
911 public int getUnusedHorizontalSpace() {
912 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
913 }
914
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800915 @Override
Michael Jurkadee05892010-07-27 10:01:56 -0700916 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
917 super.onSizeChanged(w, h, oldw, oldh);
Winson Chung82a9bd22013-10-08 16:02:34 -0700918
919 // Expand the background drawing bounds by the padding baked into the background drawable
Sunny Goyal2805e632015-05-20 15:35:32 -0700920 mBackground.getPadding(mTempRect);
921 mBackground.setBounds(-mTempRect.left, -mTempRect.top,
922 w + mTempRect.right, h + mTempRect.bottom);
Michael Jurkadee05892010-07-27 10:01:56 -0700923 }
924
925 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800926 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700927 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800928 }
929
930 @Override
931 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700932 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800933 }
934
Michael Jurka5f1c5092010-09-03 14:15:02 -0700935 public float getBackgroundAlpha() {
936 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -0700937 }
938
Michael Jurka5f1c5092010-09-03 14:15:02 -0700939 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -0800940 if (mBackgroundAlpha != alpha) {
941 mBackgroundAlpha = alpha;
Sunny Goyal2805e632015-05-20 15:35:32 -0700942 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurkaafaa0502011-12-13 18:22:50 -0800943 }
Michael Jurkadee05892010-07-27 10:01:56 -0700944 }
945
Sunny Goyal2805e632015-05-20 15:35:32 -0700946 @Override
947 protected boolean verifyDrawable(Drawable who) {
948 return super.verifyDrawable(who) || (mIsDragTarget && who == mBackground);
949 }
950
Michael Jurkaa52570f2012-03-20 03:18:20 -0700951 public void setShortcutAndWidgetAlpha(float alpha) {
Sunny Goyal02b50812014-09-10 15:44:42 -0700952 mShortcutsAndWidgets.setAlpha(alpha);
Michael Jurkadee05892010-07-27 10:01:56 -0700953 }
954
Michael Jurkaa52570f2012-03-20 03:18:20 -0700955 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -0700956 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700957 }
958
Patrick Dubroy440c3602010-07-13 17:50:32 -0700959 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700960 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -0700961 }
962
Adam Cohen76fc0852011-06-17 13:26:23 -0700963 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -0800964 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700965 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -0800966 boolean[][] occupied = mOccupied;
967 if (!permanent) {
968 occupied = mTmpOccupied;
969 }
970
Adam Cohen19f37922012-03-21 11:59:11 -0700971 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700972 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
973 final ItemInfo info = (ItemInfo) child.getTag();
974
975 // We cancel any existing animations
976 if (mReorderAnimators.containsKey(lp)) {
977 mReorderAnimators.get(lp).cancel();
978 mReorderAnimators.remove(lp);
979 }
980
Adam Cohen482ed822012-03-02 14:15:13 -0800981 final int oldX = lp.x;
982 final int oldY = lp.y;
983 if (adjustOccupied) {
984 occupied[lp.cellX][lp.cellY] = false;
985 occupied[cellX][cellY] = true;
986 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700987 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -0800988 if (permanent) {
989 lp.cellX = info.cellX = cellX;
990 lp.cellY = info.cellY = cellY;
991 } else {
992 lp.tmpCellX = cellX;
993 lp.tmpCellY = cellY;
994 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700995 clc.setupLp(lp);
996 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800997 final int newX = lp.x;
998 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700999
Adam Cohen76fc0852011-06-17 13:26:23 -07001000 lp.x = oldX;
1001 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001002
Adam Cohen482ed822012-03-02 14:15:13 -08001003 // Exit early if we're not actually moving the view
1004 if (oldX == newX && oldY == newY) {
1005 lp.isLockedToGrid = true;
1006 return true;
1007 }
1008
Michael Jurkaf1ad6082013-03-13 12:55:46 +01001009 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001010 va.setDuration(duration);
1011 mReorderAnimators.put(lp, va);
1012
1013 va.addUpdateListener(new AnimatorUpdateListener() {
1014 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001015 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001016 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001017 lp.x = (int) ((1 - r) * oldX + r * newX);
1018 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001019 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001020 }
1021 });
Adam Cohen482ed822012-03-02 14:15:13 -08001022 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001023 boolean cancelled = false;
1024 public void onAnimationEnd(Animator animation) {
1025 // If the animation was cancelled, it means that another animation
1026 // has interrupted this one, and we don't want to lock the item into
1027 // place just yet.
1028 if (!cancelled) {
1029 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001030 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001031 }
1032 if (mReorderAnimators.containsKey(lp)) {
1033 mReorderAnimators.remove(lp);
1034 }
1035 }
1036 public void onAnimationCancel(Animator animation) {
1037 cancelled = true;
1038 }
1039 });
Adam Cohen482ed822012-03-02 14:15:13 -08001040 va.setStartDelay(delay);
1041 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001042 return true;
1043 }
1044 return false;
1045 }
1046
Tony Wickhama501d492015-11-03 18:05:01 -08001047 void visualizeDropLocation(View v, Bitmap dragOutline, int cellX, int cellY, int spanX,
1048 int spanY, boolean resize, DropTarget.DragObject dragObject) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001049 final int oldDragCellX = mDragCell[0];
1050 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001051
Adam Cohen2801caf2011-05-13 20:57:39 -07001052 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001053 return;
1054 }
1055
Adam Cohen482ed822012-03-02 14:15:13 -08001056 if (cellX != oldDragCellX || cellY != oldDragCellY) {
Sunny Goyale78e3d72015-09-24 11:23:31 -07001057 Point dragOffset = dragObject.dragView.getDragVisualizeOffset();
1058 Rect dragRegion = dragObject.dragView.getDragRegion();
1059
Adam Cohen482ed822012-03-02 14:15:13 -08001060 mDragCell[0] = cellX;
1061 mDragCell[1] = cellY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001062
Joe Onorato4be866d2010-10-10 11:26:02 -07001063 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001064 mDragOutlineAnims[oldIndex].animateOut();
1065 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001066 Rect r = mDragOutlines[mDragOutlineCurrent];
Sunny Goyal106bf642015-07-16 12:18:06 -07001067
Adam Cohend41fbf52012-02-16 23:53:59 -08001068 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001069 cellToRect(cellX, cellY, spanX, spanY, r);
Sunny Goyal106bf642015-07-16 12:18:06 -07001070 } else {
1071 // Find the top left corner of the rect the object will occupy
1072 final int[] topLeft = mTmpPoint;
1073 cellToPoint(cellX, cellY, topLeft);
1074
1075 int left = topLeft[0];
1076 int top = topLeft[1];
1077
1078 if (v != null && dragOffset == null) {
1079 // When drawing the drag outline, it did not account for margin offsets
1080 // added by the view's parent.
1081 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1082 left += lp.leftMargin;
1083 top += lp.topMargin;
1084
1085 // Offsets due to the size difference between the View and the dragOutline.
1086 // There is a size difference to account for the outer blur, which may lie
1087 // outside the bounds of the view.
1088 top += (v.getHeight() - dragOutline.getHeight()) / 2;
1089 // We center about the x axis
1090 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1091 - dragOutline.getWidth()) / 2;
1092 } else {
1093 if (dragOffset != null && dragRegion != null) {
1094 // Center the drag region *horizontally* in the cell and apply a drag
1095 // outline offset
1096 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1097 - dragRegion.width()) / 2;
1098 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
1099 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
1100 top += dragOffset.y + cellPaddingY;
1101 } else {
1102 // Center the drag outline in the cell
1103 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1104 - dragOutline.getWidth()) / 2;
1105 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1106 - dragOutline.getHeight()) / 2;
1107 }
1108 }
1109 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
Adam Cohend41fbf52012-02-16 23:53:59 -08001110 }
Winson Chung150fbab2010-09-29 17:14:26 -07001111
Sunny Goyal106bf642015-07-16 12:18:06 -07001112 Utilities.scaleRectAboutCenter(r, getChildrenScale());
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001113 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1114 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001115
1116 if (dragObject.stateAnnouncer != null) {
1117 String msg;
1118 if (isHotseat()) {
1119 msg = getContext().getString(R.string.move_to_hotseat_position,
1120 Math.max(cellX, cellY) + 1);
1121 } else {
1122 msg = getContext().getString(R.string.move_to_empty_cell,
1123 cellY + 1, cellX + 1);
1124 }
1125 dragObject.stateAnnouncer.announce(msg);
1126 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001127 }
1128 }
1129
Adam Cohene0310962011-04-18 16:15:31 -07001130 public void clearDragOutlines() {
1131 final int oldIndex = mDragOutlineCurrent;
1132 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001133 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001134 }
1135
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001136 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001137 * Find a vacant area that will fit the given bounds nearest the requested
1138 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001139 *
Romain Guy51afc022009-05-04 18:03:43 -07001140 * @param pixelX The X location at which you want to search for a vacant area.
1141 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001142 * @param minSpanX The minimum horizontal span required
1143 * @param minSpanY The minimum vertical span required
1144 * @param spanX Horizontal span of the object.
1145 * @param spanY Vertical span of the object.
1146 * @param result Array in which to place the result, or null (in which case a new array will
1147 * be allocated)
1148 * @return The X, Y cell of a vacant area that can contain this object,
1149 * nearest the requested location.
1150 */
1151 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1152 int spanY, int[] result, int[] resultSpan) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001153 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
Adam Cohend41fbf52012-02-16 23:53:59 -08001154 result, resultSpan);
1155 }
1156
Adam Cohend41fbf52012-02-16 23:53:59 -08001157 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1158 private void lazyInitTempRectStack() {
1159 if (mTempRectStack.isEmpty()) {
1160 for (int i = 0; i < mCountX * mCountY; i++) {
1161 mTempRectStack.push(new Rect());
1162 }
1163 }
1164 }
Adam Cohen482ed822012-03-02 14:15:13 -08001165
Adam Cohend41fbf52012-02-16 23:53:59 -08001166 private void recycleTempRects(Stack<Rect> used) {
1167 while (!used.isEmpty()) {
1168 mTempRectStack.push(used.pop());
1169 }
1170 }
1171
1172 /**
1173 * Find a vacant area that will fit the given bounds nearest the requested
1174 * cell location. Uses Euclidean distance to score multiple vacant areas.
1175 *
1176 * @param pixelX The X location at which you want to search for a vacant area.
1177 * @param pixelY The Y location at which you want to search for a vacant area.
1178 * @param minSpanX The minimum horizontal span required
1179 * @param minSpanY The minimum vertical span required
1180 * @param spanX Horizontal span of the object.
1181 * @param spanY Vertical span of the object.
1182 * @param ignoreOccupied If true, the result can be an occupied cell
1183 * @param result Array in which to place the result, or null (in which case a new array will
1184 * be allocated)
1185 * @return The X, Y cell of a vacant area that can contain this object,
1186 * nearest the requested location.
1187 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001188 private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1189 int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001190 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001191
Adam Cohene3e27a82011-04-15 12:07:39 -07001192 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1193 // to the center of the item, but we are searching based on the top-left cell, so
1194 // we translate the point over to correspond to the top-left.
1195 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1196 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1197
Jeff Sharkey70864282009-04-07 21:08:40 -07001198 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001199 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001200 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001201 final Rect bestRect = new Rect(-1, -1, -1, -1);
1202 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001203
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001204 final int countX = mCountX;
1205 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001206
Adam Cohend41fbf52012-02-16 23:53:59 -08001207 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1208 spanX < minSpanX || spanY < minSpanY) {
1209 return bestXY;
1210 }
1211
1212 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001213 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001214 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1215 int ySize = -1;
1216 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001217 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001218 // First, let's see if this thing fits anywhere
1219 for (int i = 0; i < minSpanX; i++) {
1220 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001221 if (mOccupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001222 continue inner;
1223 }
Michael Jurkac28de512010-08-13 11:27:44 -07001224 }
1225 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001226 xSize = minSpanX;
1227 ySize = minSpanY;
1228
1229 // We know that the item will fit at _some_ acceptable size, now let's see
1230 // how big we can make it. We'll alternate between incrementing x and y spans
1231 // until we hit a limit.
1232 boolean incX = true;
1233 boolean hitMaxX = xSize >= spanX;
1234 boolean hitMaxY = ySize >= spanY;
1235 while (!(hitMaxX && hitMaxY)) {
1236 if (incX && !hitMaxX) {
1237 for (int j = 0; j < ySize; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001238 if (x + xSize > countX -1 || mOccupied[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001239 // We can't move out horizontally
1240 hitMaxX = true;
1241 }
1242 }
1243 if (!hitMaxX) {
1244 xSize++;
1245 }
1246 } else if (!hitMaxY) {
1247 for (int i = 0; i < xSize; i++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001248 if (y + ySize > countY - 1 || mOccupied[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001249 // We can't move out vertically
1250 hitMaxY = true;
1251 }
1252 }
1253 if (!hitMaxY) {
1254 ySize++;
1255 }
1256 }
1257 hitMaxX |= xSize >= spanX;
1258 hitMaxY |= ySize >= spanY;
1259 incX = !incX;
1260 }
1261 incX = true;
1262 hitMaxX = xSize >= spanX;
1263 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001264 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001265 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001266 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001267
Adam Cohend41fbf52012-02-16 23:53:59 -08001268 // We verify that the current rect is not a sub-rect of any of our previous
1269 // candidates. In this case, the current rect is disqualified in favour of the
1270 // containing rect.
1271 Rect currentRect = mTempRectStack.pop();
1272 currentRect.set(x, y, x + xSize, y + ySize);
1273 boolean contained = false;
1274 for (Rect r : validRegions) {
1275 if (r.contains(currentRect)) {
1276 contained = true;
1277 break;
1278 }
1279 }
1280 validRegions.push(currentRect);
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001281 double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
Adam Cohen482ed822012-03-02 14:15:13 -08001282
Adam Cohend41fbf52012-02-16 23:53:59 -08001283 if ((distance <= bestDistance && !contained) ||
1284 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001285 bestDistance = distance;
1286 bestXY[0] = x;
1287 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001288 if (resultSpan != null) {
1289 resultSpan[0] = xSize;
1290 resultSpan[1] = ySize;
1291 }
1292 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001293 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001294 }
1295 }
1296
Adam Cohenc0dcf592011-06-01 15:30:43 -07001297 // Return -1, -1 if no suitable location found
1298 if (bestDistance == Double.MAX_VALUE) {
1299 bestXY[0] = -1;
1300 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001301 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001302 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001303 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001304 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001305
Adam Cohen482ed822012-03-02 14:15:13 -08001306 /**
1307 * Find a vacant area that will fit the given bounds nearest the requested
1308 * cell location, and will also weigh in a suggested direction vector of the
1309 * desired location. This method computers distance based on unit grid distances,
1310 * not pixel distances.
1311 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001312 * @param cellX The X cell nearest to which you want to search for a vacant area.
1313 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001314 * @param spanX Horizontal span of the object.
1315 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001316 * @param direction The favored direction in which the views should move from x, y
Sunny Goyal9eba1fd2015-10-16 08:58:57 -07001317 * @param occupied The array which represents which cells in the CellLayout are occupied
Adam Cohen47a876d2012-03-19 13:21:41 -07001318 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001319 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001320 * @param result Array in which to place the result, or null (in which case a new array will
1321 * be allocated)
1322 * @return The X, Y cell of a vacant area that can contain this object,
1323 * nearest the requested location.
1324 */
1325 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001326 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001327 // Keep track of best-scoring drop area
1328 final int[] bestXY = result != null ? result : new int[2];
1329 float bestDistance = Float.MAX_VALUE;
1330 int bestDirectionScore = Integer.MIN_VALUE;
1331
1332 final int countX = mCountX;
1333 final int countY = mCountY;
1334
1335 for (int y = 0; y < countY - (spanY - 1); y++) {
1336 inner:
1337 for (int x = 0; x < countX - (spanX - 1); x++) {
1338 // First, let's see if this thing fits anywhere
1339 for (int i = 0; i < spanX; i++) {
1340 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001341 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001342 continue inner;
1343 }
1344 }
1345 }
1346
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001347 float distance = (float) Math.hypot(x - cellX, y - cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001348 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001349 computeDirectionVector(x - cellX, y - cellY, curDirection);
1350 // The direction score is just the dot product of the two candidate direction
1351 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001352 int curDirectionScore = direction[0] * curDirection[0] +
1353 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001354 boolean exactDirectionOnly = false;
1355 boolean directionMatches = direction[0] == curDirection[0] &&
1356 direction[0] == curDirection[0];
1357 if ((directionMatches || !exactDirectionOnly) &&
1358 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001359 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1360 bestDistance = distance;
1361 bestDirectionScore = curDirectionScore;
1362 bestXY[0] = x;
1363 bestXY[1] = y;
1364 }
1365 }
1366 }
1367
1368 // Return -1, -1 if no suitable location found
1369 if (bestDistance == Float.MAX_VALUE) {
1370 bestXY[0] = -1;
1371 bestXY[1] = -1;
1372 }
1373 return bestXY;
1374 }
1375
1376 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001377 int[] direction, ItemConfiguration currentState) {
1378 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001379 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001380 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001381 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1382
Adam Cohen8baab352012-03-20 17:39:21 -07001383 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001384
1385 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001386 c.x = mTempLocation[0];
1387 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001388 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001389 }
Adam Cohen8baab352012-03-20 17:39:21 -07001390 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001391 return success;
1392 }
1393
Adam Cohenf3900c22012-11-16 18:28:11 -08001394 /**
1395 * This helper class defines a cluster of views. It helps with defining complex edges
1396 * of the cluster and determining how those edges interact with other views. The edges
1397 * essentially define a fine-grained boundary around the cluster of views -- like a more
1398 * precise version of a bounding box.
1399 */
1400 private class ViewCluster {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001401 final static int LEFT = 1 << 0;
1402 final static int TOP = 1 << 1;
1403 final static int RIGHT = 1 << 2;
1404 final static int BOTTOM = 1 << 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001405
Adam Cohenf3900c22012-11-16 18:28:11 -08001406 ArrayList<View> views;
1407 ItemConfiguration config;
1408 Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001409
Adam Cohenf3900c22012-11-16 18:28:11 -08001410 int[] leftEdge = new int[mCountY];
1411 int[] rightEdge = new int[mCountY];
1412 int[] topEdge = new int[mCountX];
1413 int[] bottomEdge = new int[mCountX];
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001414 int dirtyEdges;
1415 boolean boundingRectDirty;
Adam Cohenf3900c22012-11-16 18:28:11 -08001416
1417 @SuppressWarnings("unchecked")
1418 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1419 this.views = (ArrayList<View>) views.clone();
1420 this.config = config;
1421 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001422 }
1423
Adam Cohenf3900c22012-11-16 18:28:11 -08001424 void resetEdges() {
1425 for (int i = 0; i < mCountX; i++) {
1426 topEdge[i] = -1;
1427 bottomEdge[i] = -1;
1428 }
1429 for (int i = 0; i < mCountY; i++) {
1430 leftEdge[i] = -1;
1431 rightEdge[i] = -1;
1432 }
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001433 dirtyEdges = LEFT | TOP | RIGHT | BOTTOM;
Adam Cohenf3900c22012-11-16 18:28:11 -08001434 boundingRectDirty = true;
1435 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001436
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001437 void computeEdge(int which) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001438 int count = views.size();
1439 for (int i = 0; i < count; i++) {
1440 CellAndSpan cs = config.map.get(views.get(i));
1441 switch (which) {
1442 case LEFT:
1443 int left = cs.x;
1444 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001445 if (left < leftEdge[j] || leftEdge[j] < 0) {
1446 leftEdge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001447 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001448 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001449 break;
1450 case RIGHT:
1451 int right = cs.x + cs.spanX;
1452 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001453 if (right > rightEdge[j]) {
1454 rightEdge[j] = right;
Adam Cohenf3900c22012-11-16 18:28:11 -08001455 }
1456 }
1457 break;
1458 case TOP:
1459 int top = cs.y;
1460 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001461 if (top < topEdge[j] || topEdge[j] < 0) {
1462 topEdge[j] = top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001463 }
1464 }
1465 break;
1466 case BOTTOM:
1467 int bottom = cs.y + cs.spanY;
1468 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001469 if (bottom > bottomEdge[j]) {
1470 bottomEdge[j] = bottom;
Adam Cohenf3900c22012-11-16 18:28:11 -08001471 }
1472 }
1473 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001474 }
1475 }
1476 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001477
1478 boolean isViewTouchingEdge(View v, int whichEdge) {
1479 CellAndSpan cs = config.map.get(v);
1480
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001481 if ((dirtyEdges & whichEdge) == whichEdge) {
1482 computeEdge(whichEdge);
1483 dirtyEdges &= ~whichEdge;
1484 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001485
1486 switch (whichEdge) {
1487 case LEFT:
1488 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001489 if (leftEdge[i] == cs.x + cs.spanX) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001490 return true;
1491 }
1492 }
1493 break;
1494 case RIGHT:
1495 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001496 if (rightEdge[i] == cs.x) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001497 return true;
1498 }
1499 }
1500 break;
1501 case TOP:
1502 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001503 if (topEdge[i] == cs.y + cs.spanY) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001504 return true;
1505 }
1506 }
1507 break;
1508 case BOTTOM:
1509 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001510 if (bottomEdge[i] == cs.y) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001511 return true;
1512 }
1513 }
1514 break;
1515 }
1516 return false;
1517 }
1518
1519 void shift(int whichEdge, int delta) {
1520 for (View v: views) {
1521 CellAndSpan c = config.map.get(v);
1522 switch (whichEdge) {
1523 case LEFT:
1524 c.x -= delta;
1525 break;
1526 case RIGHT:
1527 c.x += delta;
1528 break;
1529 case TOP:
1530 c.y -= delta;
1531 break;
1532 case BOTTOM:
1533 default:
1534 c.y += delta;
1535 break;
1536 }
1537 }
1538 resetEdges();
1539 }
1540
1541 public void addView(View v) {
1542 views.add(v);
1543 resetEdges();
1544 }
1545
1546 public Rect getBoundingRect() {
1547 if (boundingRectDirty) {
1548 boolean first = true;
1549 for (View v: views) {
1550 CellAndSpan c = config.map.get(v);
1551 if (first) {
1552 boundingRect.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1553 first = false;
1554 } else {
1555 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1556 }
1557 }
1558 }
1559 return boundingRect;
1560 }
1561
Adam Cohenf3900c22012-11-16 18:28:11 -08001562 PositionComparator comparator = new PositionComparator();
1563 class PositionComparator implements Comparator<View> {
1564 int whichEdge = 0;
1565 public int compare(View left, View right) {
1566 CellAndSpan l = config.map.get(left);
1567 CellAndSpan r = config.map.get(right);
1568 switch (whichEdge) {
1569 case LEFT:
1570 return (r.x + r.spanX) - (l.x + l.spanX);
1571 case RIGHT:
1572 return l.x - r.x;
1573 case TOP:
1574 return (r.y + r.spanY) - (l.y + l.spanY);
1575 case BOTTOM:
1576 default:
1577 return l.y - r.y;
1578 }
1579 }
1580 }
1581
1582 public void sortConfigurationForEdgePush(int edge) {
1583 comparator.whichEdge = edge;
1584 Collections.sort(config.sortedViews, comparator);
1585 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001586 }
1587
Adam Cohenf3900c22012-11-16 18:28:11 -08001588 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1589 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001590
Adam Cohenf3900c22012-11-16 18:28:11 -08001591 ViewCluster cluster = new ViewCluster(views, currentState);
1592 Rect clusterRect = cluster.getBoundingRect();
1593 int whichEdge;
1594 int pushDistance;
1595 boolean fail = false;
1596
1597 // Determine the edge of the cluster that will be leading the push and how far
1598 // the cluster must be shifted.
1599 if (direction[0] < 0) {
1600 whichEdge = ViewCluster.LEFT;
1601 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001602 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001603 whichEdge = ViewCluster.RIGHT;
1604 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1605 } else if (direction[1] < 0) {
1606 whichEdge = ViewCluster.TOP;
1607 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1608 } else {
1609 whichEdge = ViewCluster.BOTTOM;
1610 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07001611 }
1612
Adam Cohenf3900c22012-11-16 18:28:11 -08001613 // Break early for invalid push distance.
1614 if (pushDistance <= 0) {
1615 return false;
Adam Cohene0489502012-08-27 15:18:53 -07001616 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001617
1618 // Mark the occupied state as false for the group of views we want to move.
1619 for (View v: views) {
1620 CellAndSpan c = currentState.map.get(v);
1621 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1622 }
1623
1624 // We save the current configuration -- if we fail to find a solution we will revert
1625 // to the initial state. The process of finding a solution modifies the configuration
1626 // in place, hence the need for revert in the failure case.
1627 currentState.save();
1628
1629 // The pushing algorithm is simplified by considering the views in the order in which
1630 // they would be pushed by the cluster. For example, if the cluster is leading with its
1631 // left edge, we consider sort the views by their right edge, from right to left.
1632 cluster.sortConfigurationForEdgePush(whichEdge);
1633
1634 while (pushDistance > 0 && !fail) {
1635 for (View v: currentState.sortedViews) {
1636 // For each view that isn't in the cluster, we see if the leading edge of the
1637 // cluster is contacting the edge of that view. If so, we add that view to the
1638 // cluster.
1639 if (!cluster.views.contains(v) && v != dragView) {
1640 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1641 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1642 if (!lp.canReorder) {
1643 // The push solution includes the all apps button, this is not viable.
1644 fail = true;
1645 break;
1646 }
1647 cluster.addView(v);
1648 CellAndSpan c = currentState.map.get(v);
1649
1650 // Adding view to cluster, mark it as not occupied.
1651 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1652 }
1653 }
1654 }
1655 pushDistance--;
1656
1657 // The cluster has been completed, now we move the whole thing over in the appropriate
1658 // direction.
1659 cluster.shift(whichEdge, 1);
1660 }
1661
1662 boolean foundSolution = false;
1663 clusterRect = cluster.getBoundingRect();
1664
1665 // Due to the nature of the algorithm, the only check required to verify a valid solution
1666 // is to ensure that completed shifted cluster lies completely within the cell layout.
1667 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1668 clusterRect.bottom <= mCountY) {
1669 foundSolution = true;
1670 } else {
1671 currentState.restore();
1672 }
1673
1674 // In either case, we set the occupied array as marked for the location of the views
1675 for (View v: cluster.views) {
1676 CellAndSpan c = currentState.map.get(v);
1677 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
1678 }
1679
1680 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07001681 }
1682
Adam Cohen482ed822012-03-02 14:15:13 -08001683 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08001684 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001685 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001686
Adam Cohen8baab352012-03-20 17:39:21 -07001687 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001688 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001689 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001690 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001691 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001692 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001693 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001694 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001695 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001696 }
1697 }
Adam Cohen8baab352012-03-20 17:39:21 -07001698
Adam Cohen8baab352012-03-20 17:39:21 -07001699 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08001700 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001701 CellAndSpan c = currentState.map.get(v);
1702 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1703 }
1704
Adam Cohen47a876d2012-03-19 13:21:41 -07001705 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1706 int top = boundingRect.top;
1707 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001708 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001709 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08001710 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001711 CellAndSpan c = currentState.map.get(v);
1712 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001713 }
1714
Adam Cohen482ed822012-03-02 14:15:13 -08001715 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1716
Adam Cohenf3900c22012-11-16 18:28:11 -08001717 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1718 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001719
Adam Cohen8baab352012-03-20 17:39:21 -07001720 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001721 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001722 int deltaX = mTempLocation[0] - boundingRect.left;
1723 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001724 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001725 CellAndSpan c = currentState.map.get(v);
1726 c.x += deltaX;
1727 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001728 }
1729 success = true;
1730 }
Adam Cohen8baab352012-03-20 17:39:21 -07001731
1732 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08001733 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001734 CellAndSpan c = currentState.map.get(v);
1735 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001736 }
1737 return success;
1738 }
1739
1740 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1741 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1742 }
1743
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001744 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1745 // to push items in each of the cardinal directions, in an order based on the direction vector
1746 // passed.
1747 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1748 int[] direction, View ignoreView, ItemConfiguration solution) {
1749 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001750 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001751 // separately in each of the components.
1752 int temp = direction[1];
1753 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001754
1755 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001756 ignoreView, solution)) {
1757 return true;
1758 }
1759 direction[1] = temp;
1760 temp = direction[0];
1761 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001762
1763 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001764 ignoreView, solution)) {
1765 return true;
1766 }
1767 // Revert the direction
1768 direction[0] = temp;
1769
1770 // Now we try pushing in each component of the opposite direction
1771 direction[0] *= -1;
1772 direction[1] *= -1;
1773 temp = direction[1];
1774 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001775 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001776 ignoreView, solution)) {
1777 return true;
1778 }
1779
1780 direction[1] = temp;
1781 temp = direction[0];
1782 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001783 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001784 ignoreView, solution)) {
1785 return true;
1786 }
1787 // revert the direction
1788 direction[0] = temp;
1789 direction[0] *= -1;
1790 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001791
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001792 } else {
1793 // If the direction vector has a single non-zero component, we push first in the
1794 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08001795 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001796 ignoreView, solution)) {
1797 return true;
1798 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001799 // Then we try the opposite direction
1800 direction[0] *= -1;
1801 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001802 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001803 ignoreView, solution)) {
1804 return true;
1805 }
1806 // Switch the direction back
1807 direction[0] *= -1;
1808 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001809
1810 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001811 // to find a solution by pushing along the perpendicular axis.
1812
1813 // Swap the components
1814 int temp = direction[1];
1815 direction[1] = direction[0];
1816 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08001817 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001818 ignoreView, solution)) {
1819 return true;
1820 }
1821
1822 // Then we try the opposite direction
1823 direction[0] *= -1;
1824 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001825 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001826 ignoreView, solution)) {
1827 return true;
1828 }
1829 // Switch the direction back
1830 direction[0] *= -1;
1831 direction[1] *= -1;
1832
1833 // Swap the components back
1834 temp = direction[1];
1835 direction[1] = direction[0];
1836 direction[0] = temp;
1837 }
1838 return false;
1839 }
1840
Adam Cohen482ed822012-03-02 14:15:13 -08001841 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001842 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001843 // Return early if get invalid cell positions
1844 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001845
Adam Cohen8baab352012-03-20 17:39:21 -07001846 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001847 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001848
Adam Cohen8baab352012-03-20 17:39:21 -07001849 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001850 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001851 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001852 if (c != null) {
1853 c.x = cellX;
1854 c.y = cellY;
1855 }
Adam Cohen482ed822012-03-02 14:15:13 -08001856 }
Adam Cohen482ed822012-03-02 14:15:13 -08001857 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1858 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001859 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001860 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001861 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001862 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001863 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001864 if (Rect.intersects(r0, r1)) {
1865 if (!lp.canReorder) {
1866 return false;
1867 }
1868 mIntersectingViews.add(child);
1869 }
1870 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001871
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001872 solution.intersectingViews = new ArrayList<View>(mIntersectingViews);
1873
Winson Chung5f8afe62013-08-12 16:19:28 -07001874 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001875 // we try to find a solution such that no displaced item travels through another item
1876 // without also displacing that item.
1877 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001878 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001879 return true;
1880 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001881
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001882 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08001883 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001884 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001885 return true;
1886 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001887
Adam Cohen482ed822012-03-02 14:15:13 -08001888 // Ok, they couldn't move as a block, let's move them individually
1889 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001890 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001891 return false;
1892 }
1893 }
1894 return true;
1895 }
1896
1897 /*
1898 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1899 * the provided point and the provided cell
1900 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001901 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001902 double angle = Math.atan(((float) deltaY) / deltaX);
1903
1904 result[0] = 0;
1905 result[1] = 0;
1906 if (Math.abs(Math.cos(angle)) > 0.5f) {
1907 result[0] = (int) Math.signum(deltaX);
1908 }
1909 if (Math.abs(Math.sin(angle)) > 0.5f) {
1910 result[1] = (int) Math.signum(deltaY);
1911 }
1912 }
1913
Adam Cohen8baab352012-03-20 17:39:21 -07001914 private void copyOccupiedArray(boolean[][] occupied) {
1915 for (int i = 0; i < mCountX; i++) {
1916 for (int j = 0; j < mCountY; j++) {
1917 occupied[i][j] = mOccupied[i][j];
1918 }
1919 }
1920 }
1921
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001922 private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001923 int spanX, int spanY, int[] direction, View dragView, boolean decX,
1924 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001925 // Copy the current state into the solution. This solution will be manipulated as necessary.
1926 copyCurrentStateToSolution(solution, false);
1927 // Copy the current occupied array into the temporary occupied array. This array will be
1928 // manipulated as necessary to find a solution.
1929 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001930
1931 // We find the nearest cell into which we would place the dragged item, assuming there's
1932 // nothing in its way.
1933 int result[] = new int[2];
1934 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1935
1936 boolean success = false;
1937 // First we try the exact nearest position of the item being dragged,
1938 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001939 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1940 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001941
1942 if (!success) {
1943 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1944 // x, then 1 in y etc.
1945 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001946 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
1947 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001948 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001949 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
1950 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001951 }
1952 solution.isSolution = false;
1953 } else {
1954 solution.isSolution = true;
1955 solution.dragViewX = result[0];
1956 solution.dragViewY = result[1];
1957 solution.dragViewSpanX = spanX;
1958 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001959 }
1960 return solution;
1961 }
1962
1963 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001964 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001965 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001966 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001967 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001968 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08001969 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07001970 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001971 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001972 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001973 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001974 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08001975 }
1976 }
1977
1978 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
1979 for (int i = 0; i < mCountX; i++) {
1980 for (int j = 0; j < mCountY; j++) {
1981 mTmpOccupied[i][j] = false;
1982 }
1983 }
1984
Michael Jurkaa52570f2012-03-20 03:18:20 -07001985 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001986 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001987 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001988 if (child == dragView) continue;
1989 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001990 CellAndSpan c = solution.map.get(child);
1991 if (c != null) {
1992 lp.tmpCellX = c.x;
1993 lp.tmpCellY = c.y;
1994 lp.cellHSpan = c.spanX;
1995 lp.cellVSpan = c.spanY;
1996 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001997 }
1998 }
1999 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2000 solution.dragViewSpanY, mTmpOccupied, true);
2001 }
2002
2003 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
2004 commitDragView) {
2005
2006 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
2007 for (int i = 0; i < mCountX; i++) {
2008 for (int j = 0; j < mCountY; j++) {
2009 occupied[i][j] = false;
2010 }
2011 }
2012
Michael Jurkaa52570f2012-03-20 03:18:20 -07002013 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002014 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002015 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002016 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002017 CellAndSpan c = solution.map.get(child);
2018 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002019 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2020 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002021 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002022 }
2023 }
2024 if (commitDragView) {
2025 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2026 solution.dragViewSpanY, occupied, true);
2027 }
2028 }
2029
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002030
2031 // This method starts or changes the reorder preview animations
2032 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
2033 View dragView, int delay, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07002034 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002035 for (int i = 0; i < childCount; i++) {
2036 View child = mShortcutsAndWidgets.getChildAt(i);
2037 if (child == dragView) continue;
2038 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002039 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
2040 != null && !solution.intersectingViews.contains(child);
2041
Adam Cohen19f37922012-03-21 11:59:11 -07002042 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002043 if (c != null && !skip) {
2044 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
2045 lp.cellY, c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002046 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002047 }
2048 }
2049 }
2050
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002051 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07002052 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002053 class ReorderPreviewAnimation {
Adam Cohen19f37922012-03-21 11:59:11 -07002054 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002055 float finalDeltaX;
2056 float finalDeltaY;
2057 float initDeltaX;
2058 float initDeltaY;
2059 float finalScale;
2060 float initScale;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002061 int mode;
2062 boolean repeating = false;
2063 private static final int PREVIEW_DURATION = 300;
2064 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
2065
2066 public static final int MODE_HINT = 0;
2067 public static final int MODE_PREVIEW = 1;
2068
Adam Cohene7587d22012-05-24 18:50:02 -07002069 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002070
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002071 public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
2072 int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07002073 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2074 final int x0 = mTmpPoint[0];
2075 final int y0 = mTmpPoint[1];
2076 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2077 final int x1 = mTmpPoint[0];
2078 final int y1 = mTmpPoint[1];
2079 final int dX = x1 - x0;
2080 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002081 finalDeltaX = 0;
2082 finalDeltaY = 0;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002083 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07002084 if (dX == dY && dX == 0) {
2085 } else {
2086 if (dY == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002087 finalDeltaX = - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002088 } else if (dX == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002089 finalDeltaY = - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002090 } else {
2091 double angle = Math.atan( (float) (dY) / dX);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002092 finalDeltaX = (int) (- dir * Math.signum(dX) *
2093 Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
2094 finalDeltaY = (int) (- dir * Math.signum(dY) *
2095 Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002096 }
2097 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002098 this.mode = mode;
Adam Cohend024f982012-05-23 18:26:45 -07002099 initDeltaX = child.getTranslationX();
2100 initDeltaY = child.getTranslationY();
Adam Cohen307fe232012-08-16 17:55:58 -07002101 finalScale = getChildrenScale() - 4.0f / child.getWidth();
Adam Cohend024f982012-05-23 18:26:45 -07002102 initScale = child.getScaleX();
Adam Cohen19f37922012-03-21 11:59:11 -07002103 this.child = child;
2104 }
2105
Adam Cohend024f982012-05-23 18:26:45 -07002106 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002107 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002108 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002109 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002110 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002111 if (finalDeltaX == 0 && finalDeltaY == 0) {
2112 completeAnimationImmediately();
2113 return;
2114 }
Adam Cohen19f37922012-03-21 11:59:11 -07002115 }
Adam Cohend024f982012-05-23 18:26:45 -07002116 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002117 return;
2118 }
Michael Jurkaf1ad6082013-03-13 12:55:46 +01002119 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002120 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07002121
2122 // Animations are disabled in power save mode, causing the repeated animation to jump
2123 // spastically between beginning and end states. Since this looks bad, we don't repeat
2124 // the animation in power save mode.
Tony Wickham112ac952015-11-12 12:31:50 -08002125 if (!Utilities.isPowerSaverOn(getContext())) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07002126 va.setRepeatMode(ValueAnimator.REVERSE);
2127 va.setRepeatCount(ValueAnimator.INFINITE);
2128 }
2129
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002130 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002131 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002132 va.addUpdateListener(new AnimatorUpdateListener() {
2133 @Override
2134 public void onAnimationUpdate(ValueAnimator animation) {
2135 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002136 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : r;
2137 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2138 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002139 child.setTranslationX(x);
2140 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002141 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002142 child.setScaleX(s);
2143 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002144 }
2145 });
2146 va.addListener(new AnimatorListenerAdapter() {
2147 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002148 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002149 initDeltaX = 0;
2150 initDeltaY = 0;
Adam Cohen307fe232012-08-16 17:55:58 -07002151 initScale = getChildrenScale();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002152 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002153 }
2154 });
Adam Cohen19f37922012-03-21 11:59:11 -07002155 mShakeAnimators.put(child, this);
2156 va.start();
2157 }
2158
Adam Cohend024f982012-05-23 18:26:45 -07002159 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002160 if (a != null) {
2161 a.cancel();
2162 }
Adam Cohen19f37922012-03-21 11:59:11 -07002163 }
Adam Cohene7587d22012-05-24 18:50:02 -07002164
Adam Cohen091440a2015-03-18 14:16:05 -07002165 @Thunk void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002166 if (a != null) {
2167 a.cancel();
2168 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002169
Sunny Goyal5d2fc322015-07-06 22:52:49 -07002170 a = new LauncherViewPropertyAnimator(child)
2171 .scaleX(getChildrenScale())
2172 .scaleY(getChildrenScale())
2173 .translationX(0)
2174 .translationY(0)
2175 .setDuration(REORDER_ANIMATION_DURATION);
2176 a.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2177 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07002178 }
Adam Cohen19f37922012-03-21 11:59:11 -07002179 }
2180
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002181 private void completeAndClearReorderPreviewAnimations() {
2182 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002183 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002184 }
2185 mShakeAnimators.clear();
2186 }
2187
Adam Cohen482ed822012-03-02 14:15:13 -08002188 private void commitTempPlacement() {
2189 for (int i = 0; i < mCountX; i++) {
2190 for (int j = 0; j < mCountY; j++) {
2191 mOccupied[i][j] = mTmpOccupied[i][j];
2192 }
2193 }
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002194
2195 long screenId = mLauncher.getWorkspace().getIdForScreen(this);
2196 int container = Favorites.CONTAINER_DESKTOP;
2197
2198 if (mLauncher.isHotseatLayout(this)) {
2199 screenId = -1;
2200 container = Favorites.CONTAINER_HOTSEAT;
2201 }
2202
Michael Jurkaa52570f2012-03-20 03:18:20 -07002203 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002204 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002205 View child = mShortcutsAndWidgets.getChildAt(i);
2206 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2207 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002208 // We do a null check here because the item info can be null in the case of the
2209 // AllApps button in the hotseat.
2210 if (info != null) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002211 final boolean requiresDbUpdate = (info.cellX != lp.tmpCellX
2212 || info.cellY != lp.tmpCellY || info.spanX != lp.cellHSpan
2213 || info.spanY != lp.cellVSpan);
2214
Adam Cohen2acce882012-03-28 19:03:19 -07002215 info.cellX = lp.cellX = lp.tmpCellX;
2216 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002217 info.spanX = lp.cellHSpan;
2218 info.spanY = lp.cellVSpan;
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002219
2220 if (requiresDbUpdate) {
2221 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId,
2222 info.cellX, info.cellY, info.spanX, info.spanY);
2223 }
Adam Cohen2acce882012-03-28 19:03:19 -07002224 }
Adam Cohen482ed822012-03-02 14:15:13 -08002225 }
2226 }
2227
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002228 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002229 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002230 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002231 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002232 lp.useTmpCoords = useTempCoords;
2233 }
2234 }
2235
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002236 private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002237 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2238 int[] result = new int[2];
2239 int[] resultSpan = new int[2];
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002240 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
Adam Cohen482ed822012-03-02 14:15:13 -08002241 resultSpan);
2242 if (result[0] >= 0 && result[1] >= 0) {
2243 copyCurrentStateToSolution(solution, false);
2244 solution.dragViewX = result[0];
2245 solution.dragViewY = result[1];
2246 solution.dragViewSpanX = resultSpan[0];
2247 solution.dragViewSpanY = resultSpan[1];
2248 solution.isSolution = true;
2249 } else {
2250 solution.isSolution = false;
2251 }
2252 return solution;
2253 }
2254
2255 public void prepareChildForDrag(View child) {
2256 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002257 }
2258
Adam Cohen19f37922012-03-21 11:59:11 -07002259 /* This seems like it should be obvious and straight-forward, but when the direction vector
2260 needs to match with the notion of the dragView pushing other views, we have to employ
2261 a slightly more subtle notion of the direction vector. The question is what two points is
2262 the vector between? The center of the dragView and its desired destination? Not quite, as
2263 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2264 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2265 or right, which helps make pushing feel right.
2266 */
2267 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2268 int spanY, View dragView, int[] resultDirection) {
2269 int[] targetDestination = new int[2];
2270
2271 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2272 Rect dragRect = new Rect();
2273 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2274 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2275
2276 Rect dropRegionRect = new Rect();
2277 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2278 dragView, dropRegionRect, mIntersectingViews);
2279
2280 int dropRegionSpanX = dropRegionRect.width();
2281 int dropRegionSpanY = dropRegionRect.height();
2282
2283 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2284 dropRegionRect.height(), dropRegionRect);
2285
2286 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2287 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2288
2289 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2290 deltaX = 0;
2291 }
2292 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2293 deltaY = 0;
2294 }
2295
2296 if (deltaX == 0 && deltaY == 0) {
2297 // No idea what to do, give a random direction.
2298 resultDirection[0] = 1;
2299 resultDirection[1] = 0;
2300 } else {
2301 computeDirectionVector(deltaX, deltaY, resultDirection);
2302 }
2303 }
2304
2305 // For a given cell and span, fetch the set of views intersecting the region.
2306 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2307 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2308 if (boundingRect != null) {
2309 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2310 }
2311 intersectingViews.clear();
2312 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2313 Rect r1 = new Rect();
2314 final int count = mShortcutsAndWidgets.getChildCount();
2315 for (int i = 0; i < count; i++) {
2316 View child = mShortcutsAndWidgets.getChildAt(i);
2317 if (child == dragView) continue;
2318 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2319 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2320 if (Rect.intersects(r0, r1)) {
2321 mIntersectingViews.add(child);
2322 if (boundingRect != null) {
2323 boundingRect.union(r1);
2324 }
2325 }
2326 }
2327 }
2328
2329 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2330 View dragView, int[] result) {
2331 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2332 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2333 mIntersectingViews);
2334 return !mIntersectingViews.isEmpty();
2335 }
2336
2337 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002338 completeAndClearReorderPreviewAnimations();
2339 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2340 final int count = mShortcutsAndWidgets.getChildCount();
2341 for (int i = 0; i < count; i++) {
2342 View child = mShortcutsAndWidgets.getChildAt(i);
2343 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2344 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2345 lp.tmpCellX = lp.cellX;
2346 lp.tmpCellY = lp.cellY;
2347 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2348 0, false, false);
2349 }
Adam Cohen19f37922012-03-21 11:59:11 -07002350 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002351 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002352 }
Adam Cohen19f37922012-03-21 11:59:11 -07002353 }
2354
Adam Cohenbebf0422012-04-11 18:06:28 -07002355 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2356 View dragView, int[] direction, boolean commit) {
2357 int[] pixelXY = new int[2];
2358 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2359
2360 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002361 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002362 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2363
2364 setUseTempCoords(true);
2365 if (swapSolution != null && swapSolution.isSolution) {
2366 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2367 // committing anything or animating anything as we just want to determine if a solution
2368 // exists
2369 copySolutionToTempState(swapSolution, dragView);
2370 setItemPlacementDirty(true);
2371 animateItemsToSolution(swapSolution, dragView, commit);
2372
2373 if (commit) {
2374 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002375 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002376 setItemPlacementDirty(false);
2377 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002378 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
2379 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002380 }
2381 mShortcutsAndWidgets.requestLayout();
2382 }
2383 return swapSolution.isSolution;
2384 }
2385
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002386 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002387 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002388 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002389 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002390
2391 if (resultSpan == null) {
2392 resultSpan = new int[2];
2393 }
2394
Adam Cohen19f37922012-03-21 11:59:11 -07002395 // When we are checking drop validity or actually dropping, we don't recompute the
2396 // direction vector, since we want the solution to match the preview, and it's possible
2397 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002398 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2399 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002400 mDirectionVector[0] = mPreviousReorderDirection[0];
2401 mDirectionVector[1] = mPreviousReorderDirection[1];
2402 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002403 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2404 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2405 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002406 }
2407 } else {
2408 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2409 mPreviousReorderDirection[0] = mDirectionVector[0];
2410 mPreviousReorderDirection[1] = mDirectionVector[1];
2411 }
2412
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002413 // Find a solution involving pushing / displacing any items in the way
2414 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002415 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2416
2417 // We attempt the approach which doesn't shuffle views at all
2418 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2419 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2420
2421 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002422
2423 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2424 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002425 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2426 finalSolution = swapSolution;
2427 } else if (noShuffleSolution.isSolution) {
2428 finalSolution = noShuffleSolution;
2429 }
2430
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002431 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002432 if (finalSolution != null) {
Adam Cohenfe692872013-12-11 14:47:23 -08002433 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
2434 ReorderPreviewAnimation.MODE_HINT);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002435 result[0] = finalSolution.dragViewX;
2436 result[1] = finalSolution.dragViewY;
2437 resultSpan[0] = finalSolution.dragViewSpanX;
2438 resultSpan[1] = finalSolution.dragViewSpanY;
2439 } else {
2440 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2441 }
2442 return result;
2443 }
2444
Adam Cohen482ed822012-03-02 14:15:13 -08002445 boolean foundSolution = true;
2446 if (!DESTRUCTIVE_REORDER) {
2447 setUseTempCoords(true);
2448 }
2449
2450 if (finalSolution != null) {
2451 result[0] = finalSolution.dragViewX;
2452 result[1] = finalSolution.dragViewY;
2453 resultSpan[0] = finalSolution.dragViewSpanX;
2454 resultSpan[1] = finalSolution.dragViewSpanY;
2455
2456 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2457 // committing anything or animating anything as we just want to determine if a solution
2458 // exists
2459 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2460 if (!DESTRUCTIVE_REORDER) {
2461 copySolutionToTempState(finalSolution, dragView);
2462 }
2463 setItemPlacementDirty(true);
2464 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2465
Adam Cohen19f37922012-03-21 11:59:11 -07002466 if (!DESTRUCTIVE_REORDER &&
2467 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002468 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002469 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002470 setItemPlacementDirty(false);
2471 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002472 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
2473 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002474 }
2475 }
2476 } else {
2477 foundSolution = false;
2478 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2479 }
2480
2481 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2482 setUseTempCoords(false);
2483 }
Adam Cohen482ed822012-03-02 14:15:13 -08002484
Michael Jurkaa52570f2012-03-20 03:18:20 -07002485 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002486 return result;
2487 }
2488
Adam Cohen19f37922012-03-21 11:59:11 -07002489 void setItemPlacementDirty(boolean dirty) {
2490 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002491 }
Adam Cohen19f37922012-03-21 11:59:11 -07002492 boolean isItemPlacementDirty() {
2493 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002494 }
2495
Adam Cohen091440a2015-03-18 14:16:05 -07002496 @Thunk class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002497 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohenf3900c22012-11-16 18:28:11 -08002498 private HashMap<View, CellAndSpan> savedMap = new HashMap<View, CellAndSpan>();
2499 ArrayList<View> sortedViews = new ArrayList<View>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002500 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002501 boolean isSolution = false;
2502 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2503
Adam Cohenf3900c22012-11-16 18:28:11 -08002504 void save() {
2505 // Copy current state into savedMap
2506 for (View v: map.keySet()) {
2507 map.get(v).copy(savedMap.get(v));
2508 }
2509 }
2510
2511 void restore() {
2512 // Restore current state from savedMap
2513 for (View v: savedMap.keySet()) {
2514 savedMap.get(v).copy(map.get(v));
2515 }
2516 }
2517
2518 void add(View v, CellAndSpan cs) {
2519 map.put(v, cs);
2520 savedMap.put(v, new CellAndSpan());
2521 sortedViews.add(v);
2522 }
2523
Adam Cohen482ed822012-03-02 14:15:13 -08002524 int area() {
2525 return dragViewSpanX * dragViewSpanY;
2526 }
Adam Cohen8baab352012-03-20 17:39:21 -07002527 }
2528
2529 private class CellAndSpan {
2530 int x, y;
2531 int spanX, spanY;
2532
Adam Cohenf3900c22012-11-16 18:28:11 -08002533 public CellAndSpan() {
2534 }
2535
2536 public void copy(CellAndSpan copy) {
2537 copy.x = x;
2538 copy.y = y;
2539 copy.spanX = spanX;
2540 copy.spanY = spanY;
2541 }
2542
Adam Cohen8baab352012-03-20 17:39:21 -07002543 public CellAndSpan(int x, int y, int spanX, int spanY) {
2544 this.x = x;
2545 this.y = y;
2546 this.spanX = spanX;
2547 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002548 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002549
2550 public String toString() {
2551 return "(" + x + ", " + y + ": " + spanX + ", " + spanY + ")";
2552 }
2553
Adam Cohen482ed822012-03-02 14:15:13 -08002554 }
2555
Adam Cohendf035382011-04-11 17:22:04 -07002556 /**
Adam Cohendf035382011-04-11 17:22:04 -07002557 * Find a starting cell position that will fit the given bounds nearest the requested
2558 * cell location. Uses Euclidean distance to score multiple vacant areas.
2559 *
2560 * @param pixelX The X location at which you want to search for a vacant area.
2561 * @param pixelY The Y location at which you want to search for a vacant area.
2562 * @param spanX Horizontal span of the object.
2563 * @param spanY Vertical span of the object.
2564 * @param ignoreView Considers space occupied by this view as unoccupied
2565 * @param result Previously returned value to possibly recycle.
2566 * @return The X, Y cell of a vacant area that can contain this object,
2567 * nearest the requested location.
2568 */
Adam Cohenf9c184a2016-01-15 16:47:43 -08002569 public int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002570 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002571 }
2572
Michael Jurka0280c3b2010-09-17 15:00:07 -07002573 boolean existsEmptyCell() {
2574 return findCellForSpan(null, 1, 1);
2575 }
2576
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002577 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002578 * Finds the upper-left coordinate of the first rectangle in the grid that can
2579 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2580 * then this method will only return coordinates for rectangles that contain the cell
2581 * (intersectX, intersectY)
2582 *
2583 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2584 * can be found.
2585 * @param spanX The horizontal span of the cell we want to find.
2586 * @param spanY The vertical span of the cell we want to find.
2587 *
2588 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002589 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002590 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Michael Jurka28750fb2010-09-24 17:43:49 -07002591 boolean foundCell = false;
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002592 final int endX = mCountX - (spanX - 1);
2593 final int endY = mCountY - (spanY - 1);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002594
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002595 for (int y = 0; y < endY && !foundCell; y++) {
2596 inner:
2597 for (int x = 0; x < endX; x++) {
2598 for (int i = 0; i < spanX; i++) {
2599 for (int j = 0; j < spanY; j++) {
2600 if (mOccupied[x + i][y + j]) {
2601 // small optimization: we can skip to after the column we just found
2602 // an occupied cell
2603 x += i;
2604 continue inner;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002605 }
2606 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002607 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002608 if (cellXY != null) {
2609 cellXY[0] = x;
2610 cellXY[1] = y;
2611 }
2612 foundCell = true;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002613 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002614 }
2615 }
2616
Michael Jurka28750fb2010-09-24 17:43:49 -07002617 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002618 }
2619
2620 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002621 * A drag event has begun over this layout.
2622 * It may have begun over this layout (in which case onDragChild is called first),
2623 * or it may have begun on another layout.
2624 */
2625 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002626 mDragging = true;
2627 }
2628
2629 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002630 * Called when drag has left this CellLayout or has been completed (successfully or not)
2631 */
2632 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002633 // This can actually be called when we aren't in a drag, e.g. when adding a new
2634 // item to this layout via the customize drawer.
2635 // Guard against that case.
2636 if (mDragging) {
2637 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002638 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002639
2640 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002641 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002642 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2643 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002644 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002645 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002646 }
2647
2648 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002649 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002650 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002651 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002652 *
2653 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002654 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002655 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002656 if (child != null) {
2657 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002658 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002659 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002660 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002661 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002662 }
2663
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002664 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002665 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002666 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002667 * @param cellX X coordinate of upper left corner expressed as a cell position
2668 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002669 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002670 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002671 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002672 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002673 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002674 final int cellWidth = mCellWidth;
2675 final int cellHeight = mCellHeight;
2676 final int widthGap = mWidthGap;
2677 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002678
Winson Chung4b825dcd2011-06-19 12:41:22 -07002679 final int hStartPadding = getPaddingLeft();
2680 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002681
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002682 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2683 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2684
2685 int x = hStartPadding + cellX * (cellWidth + widthGap);
2686 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002687
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002688 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002689 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002690
Michael Jurka0280c3b2010-09-17 15:00:07 -07002691 private void clearOccupiedCells() {
2692 for (int x = 0; x < mCountX; x++) {
2693 for (int y = 0; y < mCountY; y++) {
2694 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002695 }
2696 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002697 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002698
Adam Cohend4844c32011-02-18 19:25:06 -08002699 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002700 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002701 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002702 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002703 }
2704
Adam Cohend4844c32011-02-18 19:25:06 -08002705 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002706 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002707 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002708 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002709 }
2710
Adam Cohen482ed822012-03-02 14:15:13 -08002711 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2712 boolean value) {
2713 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002714 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2715 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002716 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002717 }
2718 }
2719 }
2720
Adam Cohen2801caf2011-05-13 20:57:39 -07002721 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002722 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002723 (Math.max((mCountX - 1), 0) * mWidthGap);
2724 }
2725
2726 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002727 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002728 (Math.max((mCountY - 1), 0) * mHeightGap);
2729 }
2730
Michael Jurka66d72172011-04-12 16:29:25 -07002731 public boolean isOccupied(int x, int y) {
2732 if (x < mCountX && y < mCountY) {
2733 return mOccupied[x][y];
2734 } else {
2735 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2736 }
2737 }
2738
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002739 @Override
2740 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2741 return new CellLayout.LayoutParams(getContext(), attrs);
2742 }
2743
2744 @Override
2745 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2746 return p instanceof CellLayout.LayoutParams;
2747 }
2748
2749 @Override
2750 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2751 return new CellLayout.LayoutParams(p);
2752 }
2753
2754 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2755 /**
2756 * Horizontal location of the item in the grid.
2757 */
2758 @ViewDebug.ExportedProperty
2759 public int cellX;
2760
2761 /**
2762 * Vertical location of the item in the grid.
2763 */
2764 @ViewDebug.ExportedProperty
2765 public int cellY;
2766
2767 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002768 * Temporary horizontal location of the item in the grid during reorder
2769 */
2770 public int tmpCellX;
2771
2772 /**
2773 * Temporary vertical location of the item in the grid during reorder
2774 */
2775 public int tmpCellY;
2776
2777 /**
2778 * Indicates that the temporary coordinates should be used to layout the items
2779 */
2780 public boolean useTmpCoords;
2781
2782 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002783 * Number of cells spanned horizontally by the item.
2784 */
2785 @ViewDebug.ExportedProperty
2786 public int cellHSpan;
2787
2788 /**
2789 * Number of cells spanned vertically by the item.
2790 */
2791 @ViewDebug.ExportedProperty
2792 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002793
Adam Cohen1b607ed2011-03-03 17:26:50 -08002794 /**
2795 * Indicates whether the item will set its x, y, width and height parameters freely,
2796 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2797 */
Adam Cohend4844c32011-02-18 19:25:06 -08002798 public boolean isLockedToGrid = true;
2799
Adam Cohen482ed822012-03-02 14:15:13 -08002800 /**
Adam Cohenec40b2b2013-07-23 15:52:40 -07002801 * Indicates that this item should use the full extents of its parent.
2802 */
2803 public boolean isFullscreen = false;
2804
2805 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002806 * Indicates whether this item can be reordered. Always true except in the case of the
2807 * the AllApps button.
2808 */
2809 public boolean canReorder = true;
2810
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002811 // X coordinate of the view in the layout.
2812 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002813 public int x;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002814 // Y coordinate of the view in the layout.
2815 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002816 public int y;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002817
Romain Guy84f296c2009-11-04 15:00:44 -08002818 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002819
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002820 public LayoutParams(Context c, AttributeSet attrs) {
2821 super(c, attrs);
2822 cellHSpan = 1;
2823 cellVSpan = 1;
2824 }
2825
2826 public LayoutParams(ViewGroup.LayoutParams source) {
2827 super(source);
2828 cellHSpan = 1;
2829 cellVSpan = 1;
2830 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002831
2832 public LayoutParams(LayoutParams source) {
2833 super(source);
2834 this.cellX = source.cellX;
2835 this.cellY = source.cellY;
2836 this.cellHSpan = source.cellHSpan;
2837 this.cellVSpan = source.cellVSpan;
2838 }
2839
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002840 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002841 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002842 this.cellX = cellX;
2843 this.cellY = cellY;
2844 this.cellHSpan = cellHSpan;
2845 this.cellVSpan = cellVSpan;
2846 }
2847
Adam Cohen2374abf2013-04-16 14:56:57 -07002848 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap,
2849 boolean invertHorizontally, int colCount) {
Adam Cohend4844c32011-02-18 19:25:06 -08002850 if (isLockedToGrid) {
2851 final int myCellHSpan = cellHSpan;
2852 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002853 int myCellX = useTmpCoords ? tmpCellX : cellX;
2854 int myCellY = useTmpCoords ? tmpCellY : cellY;
2855
2856 if (invertHorizontally) {
2857 myCellX = colCount - myCellX - cellHSpan;
2858 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002859
Adam Cohend4844c32011-02-18 19:25:06 -08002860 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2861 leftMargin - rightMargin;
2862 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2863 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002864 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2865 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002866 }
2867 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002868
Winson Chungaafa03c2010-06-11 17:34:16 -07002869 public String toString() {
2870 return "(" + this.cellX + ", " + this.cellY + ")";
2871 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002872
2873 public void setWidth(int width) {
2874 this.width = width;
2875 }
2876
2877 public int getWidth() {
2878 return width;
2879 }
2880
2881 public void setHeight(int height) {
2882 this.height = height;
2883 }
2884
2885 public int getHeight() {
2886 return height;
2887 }
2888
2889 public void setX(int x) {
2890 this.x = x;
2891 }
2892
2893 public int getX() {
2894 return x;
2895 }
2896
2897 public void setY(int y) {
2898 this.y = y;
2899 }
2900
2901 public int getY() {
2902 return y;
2903 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002904 }
2905
Michael Jurka0280c3b2010-09-17 15:00:07 -07002906 // This class stores info for two purposes:
2907 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2908 // its spanX, spanY, and the screen it is on
2909 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2910 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2911 // the CellLayout that was long clicked
Sunny Goyal83a8f042015-05-19 12:52:12 -07002912 public static final class CellInfo {
Adam Cohenf9c184a2016-01-15 16:47:43 -08002913 public View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002914 int cellX = -1;
2915 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002916 int spanX;
2917 int spanY;
Adam Cohendcd297f2013-06-18 13:13:40 -07002918 long screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07002919 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002920
Sunny Goyal83a8f042015-05-19 12:52:12 -07002921 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002922 cell = v;
2923 cellX = info.cellX;
2924 cellY = info.cellY;
2925 spanX = info.spanX;
2926 spanY = info.spanY;
2927 screenId = info.screenId;
2928 container = info.container;
2929 }
2930
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002931 @Override
2932 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002933 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2934 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002935 }
2936 }
Michael Jurkad771c962011-08-09 15:00:48 -07002937
Sunny Goyala9116722015-04-29 13:55:58 -07002938 public boolean findVacantCell(int spanX, int spanY, int[] outXY) {
2939 return Utilities.findVacantCell(outXY, spanX, spanY, mCountX, mCountY, mOccupied);
2940 }
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002941
Tony Wickham86930612015-09-09 13:50:40 -07002942 /**
2943 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2944 * if necessary).
2945 */
2946 public boolean hasReorderSolution(ItemInfo itemInfo) {
2947 int[] cellPoint = new int[2];
2948 // Check for a solution starting at every cell.
2949 for (int cellX = 0; cellX < getCountX(); cellX++) {
2950 for (int cellY = 0; cellY < getCountY(); cellY++) {
2951 cellToPoint(cellX, cellY, cellPoint);
2952 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2953 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2954 true, new ItemConfiguration()).isSolution) {
2955 return true;
2956 }
2957 }
2958 }
2959 return false;
2960 }
2961
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002962 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
2963 int x2 = x + spanX - 1;
2964 int y2 = y + spanY - 1;
2965 if (x < 0 || y < 0 || x2 >= mCountX || y2 >= mCountY) {
2966 return false;
2967 }
2968 for (int i = x; i <= x2; i++) {
2969 for (int j = y; j <= y2; j++) {
2970 if (mOccupied[i][j]) {
2971 return false;
2972 }
2973 }
2974 }
2975
2976 return true;
2977 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002978}