blob: 29812fda9f78f910e2b0ba72b6a7f47012729209 [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
Sunny Goyaleaf7a952020-07-29 16:54:20 -070019import static android.animation.ValueAnimator.areAnimatorsEnabled;
20
Sunny Goyalf0b6db72018-08-13 16:10:14 -070021import static com.android.launcher3.anim.Interpolators.DEACCEL_1_5;
22
Joe Onorato4be866d2010-10-10 11:26:02 -070023import android.animation.Animator;
Michael Jurka629758f2012-06-14 16:18:21 -070024import android.animation.AnimatorListenerAdapter;
Sunny Goyal849c6a22018-08-08 16:33:46 -070025import android.animation.ObjectAnimator;
Chet Haase00397b12010-10-07 11:13:10 -070026import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070027import android.animation.ValueAnimator;
28import android.animation.ValueAnimator.AnimatorUpdateListener;
Sunny Goyal726bee72018-03-05 12:54:24 -080029import android.annotation.SuppressLint;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080030import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040031import android.content.res.Resources;
Sunny Goyalc13403c2016-11-18 23:44:48 -080032import android.content.res.TypedArray;
Joe Onorato4be866d2010-10-10 11:26:02 -070033import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070034import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080035import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070036import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070037import android.graphics.Point;
Adam Cohend9162062020-03-24 16:35:35 -070038import android.graphics.PointF;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080040import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070041import android.graphics.drawable.Drawable;
Adam Cohen1462de32012-07-24 22:34:36 -070042import android.os.Parcelable;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -070043import android.util.ArrayMap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080044import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070045import android.util.Log;
Sunny Goyal849c6a22018-08-08 16:33:46 -070046import android.util.Property;
Adam Cohen1462de32012-07-24 22:34:36 -070047import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080048import android.view.MotionEvent;
49import android.view.View;
50import android.view.ViewDebug;
51import android.view.ViewGroup;
Adam Cohenc9735cf2015-01-23 16:11:55 -080052import android.view.accessibility.AccessibilityEvent;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070053
vadimt04f356f2019-02-14 18:46:36 -080054import androidx.annotation.IntDef;
55import androidx.core.view.ViewCompat;
56
Sunny Goyalaa8ef112015-06-12 20:04:41 -070057import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyale9b651e2015-04-24 11:44:51 -070058import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070059import com.android.launcher3.anim.Interpolators;
Sunny Goyal3d706ad2017-03-06 16:56:39 -080060import com.android.launcher3.config.FeatureFlags;
Adam Cohen65086992020-02-19 08:40:49 -080061import com.android.launcher3.dragndrop.DraggableView;
Jon Mirandaa0233f72017-06-22 18:34:45 -070062import com.android.launcher3.folder.PreviewBackground;
Sunny Goyal06e21a22016-08-11 16:02:02 -070063import com.android.launcher3.graphics.DragPreviewProvider;
Sunny Goyale396abf2020-04-06 15:11:17 -070064import com.android.launcher3.model.data.ItemInfo;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -070065import com.android.launcher3.util.CellAndSpan;
66import com.android.launcher3.util.GridOccupancy;
Sunny Goyale2fd14b2015-08-27 17:45:46 -070067import com.android.launcher3.util.ParcelableSparseArray;
Sunny Goyal9b29ca52017-02-17 10:39:44 -080068import com.android.launcher3.util.Themes;
Adam Cohen091440a2015-03-18 14:16:05 -070069import com.android.launcher3.util.Thunk;
Sunny Goyalab770a12018-11-14 15:17:26 -080070import com.android.launcher3.views.ActivityContext;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070071
Sunny Goyalc13403c2016-11-18 23:44:48 -080072import java.lang.annotation.Retention;
73import java.lang.annotation.RetentionPolicy;
Adam Cohen69ce2e52011-07-03 19:25:21 -070074import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070075import java.util.Arrays;
Adam Cohenf3900c22012-11-16 18:28:11 -080076import java.util.Collections;
77import java.util.Comparator;
Adam Cohend41fbf52012-02-16 23:53:59 -080078import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070079
Sunny Goyalc4d32012020-04-03 17:10:11 -070080public class CellLayout extends ViewGroup {
Tony Wickhama0628cc2015-10-14 15:23:04 -070081 private static final String TAG = "CellLayout";
82 private static final boolean LOGD = false;
Winson Chungaafa03c2010-06-11 17:34:16 -070083
Sunny Goyalab770a12018-11-14 15:17:26 -080084 protected final ActivityContext mActivity;
Sunny Goyal4ffec482016-02-09 11:28:52 -080085 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070086 @Thunk int mCellWidth;
Sunny Goyal4ffec482016-02-09 11:28:52 -080087 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070088 @Thunk int mCellHeight;
Winson Chung11a1a532013-09-13 11:14:45 -070089 private int mFixedCellWidth;
90 private int mFixedCellHeight;
Jon Miranda228877d2021-02-09 11:05:00 -050091 @ViewDebug.ExportedProperty(category = "launcher")
92 private final int mBorderSpacing;
Winson Chungaafa03c2010-06-11 17:34:16 -070093
Sunny Goyal4ffec482016-02-09 11:28:52 -080094 @ViewDebug.ExportedProperty(category = "launcher")
Sunny Goyalff4ba2d2016-04-02 14:12:34 -070095 private int mCountX;
Sunny Goyal4ffec482016-02-09 11:28:52 -080096 @ViewDebug.ExportedProperty(category = "launcher")
Sunny Goyalff4ba2d2016-04-02 14:12:34 -070097 private int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098
Adam Cohen917e3882013-10-31 15:03:35 -070099 private boolean mDropPending = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800100
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700101 // These are temporary variables to prevent having to allocate a new object just to
102 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Adam Cohen091440a2015-03-18 14:16:05 -0700103 @Thunk final int[] mTmpPoint = new int[2];
Sunny Goyal2805e632015-05-20 15:35:32 -0700104 @Thunk final int[] mTempLocation = new int[2];
Adam Cohend9162062020-03-24 16:35:35 -0700105 final PointF mTmpPointF = new PointF();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700106
Adam Cohen65086992020-02-19 08:40:49 -0800107 // Used to visualize / debug the Grid of the CellLayout
108 private static final boolean VISUALIZE_GRID = false;
109 private Rect mVisualizeGridRect = new Rect();
110 private Paint mVisualizeGridPaint = new Paint();
111
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700112 private GridOccupancy mOccupied;
113 private GridOccupancy mTmpOccupied;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800114
Michael Jurkadee05892010-07-27 10:01:56 -0700115 private OnTouchListener mInterceptTouchListener;
116
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800117 private final ArrayList<DelegatedCellDrawing> mDelegatedCellDrawings = new ArrayList<>();
Jon Mirandaa0233f72017-06-22 18:34:45 -0700118 final PreviewBackground mFolderLeaveBehind = new PreviewBackground();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700119
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800120 private static final int[] BACKGROUND_STATE_ACTIVE = new int[] { android.R.attr.state_active };
Sunny Goyale15e2a82017-12-15 13:05:42 -0800121 private static final int[] BACKGROUND_STATE_DEFAULT = EMPTY_STATE_SET;
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800122 private final Drawable mBackground;
Sunny Goyal2805e632015-05-20 15:35:32 -0700123
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700124 // These values allow a fixed measurement to be set on the CellLayout.
125 private int mFixedWidth = -1;
126 private int mFixedHeight = -1;
127
Michael Jurka33945b22010-12-21 18:19:38 -0800128 // If we're actively dragging something over this screen, mIsDragOverlapping is true
129 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700130
Winson Chung150fbab2010-09-29 17:14:26 -0700131 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700132 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700133 @Thunk final Rect[] mDragOutlines = new Rect[4];
134 @Thunk final float[] mDragOutlineAlphas = new float[mDragOutlines.length];
135 private final InterruptibleInOutAnimator[] mDragOutlineAnims =
Joe Onorato4be866d2010-10-10 11:26:02 -0700136 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700137
138 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700139 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700140 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700141
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700142 @Thunk final ArrayMap<LayoutParams, Animator> mReorderAnimators = new ArrayMap<>();
Adam Cohend9162062020-03-24 16:35:35 -0700143 @Thunk final ArrayMap<Reorderable, ReorderPreviewAnimation> mShakeAnimators = new ArrayMap<>();
Adam Cohen19f37922012-03-21 11:59:11 -0700144
145 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700146
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700147 // When a drag operation is in progress, holds the nearest cell to the touch point
148 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800149
Joe Onorato4be866d2010-10-10 11:26:02 -0700150 private boolean mDragging = false;
151
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700152 private final TimeInterpolator mEaseOutInterpolator;
153 private final ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700154
Sunny Goyalc13403c2016-11-18 23:44:48 -0800155 @Retention(RetentionPolicy.SOURCE)
156 @IntDef({WORKSPACE, HOTSEAT, FOLDER})
157 public @interface ContainerType{}
158 public static final int WORKSPACE = 0;
159 public static final int HOTSEAT = 1;
160 public static final int FOLDER = 2;
161
162 @ContainerType private final int mContainerType;
163
Jon Mirandab28c4fc2017-06-20 10:58:36 -0700164 private final float mChildScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800165
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800166 public static final int MODE_SHOW_REORDER_HINT = 0;
167 public static final int MODE_DRAG_OVER = 1;
168 public static final int MODE_ON_DROP = 2;
169 public static final int MODE_ON_DROP_EXTERNAL = 3;
170 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700171 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800172 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
173
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800174 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700175 private static final int REORDER_ANIMATION_DURATION = 150;
Sunny Goyalc13403c2016-11-18 23:44:48 -0800176 @Thunk final float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700177
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700178 private final ArrayList<View> mIntersectingViews = new ArrayList<>();
179 private final Rect mOccupiedRect = new Rect();
180 private final int[] mDirectionVector = new int[2];
181 final int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700182 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800183
Sunny Goyal2805e632015-05-20 15:35:32 -0700184 private final Rect mTempRect = new Rect();
Winson Chung3a6e7f32013-10-09 15:50:52 -0700185
Sunny Goyal73b5a272019-12-09 14:55:56 -0800186 private static final Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700187
Adam Cohenc9735cf2015-01-23 16:11:55 -0800188 // Related to accessible drag and drop
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700189 DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800190
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800191 public CellLayout(Context context) {
192 this(context, null);
193 }
194
195 public CellLayout(Context context, AttributeSet attrs) {
196 this(context, attrs, 0);
197 }
198
199 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
200 super(context, attrs, defStyle);
Sunny Goyalc13403c2016-11-18 23:44:48 -0800201 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
202 mContainerType = a.getInteger(R.styleable.CellLayout_containerType, WORKSPACE);
203 a.recycle();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700204
205 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
206 // the user where a dragged item will land when dropped.
207 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800208 setClipToPadding(false);
Sunny Goyalab770a12018-11-14 15:17:26 -0800209 mActivity = ActivityContext.lookupContext(context);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700210
Sunny Goyalc4d32012020-04-03 17:10:11 -0700211 DeviceProfile grid = mActivity.getDeviceProfile();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212
Jon Miranda228877d2021-02-09 11:05:00 -0500213 mBorderSpacing = grid.cellLayoutBorderSpacingPx;
Winson Chung11a1a532013-09-13 11:14:45 -0700214 mCellWidth = mCellHeight = -1;
Nilesh Agrawal5f7099a2014-01-02 15:54:57 -0800215 mFixedCellWidth = mFixedCellHeight = -1;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700216
217 mCountX = grid.inv.numColumns;
218 mCountY = grid.inv.numRows;
219 mOccupied = new GridOccupancy(mCountX, mCountY);
220 mTmpOccupied = new GridOccupancy(mCountX, mCountY);
221
Adam Cohen5b53f292012-03-29 14:30:35 -0700222 mPreviousReorderDirection[0] = INVALID_DIRECTION;
223 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800224
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800225 mFolderLeaveBehind.mDelegateCellX = -1;
226 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenefca0272016-02-24 19:19:06 -0800227
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800228 setAlwaysDrawnWithCacheEnabled(false);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700229 final Resources res = getResources();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700230
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800231 mBackground = res.getDrawable(R.drawable.bg_celllayout);
Sunny Goyal2805e632015-05-20 15:35:32 -0700232 mBackground.setCallback(this);
Sunny Goyalaeb16432017-10-16 11:46:41 -0700233 mBackground.setAlpha(0);
Michael Jurka33945b22010-12-21 18:19:38 -0800234
Sunny Goyalc13403c2016-11-18 23:44:48 -0800235 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE * grid.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700236
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700237 // Initialize the data structures used for the drag visualization.
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -0700238 mEaseOutInterpolator = Interpolators.DEACCEL_2_5; // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700239 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700240 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800241 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700242 }
Mario Bertschler54ba6012017-06-08 10:53:53 -0700243 mDragOutlinePaint.setColor(Themes.getAttrColor(context, R.attr.workspaceTextColor));
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700244
245 // When dragging things around the home screens, we show a green outline of
246 // where the item will land. The outlines gradually fade out, leaving a trail
247 // behind the drag path.
248 // Set up all the animations that are used to implement this fading.
249 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700250 final float fromAlphaValue = 0;
251 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700252
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700253 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700254
255 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700256 final InterruptibleInOutAnimator anim =
Sunny Goyal849c6a22018-08-08 16:33:46 -0700257 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700258 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700259 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700260 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700261 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700262 final Bitmap outline = (Bitmap)anim.getTag();
263
264 // If an animation is started and then stopped very quickly, we can still
265 // get spurious updates we've cleared the tag. Guard against this.
266 if (outline == null) {
Tony Wickhama0628cc2015-10-14 15:23:04 -0700267 if (LOGD) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700268 Object val = animation.getAnimatedValue();
269 Log.d(TAG, "anim " + thisIndex + " update: " + val +
270 ", isStopped " + anim.isStopped());
271 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700272 // Try to prevent it from continuing to run
273 animation.cancel();
274 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700275 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800276 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700277 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700278 }
279 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700280 // The animation holds a reference to the drag outline bitmap as long is it's
281 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700282 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700283 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700284 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700285 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700286 anim.setTag(null);
287 }
288 }
289 });
290 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700291 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700292
Sunny Goyalc13403c2016-11-18 23:44:48 -0800293 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context, mContainerType);
Jon Miranda228877d2021-02-09 11:05:00 -0500294 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
295 mBorderSpacing);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700296 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700297 }
298
Sunny Goyal9b180102020-03-11 10:02:29 -0700299 /**
300 * Sets or clears a delegate used for accessible drag and drop
301 */
302 public void setDragAndDropAccessibilityDelegate(DragAndDropAccessibilityDelegate delegate) {
303 setOnClickListener(delegate);
Sunny Goyal9b180102020-03-11 10:02:29 -0700304 ViewCompat.setAccessibilityDelegate(this, delegate);
305
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700306 mTouchHelper = delegate;
307 int accessibilityFlag = mTouchHelper != null
Sunny Goyal9b180102020-03-11 10:02:29 -0700308 ? IMPORTANT_FOR_ACCESSIBILITY_YES : IMPORTANT_FOR_ACCESSIBILITY_NO;
309 setImportantForAccessibility(accessibilityFlag);
310 getShortcutsAndWidgets().setImportantForAccessibility(accessibilityFlag);
Adam Cohenc9735cf2015-01-23 16:11:55 -0800311
312 // Invalidate the accessibility hierarchy
313 if (getParent() != null) {
314 getParent().notifySubtreeAccessibilityStateChanged(
315 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
316 }
317 }
318
Sunny Goyala4647b62021-02-02 13:45:34 -0800319 /**
320 * Returns the currently set accessibility delegate
321 */
322 public DragAndDropAccessibilityDelegate getDragAndDropAccessibilityDelegate() {
323 return mTouchHelper;
324 }
325
Adam Cohenc9735cf2015-01-23 16:11:55 -0800326 @Override
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700327 public boolean dispatchHoverEvent(MotionEvent event) {
328 // Always attempt to dispatch hover events to accessibility first.
329 if (mTouchHelper != null && mTouchHelper.dispatchHoverEvent(event)) {
330 return true;
331 }
332 return super.dispatchHoverEvent(event);
333 }
334
335 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800336 public boolean onInterceptTouchEvent(MotionEvent ev) {
Winson Chungf9935182020-10-23 09:26:44 -0700337 return mTouchHelper != null
338 || (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev));
Adam Cohenc9735cf2015-01-23 16:11:55 -0800339 }
340
Chris Craik01f2d7f2013-10-01 14:41:56 -0700341 public void enableHardwareLayer(boolean hasLayer) {
342 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700343 }
344
vadimt04f356f2019-02-14 18:46:36 -0800345 public boolean isHardwareLayerEnabled() {
346 return mShortcutsAndWidgets.getLayerType() == LAYER_TYPE_HARDWARE;
347 }
348
Winson Chung5f8afe62013-08-12 16:19:28 -0700349 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700350 mFixedCellWidth = mCellWidth = width;
351 mFixedCellHeight = mCellHeight = height;
Jon Miranda228877d2021-02-09 11:05:00 -0500352 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
353 mBorderSpacing);
Winson Chung5f8afe62013-08-12 16:19:28 -0700354 }
355
Adam Cohen2801caf2011-05-13 20:57:39 -0700356 public void setGridSize(int x, int y) {
357 mCountX = x;
358 mCountY = y;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700359 mOccupied = new GridOccupancy(mCountX, mCountY);
360 mTmpOccupied = new GridOccupancy(mCountX, mCountY);
Adam Cohen7fbec102012-03-27 12:42:19 -0700361 mTempRectStack.clear();
Jon Miranda228877d2021-02-09 11:05:00 -0500362 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
363 mBorderSpacing);
Adam Cohen76fc0852011-06-17 13:26:23 -0700364 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700365 }
366
Adam Cohen2374abf2013-04-16 14:56:57 -0700367 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
368 public void setInvertIfRtl(boolean invert) {
369 mShortcutsAndWidgets.setInvertIfRtl(invert);
370 }
371
Adam Cohen917e3882013-10-31 15:03:35 -0700372 public void setDropPending(boolean pending) {
373 mDropPending = pending;
374 }
375
376 public boolean isDropPending() {
377 return mDropPending;
378 }
379
Adam Cohenc50438c2014-08-19 17:43:05 -0700380 void setIsDragOverlapping(boolean isDragOverlapping) {
381 if (mIsDragOverlapping != isDragOverlapping) {
382 mIsDragOverlapping = isDragOverlapping;
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800383 mBackground.setState(mIsDragOverlapping
384 ? BACKGROUND_STATE_ACTIVE : BACKGROUND_STATE_DEFAULT);
Adam Cohenc50438c2014-08-19 17:43:05 -0700385 invalidate();
386 }
387 }
388
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700389 @Override
390 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700391 ParcelableSparseArray jail = getJailedArray(container);
392 super.dispatchSaveInstanceState(jail);
393 container.put(R.id.cell_layout_jail_id, jail);
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700394 }
395
396 @Override
397 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700398 super.dispatchRestoreInstanceState(getJailedArray(container));
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700399 }
400
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700401 /**
402 * Wrap the SparseArray in another Parcelable so that the item ids do not conflict with our
403 * our internal resource ids
404 */
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700405 private ParcelableSparseArray getJailedArray(SparseArray<Parcelable> container) {
406 final Parcelable parcelable = container.get(R.id.cell_layout_jail_id);
407 return parcelable instanceof ParcelableSparseArray ?
408 (ParcelableSparseArray) parcelable : new ParcelableSparseArray();
409 }
410
Tony Wickham0f97b782015-12-02 17:55:07 -0800411 public boolean getIsDragOverlapping() {
412 return mIsDragOverlapping;
413 }
414
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700415 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700416 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700417 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
418 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
419 // When we're small, we are either drawn normally or in the "accepts drops" state (during
420 // a drag). However, we also drag the mini hover background *over* one of those two
421 // backgrounds
Sunny Goyalaeb16432017-10-16 11:46:41 -0700422 if (mBackground.getAlpha() > 0) {
Sunny Goyal2805e632015-05-20 15:35:32 -0700423 mBackground.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700424 }
Romain Guya6abce82009-11-10 02:54:41 -0800425
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700426 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700427 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700428 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700429 if (alpha > 0) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700430 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700431 paint.setAlpha((int)(alpha + .5f));
Sunny Goyal106bf642015-07-16 12:18:06 -0700432 canvas.drawBitmap(b, null, mDragOutlines[i], paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700433 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700434 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800435
Adam Cohen482ed822012-03-02 14:15:13 -0800436 if (DEBUG_VISUALIZE_OCCUPIED) {
437 int[] pt = new int[2];
438 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700439 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800440 for (int i = 0; i < mCountX; i++) {
441 for (int j = 0; j < mCountY; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700442 if (mOccupied.cells[i][j]) {
Adam Cohen482ed822012-03-02 14:15:13 -0800443 cellToPoint(i, j, pt);
444 canvas.save();
445 canvas.translate(pt[0], pt[1]);
446 cd.draw(canvas);
447 canvas.restore();
448 }
449 }
450 }
451 }
452
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800453 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
454 DelegatedCellDrawing cellDrawing = mDelegatedCellDrawings.get(i);
455 cellToPoint(cellDrawing.mDelegateCellX, cellDrawing.mDelegateCellY, mTempLocation);
Adam Cohenefca0272016-02-24 19:19:06 -0800456 canvas.save();
457 canvas.translate(mTempLocation[0], mTempLocation[1]);
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800458 cellDrawing.drawUnderItem(canvas);
Adam Cohenefca0272016-02-24 19:19:06 -0800459 canvas.restore();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700460 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700461
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800462 if (mFolderLeaveBehind.mDelegateCellX >= 0 && mFolderLeaveBehind.mDelegateCellY >= 0) {
463 cellToPoint(mFolderLeaveBehind.mDelegateCellX,
464 mFolderLeaveBehind.mDelegateCellY, mTempLocation);
Adam Cohenefca0272016-02-24 19:19:06 -0800465 canvas.save();
466 canvas.translate(mTempLocation[0], mTempLocation[1]);
Sunny Goyal19b93b72017-02-19 20:21:37 -0800467 mFolderLeaveBehind.drawLeaveBehind(canvas);
Adam Cohenefca0272016-02-24 19:19:06 -0800468 canvas.restore();
Adam Cohenc51934b2011-07-26 21:07:43 -0700469 }
Adam Cohen65086992020-02-19 08:40:49 -0800470
471 if (VISUALIZE_GRID) {
472 visualizeGrid(canvas);
473 }
474 }
475
476 protected void visualizeGrid(Canvas canvas) {
477 mVisualizeGridRect.set(0, 0, mCellWidth, mCellHeight);
478 mVisualizeGridPaint.setStrokeWidth(4);
479
480 for (int i = 0; i < mCountX; i++) {
481 for (int j = 0; j < mCountY; j++) {
482 canvas.save();
483
Jon Miranda228877d2021-02-09 11:05:00 -0500484 int transX = i * mCellWidth + (i * mBorderSpacing);
485 int transY = j * mCellHeight + (j * mBorderSpacing);
Adam Cohen65086992020-02-19 08:40:49 -0800486
487 canvas.translate(getPaddingLeft() + transX, getPaddingTop() + transY);
488
489 mVisualizeGridPaint.setStyle(Paint.Style.FILL);
490 mVisualizeGridPaint.setColor(Color.argb(80, 255, 100, 100));
491
492 canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
493
494 mVisualizeGridPaint.setStyle(Paint.Style.STROKE);
495 mVisualizeGridPaint.setColor(Color.argb(255, 255, 100, 100));
496
497 canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
498 canvas.restore();
499 }
500 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700501 }
502
Adam Cohenefca0272016-02-24 19:19:06 -0800503 @Override
504 protected void dispatchDraw(Canvas canvas) {
505 super.dispatchDraw(canvas);
506
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800507 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
508 DelegatedCellDrawing bg = mDelegatedCellDrawings.get(i);
509 cellToPoint(bg.mDelegateCellX, bg.mDelegateCellY, mTempLocation);
510 canvas.save();
511 canvas.translate(mTempLocation[0], mTempLocation[1]);
512 bg.drawOverItem(canvas);
513 canvas.restore();
Adam Cohenefca0272016-02-24 19:19:06 -0800514 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700515 }
516
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800517 /**
518 * Add Delegated cell drawing
519 */
520 public void addDelegatedCellDrawing(DelegatedCellDrawing bg) {
521 mDelegatedCellDrawings.add(bg);
Adam Cohenefca0272016-02-24 19:19:06 -0800522 }
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800523
524 /**
525 * Remove item from DelegatedCellDrawings
526 */
527 public void removeDelegatedCellDrawing(DelegatedCellDrawing bg) {
528 mDelegatedCellDrawings.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700529 }
530
Adam Cohenc51934b2011-07-26 21:07:43 -0700531 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800532 View child = getChildAt(x, y);
Sunny Goyalab770a12018-11-14 15:17:26 -0800533 mFolderLeaveBehind.setup(getContext(), mActivity, null,
Adam Cohenefca0272016-02-24 19:19:06 -0800534 child.getMeasuredWidth(), child.getPaddingTop());
535
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800536 mFolderLeaveBehind.mDelegateCellX = x;
537 mFolderLeaveBehind.mDelegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700538 invalidate();
539 }
540
541 public void clearFolderLeaveBehind() {
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800542 mFolderLeaveBehind.mDelegateCellX = -1;
543 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700544 invalidate();
545 }
546
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700547 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700548 public boolean shouldDelayChildPressedState() {
549 return false;
550 }
551
Adam Cohen1462de32012-07-24 22:34:36 -0700552 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700553 try {
554 dispatchRestoreInstanceState(states);
555 } catch (IllegalArgumentException ex) {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800556 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700557 throw ex;
558 }
559 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
560 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
561 }
Adam Cohen1462de32012-07-24 22:34:36 -0700562 }
563
Michael Jurkae6235dd2011-10-04 15:02:05 -0700564 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700565 public void cancelLongPress() {
566 super.cancelLongPress();
567
568 // Cancel long press for all children
569 final int count = getChildCount();
570 for (int i = 0; i < count; i++) {
571 final View child = getChildAt(i);
572 child.cancelLongPress();
573 }
574 }
575
Michael Jurkadee05892010-07-27 10:01:56 -0700576 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
577 mInterceptTouchListener = listener;
578 }
579
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800580 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700581 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800582 }
583
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800584 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700585 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800586 }
587
Sunny Goyalc13403c2016-11-18 23:44:48 -0800588 public boolean acceptsWidget() {
589 return mContainerType == WORKSPACE;
Sunny Goyale9b651e2015-04-24 11:44:51 -0700590 }
591
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800592 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700593 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700594 final LayoutParams lp = params;
595
Andrew Flynnde38e422012-05-08 11:22:15 -0700596 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800597 if (child instanceof BubbleTextView) {
598 BubbleTextView bubbleChild = (BubbleTextView) child;
Jon Mirandaf1eae802017-10-04 11:23:33 -0700599 bubbleChild.setTextVisibility(mContainerType != HOTSEAT);
Jon Miranda228877d2021-02-09 11:05:00 -0500600 bubbleChild.setCenterVertically(mContainerType != HOTSEAT);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800601 }
602
Sunny Goyalc13403c2016-11-18 23:44:48 -0800603 child.setScaleX(mChildScale);
604 child.setScaleY(mChildScale);
Adam Cohen307fe232012-08-16 17:55:58 -0700605
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800606 // Generate an id for each view, this assumes we have at most 256x256 cells
607 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700608 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700609 // If the horizontal or vertical span is set to -1, it is taken to
610 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700611 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
612 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800613
Winson Chungaafa03c2010-06-11 17:34:16 -0700614 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700615 if (LOGD) {
616 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
617 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700618 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700619
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700620 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700621
Winson Chungaafa03c2010-06-11 17:34:16 -0700622 return true;
623 }
624 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800625 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700626
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700628 public void removeAllViews() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700629 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700630 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700631 }
632
633 @Override
634 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700635 if (mShortcutsAndWidgets.getChildCount() > 0) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700636 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700637 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700638 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700639 }
640
641 @Override
642 public void removeView(View view) {
643 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700644 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700645 }
646
647 @Override
648 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700649 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
650 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700651 }
652
653 @Override
654 public void removeViewInLayout(View view) {
655 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700656 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700657 }
658
659 @Override
660 public void removeViews(int start, int count) {
661 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700662 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700663 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700664 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700665 }
666
667 @Override
668 public void removeViewsInLayout(int start, int count) {
669 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700670 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700671 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700672 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800673 }
674
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700675 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700676 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800677 * @param x X coordinate of the point
678 * @param y Y coordinate of the point
679 * @param result Array of 2 ints to hold the x and y coordinate of the cell
680 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700681 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700682 final int hStartPadding = getPaddingLeft();
683 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800684
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530685 result[0] = (x - hStartPadding) / mCellWidth;
686 result[1] = (y - vStartPadding) / mCellHeight;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800687
Adam Cohend22015c2010-07-26 22:02:18 -0700688 final int xAxis = mCountX;
689 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800690
691 if (result[0] < 0) result[0] = 0;
692 if (result[0] >= xAxis) result[0] = xAxis - 1;
693 if (result[1] < 0) result[1] = 0;
694 if (result[1] >= yAxis) result[1] = yAxis - 1;
695 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700696
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800697 /**
698 * Given a point, return the cell that most closely encloses that point
699 * @param x X coordinate of the point
700 * @param y Y coordinate of the point
701 * @param result Array of 2 ints to hold the x and y coordinate of the cell
702 */
703 void pointToCellRounded(int x, int y, int[] result) {
704 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
705 }
706
707 /**
708 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700709 *
710 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800711 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700712 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800713 * @param result Array of 2 ints to hold the x and y coordinate of the point
714 */
715 void cellToPoint(int cellX, int cellY, int[] result) {
Jon Miranda228877d2021-02-09 11:05:00 -0500716 cellToRect(cellX, cellY, 1, 1, mTempRect);
717 result[0] = mTempRect.left;
718 result[1] = mTempRect.top;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800719 }
720
Adam Cohene3e27a82011-04-15 12:07:39 -0700721 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800722 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700723 *
724 * @param cellX X coordinate of the cell
725 * @param cellY Y coordinate of the cell
726 *
727 * @param result Array of 2 ints to hold the x and y coordinate of the point
728 */
729 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700730 regionToCenterPoint(cellX, cellY, 1, 1, result);
731 }
732
733 /**
734 * Given a cell coordinate and span return the point that represents the center of the regio
735 *
736 * @param cellX X coordinate of the cell
737 * @param cellY Y coordinate of the cell
738 *
739 * @param result Array of 2 ints to hold the x and y coordinate of the point
740 */
741 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Jon Miranda228877d2021-02-09 11:05:00 -0500742 cellToRect(cellX, cellY, spanX, spanY, mTempRect);
743 result[0] = mTempRect.centerX();
744 result[1] = mTempRect.centerY();
Adam Cohen19f37922012-03-21 11:59:11 -0700745 }
746
Adam Cohen482ed822012-03-02 14:15:13 -0800747 public float getDistanceFromCell(float x, float y, int[] cell) {
748 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700749 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800750 }
751
Adam Cohenf9c184a2016-01-15 16:47:43 -0800752 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800753 return mCellWidth;
754 }
755
Sunny Goyal0b754e52017-08-07 07:42:45 -0700756 public int getCellHeight() {
Romain Guy84f296c2009-11-04 15:00:44 -0800757 return mCellHeight;
758 }
759
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700760 public void setFixedSize(int width, int height) {
761 mFixedWidth = width;
762 mFixedHeight = height;
763 }
764
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800765 @Override
766 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800767 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800768 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700769 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
770 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700771 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
772 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -0700773
Winson Chung11a1a532013-09-13 11:14:45 -0700774 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Jon Miranda228877d2021-02-09 11:05:00 -0500775 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mBorderSpacing,
776 mCountX);
777 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mBorderSpacing,
778 mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700779 if (cw != mCellWidth || ch != mCellHeight) {
780 mCellWidth = cw;
781 mCellHeight = ch;
Jon Miranda228877d2021-02-09 11:05:00 -0500782 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
783 mBorderSpacing);
Winson Chung11a1a532013-09-13 11:14:45 -0700784 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700785 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700786
Winson Chung2d75f122013-09-23 16:53:31 -0700787 int newWidth = childWidthSize;
788 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700789 if (mFixedWidth > 0 && mFixedHeight > 0) {
790 newWidth = mFixedWidth;
791 newHeight = mFixedHeight;
792 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800793 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
794 }
795
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700796 mShortcutsAndWidgets.measure(
797 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
798 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
799
800 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
801 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700802 if (mFixedWidth > 0 && mFixedHeight > 0) {
803 setMeasuredDimension(maxWidth, maxHeight);
804 } else {
805 setMeasuredDimension(widthSize, heightSize);
806 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800807 }
808
809 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700810 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -0800811 int left = getPaddingLeft();
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700812 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -0700813 int right = r - l - getPaddingRight();
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700814 right -= (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -0700815
Winson Chung38848ca2013-10-08 12:03:44 -0700816 int top = getPaddingTop();
Sunny Goyal7c786f72016-06-01 14:08:21 -0700817 int bottom = b - t - getPaddingBottom();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700818
Sunny Goyal7c786f72016-06-01 14:08:21 -0700819 // Expand the background drawing bounds by the padding baked into the background drawable
820 mBackground.getPadding(mTempRect);
821 mBackground.setBounds(
Jon Miranda28032002017-07-13 16:18:56 -0700822 left - mTempRect.left - getPaddingLeft(),
823 top - mTempRect.top - getPaddingTop(),
824 right + mTempRect.right + getPaddingRight(),
825 bottom + mTempRect.bottom + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -0700826
Sunny Goyalc4d32012020-04-03 17:10:11 -0700827 mShortcutsAndWidgets.layout(left, top, right, bottom);
Sunny Goyal7c786f72016-06-01 14:08:21 -0700828 }
829
Tony Wickhama501d492015-11-03 18:05:01 -0800830 /**
831 * Returns the amount of space left over after subtracting padding and cells. This space will be
832 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
Jon Miranda228877d2021-02-09 11:05:00 -0500833 * width in {@link DeviceProfile#calculateCellWidth(int, int, int)}.
Tony Wickhama501d492015-11-03 18:05:01 -0800834 */
835 public int getUnusedHorizontalSpace() {
Jon Miranda228877d2021-02-09 11:05:00 -0500836 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth)
837 - ((mCountX - 1) * mBorderSpacing);
Tony Wickhama501d492015-11-03 18:05:01 -0800838 }
839
Sunny Goyalaeb16432017-10-16 11:46:41 -0700840 public Drawable getScrimBackground() {
841 return mBackground;
Michael Jurkadee05892010-07-27 10:01:56 -0700842 }
843
Sunny Goyal2805e632015-05-20 15:35:32 -0700844 @Override
845 protected boolean verifyDrawable(Drawable who) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700846 return super.verifyDrawable(who) || (who == mBackground);
Sunny Goyal2805e632015-05-20 15:35:32 -0700847 }
848
Michael Jurkaa52570f2012-03-20 03:18:20 -0700849 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -0700850 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700851 }
852
Jon Miranda228877d2021-02-09 11:05:00 -0500853 public View getChildAt(int cellX, int cellY) {
854 return mShortcutsAndWidgets.getChildAt(cellX, cellY);
Patrick Dubroy440c3602010-07-13 17:50:32 -0700855 }
856
Adam Cohen76fc0852011-06-17 13:26:23 -0700857 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -0800858 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700859 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -0800860
Adam Cohen1d13c0b2020-04-21 16:29:12 -0700861 if (clc.indexOfChild(child) != -1 && (child instanceof Reorderable)) {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700862 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
863 final ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen1d13c0b2020-04-21 16:29:12 -0700864 final Reorderable item = (Reorderable) child;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700865
866 // We cancel any existing animations
867 if (mReorderAnimators.containsKey(lp)) {
868 mReorderAnimators.get(lp).cancel();
869 mReorderAnimators.remove(lp);
870 }
871
Adam Cohen1d13c0b2020-04-21 16:29:12 -0700872
Adam Cohen482ed822012-03-02 14:15:13 -0800873 if (adjustOccupied) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700874 GridOccupancy occupied = permanent ? mOccupied : mTmpOccupied;
875 occupied.markCells(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, false);
876 occupied.markCells(cellX, cellY, lp.cellHSpan, lp.cellVSpan, true);
Adam Cohen482ed822012-03-02 14:15:13 -0800877 }
Adam Cohen1d13c0b2020-04-21 16:29:12 -0700878
879 // Compute the new x and y position based on the new cellX and cellY
880 // We leverage the actual layout logic in the layout params and hence need to modify
881 // state and revert that state.
882 final int oldX = lp.x;
883 final int oldY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700884 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -0800885 if (permanent) {
886 lp.cellX = info.cellX = cellX;
887 lp.cellY = info.cellY = cellY;
888 } else {
889 lp.tmpCellX = cellX;
890 lp.tmpCellY = cellY;
891 }
Jon Mirandae96798e2016-12-07 12:10:44 -0800892 clc.setupLp(child);
Adam Cohen482ed822012-03-02 14:15:13 -0800893 final int newX = lp.x;
894 final int newY = lp.y;
Adam Cohen76fc0852011-06-17 13:26:23 -0700895 lp.x = oldX;
896 lp.y = oldY;
Adam Cohen1d13c0b2020-04-21 16:29:12 -0700897 lp.isLockedToGrid = false;
898 // End compute new x and y
899
900 item.getReorderPreviewOffset(mTmpPointF);
901 final float initPreviewOffsetX = mTmpPointF.x;
902 final float initPreviewOffsetY = mTmpPointF.y;
903 final float finalPreviewOffsetX = newX - oldX;
904 final float finalPreviewOffsetY = newY - oldY;
905
Adam Cohen76fc0852011-06-17 13:26:23 -0700906
Adam Cohen482ed822012-03-02 14:15:13 -0800907 // Exit early if we're not actually moving the view
Adam Cohen1d13c0b2020-04-21 16:29:12 -0700908 if (finalPreviewOffsetX == 0 && finalPreviewOffsetY == 0
909 && initPreviewOffsetX == 0 && initPreviewOffsetY == 0) {
Adam Cohen482ed822012-03-02 14:15:13 -0800910 lp.isLockedToGrid = true;
911 return true;
912 }
913
Sunny Goyal849c6a22018-08-08 16:33:46 -0700914 ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -0800915 va.setDuration(duration);
916 mReorderAnimators.put(lp, va);
917
918 va.addUpdateListener(new AnimatorUpdateListener() {
919 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -0700920 public void onAnimationUpdate(ValueAnimator animation) {
Jon Mirandae96798e2016-12-07 12:10:44 -0800921 float r = (Float) animation.getAnimatedValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -0700922 float x = (1 - r) * initPreviewOffsetX + r * finalPreviewOffsetX;
923 float y = (1 - r) * initPreviewOffsetY + r * finalPreviewOffsetY;
924 item.setReorderPreviewOffset(x, y);
Adam Cohenbfbfd262011-06-13 16:55:12 -0700925 }
926 });
Adam Cohen482ed822012-03-02 14:15:13 -0800927 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700928 boolean cancelled = false;
929 public void onAnimationEnd(Animator animation) {
930 // If the animation was cancelled, it means that another animation
931 // has interrupted this one, and we don't want to lock the item into
932 // place just yet.
933 if (!cancelled) {
934 lp.isLockedToGrid = true;
Adam Cohen1d13c0b2020-04-21 16:29:12 -0700935 item.setReorderPreviewOffset(0, 0);
Adam Cohen482ed822012-03-02 14:15:13 -0800936 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -0700937 }
938 if (mReorderAnimators.containsKey(lp)) {
939 mReorderAnimators.remove(lp);
940 }
941 }
942 public void onAnimationCancel(Animator animation) {
943 cancelled = true;
944 }
945 });
Adam Cohen482ed822012-03-02 14:15:13 -0800946 va.setStartDelay(delay);
947 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -0700948 return true;
949 }
950 return false;
951 }
952
Adam Cohen65086992020-02-19 08:40:49 -0800953 void visualizeDropLocation(DraggableView v, DragPreviewProvider outlineProvider, int cellX, int
954 cellY, int spanX, int spanY, boolean resize, DropTarget.DragObject dragObject) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -0700955 final int oldDragCellX = mDragCell[0];
956 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -0800957
Hyunyoung Song0de01172016-10-05 16:27:48 -0700958 if (outlineProvider == null || outlineProvider.generatedDragOutline == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -0700959 return;
960 }
961
Hyunyoung Song0de01172016-10-05 16:27:48 -0700962 Bitmap dragOutline = outlineProvider.generatedDragOutline;
Adam Cohen482ed822012-03-02 14:15:13 -0800963 if (cellX != oldDragCellX || cellY != oldDragCellY) {
964 mDragCell[0] = cellX;
965 mDragCell[1] = cellY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700966
Joe Onorato4be866d2010-10-10 11:26:02 -0700967 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -0700968 mDragOutlineAnims[oldIndex].animateOut();
969 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -0800970 Rect r = mDragOutlines[mDragOutlineCurrent];
Sunny Goyal106bf642015-07-16 12:18:06 -0700971
Adam Cohen65086992020-02-19 08:40:49 -0800972 cellToRect(cellX, cellY, spanX, spanY, r);
973 int left = r.left;
974 int top = r.top;
975
976 int width = dragOutline.getWidth();
977 int height = dragOutline.getHeight();
978
Adam Cohend41fbf52012-02-16 23:53:59 -0800979 if (resize) {
Adam Cohen65086992020-02-19 08:40:49 -0800980 width = r.width();
981 height = r.height();
Adam Cohend41fbf52012-02-16 23:53:59 -0800982 }
Winson Chung150fbab2010-09-29 17:14:26 -0700983
Adam Cohen370164c2020-04-08 18:00:30 -0700984 // Center horizontaly
Jon Miranda228877d2021-02-09 11:05:00 -0500985 left += (r.width() - dragOutline.getWidth()) / 2;
Adam Cohen370164c2020-04-08 18:00:30 -0700986
987 if (v != null && v.getViewType() == DraggableView.DRAGGABLE_WIDGET) {
988 // Center vertically
Jon Miranda228877d2021-02-09 11:05:00 -0500989 top += (r.height() - dragOutline.getHeight()) / 2;
Adam Cohen370164c2020-04-08 18:00:30 -0700990 } else if (v != null && v.getViewType() == DraggableView.DRAGGABLE_ICON) {
Adam Cohen65086992020-02-19 08:40:49 -0800991 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
992 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
993 top += cellPaddingY;
994 }
995
996 r.set(left, top, left + width, top + height);
997
Jon Miranda6f6a06a2016-12-15 11:24:18 -0800998 Utilities.scaleRectAboutCenter(r, mChildScale);
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -0700999 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1000 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001001
1002 if (dragObject.stateAnnouncer != null) {
Sunny Goyalc13403c2016-11-18 23:44:48 -08001003 dragObject.stateAnnouncer.announce(getItemMoveDescription(cellX, cellY));
Sunny Goyale78e3d72015-09-24 11:23:31 -07001004 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001005 }
1006 }
1007
Sunny Goyal726bee72018-03-05 12:54:24 -08001008 @SuppressLint("StringFormatMatches")
Sunny Goyalc13403c2016-11-18 23:44:48 -08001009 public String getItemMoveDescription(int cellX, int cellY) {
1010 if (mContainerType == HOTSEAT) {
1011 return getContext().getString(R.string.move_to_hotseat_position,
1012 Math.max(cellX, cellY) + 1);
1013 } else {
1014 return getContext().getString(R.string.move_to_empty_cell,
1015 cellY + 1, cellX + 1);
1016 }
1017 }
1018
Adam Cohene0310962011-04-18 16:15:31 -07001019 public void clearDragOutlines() {
1020 final int oldIndex = mDragOutlineCurrent;
1021 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001022 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001023 }
1024
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001025 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001026 * Find a vacant area that will fit the given bounds nearest the requested
1027 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001028 *
Romain Guy51afc022009-05-04 18:03:43 -07001029 * @param pixelX The X location at which you want to search for a vacant area.
1030 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001031 * @param minSpanX The minimum horizontal span required
1032 * @param minSpanY The minimum vertical span required
1033 * @param spanX Horizontal span of the object.
1034 * @param spanY Vertical span of the object.
1035 * @param result Array in which to place the result, or null (in which case a new array will
1036 * be allocated)
1037 * @return The X, Y cell of a vacant area that can contain this object,
1038 * nearest the requested location.
1039 */
1040 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1041 int spanY, int[] result, int[] resultSpan) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001042 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
Adam Cohend41fbf52012-02-16 23:53:59 -08001043 result, resultSpan);
1044 }
1045
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001046 private final Stack<Rect> mTempRectStack = new Stack<>();
Adam Cohend41fbf52012-02-16 23:53:59 -08001047 private void lazyInitTempRectStack() {
1048 if (mTempRectStack.isEmpty()) {
1049 for (int i = 0; i < mCountX * mCountY; i++) {
1050 mTempRectStack.push(new Rect());
1051 }
1052 }
1053 }
Adam Cohen482ed822012-03-02 14:15:13 -08001054
Adam Cohend41fbf52012-02-16 23:53:59 -08001055 private void recycleTempRects(Stack<Rect> used) {
1056 while (!used.isEmpty()) {
1057 mTempRectStack.push(used.pop());
1058 }
1059 }
1060
1061 /**
1062 * Find a vacant area that will fit the given bounds nearest the requested
1063 * cell location. Uses Euclidean distance to score multiple vacant areas.
1064 *
1065 * @param pixelX The X location at which you want to search for a vacant area.
1066 * @param pixelY The Y location at which you want to search for a vacant area.
1067 * @param minSpanX The minimum horizontal span required
1068 * @param minSpanY The minimum vertical span required
1069 * @param spanX Horizontal span of the object.
1070 * @param spanY Vertical span of the object.
1071 * @param ignoreOccupied If true, the result can be an occupied cell
1072 * @param result Array in which to place the result, or null (in which case a new array will
1073 * be allocated)
1074 * @return The X, Y cell of a vacant area that can contain this object,
1075 * nearest the requested location.
1076 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001077 private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1078 int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001079 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001080
Adam Cohene3e27a82011-04-15 12:07:39 -07001081 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1082 // to the center of the item, but we are searching based on the top-left cell, so
1083 // we translate the point over to correspond to the top-left.
Sunny Goyalaa8a8712016-11-20 15:26:01 +05301084 pixelX -= mCellWidth * (spanX - 1) / 2f;
1085 pixelY -= mCellHeight * (spanY - 1) / 2f;
Adam Cohene3e27a82011-04-15 12:07:39 -07001086
Jeff Sharkey70864282009-04-07 21:08:40 -07001087 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001088 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001089 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001090 final Rect bestRect = new Rect(-1, -1, -1, -1);
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001091 final Stack<Rect> validRegions = new Stack<>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001092
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001093 final int countX = mCountX;
1094 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001095
Adam Cohend41fbf52012-02-16 23:53:59 -08001096 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1097 spanX < minSpanX || spanY < minSpanY) {
1098 return bestXY;
1099 }
1100
1101 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001102 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001103 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1104 int ySize = -1;
1105 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001106 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001107 // First, let's see if this thing fits anywhere
1108 for (int i = 0; i < minSpanX; i++) {
1109 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001110 if (mOccupied.cells[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001111 continue inner;
1112 }
Michael Jurkac28de512010-08-13 11:27:44 -07001113 }
1114 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001115 xSize = minSpanX;
1116 ySize = minSpanY;
1117
1118 // We know that the item will fit at _some_ acceptable size, now let's see
1119 // how big we can make it. We'll alternate between incrementing x and y spans
1120 // until we hit a limit.
1121 boolean incX = true;
1122 boolean hitMaxX = xSize >= spanX;
1123 boolean hitMaxY = ySize >= spanY;
1124 while (!(hitMaxX && hitMaxY)) {
1125 if (incX && !hitMaxX) {
1126 for (int j = 0; j < ySize; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001127 if (x + xSize > countX -1 || mOccupied.cells[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001128 // We can't move out horizontally
1129 hitMaxX = true;
1130 }
1131 }
1132 if (!hitMaxX) {
1133 xSize++;
1134 }
1135 } else if (!hitMaxY) {
1136 for (int i = 0; i < xSize; i++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001137 if (y + ySize > countY - 1 || mOccupied.cells[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001138 // We can't move out vertically
1139 hitMaxY = true;
1140 }
1141 }
1142 if (!hitMaxY) {
1143 ySize++;
1144 }
1145 }
1146 hitMaxX |= xSize >= spanX;
1147 hitMaxY |= ySize >= spanY;
1148 incX = !incX;
1149 }
1150 incX = true;
1151 hitMaxX = xSize >= spanX;
1152 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001153 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001154 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001155 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001156
Adam Cohend41fbf52012-02-16 23:53:59 -08001157 // We verify that the current rect is not a sub-rect of any of our previous
1158 // candidates. In this case, the current rect is disqualified in favour of the
1159 // containing rect.
1160 Rect currentRect = mTempRectStack.pop();
1161 currentRect.set(x, y, x + xSize, y + ySize);
1162 boolean contained = false;
1163 for (Rect r : validRegions) {
1164 if (r.contains(currentRect)) {
1165 contained = true;
1166 break;
1167 }
1168 }
1169 validRegions.push(currentRect);
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001170 double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
Adam Cohen482ed822012-03-02 14:15:13 -08001171
Adam Cohend41fbf52012-02-16 23:53:59 -08001172 if ((distance <= bestDistance && !contained) ||
1173 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001174 bestDistance = distance;
1175 bestXY[0] = x;
1176 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001177 if (resultSpan != null) {
1178 resultSpan[0] = xSize;
1179 resultSpan[1] = ySize;
1180 }
1181 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001182 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001183 }
1184 }
1185
Adam Cohenc0dcf592011-06-01 15:30:43 -07001186 // Return -1, -1 if no suitable location found
1187 if (bestDistance == Double.MAX_VALUE) {
1188 bestXY[0] = -1;
1189 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001190 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001191 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001192 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001193 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001194
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001195 /**
Adam Cohen482ed822012-03-02 14:15:13 -08001196 * Find a vacant area that will fit the given bounds nearest the requested
1197 * cell location, and will also weigh in a suggested direction vector of the
1198 * desired location. This method computers distance based on unit grid distances,
1199 * not pixel distances.
1200 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001201 * @param cellX The X cell nearest to which you want to search for a vacant area.
1202 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001203 * @param spanX Horizontal span of the object.
1204 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001205 * @param direction The favored direction in which the views should move from x, y
Sunny Goyal9eba1fd2015-10-16 08:58:57 -07001206 * @param occupied The array which represents which cells in the CellLayout are occupied
Adam Cohen47a876d2012-03-19 13:21:41 -07001207 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001208 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001209 * @param result Array in which to place the result, or null (in which case a new array will
1210 * be allocated)
1211 * @return The X, Y cell of a vacant area that can contain this object,
1212 * nearest the requested location.
1213 */
1214 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001215 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001216 // Keep track of best-scoring drop area
1217 final int[] bestXY = result != null ? result : new int[2];
1218 float bestDistance = Float.MAX_VALUE;
1219 int bestDirectionScore = Integer.MIN_VALUE;
1220
1221 final int countX = mCountX;
1222 final int countY = mCountY;
1223
1224 for (int y = 0; y < countY - (spanY - 1); y++) {
1225 inner:
1226 for (int x = 0; x < countX - (spanX - 1); x++) {
1227 // First, let's see if this thing fits anywhere
1228 for (int i = 0; i < spanX; i++) {
1229 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001230 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001231 continue inner;
1232 }
1233 }
1234 }
1235
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001236 float distance = (float) Math.hypot(x - cellX, y - cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001237 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001238 computeDirectionVector(x - cellX, y - cellY, curDirection);
1239 // The direction score is just the dot product of the two candidate direction
1240 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001241 int curDirectionScore = direction[0] * curDirection[0] +
1242 direction[1] * curDirection[1];
Sunny Goyal8f90dcf2016-08-18 15:01:11 -07001243 if (Float.compare(distance, bestDistance) < 0 ||
1244 (Float.compare(distance, bestDistance) == 0
1245 && curDirectionScore > bestDirectionScore)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001246 bestDistance = distance;
1247 bestDirectionScore = curDirectionScore;
1248 bestXY[0] = x;
1249 bestXY[1] = y;
1250 }
1251 }
1252 }
1253
1254 // Return -1, -1 if no suitable location found
1255 if (bestDistance == Float.MAX_VALUE) {
1256 bestXY[0] = -1;
1257 bestXY[1] = -1;
1258 }
1259 return bestXY;
1260 }
1261
1262 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001263 int[] direction, ItemConfiguration currentState) {
1264 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001265 boolean success = false;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001266 mTmpOccupied.markCells(c, false);
1267 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001268
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001269 findNearestArea(c.cellX, c.cellY, c.spanX, c.spanY, direction,
1270 mTmpOccupied.cells, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001271
1272 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001273 c.cellX = mTempLocation[0];
1274 c.cellY = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001275 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001276 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001277 mTmpOccupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001278 return success;
1279 }
1280
Adam Cohenf3900c22012-11-16 18:28:11 -08001281 /**
1282 * This helper class defines a cluster of views. It helps with defining complex edges
1283 * of the cluster and determining how those edges interact with other views. The edges
1284 * essentially define a fine-grained boundary around the cluster of views -- like a more
1285 * precise version of a bounding box.
1286 */
1287 private class ViewCluster {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001288 final static int LEFT = 1 << 0;
1289 final static int TOP = 1 << 1;
1290 final static int RIGHT = 1 << 2;
1291 final static int BOTTOM = 1 << 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001292
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001293 final ArrayList<View> views;
1294 final ItemConfiguration config;
1295 final Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001296
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001297 final int[] leftEdge = new int[mCountY];
1298 final int[] rightEdge = new int[mCountY];
1299 final int[] topEdge = new int[mCountX];
1300 final int[] bottomEdge = new int[mCountX];
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001301 int dirtyEdges;
1302 boolean boundingRectDirty;
Adam Cohenf3900c22012-11-16 18:28:11 -08001303
1304 @SuppressWarnings("unchecked")
1305 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1306 this.views = (ArrayList<View>) views.clone();
1307 this.config = config;
1308 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001309 }
1310
Adam Cohenf3900c22012-11-16 18:28:11 -08001311 void resetEdges() {
1312 for (int i = 0; i < mCountX; i++) {
1313 topEdge[i] = -1;
1314 bottomEdge[i] = -1;
1315 }
1316 for (int i = 0; i < mCountY; i++) {
1317 leftEdge[i] = -1;
1318 rightEdge[i] = -1;
1319 }
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001320 dirtyEdges = LEFT | TOP | RIGHT | BOTTOM;
Adam Cohenf3900c22012-11-16 18:28:11 -08001321 boundingRectDirty = true;
1322 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001323
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001324 void computeEdge(int which) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001325 int count = views.size();
1326 for (int i = 0; i < count; i++) {
1327 CellAndSpan cs = config.map.get(views.get(i));
1328 switch (which) {
1329 case LEFT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001330 int left = cs.cellX;
1331 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001332 if (left < leftEdge[j] || leftEdge[j] < 0) {
1333 leftEdge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001334 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001335 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001336 break;
1337 case RIGHT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001338 int right = cs.cellX + cs.spanX;
1339 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001340 if (right > rightEdge[j]) {
1341 rightEdge[j] = right;
Adam Cohenf3900c22012-11-16 18:28:11 -08001342 }
1343 }
1344 break;
1345 case TOP:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001346 int top = cs.cellY;
1347 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001348 if (top < topEdge[j] || topEdge[j] < 0) {
1349 topEdge[j] = top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001350 }
1351 }
1352 break;
1353 case BOTTOM:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001354 int bottom = cs.cellY + cs.spanY;
1355 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001356 if (bottom > bottomEdge[j]) {
1357 bottomEdge[j] = bottom;
Adam Cohenf3900c22012-11-16 18:28:11 -08001358 }
1359 }
1360 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001361 }
1362 }
1363 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001364
1365 boolean isViewTouchingEdge(View v, int whichEdge) {
1366 CellAndSpan cs = config.map.get(v);
1367
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001368 if ((dirtyEdges & whichEdge) == whichEdge) {
1369 computeEdge(whichEdge);
1370 dirtyEdges &= ~whichEdge;
1371 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001372
1373 switch (whichEdge) {
1374 case LEFT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001375 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
1376 if (leftEdge[i] == cs.cellX + cs.spanX) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001377 return true;
1378 }
1379 }
1380 break;
1381 case RIGHT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001382 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
1383 if (rightEdge[i] == cs.cellX) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001384 return true;
1385 }
1386 }
1387 break;
1388 case TOP:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001389 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
1390 if (topEdge[i] == cs.cellY + cs.spanY) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001391 return true;
1392 }
1393 }
1394 break;
1395 case BOTTOM:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001396 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
1397 if (bottomEdge[i] == cs.cellY) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001398 return true;
1399 }
1400 }
1401 break;
1402 }
1403 return false;
1404 }
1405
1406 void shift(int whichEdge, int delta) {
1407 for (View v: views) {
1408 CellAndSpan c = config.map.get(v);
1409 switch (whichEdge) {
1410 case LEFT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001411 c.cellX -= delta;
Adam Cohenf3900c22012-11-16 18:28:11 -08001412 break;
1413 case RIGHT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001414 c.cellX += delta;
Adam Cohenf3900c22012-11-16 18:28:11 -08001415 break;
1416 case TOP:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001417 c.cellY -= delta;
Adam Cohenf3900c22012-11-16 18:28:11 -08001418 break;
1419 case BOTTOM:
1420 default:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001421 c.cellY += delta;
Adam Cohenf3900c22012-11-16 18:28:11 -08001422 break;
1423 }
1424 }
1425 resetEdges();
1426 }
1427
1428 public void addView(View v) {
1429 views.add(v);
1430 resetEdges();
1431 }
1432
1433 public Rect getBoundingRect() {
1434 if (boundingRectDirty) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001435 config.getBoundingRectForViews(views, boundingRect);
Adam Cohenf3900c22012-11-16 18:28:11 -08001436 }
1437 return boundingRect;
1438 }
1439
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001440 final PositionComparator comparator = new PositionComparator();
Adam Cohenf3900c22012-11-16 18:28:11 -08001441 class PositionComparator implements Comparator<View> {
1442 int whichEdge = 0;
1443 public int compare(View left, View right) {
1444 CellAndSpan l = config.map.get(left);
1445 CellAndSpan r = config.map.get(right);
1446 switch (whichEdge) {
1447 case LEFT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001448 return (r.cellX + r.spanX) - (l.cellX + l.spanX);
Adam Cohenf3900c22012-11-16 18:28:11 -08001449 case RIGHT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001450 return l.cellX - r.cellX;
Adam Cohenf3900c22012-11-16 18:28:11 -08001451 case TOP:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001452 return (r.cellY + r.spanY) - (l.cellY + l.spanY);
Adam Cohenf3900c22012-11-16 18:28:11 -08001453 case BOTTOM:
1454 default:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001455 return l.cellY - r.cellY;
Adam Cohenf3900c22012-11-16 18:28:11 -08001456 }
1457 }
1458 }
1459
1460 public void sortConfigurationForEdgePush(int edge) {
1461 comparator.whichEdge = edge;
1462 Collections.sort(config.sortedViews, comparator);
1463 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001464 }
1465
Adam Cohenf3900c22012-11-16 18:28:11 -08001466 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1467 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001468
Adam Cohenf3900c22012-11-16 18:28:11 -08001469 ViewCluster cluster = new ViewCluster(views, currentState);
1470 Rect clusterRect = cluster.getBoundingRect();
1471 int whichEdge;
1472 int pushDistance;
1473 boolean fail = false;
1474
1475 // Determine the edge of the cluster that will be leading the push and how far
1476 // the cluster must be shifted.
1477 if (direction[0] < 0) {
1478 whichEdge = ViewCluster.LEFT;
1479 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001480 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001481 whichEdge = ViewCluster.RIGHT;
1482 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1483 } else if (direction[1] < 0) {
1484 whichEdge = ViewCluster.TOP;
1485 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1486 } else {
1487 whichEdge = ViewCluster.BOTTOM;
1488 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07001489 }
1490
Adam Cohenf3900c22012-11-16 18:28:11 -08001491 // Break early for invalid push distance.
1492 if (pushDistance <= 0) {
1493 return false;
Adam Cohene0489502012-08-27 15:18:53 -07001494 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001495
1496 // Mark the occupied state as false for the group of views we want to move.
1497 for (View v: views) {
1498 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001499 mTmpOccupied.markCells(c, false);
Adam Cohenf3900c22012-11-16 18:28:11 -08001500 }
1501
1502 // We save the current configuration -- if we fail to find a solution we will revert
1503 // to the initial state. The process of finding a solution modifies the configuration
1504 // in place, hence the need for revert in the failure case.
1505 currentState.save();
1506
1507 // The pushing algorithm is simplified by considering the views in the order in which
1508 // they would be pushed by the cluster. For example, if the cluster is leading with its
1509 // left edge, we consider sort the views by their right edge, from right to left.
1510 cluster.sortConfigurationForEdgePush(whichEdge);
1511
1512 while (pushDistance > 0 && !fail) {
1513 for (View v: currentState.sortedViews) {
1514 // For each view that isn't in the cluster, we see if the leading edge of the
1515 // cluster is contacting the edge of that view. If so, we add that view to the
1516 // cluster.
1517 if (!cluster.views.contains(v) && v != dragView) {
1518 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1519 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1520 if (!lp.canReorder) {
1521 // The push solution includes the all apps button, this is not viable.
1522 fail = true;
1523 break;
1524 }
1525 cluster.addView(v);
1526 CellAndSpan c = currentState.map.get(v);
1527
1528 // Adding view to cluster, mark it as not occupied.
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001529 mTmpOccupied.markCells(c, false);
Adam Cohenf3900c22012-11-16 18:28:11 -08001530 }
1531 }
1532 }
1533 pushDistance--;
1534
1535 // The cluster has been completed, now we move the whole thing over in the appropriate
1536 // direction.
1537 cluster.shift(whichEdge, 1);
1538 }
1539
1540 boolean foundSolution = false;
1541 clusterRect = cluster.getBoundingRect();
1542
1543 // Due to the nature of the algorithm, the only check required to verify a valid solution
1544 // is to ensure that completed shifted cluster lies completely within the cell layout.
1545 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1546 clusterRect.bottom <= mCountY) {
1547 foundSolution = true;
1548 } else {
1549 currentState.restore();
1550 }
1551
1552 // In either case, we set the occupied array as marked for the location of the views
1553 for (View v: cluster.views) {
1554 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001555 mTmpOccupied.markCells(c, true);
Adam Cohenf3900c22012-11-16 18:28:11 -08001556 }
1557
1558 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07001559 }
1560
Adam Cohen482ed822012-03-02 14:15:13 -08001561 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08001562 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001563 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001564
Adam Cohen8baab352012-03-20 17:39:21 -07001565 boolean success = false;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001566 Rect boundingRect = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001567 // We construct a rect which represents the entire group of views passed in
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001568 currentState.getBoundingRectForViews(views, boundingRect);
Adam Cohen8baab352012-03-20 17:39:21 -07001569
Adam Cohen8baab352012-03-20 17:39:21 -07001570 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08001571 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001572 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001573 mTmpOccupied.markCells(c, false);
Adam Cohen8baab352012-03-20 17:39:21 -07001574 }
1575
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001576 GridOccupancy blockOccupied = new GridOccupancy(boundingRect.width(), boundingRect.height());
Adam Cohen47a876d2012-03-19 13:21:41 -07001577 int top = boundingRect.top;
1578 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001579 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001580 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08001581 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001582 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001583 blockOccupied.markCells(c.cellX - left, c.cellY - top, c.spanX, c.spanY, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001584 }
1585
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001586 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001587
Adam Cohenf3900c22012-11-16 18:28:11 -08001588 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001589 boundingRect.height(), direction,
1590 mTmpOccupied.cells, blockOccupied.cells, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001591
Adam Cohen8baab352012-03-20 17:39:21 -07001592 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001593 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001594 int deltaX = mTempLocation[0] - boundingRect.left;
1595 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001596 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001597 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001598 c.cellX += deltaX;
1599 c.cellY += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001600 }
1601 success = true;
1602 }
Adam Cohen8baab352012-03-20 17:39:21 -07001603
1604 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08001605 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001606 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001607 mTmpOccupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001608 }
1609 return success;
1610 }
1611
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001612 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1613 // to push items in each of the cardinal directions, in an order based on the direction vector
1614 // passed.
1615 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1616 int[] direction, View ignoreView, ItemConfiguration solution) {
1617 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001618 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001619 // separately in each of the components.
1620 int temp = direction[1];
1621 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001622
1623 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001624 ignoreView, solution)) {
1625 return true;
1626 }
1627 direction[1] = temp;
1628 temp = direction[0];
1629 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001630
1631 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001632 ignoreView, solution)) {
1633 return true;
1634 }
1635 // Revert the direction
1636 direction[0] = temp;
1637
1638 // Now we try pushing in each component of the opposite direction
1639 direction[0] *= -1;
1640 direction[1] *= -1;
1641 temp = direction[1];
1642 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001643 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001644 ignoreView, solution)) {
1645 return true;
1646 }
1647
1648 direction[1] = temp;
1649 temp = direction[0];
1650 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001651 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001652 ignoreView, solution)) {
1653 return true;
1654 }
1655 // revert the direction
1656 direction[0] = temp;
1657 direction[0] *= -1;
1658 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001659
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001660 } else {
1661 // If the direction vector has a single non-zero component, we push first in the
1662 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08001663 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001664 ignoreView, solution)) {
1665 return true;
1666 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001667 // Then we try the opposite direction
1668 direction[0] *= -1;
1669 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001670 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001671 ignoreView, solution)) {
1672 return true;
1673 }
1674 // Switch the direction back
1675 direction[0] *= -1;
1676 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001677
1678 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001679 // to find a solution by pushing along the perpendicular axis.
1680
1681 // Swap the components
1682 int temp = direction[1];
1683 direction[1] = direction[0];
1684 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08001685 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001686 ignoreView, solution)) {
1687 return true;
1688 }
1689
1690 // Then we try the opposite direction
1691 direction[0] *= -1;
1692 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001693 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001694 ignoreView, solution)) {
1695 return true;
1696 }
1697 // Switch the direction back
1698 direction[0] *= -1;
1699 direction[1] *= -1;
1700
1701 // Swap the components back
1702 temp = direction[1];
1703 direction[1] = direction[0];
1704 direction[0] = temp;
1705 }
1706 return false;
1707 }
1708
Adam Cohen482ed822012-03-02 14:15:13 -08001709 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001710 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001711 // Return early if get invalid cell positions
1712 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001713
Adam Cohen8baab352012-03-20 17:39:21 -07001714 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001715 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001716
Adam Cohen8baab352012-03-20 17:39:21 -07001717 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001718 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001719 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001720 if (c != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001721 c.cellX = cellX;
1722 c.cellY = cellY;
Adam Cohen19f37922012-03-21 11:59:11 -07001723 }
Adam Cohen482ed822012-03-02 14:15:13 -08001724 }
Adam Cohen482ed822012-03-02 14:15:13 -08001725 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1726 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001727 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001728 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001729 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001730 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001731 r1.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001732 if (Rect.intersects(r0, r1)) {
1733 if (!lp.canReorder) {
1734 return false;
1735 }
1736 mIntersectingViews.add(child);
1737 }
1738 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001739
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001740 solution.intersectingViews = new ArrayList<>(mIntersectingViews);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001741
Winson Chung5f8afe62013-08-12 16:19:28 -07001742 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001743 // we try to find a solution such that no displaced item travels through another item
1744 // without also displacing that item.
1745 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001746 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001747 return true;
1748 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001749
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001750 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08001751 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001752 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001753 return true;
1754 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001755
Adam Cohen482ed822012-03-02 14:15:13 -08001756 // Ok, they couldn't move as a block, let's move them individually
1757 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001758 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001759 return false;
1760 }
1761 }
1762 return true;
1763 }
1764
1765 /*
1766 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1767 * the provided point and the provided cell
1768 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001769 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Jon Mirandae96798e2016-12-07 12:10:44 -08001770 double angle = Math.atan(deltaY / deltaX);
Adam Cohen482ed822012-03-02 14:15:13 -08001771
1772 result[0] = 0;
1773 result[1] = 0;
1774 if (Math.abs(Math.cos(angle)) > 0.5f) {
1775 result[0] = (int) Math.signum(deltaX);
1776 }
1777 if (Math.abs(Math.sin(angle)) > 0.5f) {
1778 result[1] = (int) Math.signum(deltaY);
1779 }
1780 }
1781
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001782 private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001783 int spanX, int spanY, int[] direction, View dragView, boolean decX,
1784 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001785 // Copy the current state into the solution. This solution will be manipulated as necessary.
1786 copyCurrentStateToSolution(solution, false);
1787 // Copy the current occupied array into the temporary occupied array. This array will be
1788 // manipulated as necessary to find a solution.
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001789 mOccupied.copyTo(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001790
1791 // We find the nearest cell into which we would place the dragged item, assuming there's
1792 // nothing in its way.
1793 int result[] = new int[2];
1794 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1795
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001796 boolean success;
Adam Cohen482ed822012-03-02 14:15:13 -08001797 // First we try the exact nearest position of the item being dragged,
1798 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001799 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1800 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001801
1802 if (!success) {
1803 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1804 // x, then 1 in y etc.
1805 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001806 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
1807 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001808 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001809 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
1810 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001811 }
1812 solution.isSolution = false;
1813 } else {
1814 solution.isSolution = true;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001815 solution.cellX = result[0];
1816 solution.cellY = result[1];
1817 solution.spanX = spanX;
1818 solution.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001819 }
1820 return solution;
1821 }
1822
1823 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001824 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001825 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001826 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001827 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001828 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08001829 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07001830 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001831 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001832 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001833 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001834 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08001835 }
1836 }
1837
1838 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001839 mTmpOccupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001840
Michael Jurkaa52570f2012-03-20 03:18:20 -07001841 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001842 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001843 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001844 if (child == dragView) continue;
1845 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001846 CellAndSpan c = solution.map.get(child);
1847 if (c != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001848 lp.tmpCellX = c.cellX;
1849 lp.tmpCellY = c.cellY;
Adam Cohen8baab352012-03-20 17:39:21 -07001850 lp.cellHSpan = c.spanX;
1851 lp.cellVSpan = c.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001852 mTmpOccupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001853 }
1854 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001855 mTmpOccupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001856 }
1857
1858 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1859 commitDragView) {
1860
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001861 GridOccupancy occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1862 occupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001863
Michael Jurkaa52570f2012-03-20 03:18:20 -07001864 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001865 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001866 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001867 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001868 CellAndSpan c = solution.map.get(child);
1869 if (c != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001870 animateChildToPosition(child, c.cellX, c.cellY, REORDER_ANIMATION_DURATION, 0,
Adam Cohen19f37922012-03-21 11:59:11 -07001871 DESTRUCTIVE_REORDER, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001872 occupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001873 }
1874 }
1875 if (commitDragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001876 occupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001877 }
1878 }
1879
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001880
1881 // This method starts or changes the reorder preview animations
1882 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
Adam Cohen65086992020-02-19 08:40:49 -08001883 View dragView, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07001884 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07001885 for (int i = 0; i < childCount; i++) {
1886 View child = mShortcutsAndWidgets.getChildAt(i);
1887 if (child == dragView) continue;
1888 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001889 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
1890 != null && !solution.intersectingViews.contains(child);
1891
Adam Cohend9162062020-03-24 16:35:35 -07001892
Adam Cohen19f37922012-03-21 11:59:11 -07001893 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohend9162062020-03-24 16:35:35 -07001894 if (c != null && !skip && (child instanceof Reorderable)) {
1895 ReorderPreviewAnimation rha = new ReorderPreviewAnimation((Reorderable) child,
1896 mode, lp.cellX, lp.cellY, c.cellX, c.cellY, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07001897 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07001898 }
1899 }
1900 }
1901
Sunny Goyal849c6a22018-08-08 16:33:46 -07001902 private static final Property<ReorderPreviewAnimation, Float> ANIMATION_PROGRESS =
1903 new Property<ReorderPreviewAnimation, Float>(float.class, "animationProgress") {
1904 @Override
1905 public Float get(ReorderPreviewAnimation anim) {
1906 return anim.animationProgress;
1907 }
1908
1909 @Override
1910 public void set(ReorderPreviewAnimation anim, Float progress) {
1911 anim.setAnimationProgress(progress);
1912 }
1913 };
1914
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001915 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07001916 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001917 class ReorderPreviewAnimation {
Adam Cohend9162062020-03-24 16:35:35 -07001918 final Reorderable child;
Adam Cohend024f982012-05-23 18:26:45 -07001919 float finalDeltaX;
1920 float finalDeltaY;
1921 float initDeltaX;
1922 float initDeltaY;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001923 final float finalScale;
Adam Cohend024f982012-05-23 18:26:45 -07001924 float initScale;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001925 final int mode;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001926 boolean repeating = false;
1927 private static final int PREVIEW_DURATION = 300;
1928 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
1929
Jon Miranda21266912016-12-19 14:12:05 -08001930 private static final float CHILD_DIVIDEND = 4.0f;
1931
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001932 public static final int MODE_HINT = 0;
1933 public static final int MODE_PREVIEW = 1;
1934
Sunny Goyal849c6a22018-08-08 16:33:46 -07001935 float animationProgress = 0;
Sunny Goyalf0b6db72018-08-13 16:10:14 -07001936 ValueAnimator a;
Adam Cohen19f37922012-03-21 11:59:11 -07001937
Adam Cohend9162062020-03-24 16:35:35 -07001938 public ReorderPreviewAnimation(Reorderable child, int mode, int cellX0, int cellY0,
1939 int cellX1, int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07001940 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
1941 final int x0 = mTmpPoint[0];
1942 final int y0 = mTmpPoint[1];
1943 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
1944 final int x1 = mTmpPoint[0];
1945 final int y1 = mTmpPoint[1];
1946 final int dX = x1 - x0;
1947 final int dY = y1 - y0;
Jon Miranda21266912016-12-19 14:12:05 -08001948
1949 this.child = child;
1950 this.mode = mode;
Adam Cohend9162062020-03-24 16:35:35 -07001951 finalDeltaX = 0;
1952 finalDeltaY = 0;
Adam Cohen65086992020-02-19 08:40:49 -08001953
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001954 child.getReorderBounceOffset(mTmpPointF);
Adam Cohend9162062020-03-24 16:35:35 -07001955 initDeltaX = mTmpPointF.x;
1956 initDeltaY = mTmpPointF.y;
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001957 initScale = child.getReorderBounceScale();
Adam Cohend9162062020-03-24 16:35:35 -07001958 finalScale = mChildScale - (CHILD_DIVIDEND / child.getView().getWidth()) * initScale;
1959
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001960 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07001961 if (dX == dY && dX == 0) {
1962 } else {
1963 if (dY == 0) {
Adam Cohend9162062020-03-24 16:35:35 -07001964 finalDeltaX = -dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001965 } else if (dX == 0) {
Adam Cohend9162062020-03-24 16:35:35 -07001966 finalDeltaY = -dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001967 } else {
1968 double angle = Math.atan( (float) (dY) / dX);
Adam Cohend9162062020-03-24 16:35:35 -07001969 finalDeltaX = (int) (-dir * Math.signum(dX)
1970 * Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
1971 finalDeltaY = (int) (-dir * Math.signum(dY)
1972 * Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07001973 }
1974 }
Jon Miranda21266912016-12-19 14:12:05 -08001975 }
1976
Adam Cohend9162062020-03-24 16:35:35 -07001977 void setInitialAnimationValuesToBaseline() {
1978 initScale = mChildScale;
1979 initDeltaX = 0;
1980 initDeltaY = 0;
Adam Cohen19f37922012-03-21 11:59:11 -07001981 }
1982
Adam Cohend024f982012-05-23 18:26:45 -07001983 void animate() {
Adam Cohend9162062020-03-24 16:35:35 -07001984 boolean noMovement = (finalDeltaX == 0) && (finalDeltaY == 0);
Jon Miranda21266912016-12-19 14:12:05 -08001985
Adam Cohen19f37922012-03-21 11:59:11 -07001986 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001987 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohen19f37922012-03-21 11:59:11 -07001988 mShakeAnimators.remove(child);
Adam Cohend9162062020-03-24 16:35:35 -07001989
Jon Miranda21266912016-12-19 14:12:05 -08001990 if (noMovement) {
Adam Cohend9162062020-03-24 16:35:35 -07001991 // A previous animation for this item exists, and no new animation will exist.
1992 // Finish the old animation smoothly.
1993 oldAnimation.finishAnimation();
Adam Cohene7587d22012-05-24 18:50:02 -07001994 return;
Adam Cohend9162062020-03-24 16:35:35 -07001995 } else {
1996 // A previous animation for this item exists, and a new one will exist. Stop
1997 // the old animation in its tracks, and proceed with the new one.
1998 oldAnimation.cancel();
Adam Cohene7587d22012-05-24 18:50:02 -07001999 }
Adam Cohen19f37922012-03-21 11:59:11 -07002000 }
Jon Miranda21266912016-12-19 14:12:05 -08002001 if (noMovement) {
Adam Cohen19f37922012-03-21 11:59:11 -07002002 return;
2003 }
Adam Cohend9162062020-03-24 16:35:35 -07002004
Sunny Goyal849c6a22018-08-08 16:33:46 -07002005 ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS, 0, 1);
Adam Cohene7587d22012-05-24 18:50:02 -07002006 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07002007
2008 // Animations are disabled in power save mode, causing the repeated animation to jump
2009 // spastically between beginning and end states. Since this looks bad, we don't repeat
2010 // the animation in power save mode.
Sunny Goyaleaf7a952020-07-29 16:54:20 -07002011 if (areAnimatorsEnabled()) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07002012 va.setRepeatMode(ValueAnimator.REVERSE);
2013 va.setRepeatCount(ValueAnimator.INFINITE);
2014 }
2015
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002016 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002017 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002018 va.addListener(new AnimatorListenerAdapter() {
2019 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002020 // We make sure to end only after a full period
Adam Cohend9162062020-03-24 16:35:35 -07002021 setInitialAnimationValuesToBaseline();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002022 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002023 }
2024 });
Adam Cohen19f37922012-03-21 11:59:11 -07002025 mShakeAnimators.put(child, this);
2026 va.start();
2027 }
2028
Sunny Goyal849c6a22018-08-08 16:33:46 -07002029 private void setAnimationProgress(float progress) {
2030 animationProgress = progress;
2031 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : animationProgress;
2032 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2033 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Adam Cohen1d13c0b2020-04-21 16:29:12 -07002034 child.setReorderBounceOffset(x, y);
Sunny Goyal849c6a22018-08-08 16:33:46 -07002035 float s = animationProgress * finalScale + (1 - animationProgress) * initScale;
Adam Cohen1d13c0b2020-04-21 16:29:12 -07002036 child.setReorderBounceScale(s);
Sunny Goyal849c6a22018-08-08 16:33:46 -07002037 }
2038
Adam Cohend024f982012-05-23 18:26:45 -07002039 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002040 if (a != null) {
2041 a.cancel();
2042 }
Adam Cohen19f37922012-03-21 11:59:11 -07002043 }
Adam Cohene7587d22012-05-24 18:50:02 -07002044
Adam Cohend9162062020-03-24 16:35:35 -07002045 /**
2046 * Smoothly returns the item to its baseline position / scale
2047 */
2048 @Thunk void finishAnimation() {
Adam Cohene7587d22012-05-24 18:50:02 -07002049 if (a != null) {
2050 a.cancel();
2051 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002052
Adam Cohend9162062020-03-24 16:35:35 -07002053 setInitialAnimationValuesToBaseline();
2054 ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS,
2055 animationProgress, 0);
2056 a = va;
Sunny Goyalf0b6db72018-08-13 16:10:14 -07002057 a.setInterpolator(DEACCEL_1_5);
Adam Cohend9162062020-03-24 16:35:35 -07002058 a.setDuration(REORDER_ANIMATION_DURATION);
Sunny Goyal5d2fc322015-07-06 22:52:49 -07002059 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07002060 }
Adam Cohen19f37922012-03-21 11:59:11 -07002061 }
2062
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002063 private void completeAndClearReorderPreviewAnimations() {
2064 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Adam Cohend9162062020-03-24 16:35:35 -07002065 a.finishAnimation();
Adam Cohen19f37922012-03-21 11:59:11 -07002066 }
2067 mShakeAnimators.clear();
2068 }
2069
Adam Cohen482ed822012-03-02 14:15:13 -08002070 private void commitTempPlacement() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002071 mTmpOccupied.copyTo(mOccupied);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002072
Sunny Goyalab770a12018-11-14 15:17:26 -08002073 int screenId = Launcher.cast(mActivity).getWorkspace().getIdForScreen(this);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002074 int container = Favorites.CONTAINER_DESKTOP;
2075
Sunny Goyalc13403c2016-11-18 23:44:48 -08002076 if (mContainerType == HOTSEAT) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002077 screenId = -1;
2078 container = Favorites.CONTAINER_HOTSEAT;
2079 }
2080
Michael Jurkaa52570f2012-03-20 03:18:20 -07002081 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002082 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002083 View child = mShortcutsAndWidgets.getChildAt(i);
2084 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2085 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002086 // We do a null check here because the item info can be null in the case of the
2087 // AllApps button in the hotseat.
2088 if (info != null) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002089 final boolean requiresDbUpdate = (info.cellX != lp.tmpCellX
2090 || info.cellY != lp.tmpCellY || info.spanX != lp.cellHSpan
2091 || info.spanY != lp.cellVSpan);
2092
Adam Cohen2acce882012-03-28 19:03:19 -07002093 info.cellX = lp.cellX = lp.tmpCellX;
2094 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002095 info.spanX = lp.cellHSpan;
2096 info.spanY = lp.cellVSpan;
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002097
2098 if (requiresDbUpdate) {
Sunny Goyalab770a12018-11-14 15:17:26 -08002099 Launcher.cast(mActivity).getModelWriter().modifyItemInDatabase(info, container,
2100 screenId, info.cellX, info.cellY, info.spanX, info.spanY);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002101 }
Adam Cohen2acce882012-03-28 19:03:19 -07002102 }
Adam Cohen482ed822012-03-02 14:15:13 -08002103 }
2104 }
2105
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002106 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002107 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002108 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002109 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002110 lp.useTmpCoords = useTempCoords;
2111 }
2112 }
2113
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002114 private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002115 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2116 int[] result = new int[2];
2117 int[] resultSpan = new int[2];
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002118 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
Adam Cohen482ed822012-03-02 14:15:13 -08002119 resultSpan);
2120 if (result[0] >= 0 && result[1] >= 0) {
2121 copyCurrentStateToSolution(solution, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002122 solution.cellX = result[0];
2123 solution.cellY = result[1];
2124 solution.spanX = resultSpan[0];
2125 solution.spanY = resultSpan[1];
Adam Cohen482ed822012-03-02 14:15:13 -08002126 solution.isSolution = true;
2127 } else {
2128 solution.isSolution = false;
2129 }
2130 return solution;
2131 }
2132
Adam Cohen19f37922012-03-21 11:59:11 -07002133 /* This seems like it should be obvious and straight-forward, but when the direction vector
2134 needs to match with the notion of the dragView pushing other views, we have to employ
2135 a slightly more subtle notion of the direction vector. The question is what two points is
2136 the vector between? The center of the dragView and its desired destination? Not quite, as
2137 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2138 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2139 or right, which helps make pushing feel right.
2140 */
2141 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2142 int spanY, View dragView, int[] resultDirection) {
Adam Cohen65086992020-02-19 08:40:49 -08002143
2144 //TODO(adamcohen) b/151776141 use the items visual center for the direction vector
Adam Cohen19f37922012-03-21 11:59:11 -07002145 int[] targetDestination = new int[2];
2146
2147 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2148 Rect dragRect = new Rect();
Jon Miranda228877d2021-02-09 11:05:00 -05002149 cellToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
Adam Cohen19f37922012-03-21 11:59:11 -07002150 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2151
2152 Rect dropRegionRect = new Rect();
2153 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2154 dragView, dropRegionRect, mIntersectingViews);
2155
2156 int dropRegionSpanX = dropRegionRect.width();
2157 int dropRegionSpanY = dropRegionRect.height();
2158
Jon Miranda228877d2021-02-09 11:05:00 -05002159 cellToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
Adam Cohen19f37922012-03-21 11:59:11 -07002160 dropRegionRect.height(), dropRegionRect);
2161
2162 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2163 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2164
2165 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2166 deltaX = 0;
2167 }
2168 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2169 deltaY = 0;
2170 }
2171
2172 if (deltaX == 0 && deltaY == 0) {
2173 // No idea what to do, give a random direction.
2174 resultDirection[0] = 1;
2175 resultDirection[1] = 0;
2176 } else {
2177 computeDirectionVector(deltaX, deltaY, resultDirection);
2178 }
2179 }
2180
2181 // For a given cell and span, fetch the set of views intersecting the region.
2182 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2183 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2184 if (boundingRect != null) {
2185 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2186 }
2187 intersectingViews.clear();
2188 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2189 Rect r1 = new Rect();
2190 final int count = mShortcutsAndWidgets.getChildCount();
2191 for (int i = 0; i < count; i++) {
2192 View child = mShortcutsAndWidgets.getChildAt(i);
2193 if (child == dragView) continue;
2194 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2195 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2196 if (Rect.intersects(r0, r1)) {
2197 mIntersectingViews.add(child);
2198 if (boundingRect != null) {
2199 boundingRect.union(r1);
2200 }
2201 }
2202 }
2203 }
2204
2205 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2206 View dragView, int[] result) {
2207 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2208 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2209 mIntersectingViews);
2210 return !mIntersectingViews.isEmpty();
2211 }
2212
2213 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002214 completeAndClearReorderPreviewAnimations();
2215 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2216 final int count = mShortcutsAndWidgets.getChildCount();
2217 for (int i = 0; i < count; i++) {
2218 View child = mShortcutsAndWidgets.getChildAt(i);
2219 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2220 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2221 lp.tmpCellX = lp.cellX;
2222 lp.tmpCellY = lp.cellY;
2223 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2224 0, false, false);
2225 }
Adam Cohen19f37922012-03-21 11:59:11 -07002226 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002227 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002228 }
Adam Cohen19f37922012-03-21 11:59:11 -07002229 }
2230
Adam Cohenbebf0422012-04-11 18:06:28 -07002231 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2232 View dragView, int[] direction, boolean commit) {
2233 int[] pixelXY = new int[2];
2234 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2235
2236 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002237 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002238 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2239
2240 setUseTempCoords(true);
2241 if (swapSolution != null && swapSolution.isSolution) {
2242 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2243 // committing anything or animating anything as we just want to determine if a solution
2244 // exists
2245 copySolutionToTempState(swapSolution, dragView);
2246 setItemPlacementDirty(true);
2247 animateItemsToSolution(swapSolution, dragView, commit);
2248
2249 if (commit) {
2250 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002251 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002252 setItemPlacementDirty(false);
2253 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002254 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
Adam Cohen65086992020-02-19 08:40:49 -08002255 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002256 }
2257 mShortcutsAndWidgets.requestLayout();
2258 }
2259 return swapSolution.isSolution;
2260 }
2261
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002262 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002263 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002264 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002265 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002266
2267 if (resultSpan == null) {
2268 resultSpan = new int[2];
2269 }
2270
Adam Cohen19f37922012-03-21 11:59:11 -07002271 // When we are checking drop validity or actually dropping, we don't recompute the
2272 // direction vector, since we want the solution to match the preview, and it's possible
2273 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002274 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2275 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002276 mDirectionVector[0] = mPreviousReorderDirection[0];
2277 mDirectionVector[1] = mPreviousReorderDirection[1];
2278 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002279 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2280 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2281 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002282 }
2283 } else {
2284 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2285 mPreviousReorderDirection[0] = mDirectionVector[0];
2286 mPreviousReorderDirection[1] = mDirectionVector[1];
2287 }
2288
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002289 // Find a solution involving pushing / displacing any items in the way
2290 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002291 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2292
2293 // We attempt the approach which doesn't shuffle views at all
2294 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2295 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2296
2297 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002298
2299 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2300 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002301 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2302 finalSolution = swapSolution;
2303 } else if (noShuffleSolution.isSolution) {
2304 finalSolution = noShuffleSolution;
2305 }
2306
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002307 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002308 if (finalSolution != null) {
Adam Cohen65086992020-02-19 08:40:49 -08002309 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
Adam Cohenfe692872013-12-11 14:47:23 -08002310 ReorderPreviewAnimation.MODE_HINT);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002311 result[0] = finalSolution.cellX;
2312 result[1] = finalSolution.cellY;
2313 resultSpan[0] = finalSolution.spanX;
2314 resultSpan[1] = finalSolution.spanY;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002315 } else {
2316 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2317 }
2318 return result;
2319 }
2320
Adam Cohen482ed822012-03-02 14:15:13 -08002321 boolean foundSolution = true;
2322 if (!DESTRUCTIVE_REORDER) {
2323 setUseTempCoords(true);
2324 }
2325
2326 if (finalSolution != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002327 result[0] = finalSolution.cellX;
2328 result[1] = finalSolution.cellY;
2329 resultSpan[0] = finalSolution.spanX;
2330 resultSpan[1] = finalSolution.spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002331
2332 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2333 // committing anything or animating anything as we just want to determine if a solution
2334 // exists
2335 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2336 if (!DESTRUCTIVE_REORDER) {
2337 copySolutionToTempState(finalSolution, dragView);
2338 }
2339 setItemPlacementDirty(true);
2340 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2341
Adam Cohen19f37922012-03-21 11:59:11 -07002342 if (!DESTRUCTIVE_REORDER &&
2343 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002344 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002345 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002346 setItemPlacementDirty(false);
2347 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002348 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
Adam Cohen65086992020-02-19 08:40:49 -08002349 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002350 }
2351 }
2352 } else {
2353 foundSolution = false;
2354 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2355 }
2356
2357 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2358 setUseTempCoords(false);
2359 }
Adam Cohen482ed822012-03-02 14:15:13 -08002360
Michael Jurkaa52570f2012-03-20 03:18:20 -07002361 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002362 return result;
2363 }
2364
Adam Cohen19f37922012-03-21 11:59:11 -07002365 void setItemPlacementDirty(boolean dirty) {
2366 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002367 }
Adam Cohen19f37922012-03-21 11:59:11 -07002368 boolean isItemPlacementDirty() {
2369 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002370 }
2371
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002372 private static class ItemConfiguration extends CellAndSpan {
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002373 final ArrayMap<View, CellAndSpan> map = new ArrayMap<>();
2374 private final ArrayMap<View, CellAndSpan> savedMap = new ArrayMap<>();
2375 final ArrayList<View> sortedViews = new ArrayList<>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002376 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002377 boolean isSolution = false;
Adam Cohen482ed822012-03-02 14:15:13 -08002378
Adam Cohenf3900c22012-11-16 18:28:11 -08002379 void save() {
2380 // Copy current state into savedMap
2381 for (View v: map.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002382 savedMap.get(v).copyFrom(map.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002383 }
2384 }
2385
2386 void restore() {
2387 // Restore current state from savedMap
2388 for (View v: savedMap.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002389 map.get(v).copyFrom(savedMap.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002390 }
2391 }
2392
2393 void add(View v, CellAndSpan cs) {
2394 map.put(v, cs);
2395 savedMap.put(v, new CellAndSpan());
2396 sortedViews.add(v);
2397 }
2398
Adam Cohen482ed822012-03-02 14:15:13 -08002399 int area() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002400 return spanX * spanY;
Adam Cohenf3900c22012-11-16 18:28:11 -08002401 }
2402
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002403 void getBoundingRectForViews(ArrayList<View> views, Rect outRect) {
2404 boolean first = true;
2405 for (View v: views) {
2406 CellAndSpan c = map.get(v);
2407 if (first) {
2408 outRect.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2409 first = false;
2410 } else {
2411 outRect.union(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2412 }
2413 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002414 }
Adam Cohen482ed822012-03-02 14:15:13 -08002415 }
2416
Adam Cohendf035382011-04-11 17:22:04 -07002417 /**
Adam Cohendf035382011-04-11 17:22:04 -07002418 * Find a starting cell position that will fit the given bounds nearest the requested
2419 * cell location. Uses Euclidean distance to score multiple vacant areas.
2420 *
2421 * @param pixelX The X location at which you want to search for a vacant area.
2422 * @param pixelY The Y location at which you want to search for a vacant area.
2423 * @param spanX Horizontal span of the object.
2424 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07002425 * @param result Previously returned value to possibly recycle.
2426 * @return The X, Y cell of a vacant area that can contain this object,
2427 * nearest the requested location.
2428 */
Adam Cohenf9c184a2016-01-15 16:47:43 -08002429 public int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002430 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002431 }
2432
Michael Jurka0280c3b2010-09-17 15:00:07 -07002433 boolean existsEmptyCell() {
2434 return findCellForSpan(null, 1, 1);
2435 }
2436
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002437 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002438 * Finds the upper-left coordinate of the first rectangle in the grid that can
2439 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2440 * then this method will only return coordinates for rectangles that contain the cell
2441 * (intersectX, intersectY)
2442 *
2443 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2444 * can be found.
2445 * @param spanX The horizontal span of the cell we want to find.
2446 * @param spanY The vertical span of the cell we want to find.
2447 *
2448 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002449 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002450 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002451 if (cellXY == null) {
2452 cellXY = new int[2];
Michael Jurka0280c3b2010-09-17 15:00:07 -07002453 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002454 return mOccupied.findVacantCell(cellXY, spanX, spanY);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002455 }
2456
2457 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002458 * A drag event has begun over this layout.
2459 * It may have begun over this layout (in which case onDragChild is called first),
2460 * or it may have begun on another layout.
2461 */
2462 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002463 mDragging = true;
2464 }
2465
2466 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002467 * Called when drag has left this CellLayout or has been completed (successfully or not)
2468 */
2469 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002470 // This can actually be called when we aren't in a drag, e.g. when adding a new
2471 // item to this layout via the customize drawer.
2472 // Guard against that case.
2473 if (mDragging) {
2474 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002475 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002476
2477 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002478 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002479 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2480 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002481 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002482 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002483 }
2484
2485 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002486 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002487 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002488 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002489 *
2490 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002491 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002492 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002493 if (child != null) {
2494 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002495 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002496 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002497 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002498 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002499 }
2500
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002501 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002502 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002503 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002504 * @param cellX X coordinate of upper left corner expressed as a cell position
2505 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002506 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002507 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002508 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002509 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002510 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002511 final int cellWidth = mCellWidth;
2512 final int cellHeight = mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -07002513
Winson Chung4b825dcd2011-06-19 12:41:22 -07002514 final int hStartPadding = getPaddingLeft();
2515 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002516
Jon Miranda228877d2021-02-09 11:05:00 -05002517 int x = hStartPadding + (cellX * mBorderSpacing) + (cellX * cellWidth);
2518 int y = vStartPadding + (cellY * mBorderSpacing) + (cellY * cellHeight);
2519
2520 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * mBorderSpacing);
2521 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * mBorderSpacing);
Winson Chungaafa03c2010-06-11 17:34:16 -07002522
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002523 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002524 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002525
Adam Cohend4844c32011-02-18 19:25:06 -08002526 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002527 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002528 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002529 mOccupied.markCells(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002530 }
2531
Adam Cohend4844c32011-02-18 19:25:06 -08002532 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002533 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002534 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002535 mOccupied.markCells(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002536 }
2537
Adam Cohen2801caf2011-05-13 20:57:39 -07002538 public int getDesiredWidth() {
Jon Miranda228877d2021-02-09 11:05:00 -05002539 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth)
2540 + ((mCountX - 1) * mBorderSpacing);
Adam Cohen2801caf2011-05-13 20:57:39 -07002541 }
2542
2543 public int getDesiredHeight() {
Jon Miranda228877d2021-02-09 11:05:00 -05002544 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight)
2545 + ((mCountY - 1) * mBorderSpacing);
Adam Cohen2801caf2011-05-13 20:57:39 -07002546 }
2547
Michael Jurka66d72172011-04-12 16:29:25 -07002548 public boolean isOccupied(int x, int y) {
2549 if (x < mCountX && y < mCountY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002550 return mOccupied.cells[x][y];
Michael Jurka66d72172011-04-12 16:29:25 -07002551 } else {
2552 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2553 }
2554 }
2555
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002556 @Override
2557 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2558 return new CellLayout.LayoutParams(getContext(), attrs);
2559 }
2560
2561 @Override
2562 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2563 return p instanceof CellLayout.LayoutParams;
2564 }
2565
2566 @Override
2567 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2568 return new CellLayout.LayoutParams(p);
2569 }
2570
2571 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2572 /**
2573 * Horizontal location of the item in the grid.
2574 */
2575 @ViewDebug.ExportedProperty
2576 public int cellX;
2577
2578 /**
2579 * Vertical location of the item in the grid.
2580 */
2581 @ViewDebug.ExportedProperty
2582 public int cellY;
2583
2584 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002585 * Temporary horizontal location of the item in the grid during reorder
2586 */
2587 public int tmpCellX;
2588
2589 /**
2590 * Temporary vertical location of the item in the grid during reorder
2591 */
2592 public int tmpCellY;
2593
2594 /**
2595 * Indicates that the temporary coordinates should be used to layout the items
2596 */
2597 public boolean useTmpCoords;
2598
2599 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002600 * Number of cells spanned horizontally by the item.
2601 */
2602 @ViewDebug.ExportedProperty
2603 public int cellHSpan;
2604
2605 /**
2606 * Number of cells spanned vertically by the item.
2607 */
2608 @ViewDebug.ExportedProperty
2609 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002610
Adam Cohen1b607ed2011-03-03 17:26:50 -08002611 /**
2612 * Indicates whether the item will set its x, y, width and height parameters freely,
2613 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2614 */
Adam Cohend4844c32011-02-18 19:25:06 -08002615 public boolean isLockedToGrid = true;
2616
Adam Cohen482ed822012-03-02 14:15:13 -08002617 /**
2618 * Indicates whether this item can be reordered. Always true except in the case of the
Sunny Goyalda4fe1a2016-05-26 16:05:17 -07002619 * the AllApps button and QSB place holder.
Adam Cohen482ed822012-03-02 14:15:13 -08002620 */
2621 public boolean canReorder = true;
2622
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002623 // X coordinate of the view in the layout.
2624 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002625 public int x;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002626 // Y coordinate of the view in the layout.
2627 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002628 public int y;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002629
Romain Guy84f296c2009-11-04 15:00:44 -08002630 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002631
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002632 public LayoutParams(Context c, AttributeSet attrs) {
2633 super(c, attrs);
2634 cellHSpan = 1;
2635 cellVSpan = 1;
2636 }
2637
2638 public LayoutParams(ViewGroup.LayoutParams source) {
2639 super(source);
2640 cellHSpan = 1;
2641 cellVSpan = 1;
2642 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002643
2644 public LayoutParams(LayoutParams source) {
2645 super(source);
2646 this.cellX = source.cellX;
2647 this.cellY = source.cellY;
2648 this.cellHSpan = source.cellHSpan;
2649 this.cellVSpan = source.cellVSpan;
2650 }
2651
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002652 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002653 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002654 this.cellX = cellX;
2655 this.cellY = cellY;
2656 this.cellHSpan = cellHSpan;
2657 this.cellVSpan = cellVSpan;
2658 }
2659
Jon Miranda228877d2021-02-09 11:05:00 -05002660 public void setup(int cellWidth, int cellHeight, boolean invertHorizontally, int colCount,
2661 int rowCount, int borderSpacing) {
2662 setup(cellWidth, cellHeight, invertHorizontally, colCount, rowCount, 1.0f, 1.0f,
2663 borderSpacing);
Jon Miranda7ae64ff2016-11-21 16:18:46 -08002664 }
2665
2666 /**
Jon Miranda228877d2021-02-09 11:05:00 -05002667 * Use this method, as opposed to {@link #setup(int, int, boolean, int, int, int)},
2668 * if the view needs to be scaled.
Jon Miranda7ae64ff2016-11-21 16:18:46 -08002669 *
2670 * ie. In multi-window mode, we setup widgets so that they are measured and laid out
2671 * using their full/invariant device profile sizes.
2672 */
2673 public void setup(int cellWidth, int cellHeight, boolean invertHorizontally, int colCount,
Jon Miranda228877d2021-02-09 11:05:00 -05002674 int rowCount, float cellScaleX, float cellScaleY, int borderSpacing) {
Adam Cohend4844c32011-02-18 19:25:06 -08002675 if (isLockedToGrid) {
2676 final int myCellHSpan = cellHSpan;
2677 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002678 int myCellX = useTmpCoords ? tmpCellX : cellX;
2679 int myCellY = useTmpCoords ? tmpCellY : cellY;
2680
2681 if (invertHorizontally) {
2682 myCellX = colCount - myCellX - cellHSpan;
2683 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002684
Jon Miranda228877d2021-02-09 11:05:00 -05002685 int hBorderSpacing = (myCellHSpan - 1) * borderSpacing;
2686 int vBorderSpacing = (myCellVSpan - 1) * borderSpacing;
2687
2688 float myCellWidth = ((myCellHSpan * cellWidth) + hBorderSpacing) / cellScaleX;
2689 float myCellHeight = ((myCellVSpan * cellHeight) + vBorderSpacing) / cellScaleY;
2690
2691 width = Math.round(myCellWidth) - leftMargin - rightMargin;
2692 height = Math.round(myCellHeight) - topMargin - bottomMargin;
2693 x = leftMargin + (myCellX * cellWidth) + (myCellX * borderSpacing);
2694 y = topMargin + (myCellY * cellHeight) + (myCellY * borderSpacing);
Adam Cohend4844c32011-02-18 19:25:06 -08002695 }
2696 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002697
Sunny Goyal11a50742019-08-07 09:24:26 -07002698 /**
2699 * Sets the position to the provided point
2700 */
Jon Miranda228877d2021-02-09 11:05:00 -05002701 public void setCellXY(Point point) {
Sunny Goyal11a50742019-08-07 09:24:26 -07002702 cellX = point.x;
2703 cellY = point.y;
2704 }
2705
Winson Chungaafa03c2010-06-11 17:34:16 -07002706 public String toString() {
2707 return "(" + this.cellX + ", " + this.cellY + ")";
2708 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002709 }
2710
Michael Jurka0280c3b2010-09-17 15:00:07 -07002711 // This class stores info for two purposes:
2712 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2713 // its spanX, spanY, and the screen it is on
2714 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2715 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2716 // the CellLayout that was long clicked
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002717 public static final class CellInfo extends CellAndSpan {
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002718 public final View cell;
Sunny Goyalefb7e842018-10-04 15:11:00 -07002719 final int screenId;
2720 final int container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002721
Sunny Goyal83a8f042015-05-19 12:52:12 -07002722 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002723 cellX = info.cellX;
2724 cellY = info.cellY;
2725 spanX = info.spanX;
2726 spanY = info.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002727 cell = v;
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002728 screenId = info.screenId;
2729 container = info.container;
2730 }
2731
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002732 @Override
2733 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002734 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2735 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002736 }
2737 }
Michael Jurkad771c962011-08-09 15:00:48 -07002738
Tony Wickham86930612015-09-09 13:50:40 -07002739 /**
Samuel Fufa1e2d0042019-11-18 17:12:46 -08002740 * A Delegated cell Drawing for drawing on CellLayout
2741 */
2742 public abstract static class DelegatedCellDrawing {
2743 public int mDelegateCellX;
2744 public int mDelegateCellY;
2745
2746 /**
2747 * Draw under CellLayout
2748 */
2749 public abstract void drawUnderItem(Canvas canvas);
2750
2751 /**
2752 * Draw over CellLayout
2753 */
2754 public abstract void drawOverItem(Canvas canvas);
2755 }
2756
2757 /**
Tony Wickham86930612015-09-09 13:50:40 -07002758 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2759 * if necessary).
2760 */
2761 public boolean hasReorderSolution(ItemInfo itemInfo) {
2762 int[] cellPoint = new int[2];
2763 // Check for a solution starting at every cell.
2764 for (int cellX = 0; cellX < getCountX(); cellX++) {
2765 for (int cellY = 0; cellY < getCountY(); cellY++) {
2766 cellToPoint(cellX, cellY, cellPoint);
2767 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2768 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2769 true, new ItemConfiguration()).isSolution) {
2770 return true;
2771 }
2772 }
2773 }
2774 return false;
2775 }
2776
Samuel Fufaa4211432020-02-25 18:47:54 -08002777 /**
2778 * Finds solution to accept hotseat migration to cell layout. commits solution if commitConfig
2779 */
2780 public boolean makeSpaceForHotseatMigration(boolean commitConfig) {
Samuel Fufaa4211432020-02-25 18:47:54 -08002781 int[] cellPoint = new int[2];
2782 int[] directionVector = new int[]{0, -1};
2783 cellToPoint(0, mCountY, cellPoint);
2784 ItemConfiguration configuration = new ItemConfiguration();
2785 if (findReorderSolution(cellPoint[0], cellPoint[1], mCountX, 1, mCountX, 1,
2786 directionVector, null, false, configuration).isSolution) {
2787 if (commitConfig) {
2788 copySolutionToTempState(configuration, null);
2789 commitTempPlacement();
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002790 // undo marking cells occupied since there is actually nothing being placed yet.
2791 mOccupied.markCells(0, mCountY - 1, mCountX, 1, false);
Samuel Fufaa4211432020-02-25 18:47:54 -08002792 }
2793 return true;
2794 }
2795 return false;
2796 }
2797
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002798 /**
2799 * returns a copy of cell layout's grid occupancy
2800 */
2801 public GridOccupancy cloneGridOccupancy() {
2802 GridOccupancy occupancy = new GridOccupancy(mCountX, mCountY);
2803 mOccupied.copyTo(occupancy);
2804 return occupancy;
2805 }
2806
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002807 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002808 return mOccupied.isRegionVacant(x, y, spanX, spanY);
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002809 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002810}