blob: 6c562cfac2669f17e50252eeb17090381905bb8f [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 Goyalf0b6db72018-08-13 16:10:14 -070019import static com.android.launcher3.anim.Interpolators.DEACCEL_1_5;
20
Joe Onorato4be866d2010-10-10 11:26:02 -070021import android.animation.Animator;
Michael Jurka629758f2012-06-14 16:18:21 -070022import android.animation.AnimatorListenerAdapter;
Sunny Goyal849c6a22018-08-08 16:33:46 -070023import android.animation.ObjectAnimator;
Chet Haase00397b12010-10-07 11:13:10 -070024import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070025import android.animation.ValueAnimator;
26import android.animation.ValueAnimator.AnimatorUpdateListener;
Sunny Goyal726bee72018-03-05 12:54:24 -080027import android.annotation.SuppressLint;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080028import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040029import android.content.res.Resources;
Sunny Goyalc13403c2016-11-18 23:44:48 -080030import android.content.res.TypedArray;
Joe Onorato4be866d2010-10-10 11:26:02 -070031import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070032import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080033import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070034import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070035import android.graphics.Point;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080036import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080037import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070038import android.graphics.drawable.Drawable;
Adam Cohen1462de32012-07-24 22:34:36 -070039import android.os.Parcelable;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -070040import android.util.ArrayMap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070042import android.util.Log;
Sunny Goyal849c6a22018-08-08 16:33:46 -070043import android.util.Property;
Adam Cohen1462de32012-07-24 22:34:36 -070044import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080045import android.view.MotionEvent;
46import android.view.View;
47import android.view.ViewDebug;
48import android.view.ViewGroup;
Adam Cohenc9735cf2015-01-23 16:11:55 -080049import android.view.accessibility.AccessibilityEvent;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070050
vadimt04f356f2019-02-14 18:46:36 -080051import androidx.annotation.IntDef;
52import androidx.core.view.ViewCompat;
53
Sunny Goyalaa8ef112015-06-12 20:04:41 -070054import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyale9b651e2015-04-24 11:44:51 -070055import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
56import com.android.launcher3.accessibility.FolderAccessibilityHelper;
57import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070058import com.android.launcher3.anim.Interpolators;
Sunny Goyal9e76f682017-02-13 12:13:43 -080059import com.android.launcher3.anim.PropertyListBuilder;
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 Goyalae6e3182019-04-30 12:04:37 -070064import com.android.launcher3.graphics.RotationMode;
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 Goyalae6e3182019-04-30 12:04:37 -070071import com.android.launcher3.views.Transposable;
Sunny Goyal29947f02017-12-18 13:49:44 -080072import com.android.launcher3.widget.LauncherAppWidgetHostView;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070073
Sunny Goyalc13403c2016-11-18 23:44:48 -080074import java.lang.annotation.Retention;
75import java.lang.annotation.RetentionPolicy;
Adam Cohen69ce2e52011-07-03 19:25:21 -070076import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070077import java.util.Arrays;
Adam Cohenf3900c22012-11-16 18:28:11 -080078import java.util.Collections;
79import java.util.Comparator;
Adam Cohend41fbf52012-02-16 23:53:59 -080080import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070081
Sunny Goyalae6e3182019-04-30 12:04:37 -070082public class CellLayout extends ViewGroup implements Transposable {
Sunny Goyale9b651e2015-04-24 11:44:51 -070083 public static final int WORKSPACE_ACCESSIBILITY_DRAG = 2;
84 public static final int FOLDER_ACCESSIBILITY_DRAG = 1;
85
Tony Wickhama0628cc2015-10-14 15:23:04 -070086 private static final String TAG = "CellLayout";
87 private static final boolean LOGD = false;
Winson Chungaafa03c2010-06-11 17:34:16 -070088
Sunny Goyalab770a12018-11-14 15:17:26 -080089 protected final ActivityContext mActivity;
Sunny Goyal4ffec482016-02-09 11:28:52 -080090 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070091 @Thunk int mCellWidth;
Sunny Goyal4ffec482016-02-09 11:28:52 -080092 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -070093 @Thunk int mCellHeight;
Winson Chung11a1a532013-09-13 11:14:45 -070094 private int mFixedCellWidth;
95 private int mFixedCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070096
Sunny Goyal4ffec482016-02-09 11:28:52 -080097 @ViewDebug.ExportedProperty(category = "launcher")
Sunny Goyalff4ba2d2016-04-02 14:12:34 -070098 private int mCountX;
Sunny Goyal4ffec482016-02-09 11:28:52 -080099 @ViewDebug.ExportedProperty(category = "launcher")
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700100 private int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800101
Adam Cohen917e3882013-10-31 15:03:35 -0700102 private boolean mDropPending = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800103
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700104 // These are temporary variables to prevent having to allocate a new object just to
105 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Adam Cohen091440a2015-03-18 14:16:05 -0700106 @Thunk final int[] mTmpPoint = new int[2];
Sunny Goyal2805e632015-05-20 15:35:32 -0700107 @Thunk final int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700108
Adam Cohen65086992020-02-19 08:40:49 -0800109 // Used to visualize / debug the Grid of the CellLayout
110 private static final boolean VISUALIZE_GRID = false;
111 private Rect mVisualizeGridRect = new Rect();
112 private Paint mVisualizeGridPaint = new Paint();
113
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700114 private GridOccupancy mOccupied;
115 private GridOccupancy mTmpOccupied;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800116
Michael Jurkadee05892010-07-27 10:01:56 -0700117 private OnTouchListener mInterceptTouchListener;
118
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800119 private final ArrayList<DelegatedCellDrawing> mDelegatedCellDrawings = new ArrayList<>();
Jon Mirandaa0233f72017-06-22 18:34:45 -0700120 final PreviewBackground mFolderLeaveBehind = new PreviewBackground();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700121
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800122 private static final int[] BACKGROUND_STATE_ACTIVE = new int[] { android.R.attr.state_active };
Sunny Goyale15e2a82017-12-15 13:05:42 -0800123 private static final int[] BACKGROUND_STATE_DEFAULT = EMPTY_STATE_SET;
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800124 private final Drawable mBackground;
Sunny Goyal2805e632015-05-20 15:35:32 -0700125
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700126 // These values allow a fixed measurement to be set on the CellLayout.
127 private int mFixedWidth = -1;
128 private int mFixedHeight = -1;
129
Michael Jurka33945b22010-12-21 18:19:38 -0800130 // If we're actively dragging something over this screen, mIsDragOverlapping is true
131 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700132
Winson Chung150fbab2010-09-29 17:14:26 -0700133 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700134 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700135 @Thunk final Rect[] mDragOutlines = new Rect[4];
136 @Thunk final float[] mDragOutlineAlphas = new float[mDragOutlines.length];
137 private final InterruptibleInOutAnimator[] mDragOutlineAnims =
Joe Onorato4be866d2010-10-10 11:26:02 -0700138 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700139
140 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700141 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700142 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700143
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700144 @Thunk final ArrayMap<LayoutParams, Animator> mReorderAnimators = new ArrayMap<>();
145 @Thunk final ArrayMap<View, ReorderPreviewAnimation> mShakeAnimators = new ArrayMap<>();
Adam Cohen19f37922012-03-21 11:59:11 -0700146
147 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700148
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700149 // When a drag operation is in progress, holds the nearest cell to the touch point
150 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800151
Joe Onorato4be866d2010-10-10 11:26:02 -0700152 private boolean mDragging = false;
153
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700154 private final TimeInterpolator mEaseOutInterpolator;
155 private final ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700156
Sunny Goyalc13403c2016-11-18 23:44:48 -0800157 @Retention(RetentionPolicy.SOURCE)
158 @IntDef({WORKSPACE, HOTSEAT, FOLDER})
159 public @interface ContainerType{}
160 public static final int WORKSPACE = 0;
161 public static final int HOTSEAT = 1;
162 public static final int FOLDER = 2;
163
164 @ContainerType private final int mContainerType;
165
Jon Mirandab28c4fc2017-06-20 10:58:36 -0700166 private final float mChildScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800167
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800168 public static final int MODE_SHOW_REORDER_HINT = 0;
169 public static final int MODE_DRAG_OVER = 1;
170 public static final int MODE_ON_DROP = 2;
171 public static final int MODE_ON_DROP_EXTERNAL = 3;
172 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700173 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800174 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
175
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800176 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700177 private static final int REORDER_ANIMATION_DURATION = 150;
Sunny Goyalc13403c2016-11-18 23:44:48 -0800178 @Thunk final float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700179
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700180 private final ArrayList<View> mIntersectingViews = new ArrayList<>();
181 private final Rect mOccupiedRect = new Rect();
182 private final int[] mDirectionVector = new int[2];
183 final int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700184 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800185
Sunny Goyal2805e632015-05-20 15:35:32 -0700186 private final Rect mTempRect = new Rect();
Winson Chung3a6e7f32013-10-09 15:50:52 -0700187
Sunny Goyal73b5a272019-12-09 14:55:56 -0800188 private static final Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700189
Adam Cohenc9735cf2015-01-23 16:11:55 -0800190 // Related to accessible drag and drop
Sunny Goyale9b651e2015-04-24 11:44:51 -0700191 private DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800192 private boolean mUseTouchHelper = false;
Sunny Goyalae6e3182019-04-30 12:04:37 -0700193 private RotationMode mRotationMode = RotationMode.NORMAL;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800194
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 public CellLayout(Context context) {
196 this(context, null);
197 }
198
199 public CellLayout(Context context, AttributeSet attrs) {
200 this(context, attrs, 0);
201 }
202
203 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
204 super(context, attrs, defStyle);
Sunny Goyalc13403c2016-11-18 23:44:48 -0800205 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
206 mContainerType = a.getInteger(R.styleable.CellLayout_containerType, WORKSPACE);
207 a.recycle();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700208
209 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
210 // the user where a dragged item will land when dropped.
211 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800212 setClipToPadding(false);
Sunny Goyalab770a12018-11-14 15:17:26 -0800213 mActivity = ActivityContext.lookupContext(context);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700214
Sunny Goyalae6e3182019-04-30 12:04:37 -0700215 DeviceProfile grid = mActivity.getWallpaperDeviceProfile();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800216
Winson Chung11a1a532013-09-13 11:14:45 -0700217 mCellWidth = mCellHeight = -1;
Nilesh Agrawal5f7099a2014-01-02 15:54:57 -0800218 mFixedCellWidth = mFixedCellHeight = -1;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700219
220 mCountX = grid.inv.numColumns;
221 mCountY = grid.inv.numRows;
222 mOccupied = new GridOccupancy(mCountX, mCountY);
223 mTmpOccupied = new GridOccupancy(mCountX, mCountY);
224
Adam Cohen5b53f292012-03-29 14:30:35 -0700225 mPreviousReorderDirection[0] = INVALID_DIRECTION;
226 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800227
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800228 mFolderLeaveBehind.mDelegateCellX = -1;
229 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenefca0272016-02-24 19:19:06 -0800230
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231 setAlwaysDrawnWithCacheEnabled(false);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700232 final Resources res = getResources();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700233
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800234 mBackground = res.getDrawable(R.drawable.bg_celllayout);
Sunny Goyal2805e632015-05-20 15:35:32 -0700235 mBackground.setCallback(this);
Sunny Goyalaeb16432017-10-16 11:46:41 -0700236 mBackground.setAlpha(0);
Michael Jurka33945b22010-12-21 18:19:38 -0800237
Sunny Goyalc13403c2016-11-18 23:44:48 -0800238 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE * grid.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700239
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700240 // Initialize the data structures used for the drag visualization.
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -0700241 mEaseOutInterpolator = Interpolators.DEACCEL_2_5; // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700242 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700243 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800244 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700245 }
Mario Bertschler54ba6012017-06-08 10:53:53 -0700246 mDragOutlinePaint.setColor(Themes.getAttrColor(context, R.attr.workspaceTextColor));
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700247
248 // When dragging things around the home screens, we show a green outline of
249 // where the item will land. The outlines gradually fade out, leaving a trail
250 // behind the drag path.
251 // Set up all the animations that are used to implement this fading.
252 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700253 final float fromAlphaValue = 0;
254 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700255
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700256 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700257
258 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700259 final InterruptibleInOutAnimator anim =
Sunny Goyal849c6a22018-08-08 16:33:46 -0700260 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700261 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700262 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700263 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700264 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700265 final Bitmap outline = (Bitmap)anim.getTag();
266
267 // If an animation is started and then stopped very quickly, we can still
268 // get spurious updates we've cleared the tag. Guard against this.
269 if (outline == null) {
Tony Wickhama0628cc2015-10-14 15:23:04 -0700270 if (LOGD) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700271 Object val = animation.getAnimatedValue();
272 Log.d(TAG, "anim " + thisIndex + " update: " + val +
273 ", isStopped " + anim.isStopped());
274 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700275 // Try to prevent it from continuing to run
276 animation.cancel();
277 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700278 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800279 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700280 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700281 }
282 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700283 // The animation holds a reference to the drag outline bitmap as long is it's
284 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700285 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700286 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700287 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700288 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700289 anim.setTag(null);
290 }
291 }
292 });
293 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700294 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700295
Sunny Goyalc13403c2016-11-18 23:44:48 -0800296 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context, mContainerType);
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530297 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700298 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700299 }
300
Sunny Goyale9b651e2015-04-24 11:44:51 -0700301 public void enableAccessibleDrag(boolean enable, int dragType) {
Adam Cohenc9735cf2015-01-23 16:11:55 -0800302 mUseTouchHelper = enable;
303 if (!enable) {
304 ViewCompat.setAccessibilityDelegate(this, null);
305 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
306 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
Sunny Goyal7c7be8c2018-03-07 19:58:07 -0800307 setOnClickListener(null);
Adam Cohenc9735cf2015-01-23 16:11:55 -0800308 } else {
Sunny Goyale9b651e2015-04-24 11:44:51 -0700309 if (dragType == WORKSPACE_ACCESSIBILITY_DRAG &&
310 !(mTouchHelper instanceof WorkspaceAccessibilityHelper)) {
311 mTouchHelper = new WorkspaceAccessibilityHelper(this);
312 } else if (dragType == FOLDER_ACCESSIBILITY_DRAG &&
313 !(mTouchHelper instanceof FolderAccessibilityHelper)) {
314 mTouchHelper = new FolderAccessibilityHelper(this);
315 }
Adam Cohenc9735cf2015-01-23 16:11:55 -0800316 ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
317 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
318 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
319 setOnClickListener(mTouchHelper);
320 }
321
322 // Invalidate the accessibility hierarchy
323 if (getParent() != null) {
324 getParent().notifySubtreeAccessibilityStateChanged(
325 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
326 }
327 }
328
Sunny Goyalae6e3182019-04-30 12:04:37 -0700329 public void setRotationMode(RotationMode mode) {
330 if (mRotationMode != mode) {
331 mRotationMode = mode;
332 requestLayout();
333 }
334 }
335
336 @Override
337 public RotationMode getRotationMode() {
338 return mRotationMode;
339 }
340
341 @Override
342 public void setPadding(int left, int top, int right, int bottom) {
343 mRotationMode.mapRect(left, top, right, bottom, mTempRect);
344 super.setPadding(mTempRect.left, mTempRect.top, mTempRect.right, mTempRect.bottom);
345 }
346
Adam Cohenc9735cf2015-01-23 16:11:55 -0800347 @Override
348 public boolean dispatchHoverEvent(MotionEvent event) {
349 // Always attempt to dispatch hover events to accessibility first.
350 if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
351 return true;
352 }
353 return super.dispatchHoverEvent(event);
354 }
355
356 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800357 public boolean onInterceptTouchEvent(MotionEvent ev) {
358 if (mUseTouchHelper ||
359 (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
360 return true;
361 }
362 return false;
363 }
364
Chris Craik01f2d7f2013-10-01 14:41:56 -0700365 public void enableHardwareLayer(boolean hasLayer) {
366 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700367 }
368
vadimt04f356f2019-02-14 18:46:36 -0800369 public boolean isHardwareLayerEnabled() {
370 return mShortcutsAndWidgets.getLayerType() == LAYER_TYPE_HARDWARE;
371 }
372
Winson Chung5f8afe62013-08-12 16:19:28 -0700373 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700374 mFixedCellWidth = mCellWidth = width;
375 mFixedCellHeight = mCellHeight = height;
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530376 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY);
Winson Chung5f8afe62013-08-12 16:19:28 -0700377 }
378
Adam Cohen2801caf2011-05-13 20:57:39 -0700379 public void setGridSize(int x, int y) {
380 mCountX = x;
381 mCountY = y;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700382 mOccupied = new GridOccupancy(mCountX, mCountY);
383 mTmpOccupied = new GridOccupancy(mCountX, mCountY);
Adam Cohen7fbec102012-03-27 12:42:19 -0700384 mTempRectStack.clear();
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530385 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY);
Adam Cohen76fc0852011-06-17 13:26:23 -0700386 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700387 }
388
Adam Cohen2374abf2013-04-16 14:56:57 -0700389 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
390 public void setInvertIfRtl(boolean invert) {
391 mShortcutsAndWidgets.setInvertIfRtl(invert);
392 }
393
Adam Cohen917e3882013-10-31 15:03:35 -0700394 public void setDropPending(boolean pending) {
395 mDropPending = pending;
396 }
397
398 public boolean isDropPending() {
399 return mDropPending;
400 }
401
Adam Cohenc50438c2014-08-19 17:43:05 -0700402 void setIsDragOverlapping(boolean isDragOverlapping) {
403 if (mIsDragOverlapping != isDragOverlapping) {
404 mIsDragOverlapping = isDragOverlapping;
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800405 mBackground.setState(mIsDragOverlapping
406 ? BACKGROUND_STATE_ACTIVE : BACKGROUND_STATE_DEFAULT);
Adam Cohenc50438c2014-08-19 17:43:05 -0700407 invalidate();
408 }
409 }
410
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700411 @Override
412 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700413 ParcelableSparseArray jail = getJailedArray(container);
414 super.dispatchSaveInstanceState(jail);
415 container.put(R.id.cell_layout_jail_id, jail);
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700416 }
417
418 @Override
419 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700420 super.dispatchRestoreInstanceState(getJailedArray(container));
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700421 }
422
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700423 /**
424 * Wrap the SparseArray in another Parcelable so that the item ids do not conflict with our
425 * our internal resource ids
426 */
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700427 private ParcelableSparseArray getJailedArray(SparseArray<Parcelable> container) {
428 final Parcelable parcelable = container.get(R.id.cell_layout_jail_id);
429 return parcelable instanceof ParcelableSparseArray ?
430 (ParcelableSparseArray) parcelable : new ParcelableSparseArray();
431 }
432
Tony Wickham0f97b782015-12-02 17:55:07 -0800433 public boolean getIsDragOverlapping() {
434 return mIsDragOverlapping;
435 }
436
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700437 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700438 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700439 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
440 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
441 // When we're small, we are either drawn normally or in the "accepts drops" state (during
442 // a drag). However, we also drag the mini hover background *over* one of those two
443 // backgrounds
Sunny Goyalaeb16432017-10-16 11:46:41 -0700444 if (mBackground.getAlpha() > 0) {
Sunny Goyal2805e632015-05-20 15:35:32 -0700445 mBackground.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700446 }
Romain Guya6abce82009-11-10 02:54:41 -0800447
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700448 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700449 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700450 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700451 if (alpha > 0) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700452 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700453 paint.setAlpha((int)(alpha + .5f));
Sunny Goyal106bf642015-07-16 12:18:06 -0700454 canvas.drawBitmap(b, null, mDragOutlines[i], paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700455 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700456 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800457
Adam Cohen482ed822012-03-02 14:15:13 -0800458 if (DEBUG_VISUALIZE_OCCUPIED) {
459 int[] pt = new int[2];
460 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700461 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800462 for (int i = 0; i < mCountX; i++) {
463 for (int j = 0; j < mCountY; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700464 if (mOccupied.cells[i][j]) {
Adam Cohen482ed822012-03-02 14:15:13 -0800465 cellToPoint(i, j, pt);
466 canvas.save();
467 canvas.translate(pt[0], pt[1]);
468 cd.draw(canvas);
469 canvas.restore();
470 }
471 }
472 }
473 }
474
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800475 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
476 DelegatedCellDrawing cellDrawing = mDelegatedCellDrawings.get(i);
477 cellToPoint(cellDrawing.mDelegateCellX, cellDrawing.mDelegateCellY, mTempLocation);
Adam Cohenefca0272016-02-24 19:19:06 -0800478 canvas.save();
479 canvas.translate(mTempLocation[0], mTempLocation[1]);
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800480 cellDrawing.drawUnderItem(canvas);
Adam Cohenefca0272016-02-24 19:19:06 -0800481 canvas.restore();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700482 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700483
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800484 if (mFolderLeaveBehind.mDelegateCellX >= 0 && mFolderLeaveBehind.mDelegateCellY >= 0) {
485 cellToPoint(mFolderLeaveBehind.mDelegateCellX,
486 mFolderLeaveBehind.mDelegateCellY, mTempLocation);
Adam Cohenefca0272016-02-24 19:19:06 -0800487 canvas.save();
488 canvas.translate(mTempLocation[0], mTempLocation[1]);
Sunny Goyal19b93b72017-02-19 20:21:37 -0800489 mFolderLeaveBehind.drawLeaveBehind(canvas);
Adam Cohenefca0272016-02-24 19:19:06 -0800490 canvas.restore();
Adam Cohenc51934b2011-07-26 21:07:43 -0700491 }
Adam Cohen65086992020-02-19 08:40:49 -0800492
493 if (VISUALIZE_GRID) {
494 visualizeGrid(canvas);
495 }
496 }
497
498 protected void visualizeGrid(Canvas canvas) {
499 mVisualizeGridRect.set(0, 0, mCellWidth, mCellHeight);
500 mVisualizeGridPaint.setStrokeWidth(4);
501
502 for (int i = 0; i < mCountX; i++) {
503 for (int j = 0; j < mCountY; j++) {
504 canvas.save();
505
506 int transX = i * mCellWidth;
507 int transY = j * mCellHeight;
508
509 canvas.translate(getPaddingLeft() + transX, getPaddingTop() + transY);
510
511 mVisualizeGridPaint.setStyle(Paint.Style.FILL);
512 mVisualizeGridPaint.setColor(Color.argb(80, 255, 100, 100));
513
514 canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
515
516 mVisualizeGridPaint.setStyle(Paint.Style.STROKE);
517 mVisualizeGridPaint.setColor(Color.argb(255, 255, 100, 100));
518
519 canvas.drawRect(mVisualizeGridRect, mVisualizeGridPaint);
520 canvas.restore();
521 }
522 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700523 }
524
Adam Cohenefca0272016-02-24 19:19:06 -0800525 @Override
526 protected void dispatchDraw(Canvas canvas) {
527 super.dispatchDraw(canvas);
528
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800529 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
530 DelegatedCellDrawing bg = mDelegatedCellDrawings.get(i);
531 cellToPoint(bg.mDelegateCellX, bg.mDelegateCellY, mTempLocation);
532 canvas.save();
533 canvas.translate(mTempLocation[0], mTempLocation[1]);
534 bg.drawOverItem(canvas);
535 canvas.restore();
Adam Cohenefca0272016-02-24 19:19:06 -0800536 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700537 }
538
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800539 /**
540 * Add Delegated cell drawing
541 */
542 public void addDelegatedCellDrawing(DelegatedCellDrawing bg) {
543 mDelegatedCellDrawings.add(bg);
Adam Cohenefca0272016-02-24 19:19:06 -0800544 }
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800545
546 /**
547 * Remove item from DelegatedCellDrawings
548 */
549 public void removeDelegatedCellDrawing(DelegatedCellDrawing bg) {
550 mDelegatedCellDrawings.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700551 }
552
Adam Cohenc51934b2011-07-26 21:07:43 -0700553 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800554 View child = getChildAt(x, y);
Sunny Goyalab770a12018-11-14 15:17:26 -0800555 mFolderLeaveBehind.setup(getContext(), mActivity, null,
Adam Cohenefca0272016-02-24 19:19:06 -0800556 child.getMeasuredWidth(), child.getPaddingTop());
557
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800558 mFolderLeaveBehind.mDelegateCellX = x;
559 mFolderLeaveBehind.mDelegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700560 invalidate();
561 }
562
563 public void clearFolderLeaveBehind() {
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800564 mFolderLeaveBehind.mDelegateCellX = -1;
565 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700566 invalidate();
567 }
568
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700569 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700570 public boolean shouldDelayChildPressedState() {
571 return false;
572 }
573
Adam Cohen1462de32012-07-24 22:34:36 -0700574 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700575 try {
576 dispatchRestoreInstanceState(states);
577 } catch (IllegalArgumentException ex) {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800578 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700579 throw ex;
580 }
581 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
582 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
583 }
Adam Cohen1462de32012-07-24 22:34:36 -0700584 }
585
Michael Jurkae6235dd2011-10-04 15:02:05 -0700586 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700587 public void cancelLongPress() {
588 super.cancelLongPress();
589
590 // Cancel long press for all children
591 final int count = getChildCount();
592 for (int i = 0; i < count; i++) {
593 final View child = getChildAt(i);
594 child.cancelLongPress();
595 }
596 }
597
Michael Jurkadee05892010-07-27 10:01:56 -0700598 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
599 mInterceptTouchListener = listener;
600 }
601
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800602 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700603 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800604 }
605
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800606 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700607 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800608 }
609
Sunny Goyalc13403c2016-11-18 23:44:48 -0800610 public boolean acceptsWidget() {
611 return mContainerType == WORKSPACE;
Sunny Goyale9b651e2015-04-24 11:44:51 -0700612 }
613
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800614 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700615 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700616 final LayoutParams lp = params;
617
Andrew Flynnde38e422012-05-08 11:22:15 -0700618 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800619 if (child instanceof BubbleTextView) {
620 BubbleTextView bubbleChild = (BubbleTextView) child;
Jon Mirandaf1eae802017-10-04 11:23:33 -0700621 bubbleChild.setTextVisibility(mContainerType != HOTSEAT);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800622 }
623
Sunny Goyalc13403c2016-11-18 23:44:48 -0800624 child.setScaleX(mChildScale);
625 child.setScaleY(mChildScale);
Adam Cohen307fe232012-08-16 17:55:58 -0700626
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627 // Generate an id for each view, this assumes we have at most 256x256 cells
628 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700629 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700630 // If the horizontal or vertical span is set to -1, it is taken to
631 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700632 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
633 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800634
Winson Chungaafa03c2010-06-11 17:34:16 -0700635 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700636 if (LOGD) {
637 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
638 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700639 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700640
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700641 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700642
Winson Chungaafa03c2010-06-11 17:34:16 -0700643 return true;
644 }
645 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800646 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700647
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800648 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700649 public void removeAllViews() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700650 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700651 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700652 }
653
654 @Override
655 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700656 if (mShortcutsAndWidgets.getChildCount() > 0) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700657 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700658 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700659 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700660 }
661
662 @Override
663 public void removeView(View view) {
664 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700665 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700666 }
667
668 @Override
669 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700670 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
671 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700672 }
673
674 @Override
675 public void removeViewInLayout(View view) {
676 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700677 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700678 }
679
680 @Override
681 public void removeViews(int start, int count) {
682 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700683 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700684 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700685 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700686 }
687
688 @Override
689 public void removeViewsInLayout(int start, int count) {
690 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700691 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700692 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700693 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800694 }
695
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700696 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700697 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800698 * @param x X coordinate of the point
699 * @param y Y coordinate of the point
700 * @param result Array of 2 ints to hold the x and y coordinate of the cell
701 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700702 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700703 final int hStartPadding = getPaddingLeft();
704 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800705
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530706 result[0] = (x - hStartPadding) / mCellWidth;
707 result[1] = (y - vStartPadding) / mCellHeight;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800708
Adam Cohend22015c2010-07-26 22:02:18 -0700709 final int xAxis = mCountX;
710 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800711
712 if (result[0] < 0) result[0] = 0;
713 if (result[0] >= xAxis) result[0] = xAxis - 1;
714 if (result[1] < 0) result[1] = 0;
715 if (result[1] >= yAxis) result[1] = yAxis - 1;
716 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700717
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800718 /**
719 * Given a point, return the cell that most closely encloses that point
720 * @param x X coordinate of the point
721 * @param y Y coordinate of the point
722 * @param result Array of 2 ints to hold the x and y coordinate of the cell
723 */
724 void pointToCellRounded(int x, int y, int[] result) {
725 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
726 }
727
728 /**
729 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700730 *
731 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800732 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700733 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800734 * @param result Array of 2 ints to hold the x and y coordinate of the point
735 */
736 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700737 final int hStartPadding = getPaddingLeft();
738 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800739
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530740 result[0] = hStartPadding + cellX * mCellWidth;
741 result[1] = vStartPadding + cellY * mCellHeight;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800742 }
743
Adam Cohene3e27a82011-04-15 12:07:39 -0700744 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800745 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700746 *
747 * @param cellX X coordinate of the cell
748 * @param cellY Y coordinate of the cell
749 *
750 * @param result Array of 2 ints to hold the x and y coordinate of the point
751 */
752 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700753 regionToCenterPoint(cellX, cellY, 1, 1, result);
754 }
755
756 /**
757 * Given a cell coordinate and span return the point that represents the center of the regio
758 *
759 * @param cellX X coordinate of the cell
760 * @param cellY Y coordinate of the cell
761 *
762 * @param result Array of 2 ints to hold the x and y coordinate of the point
763 */
764 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700765 final int hStartPadding = getPaddingLeft();
766 final int vStartPadding = getPaddingTop();
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530767 result[0] = hStartPadding + cellX * mCellWidth + (spanX * mCellWidth) / 2;
768 result[1] = vStartPadding + cellY * mCellHeight + (spanY * mCellHeight) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700769 }
770
Adam Cohen19f37922012-03-21 11:59:11 -0700771 /**
772 * Given a cell coordinate and span fills out a corresponding pixel rect
773 *
774 * @param cellX X coordinate of the cell
775 * @param cellY Y coordinate of the cell
776 * @param result Rect in which to write the result
777 */
778 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
779 final int hStartPadding = getPaddingLeft();
780 final int vStartPadding = getPaddingTop();
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530781 final int left = hStartPadding + cellX * mCellWidth;
782 final int top = vStartPadding + cellY * mCellHeight;
783 result.set(left, top, left + (spanX * mCellWidth), top + (spanY * mCellHeight));
Adam Cohen19f37922012-03-21 11:59:11 -0700784 }
785
Adam Cohen482ed822012-03-02 14:15:13 -0800786 public float getDistanceFromCell(float x, float y, int[] cell) {
787 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700788 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800789 }
790
Adam Cohenf9c184a2016-01-15 16:47:43 -0800791 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800792 return mCellWidth;
793 }
794
Sunny Goyal0b754e52017-08-07 07:42:45 -0700795 public int getCellHeight() {
Romain Guy84f296c2009-11-04 15:00:44 -0800796 return mCellHeight;
797 }
798
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700799 public void setFixedSize(int width, int height) {
800 mFixedWidth = width;
801 mFixedHeight = height;
802 }
803
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800804 @Override
805 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800806 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800807 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700808 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
809 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700810 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
811 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -0700812
813 mShortcutsAndWidgets.setRotation(mRotationMode.surfaceRotation);
814 if (mRotationMode.isTransposed) {
815 int tmp = childWidthSize;
816 childWidthSize = childHeightSize;
817 childHeightSize = tmp;
818 }
819
Winson Chung11a1a532013-09-13 11:14:45 -0700820 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Sunny Goyalc6205602015-05-21 20:46:33 -0700821 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
822 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700823 if (cw != mCellWidth || ch != mCellHeight) {
824 mCellWidth = cw;
825 mCellHeight = ch;
Sunny Goyalaa8a8712016-11-20 15:26:01 +0530826 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700827 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700828 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700829
Winson Chung2d75f122013-09-23 16:53:31 -0700830 int newWidth = childWidthSize;
831 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700832 if (mFixedWidth > 0 && mFixedHeight > 0) {
833 newWidth = mFixedWidth;
834 newHeight = mFixedHeight;
835 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800836 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
837 }
838
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700839 mShortcutsAndWidgets.measure(
840 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
841 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
842
843 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
844 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700845 if (mFixedWidth > 0 && mFixedHeight > 0) {
846 setMeasuredDimension(maxWidth, maxHeight);
847 } else {
848 setMeasuredDimension(widthSize, heightSize);
849 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800850 }
851
852 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700853 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -0800854 int left = getPaddingLeft();
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700855 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -0700856 int right = r - l - getPaddingRight();
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700857 right -= (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -0700858
Winson Chung38848ca2013-10-08 12:03:44 -0700859 int top = getPaddingTop();
Sunny Goyal7c786f72016-06-01 14:08:21 -0700860 int bottom = b - t - getPaddingBottom();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700861
Sunny Goyal7c786f72016-06-01 14:08:21 -0700862 // Expand the background drawing bounds by the padding baked into the background drawable
863 mBackground.getPadding(mTempRect);
864 mBackground.setBounds(
Jon Miranda28032002017-07-13 16:18:56 -0700865 left - mTempRect.left - getPaddingLeft(),
866 top - mTempRect.top - getPaddingTop(),
867 right + mTempRect.right + getPaddingRight(),
868 bottom + mTempRect.bottom + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -0700869
870 if (mRotationMode.isTransposed) {
871 int halfW = mShortcutsAndWidgets.getMeasuredWidth() / 2;
872 int halfH = mShortcutsAndWidgets.getMeasuredHeight() / 2;
873 int cX = (left + right) / 2;
874 int cY = (top + bottom) / 2;
875 mShortcutsAndWidgets.layout(cX - halfW, cY - halfH, cX + halfW, cY + halfH);
876 } else {
877 mShortcutsAndWidgets.layout(left, top, right, bottom);
878 }
Sunny Goyal7c786f72016-06-01 14:08:21 -0700879 }
880
Tony Wickhama501d492015-11-03 18:05:01 -0800881 /**
882 * Returns the amount of space left over after subtracting padding and cells. This space will be
883 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
884 * width in {@link DeviceProfile#calculateCellWidth(int, int)}.
885 */
886 public int getUnusedHorizontalSpace() {
Sunny Goyal41d51a02019-05-14 09:44:34 -0700887 return (mRotationMode.isTransposed ? getMeasuredHeight() : getMeasuredWidth())
888 - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
Tony Wickhama501d492015-11-03 18:05:01 -0800889 }
890
Sunny Goyalaeb16432017-10-16 11:46:41 -0700891 public Drawable getScrimBackground() {
892 return mBackground;
Michael Jurkadee05892010-07-27 10:01:56 -0700893 }
894
Sunny Goyal2805e632015-05-20 15:35:32 -0700895 @Override
896 protected boolean verifyDrawable(Drawable who) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700897 return super.verifyDrawable(who) || (who == mBackground);
Sunny Goyal2805e632015-05-20 15:35:32 -0700898 }
899
Michael Jurkaa52570f2012-03-20 03:18:20 -0700900 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -0700901 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700902 }
903
Patrick Dubroy440c3602010-07-13 17:50:32 -0700904 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700905 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -0700906 }
907
Adam Cohen76fc0852011-06-17 13:26:23 -0700908 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -0800909 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700910 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -0800911
Adam Cohen19f37922012-03-21 11:59:11 -0700912 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700913 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
914 final ItemInfo info = (ItemInfo) child.getTag();
915
916 // We cancel any existing animations
917 if (mReorderAnimators.containsKey(lp)) {
918 mReorderAnimators.get(lp).cancel();
919 mReorderAnimators.remove(lp);
920 }
921
Adam Cohen482ed822012-03-02 14:15:13 -0800922 final int oldX = lp.x;
923 final int oldY = lp.y;
924 if (adjustOccupied) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700925 GridOccupancy occupied = permanent ? mOccupied : mTmpOccupied;
926 occupied.markCells(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, false);
927 occupied.markCells(cellX, cellY, lp.cellHSpan, lp.cellVSpan, true);
Adam Cohen482ed822012-03-02 14:15:13 -0800928 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700929 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -0800930 if (permanent) {
931 lp.cellX = info.cellX = cellX;
932 lp.cellY = info.cellY = cellY;
933 } else {
934 lp.tmpCellX = cellX;
935 lp.tmpCellY = cellY;
936 }
Jon Mirandae96798e2016-12-07 12:10:44 -0800937 clc.setupLp(child);
Adam Cohenbfbfd262011-06-13 16:55:12 -0700938 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800939 final int newX = lp.x;
940 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700941
Adam Cohen76fc0852011-06-17 13:26:23 -0700942 lp.x = oldX;
943 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -0700944
Adam Cohen482ed822012-03-02 14:15:13 -0800945 // Exit early if we're not actually moving the view
946 if (oldX == newX && oldY == newY) {
947 lp.isLockedToGrid = true;
948 return true;
949 }
950
Sunny Goyal849c6a22018-08-08 16:33:46 -0700951 ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -0800952 va.setDuration(duration);
953 mReorderAnimators.put(lp, va);
954
955 va.addUpdateListener(new AnimatorUpdateListener() {
956 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -0700957 public void onAnimationUpdate(ValueAnimator animation) {
Jon Mirandae96798e2016-12-07 12:10:44 -0800958 float r = (Float) animation.getAnimatedValue();
Adam Cohen19f37922012-03-21 11:59:11 -0700959 lp.x = (int) ((1 - r) * oldX + r * newX);
960 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -0700961 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -0700962 }
963 });
Adam Cohen482ed822012-03-02 14:15:13 -0800964 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700965 boolean cancelled = false;
966 public void onAnimationEnd(Animator animation) {
967 // If the animation was cancelled, it means that another animation
968 // has interrupted this one, and we don't want to lock the item into
969 // place just yet.
970 if (!cancelled) {
971 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -0800972 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -0700973 }
974 if (mReorderAnimators.containsKey(lp)) {
975 mReorderAnimators.remove(lp);
976 }
977 }
978 public void onAnimationCancel(Animator animation) {
979 cancelled = true;
980 }
981 });
Adam Cohen482ed822012-03-02 14:15:13 -0800982 va.setStartDelay(delay);
983 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -0700984 return true;
985 }
986 return false;
987 }
988
Adam Cohen65086992020-02-19 08:40:49 -0800989 void visualizeDropLocation(DraggableView v, DragPreviewProvider outlineProvider, int cellX, int
990 cellY, int spanX, int spanY, boolean resize, DropTarget.DragObject dragObject) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -0700991 final int oldDragCellX = mDragCell[0];
992 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -0800993
Hyunyoung Song0de01172016-10-05 16:27:48 -0700994 if (outlineProvider == null || outlineProvider.generatedDragOutline == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -0700995 return;
996 }
997
Hyunyoung Song0de01172016-10-05 16:27:48 -0700998 Bitmap dragOutline = outlineProvider.generatedDragOutline;
Adam Cohen482ed822012-03-02 14:15:13 -0800999 if (cellX != oldDragCellX || cellY != oldDragCellY) {
1000 mDragCell[0] = cellX;
1001 mDragCell[1] = cellY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001002
Joe Onorato4be866d2010-10-10 11:26:02 -07001003 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001004 mDragOutlineAnims[oldIndex].animateOut();
1005 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001006 Rect r = mDragOutlines[mDragOutlineCurrent];
Sunny Goyal106bf642015-07-16 12:18:06 -07001007
Adam Cohen65086992020-02-19 08:40:49 -08001008 cellToRect(cellX, cellY, spanX, spanY, r);
1009 int left = r.left;
1010 int top = r.top;
1011
1012 int width = dragOutline.getWidth();
1013 int height = dragOutline.getHeight();
1014
Adam Cohend41fbf52012-02-16 23:53:59 -08001015 if (resize) {
Adam Cohen65086992020-02-19 08:40:49 -08001016 width = r.width();
1017 height = r.height();
Adam Cohend41fbf52012-02-16 23:53:59 -08001018 }
Winson Chung150fbab2010-09-29 17:14:26 -07001019
Adam Cohen65086992020-02-19 08:40:49 -08001020 if (v != null && v.getViewType() == DraggableView.DRAGGABLE_ICON) {
1021 left += ((mCellWidth * spanX) - dragOutline.getWidth()) / 2;
1022 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
1023 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
1024 top += cellPaddingY;
1025 }
1026
1027 r.set(left, top, left + width, top + height);
1028
Jon Miranda6f6a06a2016-12-15 11:24:18 -08001029 Utilities.scaleRectAboutCenter(r, mChildScale);
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001030 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1031 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001032
1033 if (dragObject.stateAnnouncer != null) {
Sunny Goyalc13403c2016-11-18 23:44:48 -08001034 dragObject.stateAnnouncer.announce(getItemMoveDescription(cellX, cellY));
Sunny Goyale78e3d72015-09-24 11:23:31 -07001035 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001036 }
1037 }
1038
Sunny Goyal726bee72018-03-05 12:54:24 -08001039 @SuppressLint("StringFormatMatches")
Sunny Goyalc13403c2016-11-18 23:44:48 -08001040 public String getItemMoveDescription(int cellX, int cellY) {
1041 if (mContainerType == HOTSEAT) {
1042 return getContext().getString(R.string.move_to_hotseat_position,
1043 Math.max(cellX, cellY) + 1);
1044 } else {
1045 return getContext().getString(R.string.move_to_empty_cell,
1046 cellY + 1, cellX + 1);
1047 }
1048 }
1049
Adam Cohene0310962011-04-18 16:15:31 -07001050 public void clearDragOutlines() {
1051 final int oldIndex = mDragOutlineCurrent;
1052 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001053 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001054 }
1055
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001056 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001057 * Find a vacant area that will fit the given bounds nearest the requested
1058 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001059 *
Romain Guy51afc022009-05-04 18:03:43 -07001060 * @param pixelX The X location at which you want to search for a vacant area.
1061 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001062 * @param minSpanX The minimum horizontal span required
1063 * @param minSpanY The minimum vertical span required
1064 * @param spanX Horizontal span of the object.
1065 * @param spanY Vertical span of the object.
1066 * @param result Array in which to place the result, or null (in which case a new array will
1067 * be allocated)
1068 * @return The X, Y cell of a vacant area that can contain this object,
1069 * nearest the requested location.
1070 */
1071 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1072 int spanY, int[] result, int[] resultSpan) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001073 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
Adam Cohend41fbf52012-02-16 23:53:59 -08001074 result, resultSpan);
1075 }
1076
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001077 private final Stack<Rect> mTempRectStack = new Stack<>();
Adam Cohend41fbf52012-02-16 23:53:59 -08001078 private void lazyInitTempRectStack() {
1079 if (mTempRectStack.isEmpty()) {
1080 for (int i = 0; i < mCountX * mCountY; i++) {
1081 mTempRectStack.push(new Rect());
1082 }
1083 }
1084 }
Adam Cohen482ed822012-03-02 14:15:13 -08001085
Adam Cohend41fbf52012-02-16 23:53:59 -08001086 private void recycleTempRects(Stack<Rect> used) {
1087 while (!used.isEmpty()) {
1088 mTempRectStack.push(used.pop());
1089 }
1090 }
1091
1092 /**
1093 * Find a vacant area that will fit the given bounds nearest the requested
1094 * cell location. Uses Euclidean distance to score multiple vacant areas.
1095 *
1096 * @param pixelX The X location at which you want to search for a vacant area.
1097 * @param pixelY The Y location at which you want to search for a vacant area.
1098 * @param minSpanX The minimum horizontal span required
1099 * @param minSpanY The minimum vertical span required
1100 * @param spanX Horizontal span of the object.
1101 * @param spanY Vertical span of the object.
1102 * @param ignoreOccupied If true, the result can be an occupied cell
1103 * @param result Array in which to place the result, or null (in which case a new array will
1104 * be allocated)
1105 * @return The X, Y cell of a vacant area that can contain this object,
1106 * nearest the requested location.
1107 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001108 private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1109 int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001110 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001111
Adam Cohene3e27a82011-04-15 12:07:39 -07001112 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1113 // to the center of the item, but we are searching based on the top-left cell, so
1114 // we translate the point over to correspond to the top-left.
Sunny Goyalaa8a8712016-11-20 15:26:01 +05301115 pixelX -= mCellWidth * (spanX - 1) / 2f;
1116 pixelY -= mCellHeight * (spanY - 1) / 2f;
Adam Cohene3e27a82011-04-15 12:07:39 -07001117
Jeff Sharkey70864282009-04-07 21:08:40 -07001118 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001119 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001120 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001121 final Rect bestRect = new Rect(-1, -1, -1, -1);
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001122 final Stack<Rect> validRegions = new Stack<>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001123
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001124 final int countX = mCountX;
1125 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001126
Adam Cohend41fbf52012-02-16 23:53:59 -08001127 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1128 spanX < minSpanX || spanY < minSpanY) {
1129 return bestXY;
1130 }
1131
1132 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001133 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001134 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1135 int ySize = -1;
1136 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001137 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001138 // First, let's see if this thing fits anywhere
1139 for (int i = 0; i < minSpanX; i++) {
1140 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001141 if (mOccupied.cells[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001142 continue inner;
1143 }
Michael Jurkac28de512010-08-13 11:27:44 -07001144 }
1145 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001146 xSize = minSpanX;
1147 ySize = minSpanY;
1148
1149 // We know that the item will fit at _some_ acceptable size, now let's see
1150 // how big we can make it. We'll alternate between incrementing x and y spans
1151 // until we hit a limit.
1152 boolean incX = true;
1153 boolean hitMaxX = xSize >= spanX;
1154 boolean hitMaxY = ySize >= spanY;
1155 while (!(hitMaxX && hitMaxY)) {
1156 if (incX && !hitMaxX) {
1157 for (int j = 0; j < ySize; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001158 if (x + xSize > countX -1 || mOccupied.cells[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001159 // We can't move out horizontally
1160 hitMaxX = true;
1161 }
1162 }
1163 if (!hitMaxX) {
1164 xSize++;
1165 }
1166 } else if (!hitMaxY) {
1167 for (int i = 0; i < xSize; i++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001168 if (y + ySize > countY - 1 || mOccupied.cells[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001169 // We can't move out vertically
1170 hitMaxY = true;
1171 }
1172 }
1173 if (!hitMaxY) {
1174 ySize++;
1175 }
1176 }
1177 hitMaxX |= xSize >= spanX;
1178 hitMaxY |= ySize >= spanY;
1179 incX = !incX;
1180 }
1181 incX = true;
1182 hitMaxX = xSize >= spanX;
1183 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001184 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001185 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001186 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001187
Adam Cohend41fbf52012-02-16 23:53:59 -08001188 // We verify that the current rect is not a sub-rect of any of our previous
1189 // candidates. In this case, the current rect is disqualified in favour of the
1190 // containing rect.
1191 Rect currentRect = mTempRectStack.pop();
1192 currentRect.set(x, y, x + xSize, y + ySize);
1193 boolean contained = false;
1194 for (Rect r : validRegions) {
1195 if (r.contains(currentRect)) {
1196 contained = true;
1197 break;
1198 }
1199 }
1200 validRegions.push(currentRect);
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001201 double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
Adam Cohen482ed822012-03-02 14:15:13 -08001202
Adam Cohend41fbf52012-02-16 23:53:59 -08001203 if ((distance <= bestDistance && !contained) ||
1204 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001205 bestDistance = distance;
1206 bestXY[0] = x;
1207 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001208 if (resultSpan != null) {
1209 resultSpan[0] = xSize;
1210 resultSpan[1] = ySize;
1211 }
1212 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001213 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001214 }
1215 }
1216
Adam Cohenc0dcf592011-06-01 15:30:43 -07001217 // Return -1, -1 if no suitable location found
1218 if (bestDistance == Double.MAX_VALUE) {
1219 bestXY[0] = -1;
1220 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001221 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001222 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001223 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001224 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001225
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001226 /**
Adam Cohen482ed822012-03-02 14:15:13 -08001227 * Find a vacant area that will fit the given bounds nearest the requested
1228 * cell location, and will also weigh in a suggested direction vector of the
1229 * desired location. This method computers distance based on unit grid distances,
1230 * not pixel distances.
1231 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001232 * @param cellX The X cell nearest to which you want to search for a vacant area.
1233 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001234 * @param spanX Horizontal span of the object.
1235 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001236 * @param direction The favored direction in which the views should move from x, y
Sunny Goyal9eba1fd2015-10-16 08:58:57 -07001237 * @param occupied The array which represents which cells in the CellLayout are occupied
Adam Cohen47a876d2012-03-19 13:21:41 -07001238 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001239 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001240 * @param result Array in which to place the result, or null (in which case a new array will
1241 * be allocated)
1242 * @return The X, Y cell of a vacant area that can contain this object,
1243 * nearest the requested location.
1244 */
1245 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001246 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001247 // Keep track of best-scoring drop area
1248 final int[] bestXY = result != null ? result : new int[2];
1249 float bestDistance = Float.MAX_VALUE;
1250 int bestDirectionScore = Integer.MIN_VALUE;
1251
1252 final int countX = mCountX;
1253 final int countY = mCountY;
1254
1255 for (int y = 0; y < countY - (spanY - 1); y++) {
1256 inner:
1257 for (int x = 0; x < countX - (spanX - 1); x++) {
1258 // First, let's see if this thing fits anywhere
1259 for (int i = 0; i < spanX; i++) {
1260 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001261 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001262 continue inner;
1263 }
1264 }
1265 }
1266
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001267 float distance = (float) Math.hypot(x - cellX, y - cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001268 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001269 computeDirectionVector(x - cellX, y - cellY, curDirection);
1270 // The direction score is just the dot product of the two candidate direction
1271 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001272 int curDirectionScore = direction[0] * curDirection[0] +
1273 direction[1] * curDirection[1];
Sunny Goyal8f90dcf2016-08-18 15:01:11 -07001274 if (Float.compare(distance, bestDistance) < 0 ||
1275 (Float.compare(distance, bestDistance) == 0
1276 && curDirectionScore > bestDirectionScore)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001277 bestDistance = distance;
1278 bestDirectionScore = curDirectionScore;
1279 bestXY[0] = x;
1280 bestXY[1] = y;
1281 }
1282 }
1283 }
1284
1285 // Return -1, -1 if no suitable location found
1286 if (bestDistance == Float.MAX_VALUE) {
1287 bestXY[0] = -1;
1288 bestXY[1] = -1;
1289 }
1290 return bestXY;
1291 }
1292
1293 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001294 int[] direction, ItemConfiguration currentState) {
1295 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001296 boolean success = false;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001297 mTmpOccupied.markCells(c, false);
1298 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001299
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001300 findNearestArea(c.cellX, c.cellY, c.spanX, c.spanY, direction,
1301 mTmpOccupied.cells, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001302
1303 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001304 c.cellX = mTempLocation[0];
1305 c.cellY = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001306 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001307 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001308 mTmpOccupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001309 return success;
1310 }
1311
Adam Cohenf3900c22012-11-16 18:28:11 -08001312 /**
1313 * This helper class defines a cluster of views. It helps with defining complex edges
1314 * of the cluster and determining how those edges interact with other views. The edges
1315 * essentially define a fine-grained boundary around the cluster of views -- like a more
1316 * precise version of a bounding box.
1317 */
1318 private class ViewCluster {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001319 final static int LEFT = 1 << 0;
1320 final static int TOP = 1 << 1;
1321 final static int RIGHT = 1 << 2;
1322 final static int BOTTOM = 1 << 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001323
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001324 final ArrayList<View> views;
1325 final ItemConfiguration config;
1326 final Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001327
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001328 final int[] leftEdge = new int[mCountY];
1329 final int[] rightEdge = new int[mCountY];
1330 final int[] topEdge = new int[mCountX];
1331 final int[] bottomEdge = new int[mCountX];
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001332 int dirtyEdges;
1333 boolean boundingRectDirty;
Adam Cohenf3900c22012-11-16 18:28:11 -08001334
1335 @SuppressWarnings("unchecked")
1336 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1337 this.views = (ArrayList<View>) views.clone();
1338 this.config = config;
1339 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001340 }
1341
Adam Cohenf3900c22012-11-16 18:28:11 -08001342 void resetEdges() {
1343 for (int i = 0; i < mCountX; i++) {
1344 topEdge[i] = -1;
1345 bottomEdge[i] = -1;
1346 }
1347 for (int i = 0; i < mCountY; i++) {
1348 leftEdge[i] = -1;
1349 rightEdge[i] = -1;
1350 }
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001351 dirtyEdges = LEFT | TOP | RIGHT | BOTTOM;
Adam Cohenf3900c22012-11-16 18:28:11 -08001352 boundingRectDirty = true;
1353 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001354
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001355 void computeEdge(int which) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001356 int count = views.size();
1357 for (int i = 0; i < count; i++) {
1358 CellAndSpan cs = config.map.get(views.get(i));
1359 switch (which) {
1360 case LEFT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001361 int left = cs.cellX;
1362 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001363 if (left < leftEdge[j] || leftEdge[j] < 0) {
1364 leftEdge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001365 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001366 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001367 break;
1368 case RIGHT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001369 int right = cs.cellX + cs.spanX;
1370 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001371 if (right > rightEdge[j]) {
1372 rightEdge[j] = right;
Adam Cohenf3900c22012-11-16 18:28:11 -08001373 }
1374 }
1375 break;
1376 case TOP:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001377 int top = cs.cellY;
1378 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001379 if (top < topEdge[j] || topEdge[j] < 0) {
1380 topEdge[j] = top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001381 }
1382 }
1383 break;
1384 case BOTTOM:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001385 int bottom = cs.cellY + cs.spanY;
1386 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001387 if (bottom > bottomEdge[j]) {
1388 bottomEdge[j] = bottom;
Adam Cohenf3900c22012-11-16 18:28:11 -08001389 }
1390 }
1391 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001392 }
1393 }
1394 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001395
1396 boolean isViewTouchingEdge(View v, int whichEdge) {
1397 CellAndSpan cs = config.map.get(v);
1398
Sunny Goyal6dc98b92016-04-03 15:25:29 -07001399 if ((dirtyEdges & whichEdge) == whichEdge) {
1400 computeEdge(whichEdge);
1401 dirtyEdges &= ~whichEdge;
1402 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001403
1404 switch (whichEdge) {
1405 case LEFT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001406 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
1407 if (leftEdge[i] == cs.cellX + cs.spanX) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001408 return true;
1409 }
1410 }
1411 break;
1412 case RIGHT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001413 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
1414 if (rightEdge[i] == cs.cellX) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001415 return true;
1416 }
1417 }
1418 break;
1419 case TOP:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001420 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
1421 if (topEdge[i] == cs.cellY + cs.spanY) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001422 return true;
1423 }
1424 }
1425 break;
1426 case BOTTOM:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001427 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
1428 if (bottomEdge[i] == cs.cellY) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001429 return true;
1430 }
1431 }
1432 break;
1433 }
1434 return false;
1435 }
1436
1437 void shift(int whichEdge, int delta) {
1438 for (View v: views) {
1439 CellAndSpan c = config.map.get(v);
1440 switch (whichEdge) {
1441 case LEFT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001442 c.cellX -= delta;
Adam Cohenf3900c22012-11-16 18:28:11 -08001443 break;
1444 case RIGHT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001445 c.cellX += delta;
Adam Cohenf3900c22012-11-16 18:28:11 -08001446 break;
1447 case TOP:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001448 c.cellY -= delta;
Adam Cohenf3900c22012-11-16 18:28:11 -08001449 break;
1450 case BOTTOM:
1451 default:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001452 c.cellY += delta;
Adam Cohenf3900c22012-11-16 18:28:11 -08001453 break;
1454 }
1455 }
1456 resetEdges();
1457 }
1458
1459 public void addView(View v) {
1460 views.add(v);
1461 resetEdges();
1462 }
1463
1464 public Rect getBoundingRect() {
1465 if (boundingRectDirty) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001466 config.getBoundingRectForViews(views, boundingRect);
Adam Cohenf3900c22012-11-16 18:28:11 -08001467 }
1468 return boundingRect;
1469 }
1470
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001471 final PositionComparator comparator = new PositionComparator();
Adam Cohenf3900c22012-11-16 18:28:11 -08001472 class PositionComparator implements Comparator<View> {
1473 int whichEdge = 0;
1474 public int compare(View left, View right) {
1475 CellAndSpan l = config.map.get(left);
1476 CellAndSpan r = config.map.get(right);
1477 switch (whichEdge) {
1478 case LEFT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001479 return (r.cellX + r.spanX) - (l.cellX + l.spanX);
Adam Cohenf3900c22012-11-16 18:28:11 -08001480 case RIGHT:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001481 return l.cellX - r.cellX;
Adam Cohenf3900c22012-11-16 18:28:11 -08001482 case TOP:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001483 return (r.cellY + r.spanY) - (l.cellY + l.spanY);
Adam Cohenf3900c22012-11-16 18:28:11 -08001484 case BOTTOM:
1485 default:
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001486 return l.cellY - r.cellY;
Adam Cohenf3900c22012-11-16 18:28:11 -08001487 }
1488 }
1489 }
1490
1491 public void sortConfigurationForEdgePush(int edge) {
1492 comparator.whichEdge = edge;
1493 Collections.sort(config.sortedViews, comparator);
1494 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001495 }
1496
Adam Cohenf3900c22012-11-16 18:28:11 -08001497 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1498 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001499
Adam Cohenf3900c22012-11-16 18:28:11 -08001500 ViewCluster cluster = new ViewCluster(views, currentState);
1501 Rect clusterRect = cluster.getBoundingRect();
1502 int whichEdge;
1503 int pushDistance;
1504 boolean fail = false;
1505
1506 // Determine the edge of the cluster that will be leading the push and how far
1507 // the cluster must be shifted.
1508 if (direction[0] < 0) {
1509 whichEdge = ViewCluster.LEFT;
1510 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001511 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001512 whichEdge = ViewCluster.RIGHT;
1513 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1514 } else if (direction[1] < 0) {
1515 whichEdge = ViewCluster.TOP;
1516 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1517 } else {
1518 whichEdge = ViewCluster.BOTTOM;
1519 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07001520 }
1521
Adam Cohenf3900c22012-11-16 18:28:11 -08001522 // Break early for invalid push distance.
1523 if (pushDistance <= 0) {
1524 return false;
Adam Cohene0489502012-08-27 15:18:53 -07001525 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001526
1527 // Mark the occupied state as false for the group of views we want to move.
1528 for (View v: views) {
1529 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001530 mTmpOccupied.markCells(c, false);
Adam Cohenf3900c22012-11-16 18:28:11 -08001531 }
1532
1533 // We save the current configuration -- if we fail to find a solution we will revert
1534 // to the initial state. The process of finding a solution modifies the configuration
1535 // in place, hence the need for revert in the failure case.
1536 currentState.save();
1537
1538 // The pushing algorithm is simplified by considering the views in the order in which
1539 // they would be pushed by the cluster. For example, if the cluster is leading with its
1540 // left edge, we consider sort the views by their right edge, from right to left.
1541 cluster.sortConfigurationForEdgePush(whichEdge);
1542
1543 while (pushDistance > 0 && !fail) {
1544 for (View v: currentState.sortedViews) {
1545 // For each view that isn't in the cluster, we see if the leading edge of the
1546 // cluster is contacting the edge of that view. If so, we add that view to the
1547 // cluster.
1548 if (!cluster.views.contains(v) && v != dragView) {
1549 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1550 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1551 if (!lp.canReorder) {
1552 // The push solution includes the all apps button, this is not viable.
1553 fail = true;
1554 break;
1555 }
1556 cluster.addView(v);
1557 CellAndSpan c = currentState.map.get(v);
1558
1559 // Adding view to cluster, mark it as not occupied.
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001560 mTmpOccupied.markCells(c, false);
Adam Cohenf3900c22012-11-16 18:28:11 -08001561 }
1562 }
1563 }
1564 pushDistance--;
1565
1566 // The cluster has been completed, now we move the whole thing over in the appropriate
1567 // direction.
1568 cluster.shift(whichEdge, 1);
1569 }
1570
1571 boolean foundSolution = false;
1572 clusterRect = cluster.getBoundingRect();
1573
1574 // Due to the nature of the algorithm, the only check required to verify a valid solution
1575 // is to ensure that completed shifted cluster lies completely within the cell layout.
1576 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1577 clusterRect.bottom <= mCountY) {
1578 foundSolution = true;
1579 } else {
1580 currentState.restore();
1581 }
1582
1583 // In either case, we set the occupied array as marked for the location of the views
1584 for (View v: cluster.views) {
1585 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001586 mTmpOccupied.markCells(c, true);
Adam Cohenf3900c22012-11-16 18:28:11 -08001587 }
1588
1589 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07001590 }
1591
Adam Cohen482ed822012-03-02 14:15:13 -08001592 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08001593 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001594 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001595
Adam Cohen8baab352012-03-20 17:39:21 -07001596 boolean success = false;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001597 Rect boundingRect = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001598 // We construct a rect which represents the entire group of views passed in
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001599 currentState.getBoundingRectForViews(views, boundingRect);
Adam Cohen8baab352012-03-20 17:39:21 -07001600
Adam Cohen8baab352012-03-20 17:39:21 -07001601 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08001602 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001603 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001604 mTmpOccupied.markCells(c, false);
Adam Cohen8baab352012-03-20 17:39:21 -07001605 }
1606
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001607 GridOccupancy blockOccupied = new GridOccupancy(boundingRect.width(), boundingRect.height());
Adam Cohen47a876d2012-03-19 13:21:41 -07001608 int top = boundingRect.top;
1609 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001610 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001611 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08001612 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001613 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001614 blockOccupied.markCells(c.cellX - left, c.cellY - top, c.spanX, c.spanY, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001615 }
1616
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001617 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001618
Adam Cohenf3900c22012-11-16 18:28:11 -08001619 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001620 boundingRect.height(), direction,
1621 mTmpOccupied.cells, blockOccupied.cells, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001622
Adam Cohen8baab352012-03-20 17:39:21 -07001623 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001624 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001625 int deltaX = mTempLocation[0] - boundingRect.left;
1626 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001627 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001628 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001629 c.cellX += deltaX;
1630 c.cellY += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001631 }
1632 success = true;
1633 }
Adam Cohen8baab352012-03-20 17:39:21 -07001634
1635 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08001636 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001637 CellAndSpan c = currentState.map.get(v);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001638 mTmpOccupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001639 }
1640 return success;
1641 }
1642
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001643 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1644 // to push items in each of the cardinal directions, in an order based on the direction vector
1645 // passed.
1646 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1647 int[] direction, View ignoreView, ItemConfiguration solution) {
1648 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001649 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001650 // separately in each of the components.
1651 int temp = direction[1];
1652 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001653
1654 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001655 ignoreView, solution)) {
1656 return true;
1657 }
1658 direction[1] = temp;
1659 temp = direction[0];
1660 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001661
1662 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001663 ignoreView, solution)) {
1664 return true;
1665 }
1666 // Revert the direction
1667 direction[0] = temp;
1668
1669 // Now we try pushing in each component of the opposite direction
1670 direction[0] *= -1;
1671 direction[1] *= -1;
1672 temp = direction[1];
1673 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001674 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001675 ignoreView, solution)) {
1676 return true;
1677 }
1678
1679 direction[1] = temp;
1680 temp = direction[0];
1681 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001682 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001683 ignoreView, solution)) {
1684 return true;
1685 }
1686 // revert the direction
1687 direction[0] = temp;
1688 direction[0] *= -1;
1689 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001690
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001691 } else {
1692 // If the direction vector has a single non-zero component, we push first in the
1693 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08001694 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001695 ignoreView, solution)) {
1696 return true;
1697 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001698 // Then we try the opposite direction
1699 direction[0] *= -1;
1700 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001701 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001702 ignoreView, solution)) {
1703 return true;
1704 }
1705 // Switch the direction back
1706 direction[0] *= -1;
1707 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001708
1709 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001710 // to find a solution by pushing along the perpendicular axis.
1711
1712 // Swap the components
1713 int temp = direction[1];
1714 direction[1] = direction[0];
1715 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08001716 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001717 ignoreView, solution)) {
1718 return true;
1719 }
1720
1721 // Then we try the opposite direction
1722 direction[0] *= -1;
1723 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001724 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001725 ignoreView, solution)) {
1726 return true;
1727 }
1728 // Switch the direction back
1729 direction[0] *= -1;
1730 direction[1] *= -1;
1731
1732 // Swap the components back
1733 temp = direction[1];
1734 direction[1] = direction[0];
1735 direction[0] = temp;
1736 }
1737 return false;
1738 }
1739
Adam Cohen482ed822012-03-02 14:15:13 -08001740 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001741 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001742 // Return early if get invalid cell positions
1743 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001744
Adam Cohen8baab352012-03-20 17:39:21 -07001745 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001746 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001747
Adam Cohen8baab352012-03-20 17:39:21 -07001748 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001749 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001750 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001751 if (c != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001752 c.cellX = cellX;
1753 c.cellY = cellY;
Adam Cohen19f37922012-03-21 11:59:11 -07001754 }
Adam Cohen482ed822012-03-02 14:15:13 -08001755 }
Adam Cohen482ed822012-03-02 14:15:13 -08001756 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1757 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001758 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001759 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001760 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001761 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001762 r1.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001763 if (Rect.intersects(r0, r1)) {
1764 if (!lp.canReorder) {
1765 return false;
1766 }
1767 mIntersectingViews.add(child);
1768 }
1769 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001770
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001771 solution.intersectingViews = new ArrayList<>(mIntersectingViews);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001772
Winson Chung5f8afe62013-08-12 16:19:28 -07001773 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001774 // we try to find a solution such that no displaced item travels through another item
1775 // without also displacing that item.
1776 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001777 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001778 return true;
1779 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001780
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001781 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08001782 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001783 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001784 return true;
1785 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001786
Adam Cohen482ed822012-03-02 14:15:13 -08001787 // Ok, they couldn't move as a block, let's move them individually
1788 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001789 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001790 return false;
1791 }
1792 }
1793 return true;
1794 }
1795
1796 /*
1797 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1798 * the provided point and the provided cell
1799 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001800 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Jon Mirandae96798e2016-12-07 12:10:44 -08001801 double angle = Math.atan(deltaY / deltaX);
Adam Cohen482ed822012-03-02 14:15:13 -08001802
1803 result[0] = 0;
1804 result[1] = 0;
1805 if (Math.abs(Math.cos(angle)) > 0.5f) {
1806 result[0] = (int) Math.signum(deltaX);
1807 }
1808 if (Math.abs(Math.sin(angle)) > 0.5f) {
1809 result[1] = (int) Math.signum(deltaY);
1810 }
1811 }
1812
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001813 private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001814 int spanX, int spanY, int[] direction, View dragView, boolean decX,
1815 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001816 // Copy the current state into the solution. This solution will be manipulated as necessary.
1817 copyCurrentStateToSolution(solution, false);
1818 // Copy the current occupied array into the temporary occupied array. This array will be
1819 // manipulated as necessary to find a solution.
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001820 mOccupied.copyTo(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001821
1822 // We find the nearest cell into which we would place the dragged item, assuming there's
1823 // nothing in its way.
1824 int result[] = new int[2];
1825 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1826
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001827 boolean success;
Adam Cohen482ed822012-03-02 14:15:13 -08001828 // First we try the exact nearest position of the item being dragged,
1829 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001830 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1831 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001832
1833 if (!success) {
1834 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1835 // x, then 1 in y etc.
1836 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001837 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
1838 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001839 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001840 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
1841 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001842 }
1843 solution.isSolution = false;
1844 } else {
1845 solution.isSolution = true;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001846 solution.cellX = result[0];
1847 solution.cellY = result[1];
1848 solution.spanX = spanX;
1849 solution.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001850 }
1851 return solution;
1852 }
1853
1854 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001855 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001856 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001857 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001858 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001859 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08001860 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07001861 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001862 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001863 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001864 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001865 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08001866 }
1867 }
1868
1869 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001870 mTmpOccupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001871
Michael Jurkaa52570f2012-03-20 03:18:20 -07001872 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001873 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001874 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001875 if (child == dragView) continue;
1876 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001877 CellAndSpan c = solution.map.get(child);
1878 if (c != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001879 lp.tmpCellX = c.cellX;
1880 lp.tmpCellY = c.cellY;
Adam Cohen8baab352012-03-20 17:39:21 -07001881 lp.cellHSpan = c.spanX;
1882 lp.cellVSpan = c.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001883 mTmpOccupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001884 }
1885 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001886 mTmpOccupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001887 }
1888
1889 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1890 commitDragView) {
1891
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001892 GridOccupancy occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1893 occupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001894
Michael Jurkaa52570f2012-03-20 03:18:20 -07001895 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001896 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001897 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001898 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001899 CellAndSpan c = solution.map.get(child);
1900 if (c != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001901 animateChildToPosition(child, c.cellX, c.cellY, REORDER_ANIMATION_DURATION, 0,
Adam Cohen19f37922012-03-21 11:59:11 -07001902 DESTRUCTIVE_REORDER, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001903 occupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001904 }
1905 }
1906 if (commitDragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001907 occupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001908 }
1909 }
1910
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001911
1912 // This method starts or changes the reorder preview animations
1913 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
Adam Cohen65086992020-02-19 08:40:49 -08001914 View dragView, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07001915 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07001916 for (int i = 0; i < childCount; i++) {
1917 View child = mShortcutsAndWidgets.getChildAt(i);
1918 if (child == dragView) continue;
1919 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001920 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
1921 != null && !solution.intersectingViews.contains(child);
1922
Adam Cohen19f37922012-03-21 11:59:11 -07001923 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001924 if (c != null && !skip) {
1925 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001926 lp.cellY, c.cellX, c.cellY, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07001927 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07001928 }
1929 }
1930 }
1931
Sunny Goyal849c6a22018-08-08 16:33:46 -07001932 private static final Property<ReorderPreviewAnimation, Float> ANIMATION_PROGRESS =
1933 new Property<ReorderPreviewAnimation, Float>(float.class, "animationProgress") {
1934 @Override
1935 public Float get(ReorderPreviewAnimation anim) {
1936 return anim.animationProgress;
1937 }
1938
1939 @Override
1940 public void set(ReorderPreviewAnimation anim, Float progress) {
1941 anim.setAnimationProgress(progress);
1942 }
1943 };
1944
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001945 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07001946 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001947 class ReorderPreviewAnimation {
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001948 final View child;
Adam Cohend024f982012-05-23 18:26:45 -07001949 float finalDeltaX;
1950 float finalDeltaY;
1951 float initDeltaX;
1952 float initDeltaY;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001953 final float finalScale;
Adam Cohend024f982012-05-23 18:26:45 -07001954 float initScale;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001955 final int mode;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001956 boolean repeating = false;
1957 private static final int PREVIEW_DURATION = 300;
1958 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
1959
Jon Miranda21266912016-12-19 14:12:05 -08001960 private static final float CHILD_DIVIDEND = 4.0f;
1961
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001962 public static final int MODE_HINT = 0;
1963 public static final int MODE_PREVIEW = 1;
1964
Sunny Goyal849c6a22018-08-08 16:33:46 -07001965 float animationProgress = 0;
Sunny Goyalf0b6db72018-08-13 16:10:14 -07001966 ValueAnimator a;
Adam Cohen19f37922012-03-21 11:59:11 -07001967
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001968 public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
1969 int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07001970 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
1971 final int x0 = mTmpPoint[0];
1972 final int y0 = mTmpPoint[1];
1973 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
1974 final int x1 = mTmpPoint[0];
1975 final int y1 = mTmpPoint[1];
1976 final int dX = x1 - x0;
1977 final int dY = y1 - y0;
Jon Miranda21266912016-12-19 14:12:05 -08001978
1979 this.child = child;
1980 this.mode = mode;
Adam Cohen65086992020-02-19 08:40:49 -08001981
1982 // TODO issue!
Jon Miranda21266912016-12-19 14:12:05 -08001983 setInitialAnimationValues(false);
1984 finalScale = (mChildScale - (CHILD_DIVIDEND / child.getWidth())) * initScale;
1985 finalDeltaX = initDeltaX;
1986 finalDeltaY = initDeltaY;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001987 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07001988 if (dX == dY && dX == 0) {
1989 } else {
1990 if (dY == 0) {
Jon Miranda21266912016-12-19 14:12:05 -08001991 finalDeltaX += - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001992 } else if (dX == 0) {
Jon Miranda21266912016-12-19 14:12:05 -08001993 finalDeltaY += - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001994 } else {
1995 double angle = Math.atan( (float) (dY) / dX);
Jon Miranda21266912016-12-19 14:12:05 -08001996 finalDeltaX += (int) (- dir * Math.signum(dX) *
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001997 Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
Jon Miranda21266912016-12-19 14:12:05 -08001998 finalDeltaY += (int) (- dir * Math.signum(dY) *
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001999 Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002000 }
2001 }
Jon Miranda21266912016-12-19 14:12:05 -08002002 }
2003
2004 void setInitialAnimationValues(boolean restoreOriginalValues) {
2005 if (restoreOriginalValues) {
2006 if (child instanceof LauncherAppWidgetHostView) {
2007 LauncherAppWidgetHostView lahv = (LauncherAppWidgetHostView) child;
2008 initScale = lahv.getScaleToFit();
2009 initDeltaX = lahv.getTranslationForCentering().x;
2010 initDeltaY = lahv.getTranslationForCentering().y;
2011 } else {
2012 initScale = mChildScale;
2013 initDeltaX = 0;
2014 initDeltaY = 0;
2015 }
2016 } else {
2017 initScale = child.getScaleX();
2018 initDeltaX = child.getTranslationX();
2019 initDeltaY = child.getTranslationY();
2020 }
Adam Cohen19f37922012-03-21 11:59:11 -07002021 }
2022
Adam Cohend024f982012-05-23 18:26:45 -07002023 void animate() {
Jon Miranda21266912016-12-19 14:12:05 -08002024 boolean noMovement = (finalDeltaX == initDeltaX) && (finalDeltaY == initDeltaY);
2025
Adam Cohen19f37922012-03-21 11:59:11 -07002026 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002027 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002028 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002029 mShakeAnimators.remove(child);
Jon Miranda21266912016-12-19 14:12:05 -08002030 if (noMovement) {
Adam Cohene7587d22012-05-24 18:50:02 -07002031 completeAnimationImmediately();
2032 return;
2033 }
Adam Cohen19f37922012-03-21 11:59:11 -07002034 }
Jon Miranda21266912016-12-19 14:12:05 -08002035 if (noMovement) {
Adam Cohen19f37922012-03-21 11:59:11 -07002036 return;
2037 }
Sunny Goyal849c6a22018-08-08 16:33:46 -07002038 ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS, 0, 1);
Adam Cohene7587d22012-05-24 18:50:02 -07002039 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07002040
2041 // Animations are disabled in power save mode, causing the repeated animation to jump
2042 // spastically between beginning and end states. Since this looks bad, we don't repeat
2043 // the animation in power save mode.
Sunny Goyal7368fa42019-04-22 09:58:14 -07002044 if (Utilities.areAnimationsEnabled(getContext())) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07002045 va.setRepeatMode(ValueAnimator.REVERSE);
2046 va.setRepeatCount(ValueAnimator.INFINITE);
2047 }
2048
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002049 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002050 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002051 va.addListener(new AnimatorListenerAdapter() {
2052 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002053 // We make sure to end only after a full period
Jon Miranda21266912016-12-19 14:12:05 -08002054 setInitialAnimationValues(true);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002055 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002056 }
2057 });
Adam Cohen19f37922012-03-21 11:59:11 -07002058 mShakeAnimators.put(child, this);
2059 va.start();
2060 }
2061
Sunny Goyal849c6a22018-08-08 16:33:46 -07002062 private void setAnimationProgress(float progress) {
2063 animationProgress = progress;
2064 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : animationProgress;
2065 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2066 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
2067 child.setTranslationX(x);
2068 child.setTranslationY(y);
2069 float s = animationProgress * finalScale + (1 - animationProgress) * initScale;
2070 child.setScaleX(s);
2071 child.setScaleY(s);
2072 }
2073
Adam Cohend024f982012-05-23 18:26:45 -07002074 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002075 if (a != null) {
2076 a.cancel();
2077 }
Adam Cohen19f37922012-03-21 11:59:11 -07002078 }
Adam Cohene7587d22012-05-24 18:50:02 -07002079
Adam Cohen091440a2015-03-18 14:16:05 -07002080 @Thunk void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002081 if (a != null) {
2082 a.cancel();
2083 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002084
Jon Miranda72dbd912017-01-04 14:03:07 -08002085 setInitialAnimationValues(true);
Sunny Goyalf0b6db72018-08-13 16:10:14 -07002086 a = new PropertyListBuilder()
2087 .scale(initScale)
2088 .translationX(initDeltaX)
2089 .translationY(initDeltaY)
2090 .build(child)
Sunny Goyal9e76f682017-02-13 12:13:43 -08002091 .setDuration(REORDER_ANIMATION_DURATION);
Sunny Goyalab770a12018-11-14 15:17:26 -08002092 Launcher.cast(mActivity).getDragController().addFirstFrameAnimationHelper(a);
Sunny Goyalf0b6db72018-08-13 16:10:14 -07002093 a.setInterpolator(DEACCEL_1_5);
Sunny Goyal5d2fc322015-07-06 22:52:49 -07002094 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07002095 }
Adam Cohen19f37922012-03-21 11:59:11 -07002096 }
2097
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002098 private void completeAndClearReorderPreviewAnimations() {
2099 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002100 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002101 }
2102 mShakeAnimators.clear();
2103 }
2104
Adam Cohen482ed822012-03-02 14:15:13 -08002105 private void commitTempPlacement() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002106 mTmpOccupied.copyTo(mOccupied);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002107
Sunny Goyalab770a12018-11-14 15:17:26 -08002108 int screenId = Launcher.cast(mActivity).getWorkspace().getIdForScreen(this);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002109 int container = Favorites.CONTAINER_DESKTOP;
2110
Sunny Goyalc13403c2016-11-18 23:44:48 -08002111 if (mContainerType == HOTSEAT) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002112 screenId = -1;
2113 container = Favorites.CONTAINER_HOTSEAT;
2114 }
2115
Michael Jurkaa52570f2012-03-20 03:18:20 -07002116 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002117 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002118 View child = mShortcutsAndWidgets.getChildAt(i);
2119 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2120 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002121 // We do a null check here because the item info can be null in the case of the
2122 // AllApps button in the hotseat.
2123 if (info != null) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002124 final boolean requiresDbUpdate = (info.cellX != lp.tmpCellX
2125 || info.cellY != lp.tmpCellY || info.spanX != lp.cellHSpan
2126 || info.spanY != lp.cellVSpan);
2127
Adam Cohen2acce882012-03-28 19:03:19 -07002128 info.cellX = lp.cellX = lp.tmpCellX;
2129 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002130 info.spanX = lp.cellHSpan;
2131 info.spanY = lp.cellVSpan;
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002132
2133 if (requiresDbUpdate) {
Sunny Goyalab770a12018-11-14 15:17:26 -08002134 Launcher.cast(mActivity).getModelWriter().modifyItemInDatabase(info, container,
2135 screenId, info.cellX, info.cellY, info.spanX, info.spanY);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002136 }
Adam Cohen2acce882012-03-28 19:03:19 -07002137 }
Adam Cohen482ed822012-03-02 14:15:13 -08002138 }
2139 }
2140
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002141 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002142 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002143 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002144 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002145 lp.useTmpCoords = useTempCoords;
2146 }
2147 }
2148
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002149 private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002150 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2151 int[] result = new int[2];
2152 int[] resultSpan = new int[2];
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002153 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
Adam Cohen482ed822012-03-02 14:15:13 -08002154 resultSpan);
2155 if (result[0] >= 0 && result[1] >= 0) {
2156 copyCurrentStateToSolution(solution, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002157 solution.cellX = result[0];
2158 solution.cellY = result[1];
2159 solution.spanX = resultSpan[0];
2160 solution.spanY = resultSpan[1];
Adam Cohen482ed822012-03-02 14:15:13 -08002161 solution.isSolution = true;
2162 } else {
2163 solution.isSolution = false;
2164 }
2165 return solution;
2166 }
2167
Adam Cohen19f37922012-03-21 11:59:11 -07002168 /* This seems like it should be obvious and straight-forward, but when the direction vector
2169 needs to match with the notion of the dragView pushing other views, we have to employ
2170 a slightly more subtle notion of the direction vector. The question is what two points is
2171 the vector between? The center of the dragView and its desired destination? Not quite, as
2172 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2173 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2174 or right, which helps make pushing feel right.
2175 */
2176 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2177 int spanY, View dragView, int[] resultDirection) {
Adam Cohen65086992020-02-19 08:40:49 -08002178
2179 //TODO(adamcohen) b/151776141 use the items visual center for the direction vector
Adam Cohen19f37922012-03-21 11:59:11 -07002180 int[] targetDestination = new int[2];
2181
2182 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2183 Rect dragRect = new Rect();
2184 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2185 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2186
2187 Rect dropRegionRect = new Rect();
2188 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2189 dragView, dropRegionRect, mIntersectingViews);
2190
2191 int dropRegionSpanX = dropRegionRect.width();
2192 int dropRegionSpanY = dropRegionRect.height();
2193
2194 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2195 dropRegionRect.height(), dropRegionRect);
2196
2197 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2198 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2199
2200 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2201 deltaX = 0;
2202 }
2203 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2204 deltaY = 0;
2205 }
2206
2207 if (deltaX == 0 && deltaY == 0) {
2208 // No idea what to do, give a random direction.
2209 resultDirection[0] = 1;
2210 resultDirection[1] = 0;
2211 } else {
2212 computeDirectionVector(deltaX, deltaY, resultDirection);
2213 }
2214 }
2215
2216 // For a given cell and span, fetch the set of views intersecting the region.
2217 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2218 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2219 if (boundingRect != null) {
2220 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2221 }
2222 intersectingViews.clear();
2223 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2224 Rect r1 = new Rect();
2225 final int count = mShortcutsAndWidgets.getChildCount();
2226 for (int i = 0; i < count; i++) {
2227 View child = mShortcutsAndWidgets.getChildAt(i);
2228 if (child == dragView) continue;
2229 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2230 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2231 if (Rect.intersects(r0, r1)) {
2232 mIntersectingViews.add(child);
2233 if (boundingRect != null) {
2234 boundingRect.union(r1);
2235 }
2236 }
2237 }
2238 }
2239
2240 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2241 View dragView, int[] result) {
2242 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2243 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2244 mIntersectingViews);
2245 return !mIntersectingViews.isEmpty();
2246 }
2247
2248 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002249 completeAndClearReorderPreviewAnimations();
2250 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2251 final int count = mShortcutsAndWidgets.getChildCount();
2252 for (int i = 0; i < count; i++) {
2253 View child = mShortcutsAndWidgets.getChildAt(i);
2254 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2255 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2256 lp.tmpCellX = lp.cellX;
2257 lp.tmpCellY = lp.cellY;
2258 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2259 0, false, false);
2260 }
Adam Cohen19f37922012-03-21 11:59:11 -07002261 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002262 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002263 }
Adam Cohen19f37922012-03-21 11:59:11 -07002264 }
2265
Adam Cohenbebf0422012-04-11 18:06:28 -07002266 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2267 View dragView, int[] direction, boolean commit) {
2268 int[] pixelXY = new int[2];
2269 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2270
2271 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002272 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002273 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2274
2275 setUseTempCoords(true);
2276 if (swapSolution != null && swapSolution.isSolution) {
2277 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2278 // committing anything or animating anything as we just want to determine if a solution
2279 // exists
2280 copySolutionToTempState(swapSolution, dragView);
2281 setItemPlacementDirty(true);
2282 animateItemsToSolution(swapSolution, dragView, commit);
2283
2284 if (commit) {
2285 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002286 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002287 setItemPlacementDirty(false);
2288 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002289 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
Adam Cohen65086992020-02-19 08:40:49 -08002290 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002291 }
2292 mShortcutsAndWidgets.requestLayout();
2293 }
2294 return swapSolution.isSolution;
2295 }
2296
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002297 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002298 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002299 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002300 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002301
2302 if (resultSpan == null) {
2303 resultSpan = new int[2];
2304 }
2305
Adam Cohen19f37922012-03-21 11:59:11 -07002306 // When we are checking drop validity or actually dropping, we don't recompute the
2307 // direction vector, since we want the solution to match the preview, and it's possible
2308 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002309 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2310 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002311 mDirectionVector[0] = mPreviousReorderDirection[0];
2312 mDirectionVector[1] = mPreviousReorderDirection[1];
2313 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002314 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2315 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2316 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002317 }
2318 } else {
2319 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2320 mPreviousReorderDirection[0] = mDirectionVector[0];
2321 mPreviousReorderDirection[1] = mDirectionVector[1];
2322 }
2323
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002324 // Find a solution involving pushing / displacing any items in the way
2325 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002326 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2327
2328 // We attempt the approach which doesn't shuffle views at all
2329 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2330 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2331
2332 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002333
2334 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2335 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002336 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2337 finalSolution = swapSolution;
2338 } else if (noShuffleSolution.isSolution) {
2339 finalSolution = noShuffleSolution;
2340 }
2341
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002342 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002343 if (finalSolution != null) {
Adam Cohen65086992020-02-19 08:40:49 -08002344 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
Adam Cohenfe692872013-12-11 14:47:23 -08002345 ReorderPreviewAnimation.MODE_HINT);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002346 result[0] = finalSolution.cellX;
2347 result[1] = finalSolution.cellY;
2348 resultSpan[0] = finalSolution.spanX;
2349 resultSpan[1] = finalSolution.spanY;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002350 } else {
2351 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2352 }
2353 return result;
2354 }
2355
Adam Cohen482ed822012-03-02 14:15:13 -08002356 boolean foundSolution = true;
2357 if (!DESTRUCTIVE_REORDER) {
2358 setUseTempCoords(true);
2359 }
2360
2361 if (finalSolution != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002362 result[0] = finalSolution.cellX;
2363 result[1] = finalSolution.cellY;
2364 resultSpan[0] = finalSolution.spanX;
2365 resultSpan[1] = finalSolution.spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002366
2367 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2368 // committing anything or animating anything as we just want to determine if a solution
2369 // exists
2370 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2371 if (!DESTRUCTIVE_REORDER) {
2372 copySolutionToTempState(finalSolution, dragView);
2373 }
2374 setItemPlacementDirty(true);
2375 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2376
Adam Cohen19f37922012-03-21 11:59:11 -07002377 if (!DESTRUCTIVE_REORDER &&
2378 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002379 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002380 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002381 setItemPlacementDirty(false);
2382 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002383 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
Adam Cohen65086992020-02-19 08:40:49 -08002384 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002385 }
2386 }
2387 } else {
2388 foundSolution = false;
2389 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2390 }
2391
2392 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2393 setUseTempCoords(false);
2394 }
Adam Cohen482ed822012-03-02 14:15:13 -08002395
Michael Jurkaa52570f2012-03-20 03:18:20 -07002396 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002397 return result;
2398 }
2399
Adam Cohen19f37922012-03-21 11:59:11 -07002400 void setItemPlacementDirty(boolean dirty) {
2401 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002402 }
Adam Cohen19f37922012-03-21 11:59:11 -07002403 boolean isItemPlacementDirty() {
2404 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002405 }
2406
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002407 private static class ItemConfiguration extends CellAndSpan {
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002408 final ArrayMap<View, CellAndSpan> map = new ArrayMap<>();
2409 private final ArrayMap<View, CellAndSpan> savedMap = new ArrayMap<>();
2410 final ArrayList<View> sortedViews = new ArrayList<>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002411 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002412 boolean isSolution = false;
Adam Cohen482ed822012-03-02 14:15:13 -08002413
Adam Cohenf3900c22012-11-16 18:28:11 -08002414 void save() {
2415 // Copy current state into savedMap
2416 for (View v: map.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002417 savedMap.get(v).copyFrom(map.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002418 }
2419 }
2420
2421 void restore() {
2422 // Restore current state from savedMap
2423 for (View v: savedMap.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002424 map.get(v).copyFrom(savedMap.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002425 }
2426 }
2427
2428 void add(View v, CellAndSpan cs) {
2429 map.put(v, cs);
2430 savedMap.put(v, new CellAndSpan());
2431 sortedViews.add(v);
2432 }
2433
Adam Cohen482ed822012-03-02 14:15:13 -08002434 int area() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002435 return spanX * spanY;
Adam Cohenf3900c22012-11-16 18:28:11 -08002436 }
2437
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002438 void getBoundingRectForViews(ArrayList<View> views, Rect outRect) {
2439 boolean first = true;
2440 for (View v: views) {
2441 CellAndSpan c = map.get(v);
2442 if (first) {
2443 outRect.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2444 first = false;
2445 } else {
2446 outRect.union(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2447 }
2448 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002449 }
Adam Cohen482ed822012-03-02 14:15:13 -08002450 }
2451
Adam Cohendf035382011-04-11 17:22:04 -07002452 /**
Adam Cohendf035382011-04-11 17:22:04 -07002453 * Find a starting cell position that will fit the given bounds nearest the requested
2454 * cell location. Uses Euclidean distance to score multiple vacant areas.
2455 *
2456 * @param pixelX The X location at which you want to search for a vacant area.
2457 * @param pixelY The Y location at which you want to search for a vacant area.
2458 * @param spanX Horizontal span of the object.
2459 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07002460 * @param result Previously returned value to possibly recycle.
2461 * @return The X, Y cell of a vacant area that can contain this object,
2462 * nearest the requested location.
2463 */
Adam Cohenf9c184a2016-01-15 16:47:43 -08002464 public int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002465 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002466 }
2467
Michael Jurka0280c3b2010-09-17 15:00:07 -07002468 boolean existsEmptyCell() {
2469 return findCellForSpan(null, 1, 1);
2470 }
2471
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002472 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002473 * Finds the upper-left coordinate of the first rectangle in the grid that can
2474 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2475 * then this method will only return coordinates for rectangles that contain the cell
2476 * (intersectX, intersectY)
2477 *
2478 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2479 * can be found.
2480 * @param spanX The horizontal span of the cell we want to find.
2481 * @param spanY The vertical span of the cell we want to find.
2482 *
2483 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002484 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002485 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002486 if (cellXY == null) {
2487 cellXY = new int[2];
Michael Jurka0280c3b2010-09-17 15:00:07 -07002488 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002489 return mOccupied.findVacantCell(cellXY, spanX, spanY);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002490 }
2491
2492 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002493 * A drag event has begun over this layout.
2494 * It may have begun over this layout (in which case onDragChild is called first),
2495 * or it may have begun on another layout.
2496 */
2497 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002498 mDragging = true;
2499 }
2500
2501 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002502 * Called when drag has left this CellLayout or has been completed (successfully or not)
2503 */
2504 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002505 // This can actually be called when we aren't in a drag, e.g. when adding a new
2506 // item to this layout via the customize drawer.
2507 // Guard against that case.
2508 if (mDragging) {
2509 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002510 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002511
2512 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002513 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002514 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2515 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002516 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002517 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002518 }
2519
2520 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002521 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002522 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002523 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002524 *
2525 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002526 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002527 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002528 if (child != null) {
2529 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002530 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002531 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002532 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002533 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002534 }
2535
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002536 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002537 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002538 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002539 * @param cellX X coordinate of upper left corner expressed as a cell position
2540 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002541 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002542 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002543 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002544 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002545 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002546 final int cellWidth = mCellWidth;
2547 final int cellHeight = mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -07002548
Winson Chung4b825dcd2011-06-19 12:41:22 -07002549 final int hStartPadding = getPaddingLeft();
2550 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002551
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302552 int width = cellHSpan * cellWidth;
2553 int height = cellVSpan * cellHeight;
2554 int x = hStartPadding + cellX * cellWidth;
2555 int y = vStartPadding + cellY * cellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -07002556
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002557 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002558 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002559
Adam Cohend4844c32011-02-18 19:25:06 -08002560 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002561 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002562 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002563 mOccupied.markCells(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002564 }
2565
Adam Cohend4844c32011-02-18 19:25:06 -08002566 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002567 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002568 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002569 mOccupied.markCells(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002570 }
2571
Adam Cohen2801caf2011-05-13 20:57:39 -07002572 public int getDesiredWidth() {
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302573 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth);
Adam Cohen2801caf2011-05-13 20:57:39 -07002574 }
2575
2576 public int getDesiredHeight() {
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302577 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight);
Adam Cohen2801caf2011-05-13 20:57:39 -07002578 }
2579
Michael Jurka66d72172011-04-12 16:29:25 -07002580 public boolean isOccupied(int x, int y) {
2581 if (x < mCountX && y < mCountY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002582 return mOccupied.cells[x][y];
Michael Jurka66d72172011-04-12 16:29:25 -07002583 } else {
2584 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2585 }
2586 }
2587
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002588 @Override
2589 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2590 return new CellLayout.LayoutParams(getContext(), attrs);
2591 }
2592
2593 @Override
2594 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2595 return p instanceof CellLayout.LayoutParams;
2596 }
2597
2598 @Override
2599 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2600 return new CellLayout.LayoutParams(p);
2601 }
2602
2603 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2604 /**
2605 * Horizontal location of the item in the grid.
2606 */
2607 @ViewDebug.ExportedProperty
2608 public int cellX;
2609
2610 /**
2611 * Vertical location of the item in the grid.
2612 */
2613 @ViewDebug.ExportedProperty
2614 public int cellY;
2615
2616 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002617 * Temporary horizontal location of the item in the grid during reorder
2618 */
2619 public int tmpCellX;
2620
2621 /**
2622 * Temporary vertical location of the item in the grid during reorder
2623 */
2624 public int tmpCellY;
2625
2626 /**
2627 * Indicates that the temporary coordinates should be used to layout the items
2628 */
2629 public boolean useTmpCoords;
2630
2631 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002632 * Number of cells spanned horizontally by the item.
2633 */
2634 @ViewDebug.ExportedProperty
2635 public int cellHSpan;
2636
2637 /**
2638 * Number of cells spanned vertically by the item.
2639 */
2640 @ViewDebug.ExportedProperty
2641 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002642
Adam Cohen1b607ed2011-03-03 17:26:50 -08002643 /**
2644 * Indicates whether the item will set its x, y, width and height parameters freely,
2645 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2646 */
Adam Cohend4844c32011-02-18 19:25:06 -08002647 public boolean isLockedToGrid = true;
2648
Adam Cohen482ed822012-03-02 14:15:13 -08002649 /**
2650 * Indicates whether this item can be reordered. Always true except in the case of the
Sunny Goyalda4fe1a2016-05-26 16:05:17 -07002651 * the AllApps button and QSB place holder.
Adam Cohen482ed822012-03-02 14:15:13 -08002652 */
2653 public boolean canReorder = true;
2654
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002655 // X coordinate of the view in the layout.
2656 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002657 public int x;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002658 // Y coordinate of the view in the layout.
2659 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002660 public int y;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002661
Romain Guy84f296c2009-11-04 15:00:44 -08002662 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002663
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002664 public LayoutParams(Context c, AttributeSet attrs) {
2665 super(c, attrs);
2666 cellHSpan = 1;
2667 cellVSpan = 1;
2668 }
2669
2670 public LayoutParams(ViewGroup.LayoutParams source) {
2671 super(source);
2672 cellHSpan = 1;
2673 cellVSpan = 1;
2674 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002675
2676 public LayoutParams(LayoutParams source) {
2677 super(source);
2678 this.cellX = source.cellX;
2679 this.cellY = source.cellY;
2680 this.cellHSpan = source.cellHSpan;
2681 this.cellVSpan = source.cellVSpan;
2682 }
2683
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002684 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002685 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002686 this.cellX = cellX;
2687 this.cellY = cellY;
2688 this.cellHSpan = cellHSpan;
2689 this.cellVSpan = cellVSpan;
2690 }
2691
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302692 public void setup(int cellWidth, int cellHeight, boolean invertHorizontally, int colCount) {
Jon Miranda7ae64ff2016-11-21 16:18:46 -08002693 setup(cellWidth, cellHeight, invertHorizontally, colCount, 1.0f, 1.0f);
2694 }
2695
2696 /**
2697 * Use this method, as opposed to {@link #setup(int, int, boolean, int)}, if the view needs
2698 * to be scaled.
2699 *
2700 * ie. In multi-window mode, we setup widgets so that they are measured and laid out
2701 * using their full/invariant device profile sizes.
2702 */
2703 public void setup(int cellWidth, int cellHeight, boolean invertHorizontally, int colCount,
2704 float cellScaleX, float cellScaleY) {
Adam Cohend4844c32011-02-18 19:25:06 -08002705 if (isLockedToGrid) {
2706 final int myCellHSpan = cellHSpan;
2707 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002708 int myCellX = useTmpCoords ? tmpCellX : cellX;
2709 int myCellY = useTmpCoords ? tmpCellY : cellY;
2710
2711 if (invertHorizontally) {
2712 myCellX = colCount - myCellX - cellHSpan;
2713 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002714
Jon Miranda7ae64ff2016-11-21 16:18:46 -08002715 width = (int) (myCellHSpan * cellWidth / cellScaleX - leftMargin - rightMargin);
2716 height = (int) (myCellVSpan * cellHeight / cellScaleY - topMargin - bottomMargin);
Sunny Goyalaa8a8712016-11-20 15:26:01 +05302717 x = (myCellX * cellWidth + leftMargin);
2718 y = (myCellY * cellHeight + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002719 }
2720 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002721
Sunny Goyal11a50742019-08-07 09:24:26 -07002722 /**
2723 * Sets the position to the provided point
2724 */
2725 public void setXY(Point point) {
2726 cellX = point.x;
2727 cellY = point.y;
2728 }
2729
Winson Chungaafa03c2010-06-11 17:34:16 -07002730 public String toString() {
2731 return "(" + this.cellX + ", " + this.cellY + ")";
2732 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002733 }
2734
Michael Jurka0280c3b2010-09-17 15:00:07 -07002735 // This class stores info for two purposes:
2736 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2737 // its spanX, spanY, and the screen it is on
2738 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2739 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2740 // the CellLayout that was long clicked
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002741 public static final class CellInfo extends CellAndSpan {
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002742 public final View cell;
Sunny Goyalefb7e842018-10-04 15:11:00 -07002743 final int screenId;
2744 final int container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002745
Sunny Goyal83a8f042015-05-19 12:52:12 -07002746 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002747 cellX = info.cellX;
2748 cellY = info.cellY;
2749 spanX = info.spanX;
2750 spanY = info.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002751 cell = v;
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002752 screenId = info.screenId;
2753 container = info.container;
2754 }
2755
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002756 @Override
2757 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002758 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2759 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002760 }
2761 }
Michael Jurkad771c962011-08-09 15:00:48 -07002762
Tony Wickham86930612015-09-09 13:50:40 -07002763 /**
Samuel Fufa1e2d0042019-11-18 17:12:46 -08002764 * A Delegated cell Drawing for drawing on CellLayout
2765 */
2766 public abstract static class DelegatedCellDrawing {
2767 public int mDelegateCellX;
2768 public int mDelegateCellY;
2769
2770 /**
2771 * Draw under CellLayout
2772 */
2773 public abstract void drawUnderItem(Canvas canvas);
2774
2775 /**
2776 * Draw over CellLayout
2777 */
2778 public abstract void drawOverItem(Canvas canvas);
2779 }
2780
2781 /**
Tony Wickham86930612015-09-09 13:50:40 -07002782 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2783 * if necessary).
2784 */
2785 public boolean hasReorderSolution(ItemInfo itemInfo) {
2786 int[] cellPoint = new int[2];
2787 // Check for a solution starting at every cell.
2788 for (int cellX = 0; cellX < getCountX(); cellX++) {
2789 for (int cellY = 0; cellY < getCountY(); cellY++) {
2790 cellToPoint(cellX, cellY, cellPoint);
2791 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2792 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2793 true, new ItemConfiguration()).isSolution) {
2794 return true;
2795 }
2796 }
2797 }
2798 return false;
2799 }
2800
Samuel Fufaa4211432020-02-25 18:47:54 -08002801 /**
2802 * Finds solution to accept hotseat migration to cell layout. commits solution if commitConfig
2803 */
2804 public boolean makeSpaceForHotseatMigration(boolean commitConfig) {
2805 if (FeatureFlags.HOTSEAT_MIGRATE_NEW_PAGE.get()) return false;
2806 int[] cellPoint = new int[2];
2807 int[] directionVector = new int[]{0, -1};
2808 cellToPoint(0, mCountY, cellPoint);
2809 ItemConfiguration configuration = new ItemConfiguration();
2810 if (findReorderSolution(cellPoint[0], cellPoint[1], mCountX, 1, mCountX, 1,
2811 directionVector, null, false, configuration).isSolution) {
2812 if (commitConfig) {
2813 copySolutionToTempState(configuration, null);
2814 commitTempPlacement();
2815 }
2816 return true;
2817 }
2818 return false;
2819 }
2820
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002821 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002822 return mOccupied.isRegionVacant(x, y, spanX, spanY);
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002823 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002824}