blob: 2809bd5a96ac12088cce85fdfa1e4dc042ed8981 [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;
Winson Chungaafa03c2010-06-11 17:34:16 -070091
Sunny Goyal4ffec482016-02-09 11:28:52 -080092 @ViewDebug.ExportedProperty(category = "launcher")
Sunny Goyalff4ba2d2016-04-02 14:12:34 -070093 private int mCountX;
Sunny Goyal4ffec482016-02-09 11:28:52 -080094 @ViewDebug.ExportedProperty(category = "launcher")
Sunny Goyalff4ba2d2016-04-02 14:12:34 -070095 private int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080096
Adam Cohen917e3882013-10-31 15:03:35 -070097 private boolean mDropPending = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098
Patrick Dubroyde7658b2010-09-27 11:15:43 -070099 // These are temporary variables to prevent having to allocate a new object just to
100 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Adam Cohen091440a2015-03-18 14:16:05 -0700101 @Thunk final int[] mTmpPoint = new int[2];
Sunny Goyal2805e632015-05-20 15:35:32 -0700102 @Thunk final int[] mTempLocation = new int[2];
Adam Cohend9162062020-03-24 16:35:35 -0700103 final PointF mTmpPointF = new PointF();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700104
Adam Cohen65086992020-02-19 08:40:49 -0800105 // Used to visualize / debug the Grid of the CellLayout
106 private static final boolean VISUALIZE_GRID = false;
107 private Rect mVisualizeGridRect = new Rect();
108 private Paint mVisualizeGridPaint = new Paint();
109
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700110 private GridOccupancy mOccupied;
111 private GridOccupancy mTmpOccupied;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112
Michael Jurkadee05892010-07-27 10:01:56 -0700113 private OnTouchListener mInterceptTouchListener;
114
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800115 private final ArrayList<DelegatedCellDrawing> mDelegatedCellDrawings = new ArrayList<>();
Jon Mirandaa0233f72017-06-22 18:34:45 -0700116 final PreviewBackground mFolderLeaveBehind = new PreviewBackground();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700117
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800118 private static final int[] BACKGROUND_STATE_ACTIVE = new int[] { android.R.attr.state_active };
Sunny Goyale15e2a82017-12-15 13:05:42 -0800119 private static final int[] BACKGROUND_STATE_DEFAULT = EMPTY_STATE_SET;
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800120 private final Drawable mBackground;
Sunny Goyal2805e632015-05-20 15:35:32 -0700121
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700122 // These values allow a fixed measurement to be set on the CellLayout.
123 private int mFixedWidth = -1;
124 private int mFixedHeight = -1;
125
Michael Jurka33945b22010-12-21 18:19:38 -0800126 // If we're actively dragging something over this screen, mIsDragOverlapping is true
127 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700128
Winson Chung150fbab2010-09-29 17:14:26 -0700129 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700130 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700131 @Thunk final Rect[] mDragOutlines = new Rect[4];
132 @Thunk final float[] mDragOutlineAlphas = new float[mDragOutlines.length];
133 private final InterruptibleInOutAnimator[] mDragOutlineAnims =
Joe Onorato4be866d2010-10-10 11:26:02 -0700134 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700135
136 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700137 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700138 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700139
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700140 @Thunk final ArrayMap<LayoutParams, Animator> mReorderAnimators = new ArrayMap<>();
Adam Cohend9162062020-03-24 16:35:35 -0700141 @Thunk final ArrayMap<Reorderable, ReorderPreviewAnimation> mShakeAnimators = new ArrayMap<>();
Adam Cohen19f37922012-03-21 11:59:11 -0700142
143 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700144
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700145 // When a drag operation is in progress, holds the nearest cell to the touch point
146 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800147
Joe Onorato4be866d2010-10-10 11:26:02 -0700148 private boolean mDragging = false;
149
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700150 private final TimeInterpolator mEaseOutInterpolator;
151 private final ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700152
Sunny Goyalc13403c2016-11-18 23:44:48 -0800153 @Retention(RetentionPolicy.SOURCE)
154 @IntDef({WORKSPACE, HOTSEAT, FOLDER})
155 public @interface ContainerType{}
156 public static final int WORKSPACE = 0;
157 public static final int HOTSEAT = 1;
158 public static final int FOLDER = 2;
159
160 @ContainerType private final int mContainerType;
161
Jon Mirandab28c4fc2017-06-20 10:58:36 -0700162 private final float mChildScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800163
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800164 public static final int MODE_SHOW_REORDER_HINT = 0;
165 public static final int MODE_DRAG_OVER = 1;
166 public static final int MODE_ON_DROP = 2;
167 public static final int MODE_ON_DROP_EXTERNAL = 3;
168 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700169 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800170 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
171
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800172 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700173 private static final int REORDER_ANIMATION_DURATION = 150;
Sunny Goyalc13403c2016-11-18 23:44:48 -0800174 @Thunk final float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700175
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700176 private final ArrayList<View> mIntersectingViews = new ArrayList<>();
177 private final Rect mOccupiedRect = new Rect();
178 private final int[] mDirectionVector = new int[2];
179 final int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700180 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800181
Sunny Goyal2805e632015-05-20 15:35:32 -0700182 private final Rect mTempRect = new Rect();
Winson Chung3a6e7f32013-10-09 15:50:52 -0700183
Sunny Goyal73b5a272019-12-09 14:55:56 -0800184 private static final Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700185
Adam Cohenc9735cf2015-01-23 16:11:55 -0800186 // Related to accessible drag and drop
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700187 DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800188
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800189 public CellLayout(Context context) {
190 this(context, null);
191 }
192
193 public CellLayout(Context context, AttributeSet attrs) {
194 this(context, attrs, 0);
195 }
196
197 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
198 super(context, attrs, defStyle);
Sunny Goyalc13403c2016-11-18 23:44:48 -0800199 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
200 mContainerType = a.getInteger(R.styleable.CellLayout_containerType, WORKSPACE);
201 a.recycle();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700202
203 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
204 // the user where a dragged item will land when dropped.
205 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800206 setClipToPadding(false);
Sunny Goyalab770a12018-11-14 15:17:26 -0800207 mActivity = ActivityContext.lookupContext(context);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700208
Sunny Goyalc4d32012020-04-03 17:10:11 -0700209 DeviceProfile grid = mActivity.getDeviceProfile();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800210
Winson Chung11a1a532013-09-13 11:14:45 -0700211 mCellWidth = mCellHeight = -1;
Nilesh Agrawal5f7099a2014-01-02 15:54:57 -0800212 mFixedCellWidth = mFixedCellHeight = -1;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700213
214 mCountX = grid.inv.numColumns;
215 mCountY = grid.inv.numRows;
216 mOccupied = new GridOccupancy(mCountX, mCountY);
217 mTmpOccupied = new GridOccupancy(mCountX, mCountY);
218
Adam Cohen5b53f292012-03-29 14:30:35 -0700219 mPreviousReorderDirection[0] = INVALID_DIRECTION;
220 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800221
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800222 mFolderLeaveBehind.mDelegateCellX = -1;
223 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenefca0272016-02-24 19:19:06 -0800224
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800225 setAlwaysDrawnWithCacheEnabled(false);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700226 final Resources res = getResources();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700227
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800228 mBackground = res.getDrawable(R.drawable.bg_celllayout);
Sunny Goyal2805e632015-05-20 15:35:32 -0700229 mBackground.setCallback(this);
Sunny Goyalaeb16432017-10-16 11:46:41 -0700230 mBackground.setAlpha(0);
Michael Jurka33945b22010-12-21 18:19:38 -0800231
Sunny Goyalc13403c2016-11-18 23:44:48 -0800232 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE * grid.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700233
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700234 // Initialize the data structures used for the drag visualization.
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -0700235 mEaseOutInterpolator = Interpolators.DEACCEL_2_5; // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700236 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700237 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800238 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700239 }
Mario Bertschler54ba6012017-06-08 10:53:53 -0700240 mDragOutlinePaint.setColor(Themes.getAttrColor(context, R.attr.workspaceTextColor));
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700241
242 // When dragging things around the home screens, we show a green outline of
243 // where the item will land. The outlines gradually fade out, leaving a trail
244 // behind the drag path.
245 // Set up all the animations that are used to implement this fading.
246 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700247 final float fromAlphaValue = 0;
248 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700249
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700250 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700251
252 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700253 final InterruptibleInOutAnimator anim =
Sunny Goyal849c6a22018-08-08 16:33:46 -0700254 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700255 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700256 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700257 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700258 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700259 final Bitmap outline = (Bitmap)anim.getTag();
260
261 // If an animation is started and then stopped very quickly, we can still
262 // get spurious updates we've cleared the tag. Guard against this.
263 if (outline == null) {
Tony Wickhama0628cc2015-10-14 15:23:04 -0700264 if (LOGD) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700265 Object val = animation.getAnimatedValue();
266 Log.d(TAG, "anim " + thisIndex + " update: " + val +
267 ", isStopped " + anim.isStopped());
268 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700269 // Try to prevent it from continuing to run
270 animation.cancel();
271 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700272 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800273 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700274 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700275 }
276 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700277 // The animation holds a reference to the drag outline bitmap as long is it's
278 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700279 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700280 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700281 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700282 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700283 anim.setTag(null);
284 }
285 }
286 });
287 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700288 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700289
Sunny Goyalc13403c2016-11-18 23:44:48 -0800290 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context, mContainerType);
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530291 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700292 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700293 }
294
Sunny Goyal9b180102020-03-11 10:02:29 -0700295 /**
296 * Sets or clears a delegate used for accessible drag and drop
297 */
298 public void setDragAndDropAccessibilityDelegate(DragAndDropAccessibilityDelegate delegate) {
299 setOnClickListener(delegate);
Sunny Goyal9b180102020-03-11 10:02:29 -0700300 ViewCompat.setAccessibilityDelegate(this, delegate);
301
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700302 mTouchHelper = delegate;
303 int accessibilityFlag = mTouchHelper != null
Sunny Goyal9b180102020-03-11 10:02:29 -0700304 ? IMPORTANT_FOR_ACCESSIBILITY_YES : IMPORTANT_FOR_ACCESSIBILITY_NO;
305 setImportantForAccessibility(accessibilityFlag);
306 getShortcutsAndWidgets().setImportantForAccessibility(accessibilityFlag);
Adam Cohenc9735cf2015-01-23 16:11:55 -0800307
308 // Invalidate the accessibility hierarchy
309 if (getParent() != null) {
310 getParent().notifySubtreeAccessibilityStateChanged(
311 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
312 }
313 }
314
315 @Override
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700316 public boolean dispatchHoverEvent(MotionEvent event) {
317 // Always attempt to dispatch hover events to accessibility first.
318 if (mTouchHelper != null && mTouchHelper.dispatchHoverEvent(event)) {
319 return true;
320 }
321 return super.dispatchHoverEvent(event);
322 }
323
324 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800325 public boolean onInterceptTouchEvent(MotionEvent ev) {
Winson Chungf9935182020-10-23 09:26:44 -0700326 return mTouchHelper != null
327 || (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev));
Adam Cohenc9735cf2015-01-23 16:11:55 -0800328 }
329
Chris Craik01f2d7f2013-10-01 14:41:56 -0700330 public void enableHardwareLayer(boolean hasLayer) {
331 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700332 }
333
vadimt04f356f2019-02-14 18:46:36 -0800334 public boolean isHardwareLayerEnabled() {
335 return mShortcutsAndWidgets.getLayerType() == LAYER_TYPE_HARDWARE;
336 }
337
Winson Chung5f8afe62013-08-12 16:19:28 -0700338 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700339 mFixedCellWidth = mCellWidth = width;
340 mFixedCellHeight = mCellHeight = height;
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530341 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY);
Winson Chung5f8afe62013-08-12 16:19:28 -0700342 }
343
Adam Cohen2801caf2011-05-13 20:57:39 -0700344 public void setGridSize(int x, int y) {
345 mCountX = x;
346 mCountY = y;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700347 mOccupied = new GridOccupancy(mCountX, mCountY);
348 mTmpOccupied = new GridOccupancy(mCountX, mCountY);
Adam Cohen7fbec102012-03-27 12:42:19 -0700349 mTempRectStack.clear();
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530350 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY);
Adam Cohen76fc0852011-06-17 13:26:23 -0700351 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700352 }
353
Adam Cohen2374abf2013-04-16 14:56:57 -0700354 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
355 public void setInvertIfRtl(boolean invert) {
356 mShortcutsAndWidgets.setInvertIfRtl(invert);
357 }
358
Adam Cohen917e3882013-10-31 15:03:35 -0700359 public void setDropPending(boolean pending) {
360 mDropPending = pending;
361 }
362
363 public boolean isDropPending() {
364 return mDropPending;
365 }
366
Adam Cohenc50438c2014-08-19 17:43:05 -0700367 void setIsDragOverlapping(boolean isDragOverlapping) {
368 if (mIsDragOverlapping != isDragOverlapping) {
369 mIsDragOverlapping = isDragOverlapping;
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800370 mBackground.setState(mIsDragOverlapping
371 ? BACKGROUND_STATE_ACTIVE : BACKGROUND_STATE_DEFAULT);
Adam Cohenc50438c2014-08-19 17:43:05 -0700372 invalidate();
373 }
374 }
375
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700376 @Override
377 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700378 ParcelableSparseArray jail = getJailedArray(container);
379 super.dispatchSaveInstanceState(jail);
380 container.put(R.id.cell_layout_jail_id, jail);
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700381 }
382
383 @Override
384 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700385 super.dispatchRestoreInstanceState(getJailedArray(container));
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700386 }
387
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700388 /**
389 * Wrap the SparseArray in another Parcelable so that the item ids do not conflict with our
390 * our internal resource ids
391 */
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700392 private ParcelableSparseArray getJailedArray(SparseArray<Parcelable> container) {
393 final Parcelable parcelable = container.get(R.id.cell_layout_jail_id);
394 return parcelable instanceof ParcelableSparseArray ?
395 (ParcelableSparseArray) parcelable : new ParcelableSparseArray();
396 }
397
Tony Wickham0f97b782015-12-02 17:55:07 -0800398 public boolean getIsDragOverlapping() {
399 return mIsDragOverlapping;
400 }
401
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700402 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700403 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700404 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
405 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
406 // When we're small, we are either drawn normally or in the "accepts drops" state (during
407 // a drag). However, we also drag the mini hover background *over* one of those two
408 // backgrounds
Sunny Goyalaeb16432017-10-16 11:46:41 -0700409 if (mBackground.getAlpha() > 0) {
Sunny Goyal2805e632015-05-20 15:35:32 -0700410 mBackground.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700411 }
Romain Guya6abce82009-11-10 02:54:41 -0800412
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700413 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700414 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700415 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700416 if (alpha > 0) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700417 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700418 paint.setAlpha((int)(alpha + .5f));
Sunny Goyal106bf642015-07-16 12:18:06 -0700419 canvas.drawBitmap(b, null, mDragOutlines[i], paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700420 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700421 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800422
Adam Cohen482ed822012-03-02 14:15:13 -0800423 if (DEBUG_VISUALIZE_OCCUPIED) {
424 int[] pt = new int[2];
425 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700426 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800427 for (int i = 0; i < mCountX; i++) {
428 for (int j = 0; j < mCountY; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700429 if (mOccupied.cells[i][j]) {
Adam Cohen482ed822012-03-02 14:15:13 -0800430 cellToPoint(i, j, pt);
431 canvas.save();
432 canvas.translate(pt[0], pt[1]);
433 cd.draw(canvas);
434 canvas.restore();
435 }
436 }
437 }
438 }
439
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800440 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
441 DelegatedCellDrawing cellDrawing = mDelegatedCellDrawings.get(i);
442 cellToPoint(cellDrawing.mDelegateCellX, cellDrawing.mDelegateCellY, mTempLocation);
Adam Cohenefca0272016-02-24 19:19:06 -0800443 canvas.save();
444 canvas.translate(mTempLocation[0], mTempLocation[1]);
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800445 cellDrawing.drawUnderItem(canvas);
Adam Cohenefca0272016-02-24 19:19:06 -0800446 canvas.restore();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700447 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700448
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800449 if (mFolderLeaveBehind.mDelegateCellX >= 0 && mFolderLeaveBehind.mDelegateCellY >= 0) {
450 cellToPoint(mFolderLeaveBehind.mDelegateCellX,
451 mFolderLeaveBehind.mDelegateCellY, mTempLocation);
Adam Cohenefca0272016-02-24 19:19:06 -0800452 canvas.save();
453 canvas.translate(mTempLocation[0], mTempLocation[1]);
Sunny Goyal19b93b72017-02-19 20:21:37 -0800454 mFolderLeaveBehind.drawLeaveBehind(canvas);
Adam Cohenefca0272016-02-24 19:19:06 -0800455 canvas.restore();
Adam Cohenc51934b2011-07-26 21:07:43 -0700456 }
Adam Cohen65086992020-02-19 08:40:49 -0800457
458 if (VISUALIZE_GRID) {
459 visualizeGrid(canvas);
460 }
461 }
462
463 protected void visualizeGrid(Canvas canvas) {
464 mVisualizeGridRect.set(0, 0, mCellWidth, mCellHeight);
465 mVisualizeGridPaint.setStrokeWidth(4);
466
467 for (int i = 0; i < mCountX; i++) {
468 for (int j = 0; j < mCountY; j++) {
469 canvas.save();
470
471 int transX = i * mCellWidth;
472 int transY = j * mCellHeight;
473
474 canvas.translate(getPaddingLeft() + transX, getPaddingTop() + transY);
475
476 mVisualizeGridPaint.setStyle(Paint.Style.FILL);
477 mVisualizeGridPaint.setColor(Color.argb(80, 255, 100, 100));
478
479 canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
480
481 mVisualizeGridPaint.setStyle(Paint.Style.STROKE);
482 mVisualizeGridPaint.setColor(Color.argb(255, 255, 100, 100));
483
484 canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
485 canvas.restore();
486 }
487 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700488 }
489
Adam Cohenefca0272016-02-24 19:19:06 -0800490 @Override
491 protected void dispatchDraw(Canvas canvas) {
492 super.dispatchDraw(canvas);
493
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800494 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
495 DelegatedCellDrawing bg = mDelegatedCellDrawings.get(i);
496 cellToPoint(bg.mDelegateCellX, bg.mDelegateCellY, mTempLocation);
497 canvas.save();
498 canvas.translate(mTempLocation[0], mTempLocation[1]);
499 bg.drawOverItem(canvas);
500 canvas.restore();
Adam Cohenefca0272016-02-24 19:19:06 -0800501 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700502 }
503
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800504 /**
505 * Add Delegated cell drawing
506 */
507 public void addDelegatedCellDrawing(DelegatedCellDrawing bg) {
508 mDelegatedCellDrawings.add(bg);
Adam Cohenefca0272016-02-24 19:19:06 -0800509 }
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800510
511 /**
512 * Remove item from DelegatedCellDrawings
513 */
514 public void removeDelegatedCellDrawing(DelegatedCellDrawing bg) {
515 mDelegatedCellDrawings.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700516 }
517
Adam Cohenc51934b2011-07-26 21:07:43 -0700518 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800519 View child = getChildAt(x, y);
Sunny Goyalab770a12018-11-14 15:17:26 -0800520 mFolderLeaveBehind.setup(getContext(), mActivity, null,
Adam Cohenefca0272016-02-24 19:19:06 -0800521 child.getMeasuredWidth(), child.getPaddingTop());
522
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800523 mFolderLeaveBehind.mDelegateCellX = x;
524 mFolderLeaveBehind.mDelegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700525 invalidate();
526 }
527
528 public void clearFolderLeaveBehind() {
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800529 mFolderLeaveBehind.mDelegateCellX = -1;
530 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700531 invalidate();
532 }
533
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700534 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700535 public boolean shouldDelayChildPressedState() {
536 return false;
537 }
538
Adam Cohen1462de32012-07-24 22:34:36 -0700539 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700540 try {
541 dispatchRestoreInstanceState(states);
542 } catch (IllegalArgumentException ex) {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800543 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700544 throw ex;
545 }
546 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
547 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
548 }
Adam Cohen1462de32012-07-24 22:34:36 -0700549 }
550
Michael Jurkae6235dd2011-10-04 15:02:05 -0700551 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700552 public void cancelLongPress() {
553 super.cancelLongPress();
554
555 // Cancel long press for all children
556 final int count = getChildCount();
557 for (int i = 0; i < count; i++) {
558 final View child = getChildAt(i);
559 child.cancelLongPress();
560 }
561 }
562
Michael Jurkadee05892010-07-27 10:01:56 -0700563 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
564 mInterceptTouchListener = listener;
565 }
566
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800567 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700568 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800569 }
570
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800571 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700572 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800573 }
574
Sunny Goyalc13403c2016-11-18 23:44:48 -0800575 public boolean acceptsWidget() {
576 return mContainerType == WORKSPACE;
Sunny Goyale9b651e2015-04-24 11:44:51 -0700577 }
578
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800579 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700580 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700581 final LayoutParams lp = params;
582
Andrew Flynnde38e422012-05-08 11:22:15 -0700583 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800584 if (child instanceof BubbleTextView) {
585 BubbleTextView bubbleChild = (BubbleTextView) child;
Jon Mirandaf1eae802017-10-04 11:23:33 -0700586 bubbleChild.setTextVisibility(mContainerType != HOTSEAT);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800587 }
588
Sunny Goyalc13403c2016-11-18 23:44:48 -0800589 child.setScaleX(mChildScale);
590 child.setScaleY(mChildScale);
Adam Cohen307fe232012-08-16 17:55:58 -0700591
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800592 // Generate an id for each view, this assumes we have at most 256x256 cells
593 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700594 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700595 // If the horizontal or vertical span is set to -1, it is taken to
596 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700597 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
598 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599
Winson Chungaafa03c2010-06-11 17:34:16 -0700600 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700601 if (LOGD) {
602 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
603 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700604 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700605
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700606 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700607
Winson Chungaafa03c2010-06-11 17:34:16 -0700608 return true;
609 }
610 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700612
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800613 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700614 public void removeAllViews() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700615 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700616 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700617 }
618
619 @Override
620 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700621 if (mShortcutsAndWidgets.getChildCount() > 0) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700622 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700623 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700624 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700625 }
626
627 @Override
628 public void removeView(View view) {
629 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700630 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700631 }
632
633 @Override
634 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700635 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
636 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700637 }
638
639 @Override
640 public void removeViewInLayout(View view) {
641 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700642 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700643 }
644
645 @Override
646 public void removeViews(int start, int count) {
647 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700648 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700649 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700650 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700651 }
652
653 @Override
654 public void removeViewsInLayout(int start, int count) {
655 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700656 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700657 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700658 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800659 }
660
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700661 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700662 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800663 * @param x X coordinate of the point
664 * @param y Y coordinate of the point
665 * @param result Array of 2 ints to hold the x and y coordinate of the cell
666 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700667 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700668 final int hStartPadding = getPaddingLeft();
669 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800670
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530671 result[0] = (x - hStartPadding) / mCellWidth;
672 result[1] = (y - vStartPadding) / mCellHeight;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800673
Adam Cohend22015c2010-07-26 22:02:18 -0700674 final int xAxis = mCountX;
675 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800676
677 if (result[0] < 0) result[0] = 0;
678 if (result[0] >= xAxis) result[0] = xAxis - 1;
679 if (result[1] < 0) result[1] = 0;
680 if (result[1] >= yAxis) result[1] = yAxis - 1;
681 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700682
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800683 /**
684 * Given a point, return the cell that most closely encloses that point
685 * @param x X coordinate of the point
686 * @param y Y coordinate of the point
687 * @param result Array of 2 ints to hold the x and y coordinate of the cell
688 */
689 void pointToCellRounded(int x, int y, int[] result) {
690 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
691 }
692
693 /**
694 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700695 *
696 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800697 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700698 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800699 * @param result Array of 2 ints to hold the x and y coordinate of the point
700 */
701 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700702 final int hStartPadding = getPaddingLeft();
703 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800704
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530705 result[0] = hStartPadding + cellX * mCellWidth;
706 result[1] = vStartPadding + cellY * mCellHeight;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800707 }
708
Adam Cohene3e27a82011-04-15 12:07:39 -0700709 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800710 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700711 *
712 * @param cellX X coordinate of the cell
713 * @param cellY Y coordinate of the cell
714 *
715 * @param result Array of 2 ints to hold the x and y coordinate of the point
716 */
717 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700718 regionToCenterPoint(cellX, cellY, 1, 1, result);
719 }
720
721 /**
722 * Given a cell coordinate and span return the point that represents the center of the regio
723 *
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 regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700730 final int hStartPadding = getPaddingLeft();
731 final int vStartPadding = getPaddingTop();
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530732 result[0] = hStartPadding + cellX * mCellWidth + (spanX * mCellWidth) / 2;
733 result[1] = vStartPadding + cellY * mCellHeight + (spanY * mCellHeight) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700734 }
735
Adam Cohen19f37922012-03-21 11:59:11 -0700736 /**
737 * Given a cell coordinate and span fills out a corresponding pixel rect
738 *
739 * @param cellX X coordinate of the cell
740 * @param cellY Y coordinate of the cell
741 * @param result Rect in which to write the result
742 */
743 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
744 final int hStartPadding = getPaddingLeft();
745 final int vStartPadding = getPaddingTop();
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530746 final int left = hStartPadding + cellX * mCellWidth;
747 final int top = vStartPadding + cellY * mCellHeight;
748 result.set(left, top, left + (spanX * mCellWidth), top + (spanY * mCellHeight));
Adam Cohen19f37922012-03-21 11:59:11 -0700749 }
750
Adam Cohen482ed822012-03-02 14:15:13 -0800751 public float getDistanceFromCell(float x, float y, int[] cell) {
752 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700753 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800754 }
755
Adam Cohenf9c184a2016-01-15 16:47:43 -0800756 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800757 return mCellWidth;
758 }
759
Sunny Goyal0b754e52017-08-07 07:42:45 -0700760 public int getCellHeight() {
Romain Guy84f296c2009-11-04 15:00:44 -0800761 return mCellHeight;
762 }
763
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700764 public void setFixedSize(int width, int height) {
765 mFixedWidth = width;
766 mFixedHeight = height;
767 }
768
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800769 @Override
770 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800771 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800772 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700773 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
774 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700775 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
776 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -0700777
Winson Chung11a1a532013-09-13 11:14:45 -0700778 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Sunny Goyalc6205602015-05-21 20:46:33 -0700779 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
780 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700781 if (cw != mCellWidth || ch != mCellHeight) {
782 mCellWidth = cw;
783 mCellHeight = ch;
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530784 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700785 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700786 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700787
Winson Chung2d75f122013-09-23 16:53:31 -0700788 int newWidth = childWidthSize;
789 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700790 if (mFixedWidth > 0 && mFixedHeight > 0) {
791 newWidth = mFixedWidth;
792 newHeight = mFixedHeight;
793 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800794 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
795 }
796
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700797 mShortcutsAndWidgets.measure(
798 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
799 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
800
801 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
802 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700803 if (mFixedWidth > 0 && mFixedHeight > 0) {
804 setMeasuredDimension(maxWidth, maxHeight);
805 } else {
806 setMeasuredDimension(widthSize, heightSize);
807 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800808 }
809
810 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700811 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -0800812 int left = getPaddingLeft();
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700813 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -0700814 int right = r - l - getPaddingRight();
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700815 right -= (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -0700816
Winson Chung38848ca2013-10-08 12:03:44 -0700817 int top = getPaddingTop();
Sunny Goyal7c786f72016-06-01 14:08:21 -0700818 int bottom = b - t - getPaddingBottom();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700819
Sunny Goyal7c786f72016-06-01 14:08:21 -0700820 // Expand the background drawing bounds by the padding baked into the background drawable
821 mBackground.getPadding(mTempRect);
822 mBackground.setBounds(
Jon Miranda28032002017-07-13 16:18:56 -0700823 left - mTempRect.left - getPaddingLeft(),
824 top - mTempRect.top - getPaddingTop(),
825 right + mTempRect.right + getPaddingRight(),
826 bottom + mTempRect.bottom + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -0700827
Sunny Goyalc4d32012020-04-03 17:10:11 -0700828 mShortcutsAndWidgets.layout(left, top, right, bottom);
Sunny Goyal7c786f72016-06-01 14:08:21 -0700829 }
830
Tony Wickhama501d492015-11-03 18:05:01 -0800831 /**
832 * Returns the amount of space left over after subtracting padding and cells. This space will be
833 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
834 * width in {@link DeviceProfile#calculateCellWidth(int, int)}.
835 */
836 public int getUnusedHorizontalSpace() {
Sunny Goyalc4d32012020-04-03 17:10:11 -0700837 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
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
Patrick Dubroy440c3602010-07-13 17:50:32 -0700853 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700854 return mShortcutsAndWidgets.getChildAt(x, y);
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
985 left += ((mCellWidth * spanX) - dragOutline.getWidth()) / 2;
986
987 if (v != null && v.getViewType() == DraggableView.DRAGGABLE_WIDGET) {
988 // Center vertically
989 top += ((mCellHeight * spanY) - dragOutline.getHeight()) / 2;
990 } 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();
2149 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2150 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
2159 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2160 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
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302517 int width = cellHSpan * cellWidth;
2518 int height = cellVSpan * cellHeight;
2519 int x = hStartPadding + cellX * cellWidth;
2520 int y = vStartPadding + cellY * cellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -07002521
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002522 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002523 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002524
Adam Cohend4844c32011-02-18 19:25:06 -08002525 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002526 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002527 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002528 mOccupied.markCells(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002529 }
2530
Adam Cohend4844c32011-02-18 19:25:06 -08002531 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002532 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002533 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002534 mOccupied.markCells(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002535 }
2536
Adam Cohen2801caf2011-05-13 20:57:39 -07002537 public int getDesiredWidth() {
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302538 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth);
Adam Cohen2801caf2011-05-13 20:57:39 -07002539 }
2540
2541 public int getDesiredHeight() {
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302542 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight);
Adam Cohen2801caf2011-05-13 20:57:39 -07002543 }
2544
Michael Jurka66d72172011-04-12 16:29:25 -07002545 public boolean isOccupied(int x, int y) {
2546 if (x < mCountX && y < mCountY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002547 return mOccupied.cells[x][y];
Michael Jurka66d72172011-04-12 16:29:25 -07002548 } else {
2549 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2550 }
2551 }
2552
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002553 @Override
2554 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2555 return new CellLayout.LayoutParams(getContext(), attrs);
2556 }
2557
2558 @Override
2559 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2560 return p instanceof CellLayout.LayoutParams;
2561 }
2562
2563 @Override
2564 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2565 return new CellLayout.LayoutParams(p);
2566 }
2567
2568 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2569 /**
2570 * Horizontal location of the item in the grid.
2571 */
2572 @ViewDebug.ExportedProperty
2573 public int cellX;
2574
2575 /**
2576 * Vertical location of the item in the grid.
2577 */
2578 @ViewDebug.ExportedProperty
2579 public int cellY;
2580
2581 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002582 * Temporary horizontal location of the item in the grid during reorder
2583 */
2584 public int tmpCellX;
2585
2586 /**
2587 * Temporary vertical location of the item in the grid during reorder
2588 */
2589 public int tmpCellY;
2590
2591 /**
2592 * Indicates that the temporary coordinates should be used to layout the items
2593 */
2594 public boolean useTmpCoords;
2595
2596 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002597 * Number of cells spanned horizontally by the item.
2598 */
2599 @ViewDebug.ExportedProperty
2600 public int cellHSpan;
2601
2602 /**
2603 * Number of cells spanned vertically by the item.
2604 */
2605 @ViewDebug.ExportedProperty
2606 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002607
Adam Cohen1b607ed2011-03-03 17:26:50 -08002608 /**
2609 * Indicates whether the item will set its x, y, width and height parameters freely,
2610 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2611 */
Adam Cohend4844c32011-02-18 19:25:06 -08002612 public boolean isLockedToGrid = true;
2613
Adam Cohen482ed822012-03-02 14:15:13 -08002614 /**
2615 * Indicates whether this item can be reordered. Always true except in the case of the
Sunny Goyalda4fe1a2016-05-26 16:05:17 -07002616 * the AllApps button and QSB place holder.
Adam Cohen482ed822012-03-02 14:15:13 -08002617 */
2618 public boolean canReorder = true;
2619
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002620 // X coordinate of the view in the layout.
2621 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002622 public int x;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002623 // Y coordinate of the view in the layout.
2624 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002625 public int y;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002626
Romain Guy84f296c2009-11-04 15:00:44 -08002627 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002628
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002629 public LayoutParams(Context c, AttributeSet attrs) {
2630 super(c, attrs);
2631 cellHSpan = 1;
2632 cellVSpan = 1;
2633 }
2634
2635 public LayoutParams(ViewGroup.LayoutParams source) {
2636 super(source);
2637 cellHSpan = 1;
2638 cellVSpan = 1;
2639 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002640
2641 public LayoutParams(LayoutParams source) {
2642 super(source);
2643 this.cellX = source.cellX;
2644 this.cellY = source.cellY;
2645 this.cellHSpan = source.cellHSpan;
2646 this.cellVSpan = source.cellVSpan;
2647 }
2648
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002649 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002650 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002651 this.cellX = cellX;
2652 this.cellY = cellY;
2653 this.cellHSpan = cellHSpan;
2654 this.cellVSpan = cellVSpan;
2655 }
2656
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302657 public void setup(int cellWidth, int cellHeight, boolean invertHorizontally, int colCount) {
Jon Miranda7ae64ff2016-11-21 16:18:46 -08002658 setup(cellWidth, cellHeight, invertHorizontally, colCount, 1.0f, 1.0f);
2659 }
2660
2661 /**
2662 * Use this method, as opposed to {@link #setup(int, int, boolean, int)}, if the view needs
2663 * to be scaled.
2664 *
2665 * ie. In multi-window mode, we setup widgets so that they are measured and laid out
2666 * using their full/invariant device profile sizes.
2667 */
2668 public void setup(int cellWidth, int cellHeight, boolean invertHorizontally, int colCount,
2669 float cellScaleX, float cellScaleY) {
Adam Cohend4844c32011-02-18 19:25:06 -08002670 if (isLockedToGrid) {
2671 final int myCellHSpan = cellHSpan;
2672 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002673 int myCellX = useTmpCoords ? tmpCellX : cellX;
2674 int myCellY = useTmpCoords ? tmpCellY : cellY;
2675
2676 if (invertHorizontally) {
2677 myCellX = colCount - myCellX - cellHSpan;
2678 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002679
Jon Miranda7ae64ff2016-11-21 16:18:46 -08002680 width = (int) (myCellHSpan * cellWidth / cellScaleX - leftMargin - rightMargin);
2681 height = (int) (myCellVSpan * cellHeight / cellScaleY - topMargin - bottomMargin);
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302682 x = (myCellX * cellWidth + leftMargin);
2683 y = (myCellY * cellHeight + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002684 }
2685 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002686
Sunny Goyal11a50742019-08-07 09:24:26 -07002687 /**
2688 * Sets the position to the provided point
2689 */
2690 public void setXY(Point point) {
2691 cellX = point.x;
2692 cellY = point.y;
2693 }
2694
Winson Chungaafa03c2010-06-11 17:34:16 -07002695 public String toString() {
2696 return "(" + this.cellX + ", " + this.cellY + ")";
2697 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002698 }
2699
Michael Jurka0280c3b2010-09-17 15:00:07 -07002700 // This class stores info for two purposes:
2701 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2702 // its spanX, spanY, and the screen it is on
2703 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2704 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2705 // the CellLayout that was long clicked
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002706 public static final class CellInfo extends CellAndSpan {
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002707 public final View cell;
Sunny Goyalefb7e842018-10-04 15:11:00 -07002708 final int screenId;
2709 final int container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002710
Sunny Goyal83a8f042015-05-19 12:52:12 -07002711 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002712 cellX = info.cellX;
2713 cellY = info.cellY;
2714 spanX = info.spanX;
2715 spanY = info.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002716 cell = v;
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002717 screenId = info.screenId;
2718 container = info.container;
2719 }
2720
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002721 @Override
2722 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002723 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2724 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002725 }
2726 }
Michael Jurkad771c962011-08-09 15:00:48 -07002727
Tony Wickham86930612015-09-09 13:50:40 -07002728 /**
Samuel Fufa1e2d0042019-11-18 17:12:46 -08002729 * A Delegated cell Drawing for drawing on CellLayout
2730 */
2731 public abstract static class DelegatedCellDrawing {
2732 public int mDelegateCellX;
2733 public int mDelegateCellY;
2734
2735 /**
2736 * Draw under CellLayout
2737 */
2738 public abstract void drawUnderItem(Canvas canvas);
2739
2740 /**
2741 * Draw over CellLayout
2742 */
2743 public abstract void drawOverItem(Canvas canvas);
2744 }
2745
2746 /**
Tony Wickham86930612015-09-09 13:50:40 -07002747 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2748 * if necessary).
2749 */
2750 public boolean hasReorderSolution(ItemInfo itemInfo) {
2751 int[] cellPoint = new int[2];
2752 // Check for a solution starting at every cell.
2753 for (int cellX = 0; cellX < getCountX(); cellX++) {
2754 for (int cellY = 0; cellY < getCountY(); cellY++) {
2755 cellToPoint(cellX, cellY, cellPoint);
2756 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2757 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2758 true, new ItemConfiguration()).isSolution) {
2759 return true;
2760 }
2761 }
2762 }
2763 return false;
2764 }
2765
Samuel Fufaa4211432020-02-25 18:47:54 -08002766 /**
2767 * Finds solution to accept hotseat migration to cell layout. commits solution if commitConfig
2768 */
2769 public boolean makeSpaceForHotseatMigration(boolean commitConfig) {
Samuel Fufaa4211432020-02-25 18:47:54 -08002770 int[] cellPoint = new int[2];
2771 int[] directionVector = new int[]{0, -1};
2772 cellToPoint(0, mCountY, cellPoint);
2773 ItemConfiguration configuration = new ItemConfiguration();
2774 if (findReorderSolution(cellPoint[0], cellPoint[1], mCountX, 1, mCountX, 1,
2775 directionVector, null, false, configuration).isSolution) {
2776 if (commitConfig) {
2777 copySolutionToTempState(configuration, null);
2778 commitTempPlacement();
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002779 // undo marking cells occupied since there is actually nothing being placed yet.
2780 mOccupied.markCells(0, mCountY - 1, mCountX, 1, false);
Samuel Fufaa4211432020-02-25 18:47:54 -08002781 }
2782 return true;
2783 }
2784 return false;
2785 }
2786
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002787 /**
2788 * returns a copy of cell layout's grid occupancy
2789 */
2790 public GridOccupancy cloneGridOccupancy() {
2791 GridOccupancy occupancy = new GridOccupancy(mCountX, mCountY);
2792 mOccupied.copyTo(occupancy);
2793 return occupancy;
2794 }
2795
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002796 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002797 return mOccupied.isRegionVacant(x, y, spanX, spanY);
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002798 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002799}