blob: 64ac84166fe8124c50a6203604e65203047e3826 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyaleaf7a952020-07-29 16:54:20 -070019import static android.animation.ValueAnimator.areAnimatorsEnabled;
20
Kateryna Ivanova71203732023-05-24 15:09:00 +000021import static com.android.app.animation.Interpolators.DECELERATE_1_5;
Charlie Anderson438d4052023-04-25 14:38:57 -040022import static com.android.launcher3.LauncherState.EDIT_MODE;
Tony Wickham0ac045f2021-11-03 13:17:02 -070023import static com.android.launcher3.dragndrop.DraggableView.DRAGGABLE_ICON;
Tony Wickham12784902021-11-03 14:02:10 -070024import static com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR;
Sunny Goyal82dfc152023-02-24 16:50:09 -080025import static com.android.launcher3.util.MultiTranslateDelegate.INDEX_REORDER_BOUNCE_OFFSET;
26import static com.android.launcher3.util.MultiTranslateDelegate.INDEX_REORDER_PREVIEW_OFFSET;
Sunny Goyalf0b6db72018-08-13 16:10:14 -070027
Joe Onorato4be866d2010-10-10 11:26:02 -070028import android.animation.Animator;
Michael Jurka629758f2012-06-14 16:18:21 -070029import android.animation.AnimatorListenerAdapter;
Sunny Goyal849c6a22018-08-08 16:33:46 -070030import android.animation.ObjectAnimator;
Chet Haase00397b12010-10-07 11:13:10 -070031import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070032import android.animation.ValueAnimator;
33import android.animation.ValueAnimator.AnimatorUpdateListener;
Sunny Goyal726bee72018-03-05 12:54:24 -080034import android.annotation.SuppressLint;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040036import android.content.res.Resources;
Sunny Goyalc13403c2016-11-18 23:44:48 -080037import android.content.res.TypedArray;
Winson Chungaafa03c2010-06-11 17:34:16 -070038import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080039import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070040import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070041import android.graphics.Point;
Adam Cohend9162062020-03-24 16:35:35 -070042import android.graphics.PointF;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.graphics.Rect;
Adam Cohenf7ca3b42021-02-22 11:03:58 -080044import android.graphics.RectF;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070045import android.graphics.drawable.Drawable;
Adam Cohen1462de32012-07-24 22:34:36 -070046import android.os.Parcelable;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -070047import android.util.ArrayMap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080048import android.util.AttributeSet;
Adam Cohenf7ca3b42021-02-22 11:03:58 -080049import android.util.FloatProperty;
Joe Onorato4be866d2010-10-10 11:26:02 -070050import android.util.Log;
Sunny Goyal849c6a22018-08-08 16:33:46 -070051import android.util.Property;
Adam Cohen1462de32012-07-24 22:34:36 -070052import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080053import android.view.MotionEvent;
54import android.view.View;
55import android.view.ViewDebug;
56import android.view.ViewGroup;
Adam Cohenc9735cf2015-01-23 16:11:55 -080057import android.view.accessibility.AccessibilityEvent;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070058
vadimt04f356f2019-02-14 18:46:36 -080059import androidx.annotation.IntDef;
Adam Cohenf7ca3b42021-02-22 11:03:58 -080060import androidx.core.graphics.ColorUtils;
vadimt04f356f2019-02-14 18:46:36 -080061import androidx.core.view.ViewCompat;
62
Kateryna Ivanova71203732023-05-24 15:09:00 +000063import com.android.app.animation.Interpolators;
Sunny Goyalaa8ef112015-06-12 20:04:41 -070064import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyale9b651e2015-04-24 11:44:51 -070065import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
Sebastian Francod4682992022-10-05 13:03:09 -050066import com.android.launcher3.celllayout.CellLayoutLayoutParams;
Sunny Goyal669b71f2023-01-27 14:37:07 -080067import com.android.launcher3.celllayout.CellPosMapper.CellPos;
Sebastian Francoe4c03452022-12-27 14:50:02 -060068import com.android.launcher3.celllayout.ReorderAlgorithm;
Sunny Goyal3d706ad2017-03-06 16:56:39 -080069import com.android.launcher3.config.FeatureFlags;
Tony Wickham0ac045f2021-11-03 13:17:02 -070070import com.android.launcher3.dragndrop.DraggableView;
Jon Mirandaa0233f72017-06-22 18:34:45 -070071import com.android.launcher3.folder.PreviewBackground;
Sunny Goyale396abf2020-04-06 15:11:17 -070072import com.android.launcher3.model.data.ItemInfo;
Sebastian Francof153d912022-04-22 16:15:27 -050073import com.android.launcher3.model.data.LauncherAppWidgetInfo;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -070074import com.android.launcher3.util.CellAndSpan;
75import com.android.launcher3.util.GridOccupancy;
Sunny Goyal82dfc152023-02-24 16:50:09 -080076import com.android.launcher3.util.MultiTranslateDelegate;
Sunny Goyale2fd14b2015-08-27 17:45:46 -070077import com.android.launcher3.util.ParcelableSparseArray;
Sunny Goyal9b29ca52017-02-17 10:39:44 -080078import com.android.launcher3.util.Themes;
Adam Cohen091440a2015-03-18 14:16:05 -070079import com.android.launcher3.util.Thunk;
Sunny Goyalab770a12018-11-14 15:17:26 -080080import com.android.launcher3.views.ActivityContext;
Steven Ng32427202021-04-19 18:12:12 +010081import com.android.launcher3.widget.LauncherAppWidgetHostView;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070082
Sunny Goyalc13403c2016-11-18 23:44:48 -080083import java.lang.annotation.Retention;
84import java.lang.annotation.RetentionPolicy;
Adam Cohen69ce2e52011-07-03 19:25:21 -070085import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070086import java.util.Arrays;
Adam Cohenf3900c22012-11-16 18:28:11 -080087import java.util.Collections;
88import java.util.Comparator;
Sebastian Franco45b39b52023-01-10 10:47:46 -060089import java.util.List;
Adam Cohend41fbf52012-02-16 23:53:59 -080090import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070091
Sunny Goyalc4d32012020-04-03 17:10:11 -070092public class CellLayout extends ViewGroup {
Tony Wickhama0628cc2015-10-14 15:23:04 -070093 private static final String TAG = "CellLayout";
94 private static final boolean LOGD = false;
Winson Chungaafa03c2010-06-11 17:34:16 -070095
Tony Wickhamec6fd6f2023-03-11 02:08:57 +000096 /** The color of the "leave-behind" shape when a folder is opened from Hotseat. */
97 private static final int FOLDER_LEAVE_BEHIND_COLOR = Color.argb(160, 245, 245, 245);
98
Sunny Goyalab770a12018-11-14 15:17:26 -080099 protected final ActivityContext mActivity;
Sunny Goyal4ffec482016-02-09 11:28:52 -0800100 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -0700101 @Thunk int mCellWidth;
Sunny Goyal4ffec482016-02-09 11:28:52 -0800102 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -0700103 @Thunk int mCellHeight;
Winson Chung11a1a532013-09-13 11:14:45 -0700104 private int mFixedCellWidth;
105 private int mFixedCellHeight;
Jon Miranda228877d2021-02-09 11:05:00 -0500106 @ViewDebug.ExportedProperty(category = "launcher")
Sebastian Franco25423862023-03-10 10:50:37 -0800107 protected Point mBorderSpace;
Winson Chungaafa03c2010-06-11 17:34:16 -0700108
Sunny Goyal4ffec482016-02-09 11:28:52 -0800109 @ViewDebug.ExportedProperty(category = "launcher")
Sebastian Franco09589322022-11-02 15:25:58 -0700110 protected int mCountX;
Sunny Goyal4ffec482016-02-09 11:28:52 -0800111 @ViewDebug.ExportedProperty(category = "launcher")
Sebastian Franco09589322022-11-02 15:25:58 -0700112 protected int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113
Adam Cohen917e3882013-10-31 15:03:35 -0700114 private boolean mDropPending = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800115
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700116 // These are temporary variables to prevent having to allocate a new object just to
117 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Adam Cohen091440a2015-03-18 14:16:05 -0700118 @Thunk final int[] mTmpPoint = new int[2];
Sunny Goyal2805e632015-05-20 15:35:32 -0700119 @Thunk final int[] mTempLocation = new int[2];
Adam Cohend9162062020-03-24 16:35:35 -0700120 final PointF mTmpPointF = new PointF();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700121
Sebastian Franco09589322022-11-02 15:25:58 -0700122 protected GridOccupancy mOccupied;
Sebastian Francoe4c03452022-12-27 14:50:02 -0600123 public GridOccupancy mTmpOccupied;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800124
Michael Jurkadee05892010-07-27 10:01:56 -0700125 private OnTouchListener mInterceptTouchListener;
126
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800127 private final ArrayList<DelegatedCellDrawing> mDelegatedCellDrawings = new ArrayList<>();
Jon Mirandaa0233f72017-06-22 18:34:45 -0700128 final PreviewBackground mFolderLeaveBehind = new PreviewBackground();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700129
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800130 private static final int[] BACKGROUND_STATE_ACTIVE = new int[] { android.R.attr.state_active };
Sunny Goyale15e2a82017-12-15 13:05:42 -0800131 private static final int[] BACKGROUND_STATE_DEFAULT = EMPTY_STATE_SET;
Sebastian Franco09589322022-11-02 15:25:58 -0700132 protected final Drawable mBackground;
Sunny Goyal2805e632015-05-20 15:35:32 -0700133
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700134 // These values allow a fixed measurement to be set on the CellLayout.
135 private int mFixedWidth = -1;
136 private int mFixedHeight = -1;
137
Michael Jurka33945b22010-12-21 18:19:38 -0800138 // If we're actively dragging something over this screen, mIsDragOverlapping is true
139 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700140
Winson Chung150fbab2010-09-29 17:14:26 -0700141 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700142 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Sebastian Francod4682992022-10-05 13:03:09 -0500143 @Thunk final CellLayoutLayoutParams[] mDragOutlines = new CellLayoutLayoutParams[4];
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700144 @Thunk final float[] mDragOutlineAlphas = new float[mDragOutlines.length];
145 private final InterruptibleInOutAnimator[] mDragOutlineAnims =
Joe Onorato4be866d2010-10-10 11:26:02 -0700146 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700147
148 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700149 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700150 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700151
Sebastian Francod4682992022-10-05 13:03:09 -0500152 @Thunk final ArrayMap<CellLayoutLayoutParams, Animator> mReorderAnimators = new ArrayMap<>();
Adam Cohend9162062020-03-24 16:35:35 -0700153 @Thunk final ArrayMap<Reorderable, ReorderPreviewAnimation> mShakeAnimators = new ArrayMap<>();
Adam Cohen19f37922012-03-21 11:59:11 -0700154
155 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700156
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800157 // Used to visualize the grid and drop locations
158 private boolean mVisualizeCells = false;
159 private boolean mVisualizeDropLocation = true;
160 private RectF mVisualizeGridRect = new RectF();
161 private Paint mVisualizeGridPaint = new Paint();
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800162 private int mGridVisualizationRoundingRadius;
163 private float mGridAlpha = 0f;
164 private int mGridColor = 0;
Sebastian Franco09589322022-11-02 15:25:58 -0700165 protected float mSpringLoadedProgress = 0f;
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800166 private float mScrollProgress = 0f;
167
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700168 // When a drag operation is in progress, holds the nearest cell to the touch point
169 private final int[] mDragCell = new int[2];
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800170 private final int[] mDragCellSpan = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800171
Joe Onorato4be866d2010-10-10 11:26:02 -0700172 private boolean mDragging = false;
173
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700174 private final TimeInterpolator mEaseOutInterpolator;
Sebastian Franco09589322022-11-02 15:25:58 -0700175 protected final ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700176
Sunny Goyalc13403c2016-11-18 23:44:48 -0800177 @Retention(RetentionPolicy.SOURCE)
178 @IntDef({WORKSPACE, HOTSEAT, FOLDER})
179 public @interface ContainerType{}
180 public static final int WORKSPACE = 0;
181 public static final int HOTSEAT = 1;
182 public static final int FOLDER = 2;
183
184 @ContainerType private final int mContainerType;
185
Jon Mirandab28c4fc2017-06-20 10:58:36 -0700186 private final float mChildScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800187
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800188 public static final int MODE_SHOW_REORDER_HINT = 0;
189 public static final int MODE_DRAG_OVER = 1;
190 public static final int MODE_ON_DROP = 2;
191 public static final int MODE_ON_DROP_EXTERNAL = 3;
192 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700193 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800194 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
195
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800196 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700197 private static final int REORDER_ANIMATION_DURATION = 150;
Sunny Goyalc13403c2016-11-18 23:44:48 -0800198 @Thunk final float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700199
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700200 private final ArrayList<View> mIntersectingViews = new ArrayList<>();
201 private final Rect mOccupiedRect = new Rect();
Sebastian Francoe4c03452022-12-27 14:50:02 -0600202 public final int[] mDirectionVector = new int[2];
Steven Ng30dd1d62021-03-15 21:45:49 +0000203
Sebastian Franco53a15a42022-10-25 17:28:54 -0700204 ItemConfiguration mPreviousSolution = null;
Adam Cohenb209e632012-03-27 17:09:36 -0700205 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800206
Sunny Goyal2805e632015-05-20 15:35:32 -0700207 private final Rect mTempRect = new Rect();
Jonathan Miranda21930da2021-05-03 18:44:13 +0000208 private final RectF mTempRectF = new RectF();
Jon Miranda88b7f6a2021-05-03 16:49:53 -0700209 private final float[] mTmpFloatArray = new float[4];
Winson Chung3a6e7f32013-10-09 15:50:52 -0700210
Sunny Goyal73b5a272019-12-09 14:55:56 -0800211 private static final Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700212
Adam Cohenc9735cf2015-01-23 16:11:55 -0800213 // Related to accessible drag and drop
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700214 DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800215
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800216
217 public static final FloatProperty<CellLayout> SPRING_LOADED_PROGRESS =
218 new FloatProperty<CellLayout>("spring_loaded_progress") {
219 @Override
220 public Float get(CellLayout cl) {
221 return cl.getSpringLoadedProgress();
222 }
223
224 @Override
225 public void setValue(CellLayout cl, float progress) {
226 cl.setSpringLoadedProgress(progress);
227 }
228 };
229
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800230 public CellLayout(Context context) {
231 this(context, null);
232 }
233
234 public CellLayout(Context context, AttributeSet attrs) {
235 this(context, attrs, 0);
236 }
237
238 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
239 super(context, attrs, defStyle);
Sunny Goyalc13403c2016-11-18 23:44:48 -0800240 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
241 mContainerType = a.getInteger(R.styleable.CellLayout_containerType, WORKSPACE);
242 a.recycle();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700243
244 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
245 // the user where a dragged item will land when dropped.
246 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800247 setClipToPadding(false);
Sunny Goyalab770a12018-11-14 15:17:26 -0800248 mActivity = ActivityContext.lookupContext(context);
Steven Ngcc505b82021-03-18 23:04:35 +0000249 DeviceProfile deviceProfile = mActivity.getDeviceProfile();
Michael Jurkaa63c4522010-08-19 13:52:27 -0700250
Thales Lima8cd020b2022-03-15 20:15:14 +0000251 resetCellSizeInternal(deviceProfile);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700252
Steven Ngcc505b82021-03-18 23:04:35 +0000253 mCountX = deviceProfile.inv.numColumns;
254 mCountY = deviceProfile.inv.numRows;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700255 mOccupied = new GridOccupancy(mCountX, mCountY);
256 mTmpOccupied = new GridOccupancy(mCountX, mCountY);
257
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800258 mFolderLeaveBehind.mDelegateCellX = -1;
259 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenefca0272016-02-24 19:19:06 -0800260
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800261 setAlwaysDrawnWithCacheEnabled(false);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700262
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800263 Resources res = getResources();
264
265 mBackground = getContext().getDrawable(R.drawable.bg_celllayout);
Sunny Goyal2805e632015-05-20 15:35:32 -0700266 mBackground.setCallback(this);
Sunny Goyalaeb16432017-10-16 11:46:41 -0700267 mBackground.setAlpha(0);
Michael Jurka33945b22010-12-21 18:19:38 -0800268
Yogisha Dixitc0ac1dd2021-05-29 00:26:25 +0100269 mGridColor = Themes.getAttrColor(getContext(), R.attr.workspaceAccentColor);
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800270 mGridVisualizationRoundingRadius =
271 res.getDimensionPixelSize(R.dimen.grid_visualization_rounding_radius);
Steven Ngcc505b82021-03-18 23:04:35 +0000272 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE * deviceProfile.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700273
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700274 // Initialize the data structures used for the drag visualization.
Kateryna Ivanova71203732023-05-24 15:09:00 +0000275 mEaseOutInterpolator = Interpolators.DECELERATE_QUINT; // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700276 mDragCell[0] = mDragCell[1] = -1;
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800277 mDragCellSpan[0] = mDragCellSpan[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700278 for (int i = 0; i < mDragOutlines.length; i++) {
Sunny Goyal669b71f2023-01-27 14:37:07 -0800279 mDragOutlines[i] = new CellLayoutLayoutParams(0, 0, 0, 0);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700280 }
Mario Bertschler54ba6012017-06-08 10:53:53 -0700281 mDragOutlinePaint.setColor(Themes.getAttrColor(context, R.attr.workspaceTextColor));
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700282
283 // When dragging things around the home screens, we show a green outline of
284 // where the item will land. The outlines gradually fade out, leaving a trail
285 // behind the drag path.
286 // Set up all the animations that are used to implement this fading.
287 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700288 final float fromAlphaValue = 0;
289 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700290
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700291 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700292
293 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700294 final InterruptibleInOutAnimator anim =
Sebastian Francof153d912022-04-22 16:15:27 -0500295 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700296 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700297 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700298 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700299 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700300 // If an animation is started and then stopped very quickly, we can still
301 // get spurious updates we've cleared the tag. Guard against this.
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800302 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
303 CellLayout.this.invalidate();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700304 }
305 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700306 // The animation holds a reference to the drag outline bitmap as long is it's
307 // running. This way the bitmap can be GCed when the animations are complete.
Joe Onorato4be866d2010-10-10 11:26:02 -0700308 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700309 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700310
Sunny Goyalc13403c2016-11-18 23:44:48 -0800311 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context, mContainerType);
Jon Miranda228877d2021-02-09 11:05:00 -0500312 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100313 mBorderSpace);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700314 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700315 }
316
Sunny Goyal9b180102020-03-11 10:02:29 -0700317 /**
318 * Sets or clears a delegate used for accessible drag and drop
319 */
320 public void setDragAndDropAccessibilityDelegate(DragAndDropAccessibilityDelegate delegate) {
321 setOnClickListener(delegate);
Sunny Goyal9b180102020-03-11 10:02:29 -0700322 ViewCompat.setAccessibilityDelegate(this, delegate);
323
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700324 mTouchHelper = delegate;
325 int accessibilityFlag = mTouchHelper != null
Sunny Goyal9b180102020-03-11 10:02:29 -0700326 ? IMPORTANT_FOR_ACCESSIBILITY_YES : IMPORTANT_FOR_ACCESSIBILITY_NO;
327 setImportantForAccessibility(accessibilityFlag);
328 getShortcutsAndWidgets().setImportantForAccessibility(accessibilityFlag);
Adam Cohenc9735cf2015-01-23 16:11:55 -0800329
Sunny Goyal384b5782021-02-09 22:50:02 -0800330 // ExploreByTouchHelper sets focusability. Clear it when the delegate is cleared.
331 setFocusable(delegate != null);
Adam Cohenc9735cf2015-01-23 16:11:55 -0800332 // Invalidate the accessibility hierarchy
333 if (getParent() != null) {
334 getParent().notifySubtreeAccessibilityStateChanged(
335 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
336 }
337 }
338
Sunny Goyala4647b62021-02-02 13:45:34 -0800339 /**
340 * Returns the currently set accessibility delegate
341 */
342 public DragAndDropAccessibilityDelegate getDragAndDropAccessibilityDelegate() {
343 return mTouchHelper;
344 }
345
Adam Cohenc9735cf2015-01-23 16:11:55 -0800346 @Override
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700347 public boolean dispatchHoverEvent(MotionEvent event) {
348 // Always attempt to dispatch hover events to accessibility first.
349 if (mTouchHelper != null && mTouchHelper.dispatchHoverEvent(event)) {
350 return true;
351 }
352 return super.dispatchHoverEvent(event);
353 }
354
355 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800356 public boolean onInterceptTouchEvent(MotionEvent ev) {
Winson Chungf9935182020-10-23 09:26:44 -0700357 return mTouchHelper != null
358 || (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev));
Adam Cohenc9735cf2015-01-23 16:11:55 -0800359 }
360
Chris Craik01f2d7f2013-10-01 14:41:56 -0700361 public void enableHardwareLayer(boolean hasLayer) {
362 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700363 }
364
vadimt04f356f2019-02-14 18:46:36 -0800365 public boolean isHardwareLayerEnabled() {
366 return mShortcutsAndWidgets.getLayerType() == LAYER_TYPE_HARDWARE;
367 }
368
Thales Lima8cd020b2022-03-15 20:15:14 +0000369 /**
370 * Change sizes of cells
371 *
372 * @param width the new width of the cells
373 * @param height the new height of the cells
374 */
Winson Chung5f8afe62013-08-12 16:19:28 -0700375 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700376 mFixedCellWidth = mCellWidth = width;
377 mFixedCellHeight = mCellHeight = height;
Jon Miranda228877d2021-02-09 11:05:00 -0500378 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100379 mBorderSpace);
Winson Chung5f8afe62013-08-12 16:19:28 -0700380 }
381
Thales Lima8cd020b2022-03-15 20:15:14 +0000382 private void resetCellSizeInternal(DeviceProfile deviceProfile) {
383 switch (mContainerType) {
384 case FOLDER:
Jordan Silva637f4eb2023-06-13 11:21:53 +0100385 mBorderSpace = new Point(deviceProfile.folderCellLayoutBorderSpacePx);
Thales Lima8cd020b2022-03-15 20:15:14 +0000386 break;
387 case HOTSEAT:
388 mBorderSpace = new Point(deviceProfile.hotseatBorderSpace,
389 deviceProfile.hotseatBorderSpace);
390 break;
391 case WORKSPACE:
392 default:
393 mBorderSpace = new Point(deviceProfile.cellLayoutBorderSpacePx);
394 break;
395 }
396
397 mCellWidth = mCellHeight = -1;
398 mFixedCellWidth = mFixedCellHeight = -1;
399 }
400
401 /**
402 * Reset the cell sizes and border space
403 */
404 public void resetCellSize(DeviceProfile deviceProfile) {
405 resetCellSizeInternal(deviceProfile);
406 requestLayout();
407 }
408
Adam Cohen2801caf2011-05-13 20:57:39 -0700409 public void setGridSize(int x, int y) {
410 mCountX = x;
411 mCountY = y;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700412 mOccupied = new GridOccupancy(mCountX, mCountY);
413 mTmpOccupied = new GridOccupancy(mCountX, mCountY);
Jon Miranda228877d2021-02-09 11:05:00 -0500414 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100415 mBorderSpace);
Adam Cohen76fc0852011-06-17 13:26:23 -0700416 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700417 }
418
Adam Cohen2374abf2013-04-16 14:56:57 -0700419 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
420 public void setInvertIfRtl(boolean invert) {
421 mShortcutsAndWidgets.setInvertIfRtl(invert);
422 }
423
Adam Cohen917e3882013-10-31 15:03:35 -0700424 public void setDropPending(boolean pending) {
425 mDropPending = pending;
426 }
427
428 public boolean isDropPending() {
429 return mDropPending;
430 }
431
Adam Cohenc50438c2014-08-19 17:43:05 -0700432 void setIsDragOverlapping(boolean isDragOverlapping) {
433 if (mIsDragOverlapping != isDragOverlapping) {
434 mIsDragOverlapping = isDragOverlapping;
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800435 mBackground.setState(mIsDragOverlapping
436 ? BACKGROUND_STATE_ACTIVE : BACKGROUND_STATE_DEFAULT);
Adam Cohenc50438c2014-08-19 17:43:05 -0700437 invalidate();
438 }
439 }
440
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700441 @Override
442 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700443 ParcelableSparseArray jail = getJailedArray(container);
444 super.dispatchSaveInstanceState(jail);
445 container.put(R.id.cell_layout_jail_id, jail);
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700446 }
447
448 @Override
449 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700450 super.dispatchRestoreInstanceState(getJailedArray(container));
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700451 }
452
Sunny Goyal7ce471b2017-08-02 03:37:39 -0700453 /**
454 * Wrap the SparseArray in another Parcelable so that the item ids do not conflict with our
455 * our internal resource ids
456 */
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700457 private ParcelableSparseArray getJailedArray(SparseArray<Parcelable> container) {
458 final Parcelable parcelable = container.get(R.id.cell_layout_jail_id);
459 return parcelable instanceof ParcelableSparseArray ?
460 (ParcelableSparseArray) parcelable : new ParcelableSparseArray();
461 }
462
Tony Wickham0f97b782015-12-02 17:55:07 -0800463 public boolean getIsDragOverlapping() {
464 return mIsDragOverlapping;
465 }
466
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700467 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700468 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700469 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
470 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
471 // When we're small, we are either drawn normally or in the "accepts drops" state (during
472 // a drag). However, we also drag the mini hover background *over* one of those two
473 // backgrounds
Sunny Goyalaeb16432017-10-16 11:46:41 -0700474 if (mBackground.getAlpha() > 0) {
Sunny Goyal2805e632015-05-20 15:35:32 -0700475 mBackground.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700476 }
Romain Guya6abce82009-11-10 02:54:41 -0800477
Adam Cohen482ed822012-03-02 14:15:13 -0800478 if (DEBUG_VISUALIZE_OCCUPIED) {
Tony Wickham0ac045f2021-11-03 13:17:02 -0700479 Rect cellBounds = new Rect();
480 // Will contain the bounds of the cell including spacing between cells.
481 Rect cellBoundsWithSpacing = new Rect();
Tony Wickham12784902021-11-03 14:02:10 -0700482 int[] targetCell = new int[2];
Tony Wickham0ac045f2021-11-03 13:17:02 -0700483 int[] cellCenter = new int[2];
484 Paint debugPaint = new Paint();
485 debugPaint.setStrokeWidth(Utilities.dpToPx(1));
486 for (int x = 0; x < mCountX; x++) {
487 for (int y = 0; y < mCountY; y++) {
488 if (!mOccupied.cells[x][y]) {
489 continue;
Adam Cohen482ed822012-03-02 14:15:13 -0800490 }
Tony Wickham12784902021-11-03 14:02:10 -0700491 targetCell[0] = x;
492 targetCell[1] = y;
Tony Wickham0ac045f2021-11-03 13:17:02 -0700493
Tony Wickham12784902021-11-03 14:02:10 -0700494 boolean canCreateFolder = canCreateFolder(getChildAt(x, y));
Tony Wickham0ac045f2021-11-03 13:17:02 -0700495 cellToRect(x, y, 1, 1, cellBounds);
496 cellBoundsWithSpacing.set(cellBounds);
497 cellBoundsWithSpacing.inset(-mBorderSpace.x / 2, -mBorderSpace.y / 2);
Tony Wickham3cfa5ed2021-11-03 13:20:43 -0700498 getWorkspaceCellVisualCenter(x, y, cellCenter);
Tony Wickham0ac045f2021-11-03 13:17:02 -0700499
500 canvas.save();
501 canvas.clipRect(cellBoundsWithSpacing);
502
503 // Draw reorder drag target.
504 debugPaint.setColor(Color.RED);
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700505 canvas.drawCircle(cellCenter[0], cellCenter[1],
506 getReorderRadius(targetCell, 1, 1), debugPaint);
Tony Wickham0ac045f2021-11-03 13:17:02 -0700507
508 // Draw folder creation drag target.
509 if (canCreateFolder) {
510 debugPaint.setColor(Color.GREEN);
511 canvas.drawCircle(cellCenter[0], cellCenter[1],
Tony Wickham12784902021-11-03 14:02:10 -0700512 getFolderCreationRadius(targetCell), debugPaint);
Tony Wickham0ac045f2021-11-03 13:17:02 -0700513 }
514
515 canvas.restore();
Adam Cohen482ed822012-03-02 14:15:13 -0800516 }
517 }
518 }
519
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800520 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
521 DelegatedCellDrawing cellDrawing = mDelegatedCellDrawings.get(i);
522 cellToPoint(cellDrawing.mDelegateCellX, cellDrawing.mDelegateCellY, mTempLocation);
Adam Cohenefca0272016-02-24 19:19:06 -0800523 canvas.save();
524 canvas.translate(mTempLocation[0], mTempLocation[1]);
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800525 cellDrawing.drawUnderItem(canvas);
Adam Cohenefca0272016-02-24 19:19:06 -0800526 canvas.restore();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700527 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700528
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800529 if (mFolderLeaveBehind.mDelegateCellX >= 0 && mFolderLeaveBehind.mDelegateCellY >= 0) {
530 cellToPoint(mFolderLeaveBehind.mDelegateCellX,
531 mFolderLeaveBehind.mDelegateCellY, mTempLocation);
Adam Cohenefca0272016-02-24 19:19:06 -0800532 canvas.save();
533 canvas.translate(mTempLocation[0], mTempLocation[1]);
Tony Wickhamec6fd6f2023-03-11 02:08:57 +0000534 mFolderLeaveBehind.drawLeaveBehind(canvas, FOLDER_LEAVE_BEHIND_COLOR);
Adam Cohenefca0272016-02-24 19:19:06 -0800535 canvas.restore();
Adam Cohenc51934b2011-07-26 21:07:43 -0700536 }
Adam Cohen65086992020-02-19 08:40:49 -0800537
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800538 if (mVisualizeCells || mVisualizeDropLocation) {
Adam Cohen65086992020-02-19 08:40:49 -0800539 visualizeGrid(canvas);
540 }
541 }
542
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800543 /**
Tony Wickham12784902021-11-03 14:02:10 -0700544 * Returns whether dropping an icon on the given View can create (or add to) a folder.
545 */
546 private boolean canCreateFolder(View child) {
547 return child instanceof DraggableView
548 && ((DraggableView) child).getViewType() == DRAGGABLE_ICON;
549 }
550
551 /**
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800552 * Indicates the progress of the Workspace entering the SpringLoaded state; allows the
553 * CellLayout to update various visuals for this state.
554 *
555 * @param progress
556 */
557 public void setSpringLoadedProgress(float progress) {
558 if (Float.compare(progress, mSpringLoadedProgress) != 0) {
559 mSpringLoadedProgress = progress;
fbarone74256b2023-04-10 14:50:31 -0700560 updateBgAlpha();
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800561 setGridAlpha(progress);
562 }
563 }
564
565 /**
566 * See setSpringLoadedProgress
567 * @return progress
568 */
569 public float getSpringLoadedProgress() {
570 return mSpringLoadedProgress;
571 }
572
Sebastian Franco09589322022-11-02 15:25:58 -0700573 protected void updateBgAlpha() {
Charlie Anderson438d4052023-04-25 14:38:57 -0400574 if (!getWorkspace().mLauncher.isInState(EDIT_MODE)) {
575 mBackground.setAlpha((int) (mSpringLoadedProgress * 255));
576 }
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800577 }
578
579 /**
580 * Set the progress of this page's scroll
581 *
582 * @param progress 0 if the screen is centered, +/-1 if it is to the right / left respectively
583 */
584 public void setScrollProgress(float progress) {
585 if (Float.compare(Math.abs(progress), mScrollProgress) != 0) {
586 mScrollProgress = Math.abs(progress);
fbarone74256b2023-04-10 14:50:31 -0700587 updateBgAlpha();
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800588 }
589 }
590
591 private void setGridAlpha(float gridAlpha) {
592 if (Float.compare(gridAlpha, mGridAlpha) != 0) {
593 mGridAlpha = gridAlpha;
594 invalidate();
595 }
596 }
597
Adam Cohen65086992020-02-19 08:40:49 -0800598 protected void visualizeGrid(Canvas canvas) {
Adam Cohen0c4d2782021-04-29 15:56:13 -0700599 DeviceProfile dp = mActivity.getDeviceProfile();
Alex Chau51da2192022-05-20 13:32:10 +0100600 int paddingX = Math.min((mCellWidth - dp.iconSizePx) / 2, dp.gridVisualizationPaddingX);
601 int paddingY = Math.min((mCellHeight - dp.iconSizePx) / 2, dp.gridVisualizationPaddingY);
Adam Cohen0c4d2782021-04-29 15:56:13 -0700602 mVisualizeGridRect.set(paddingX, paddingY,
603 mCellWidth - paddingX,
604 mCellHeight - paddingY);
Adam Cohen65086992020-02-19 08:40:49 -0800605
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800606 mVisualizeGridPaint.setStrokeWidth(8);
607 int paintAlpha = (int) (120 * mGridAlpha);
608 mVisualizeGridPaint.setColor(ColorUtils.setAlphaComponent(mGridColor, paintAlpha));
Adam Cohen65086992020-02-19 08:40:49 -0800609
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800610 if (mVisualizeCells) {
611 for (int i = 0; i < mCountX; i++) {
612 for (int j = 0; j < mCountY; j++) {
Thales Lima78d00ad2021-09-30 11:29:06 +0100613 int transX = i * mCellWidth + (i * mBorderSpace.x) + getPaddingLeft()
Adam Cohen0c4d2782021-04-29 15:56:13 -0700614 + paddingX;
Thales Lima78d00ad2021-09-30 11:29:06 +0100615 int transY = j * mCellHeight + (j * mBorderSpace.y) + getPaddingTop()
Adam Cohen0c4d2782021-04-29 15:56:13 -0700616 + paddingY;
Adam Cohen65086992020-02-19 08:40:49 -0800617
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800618 mVisualizeGridRect.offsetTo(transX, transY);
619 mVisualizeGridPaint.setStyle(Paint.Style.FILL);
620 canvas.drawRoundRect(mVisualizeGridRect, mGridVisualizationRoundingRadius,
621 mGridVisualizationRoundingRadius, mVisualizeGridPaint);
622 }
623 }
624 }
Adam Cohen65086992020-02-19 08:40:49 -0800625
fbarone74256b2023-04-10 14:50:31 -0700626 if (mVisualizeDropLocation) {
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800627 for (int i = 0; i < mDragOutlines.length; i++) {
628 final float alpha = mDragOutlineAlphas[i];
629 if (alpha <= 0) continue;
Adam Cohen65086992020-02-19 08:40:49 -0800630
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800631 mVisualizeGridPaint.setAlpha(255);
Sebastian Franco877088e2023-01-03 15:16:22 -0700632 int x = mDragOutlines[i].getCellX();
633 int y = mDragOutlines[i].getCellY();
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800634 int spanX = mDragOutlines[i].cellHSpan;
635 int spanY = mDragOutlines[i].cellVSpan;
636
Adam Cohened82e0d2021-07-21 17:24:12 -0700637 // TODO b/194414754 clean this up, reconcile with cellToRect
Adam Cohen0c4d2782021-04-29 15:56:13 -0700638 mVisualizeGridRect.set(paddingX, paddingY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100639 mCellWidth * spanX + mBorderSpace.x * (spanX - 1) - paddingX,
640 mCellHeight * spanY + mBorderSpace.y * (spanY - 1) - paddingY);
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800641
Thales Lima78d00ad2021-09-30 11:29:06 +0100642 int transX = x * mCellWidth + (x * mBorderSpace.x)
Adam Cohen0c4d2782021-04-29 15:56:13 -0700643 + getPaddingLeft() + paddingX;
Thales Lima78d00ad2021-09-30 11:29:06 +0100644 int transY = y * mCellHeight + (y * mBorderSpace.y)
Adam Cohen0c4d2782021-04-29 15:56:13 -0700645 + getPaddingTop() + paddingY;
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800646
647 mVisualizeGridRect.offsetTo(transX, transY);
Adam Cohen65086992020-02-19 08:40:49 -0800648
649 mVisualizeGridPaint.setStyle(Paint.Style.STROKE);
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800650 mVisualizeGridPaint.setColor(Color.argb((int) (alpha),
651 Color.red(mGridColor), Color.green(mGridColor), Color.blue(mGridColor)));
Adam Cohen65086992020-02-19 08:40:49 -0800652
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800653 canvas.drawRoundRect(mVisualizeGridRect, mGridVisualizationRoundingRadius,
654 mGridVisualizationRoundingRadius, mVisualizeGridPaint);
Adam Cohen65086992020-02-19 08:40:49 -0800655 }
656 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700657 }
658
Adam Cohenefca0272016-02-24 19:19:06 -0800659 @Override
660 protected void dispatchDraw(Canvas canvas) {
661 super.dispatchDraw(canvas);
662
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800663 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
664 DelegatedCellDrawing bg = mDelegatedCellDrawings.get(i);
665 cellToPoint(bg.mDelegateCellX, bg.mDelegateCellY, mTempLocation);
666 canvas.save();
667 canvas.translate(mTempLocation[0], mTempLocation[1]);
668 bg.drawOverItem(canvas);
669 canvas.restore();
Adam Cohenefca0272016-02-24 19:19:06 -0800670 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700671 }
672
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800673 /**
674 * Add Delegated cell drawing
675 */
676 public void addDelegatedCellDrawing(DelegatedCellDrawing bg) {
677 mDelegatedCellDrawings.add(bg);
Adam Cohenefca0272016-02-24 19:19:06 -0800678 }
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800679
680 /**
681 * Remove item from DelegatedCellDrawings
682 */
683 public void removeDelegatedCellDrawing(DelegatedCellDrawing bg) {
684 mDelegatedCellDrawings.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700685 }
686
Adam Cohenc51934b2011-07-26 21:07:43 -0700687 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800688 View child = getChildAt(x, y);
Sunny Goyalab770a12018-11-14 15:17:26 -0800689 mFolderLeaveBehind.setup(getContext(), mActivity, null,
Adam Cohenefca0272016-02-24 19:19:06 -0800690 child.getMeasuredWidth(), child.getPaddingTop());
691
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800692 mFolderLeaveBehind.mDelegateCellX = x;
693 mFolderLeaveBehind.mDelegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700694 invalidate();
695 }
696
697 public void clearFolderLeaveBehind() {
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800698 mFolderLeaveBehind.mDelegateCellX = -1;
699 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700700 invalidate();
701 }
702
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700703 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700704 public boolean shouldDelayChildPressedState() {
705 return false;
706 }
707
Adam Cohen1462de32012-07-24 22:34:36 -0700708 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700709 try {
710 dispatchRestoreInstanceState(states);
711 } catch (IllegalArgumentException ex) {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800712 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700713 throw ex;
714 }
715 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
716 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
717 }
Adam Cohen1462de32012-07-24 22:34:36 -0700718 }
719
Michael Jurkae6235dd2011-10-04 15:02:05 -0700720 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700721 public void cancelLongPress() {
722 super.cancelLongPress();
723
724 // Cancel long press for all children
725 final int count = getChildCount();
726 for (int i = 0; i < count; i++) {
727 final View child = getChildAt(i);
728 child.cancelLongPress();
729 }
730 }
731
Michael Jurkadee05892010-07-27 10:01:56 -0700732 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
733 mInterceptTouchListener = listener;
734 }
735
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800736 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700737 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800738 }
739
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800740 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700741 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800742 }
743
Sunny Goyalc13403c2016-11-18 23:44:48 -0800744 public boolean acceptsWidget() {
745 return mContainerType == WORKSPACE;
Sunny Goyale9b651e2015-04-24 11:44:51 -0700746 }
747
Sebastian Francod4682992022-10-05 13:03:09 -0500748 /**
749 * Adds the given view to the CellLayout
750 *
751 * @param child view to add.
752 * @param index index of the CellLayout children where to add the view.
753 * @param childId id of the view.
754 * @param params represent the logic of the view on the CellLayout.
755 * @param markCells if the occupied cells should be marked or not
756 * @return if adding the view was successful
757 */
758 public boolean addViewToCellLayout(View child, int index, int childId,
759 CellLayoutLayoutParams params, boolean markCells) {
760 final CellLayoutLayoutParams lp = params;
Winson Chungaafa03c2010-06-11 17:34:16 -0700761
Andrew Flynnde38e422012-05-08 11:22:15 -0700762 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800763 if (child instanceof BubbleTextView) {
764 BubbleTextView bubbleChild = (BubbleTextView) child;
Jon Mirandaf1eae802017-10-04 11:23:33 -0700765 bubbleChild.setTextVisibility(mContainerType != HOTSEAT);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800766 }
767
Sunny Goyalc13403c2016-11-18 23:44:48 -0800768 child.setScaleX(mChildScale);
769 child.setScaleY(mChildScale);
Adam Cohen307fe232012-08-16 17:55:58 -0700770
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800771 // Generate an id for each view, this assumes we have at most 256x256 cells
772 // per workspace screen
Sebastian Franco877088e2023-01-03 15:16:22 -0700773 if (lp.getCellX() >= 0 && lp.getCellX() <= mCountX - 1
774 && lp.getCellY() >= 0 && lp.getCellY() <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700775 // If the horizontal or vertical span is set to -1, it is taken to
776 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700777 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
778 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800779
Winson Chungaafa03c2010-06-11 17:34:16 -0700780 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700781 if (LOGD) {
782 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
783 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700784 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700785
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700786 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700787
Winson Chungaafa03c2010-06-11 17:34:16 -0700788 return true;
789 }
790 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800791 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700792
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800793 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700794 public void removeAllViews() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700795 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700796 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700797 }
798
799 @Override
800 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700801 if (mShortcutsAndWidgets.getChildCount() > 0) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700802 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700803 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700804 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700805 }
806
807 @Override
808 public void removeView(View view) {
809 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700810 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700811 }
812
813 @Override
814 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700815 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
816 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700817 }
818
819 @Override
820 public void removeViewInLayout(View view) {
821 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700822 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700823 }
824
825 @Override
826 public void removeViews(int start, int count) {
827 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700828 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700829 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700830 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700831 }
832
833 @Override
834 public void removeViewsInLayout(int start, int count) {
835 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700836 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700837 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700838 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800839 }
840
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700841 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700842 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800843 * @param x X coordinate of the point
844 * @param y Y coordinate of the point
845 * @param result Array of 2 ints to hold the x and y coordinate of the cell
846 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700847 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700848 final int hStartPadding = getPaddingLeft();
849 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800850
Sebastian Francob57c0b22022-06-28 13:54:35 -0700851 result[0] = (x - hStartPadding) / (mCellWidth + mBorderSpace.x);
852 result[1] = (y - vStartPadding) / (mCellHeight + mBorderSpace.y);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800853
Adam Cohend22015c2010-07-26 22:02:18 -0700854 final int xAxis = mCountX;
855 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800856
857 if (result[0] < 0) result[0] = 0;
858 if (result[0] >= xAxis) result[0] = xAxis - 1;
859 if (result[1] < 0) result[1] = 0;
860 if (result[1] >= yAxis) result[1] = yAxis - 1;
861 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700862
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800863 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800864 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700865 *
866 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800867 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700868 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800869 * @param result Array of 2 ints to hold the x and y coordinate of the point
870 */
871 void cellToPoint(int cellX, int cellY, int[] result) {
Jon Miranda228877d2021-02-09 11:05:00 -0500872 cellToRect(cellX, cellY, 1, 1, mTempRect);
873 result[0] = mTempRect.left;
874 result[1] = mTempRect.top;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800875 }
876
Adam Cohene3e27a82011-04-15 12:07:39 -0700877 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800878 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700879 *
880 * @param cellX X coordinate of the cell
881 * @param cellY Y coordinate of the cell
882 *
883 * @param result Array of 2 ints to hold the x and y coordinate of the point
884 */
885 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700886 regionToCenterPoint(cellX, cellY, 1, 1, result);
887 }
888
889 /**
Tony Wickham0ac045f2021-11-03 13:17:02 -0700890 * Given a cell coordinate and span return the point that represents the center of the region
Adam Cohen47a876d2012-03-19 13:21:41 -0700891 *
892 * @param cellX X coordinate of the cell
893 * @param cellY Y coordinate of the cell
894 *
895 * @param result Array of 2 ints to hold the x and y coordinate of the point
896 */
Sebastian Franco45b39b52023-01-10 10:47:46 -0600897 public void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Jon Miranda228877d2021-02-09 11:05:00 -0500898 cellToRect(cellX, cellY, spanX, spanY, mTempRect);
899 result[0] = mTempRect.centerX();
900 result[1] = mTempRect.centerY();
Adam Cohen19f37922012-03-21 11:59:11 -0700901 }
902
Tony Wickham3cfa5ed2021-11-03 13:20:43 -0700903 /**
904 * Returns the distance between the given coordinate and the visual center of the given cell.
905 */
906 public float getDistanceFromWorkspaceCellVisualCenter(float x, float y, int[] cell) {
907 getWorkspaceCellVisualCenter(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700908 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800909 }
910
Tony Wickham3cfa5ed2021-11-03 13:20:43 -0700911 private void getWorkspaceCellVisualCenter(int cellX, int cellY, int[] outPoint) {
912 View child = getChildAt(cellX, cellY);
913 if (child instanceof DraggableView) {
914 DraggableView draggableChild = (DraggableView) child;
915 if (draggableChild.getViewType() == DRAGGABLE_ICON) {
916 cellToPoint(cellX, cellY, outPoint);
917 draggableChild.getWorkspaceVisualDragBounds(mTempRect);
918 mTempRect.offset(outPoint[0], outPoint[1]);
919 outPoint[0] = mTempRect.centerX();
920 outPoint[1] = mTempRect.centerY();
921 return;
922 }
923 }
924 cellToCenterPoint(cellX, cellY, outPoint);
925 }
926
Tony Wickham0ac045f2021-11-03 13:17:02 -0700927 /**
928 * Returns the max distance from the center of a cell that can accept a drop to create a folder.
929 */
Tony Wickham12784902021-11-03 14:02:10 -0700930 public float getFolderCreationRadius(int[] targetCell) {
Tony Wickham0ac045f2021-11-03 13:17:02 -0700931 DeviceProfile grid = mActivity.getDeviceProfile();
Tony Wickham12784902021-11-03 14:02:10 -0700932 float iconVisibleRadius = ICON_VISIBLE_AREA_FACTOR * grid.iconSizePx / 2;
933 // Halfway between reorder radius and icon.
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700934 return (getReorderRadius(targetCell, 1, 1) + iconVisibleRadius) / 2;
Tony Wickham12784902021-11-03 14:02:10 -0700935 }
936
937 /**
938 * Returns the max distance from the center of a cell that will start to reorder on drag over.
939 */
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700940 public float getReorderRadius(int[] targetCell, int spanX, int spanY) {
Tony Wickham12784902021-11-03 14:02:10 -0700941 int[] centerPoint = mTmpPoint;
942 getWorkspaceCellVisualCenter(targetCell[0], targetCell[1], centerPoint);
943
944 Rect cellBoundsWithSpacing = mTempRect;
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700945 cellToRect(targetCell[0], targetCell[1], spanX, spanY, cellBoundsWithSpacing);
Tony Wickham12784902021-11-03 14:02:10 -0700946 cellBoundsWithSpacing.inset(-mBorderSpace.x / 2, -mBorderSpace.y / 2);
947
Sebastian Francoc8392ea2022-10-28 16:38:37 -0700948 if (canCreateFolder(getChildAt(targetCell[0], targetCell[1])) && spanX == 1 && spanY == 1) {
Tony Wickham12784902021-11-03 14:02:10 -0700949 // Take only the circle in the smaller dimension, to ensure we don't start reordering
950 // too soon before accepting a folder drop.
951 int minRadius = centerPoint[0] - cellBoundsWithSpacing.left;
952 minRadius = Math.min(minRadius, centerPoint[1] - cellBoundsWithSpacing.top);
953 minRadius = Math.min(minRadius, cellBoundsWithSpacing.right - centerPoint[0]);
954 minRadius = Math.min(minRadius, cellBoundsWithSpacing.bottom - centerPoint[1]);
955 return minRadius;
956 }
957 // Take up the entire cell, including space between this cell and the adjacent ones.
Sebastian Francoc8392ea2022-10-28 16:38:37 -0700958 // Multiply by span to scale radius
959 return (float) Math.hypot(spanX * cellBoundsWithSpacing.width() / 2f,
960 spanY * cellBoundsWithSpacing.height() / 2f);
Tony Wickham0ac045f2021-11-03 13:17:02 -0700961 }
962
Adam Cohenf9c184a2016-01-15 16:47:43 -0800963 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800964 return mCellWidth;
965 }
966
Sunny Goyal0b754e52017-08-07 07:42:45 -0700967 public int getCellHeight() {
Romain Guy84f296c2009-11-04 15:00:44 -0800968 return mCellHeight;
969 }
970
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700971 public void setFixedSize(int width, int height) {
972 mFixedWidth = width;
973 mFixedHeight = height;
974 }
975
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800976 @Override
977 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800978 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800979 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700980 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
981 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700982 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
983 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -0700984
Winson Chung11a1a532013-09-13 11:14:45 -0700985 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Thales Lima78d00ad2021-09-30 11:29:06 +0100986 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mBorderSpace.x,
Jon Miranda228877d2021-02-09 11:05:00 -0500987 mCountX);
Thales Lima78d00ad2021-09-30 11:29:06 +0100988 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mBorderSpace.y,
Jon Miranda228877d2021-02-09 11:05:00 -0500989 mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700990 if (cw != mCellWidth || ch != mCellHeight) {
991 mCellWidth = cw;
992 mCellHeight = ch;
Jon Miranda228877d2021-02-09 11:05:00 -0500993 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100994 mBorderSpace);
Winson Chung11a1a532013-09-13 11:14:45 -0700995 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700996 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700997
Winson Chung2d75f122013-09-23 16:53:31 -0700998 int newWidth = childWidthSize;
999 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -07001000 if (mFixedWidth > 0 && mFixedHeight > 0) {
1001 newWidth = mFixedWidth;
1002 newHeight = mFixedHeight;
1003 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001004 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
1005 }
1006
Sunny Goyal4fe5a372015-05-14 19:55:10 -07001007 mShortcutsAndWidgets.measure(
1008 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
1009 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
1010
1011 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
1012 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -07001013 if (mFixedWidth > 0 && mFixedHeight > 0) {
1014 setMeasuredDimension(maxWidth, maxHeight);
1015 } else {
1016 setMeasuredDimension(widthSize, heightSize);
1017 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001018 }
1019
1020 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -07001021 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -08001022 int left = getPaddingLeft();
Sunny Goyal7ce471b2017-08-02 03:37:39 -07001023 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -07001024 int right = r - l - getPaddingRight();
Sunny Goyal7ce471b2017-08-02 03:37:39 -07001025 right -= (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -07001026
Winson Chung38848ca2013-10-08 12:03:44 -07001027 int top = getPaddingTop();
Sunny Goyal7c786f72016-06-01 14:08:21 -07001028 int bottom = b - t - getPaddingBottom();
Sunny Goyal4fe5a372015-05-14 19:55:10 -07001029
Sunny Goyal7c786f72016-06-01 14:08:21 -07001030 // Expand the background drawing bounds by the padding baked into the background drawable
1031 mBackground.getPadding(mTempRect);
1032 mBackground.setBounds(
Jon Miranda28032002017-07-13 16:18:56 -07001033 left - mTempRect.left - getPaddingLeft(),
1034 top - mTempRect.top - getPaddingTop(),
1035 right + mTempRect.right + getPaddingRight(),
1036 bottom + mTempRect.bottom + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -07001037
Sunny Goyalc4d32012020-04-03 17:10:11 -07001038 mShortcutsAndWidgets.layout(left, top, right, bottom);
Sunny Goyal7c786f72016-06-01 14:08:21 -07001039 }
1040
Tony Wickhama501d492015-11-03 18:05:01 -08001041 /**
1042 * Returns the amount of space left over after subtracting padding and cells. This space will be
1043 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
Jon Miranda228877d2021-02-09 11:05:00 -05001044 * width in {@link DeviceProfile#calculateCellWidth(int, int, int)}.
Tony Wickhama501d492015-11-03 18:05:01 -08001045 */
1046 public int getUnusedHorizontalSpace() {
Jon Miranda228877d2021-02-09 11:05:00 -05001047 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth)
Thales Lima78d00ad2021-09-30 11:29:06 +01001048 - ((mCountX - 1) * mBorderSpace.x);
Tony Wickhama501d492015-11-03 18:05:01 -08001049 }
1050
Sunny Goyal2805e632015-05-20 15:35:32 -07001051 @Override
1052 protected boolean verifyDrawable(Drawable who) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -07001053 return super.verifyDrawable(who) || (who == mBackground);
Sunny Goyal2805e632015-05-20 15:35:32 -07001054 }
1055
Michael Jurkaa52570f2012-03-20 03:18:20 -07001056 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -07001057 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -07001058 }
1059
Jon Miranda228877d2021-02-09 11:05:00 -05001060 public View getChildAt(int cellX, int cellY) {
1061 return mShortcutsAndWidgets.getChildAt(cellX, cellY);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001062 }
1063
Adam Cohen76fc0852011-06-17 13:26:23 -07001064 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001065 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001066 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -08001067
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001068 if (clc.indexOfChild(child) != -1 && (child instanceof Reorderable)) {
Sebastian Francod4682992022-10-05 13:03:09 -05001069 final CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001070 final ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001071 final Reorderable item = (Reorderable) child;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001072
1073 // We cancel any existing animations
1074 if (mReorderAnimators.containsKey(lp)) {
1075 mReorderAnimators.get(lp).cancel();
1076 mReorderAnimators.remove(lp);
1077 }
1078
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001079
Adam Cohen482ed822012-03-02 14:15:13 -08001080 if (adjustOccupied) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001081 GridOccupancy occupied = permanent ? mOccupied : mTmpOccupied;
Sebastian Franco877088e2023-01-03 15:16:22 -07001082 occupied.markCells(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001083 occupied.markCells(cellX, cellY, lp.cellHSpan, lp.cellVSpan, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001084 }
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001085
1086 // Compute the new x and y position based on the new cellX and cellY
1087 // We leverage the actual layout logic in the layout params and hence need to modify
1088 // state and revert that state.
1089 final int oldX = lp.x;
1090 final int oldY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001091 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001092 if (permanent) {
Sunny Goyal669b71f2023-01-27 14:37:07 -08001093 lp.setCellX(cellX);
1094 lp.setCellY(cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001095 } else {
Sebastian Franco877088e2023-01-03 15:16:22 -07001096 lp.setTmpCellX(cellX);
1097 lp.setTmpCellY(cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001098 }
Jon Mirandae96798e2016-12-07 12:10:44 -08001099 clc.setupLp(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001100 final int newX = lp.x;
1101 final int newY = lp.y;
Adam Cohen76fc0852011-06-17 13:26:23 -07001102 lp.x = oldX;
1103 lp.y = oldY;
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001104 lp.isLockedToGrid = false;
1105 // End compute new x and y
1106
Sunny Goyal82dfc152023-02-24 16:50:09 -08001107 MultiTranslateDelegate mtd = item.getTranslateDelegate();
1108 float initPreviewOffsetX = mtd.getTranslationX(INDEX_REORDER_PREVIEW_OFFSET).getValue();
1109 float initPreviewOffsetY = mtd.getTranslationY(INDEX_REORDER_PREVIEW_OFFSET).getValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001110 final float finalPreviewOffsetX = newX - oldX;
1111 final float finalPreviewOffsetY = newY - oldY;
1112
Adam Cohen482ed822012-03-02 14:15:13 -08001113 // Exit early if we're not actually moving the view
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001114 if (finalPreviewOffsetX == 0 && finalPreviewOffsetY == 0
1115 && initPreviewOffsetX == 0 && initPreviewOffsetY == 0) {
Adam Cohen482ed822012-03-02 14:15:13 -08001116 lp.isLockedToGrid = true;
1117 return true;
1118 }
1119
Sunny Goyal849c6a22018-08-08 16:33:46 -07001120 ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001121 va.setDuration(duration);
1122 mReorderAnimators.put(lp, va);
1123
1124 va.addUpdateListener(new AnimatorUpdateListener() {
1125 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001126 public void onAnimationUpdate(ValueAnimator animation) {
Jon Mirandae96798e2016-12-07 12:10:44 -08001127 float r = (Float) animation.getAnimatedValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001128 float x = (1 - r) * initPreviewOffsetX + r * finalPreviewOffsetX;
1129 float y = (1 - r) * initPreviewOffsetY + r * finalPreviewOffsetY;
Sunny Goyal82dfc152023-02-24 16:50:09 -08001130 item.getTranslateDelegate().setTranslation(INDEX_REORDER_PREVIEW_OFFSET, x, y);
Adam Cohenbfbfd262011-06-13 16:55:12 -07001131 }
1132 });
Adam Cohen482ed822012-03-02 14:15:13 -08001133 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001134 boolean cancelled = false;
1135 public void onAnimationEnd(Animator animation) {
1136 // If the animation was cancelled, it means that another animation
1137 // has interrupted this one, and we don't want to lock the item into
1138 // place just yet.
1139 if (!cancelled) {
1140 lp.isLockedToGrid = true;
Sunny Goyal82dfc152023-02-24 16:50:09 -08001141 item.getTranslateDelegate()
1142 .setTranslation(INDEX_REORDER_PREVIEW_OFFSET, 0, 0);
Adam Cohen482ed822012-03-02 14:15:13 -08001143 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001144 }
1145 if (mReorderAnimators.containsKey(lp)) {
1146 mReorderAnimators.remove(lp);
1147 }
1148 }
1149 public void onAnimationCancel(Animator animation) {
1150 cancelled = true;
1151 }
1152 });
Adam Cohen482ed822012-03-02 14:15:13 -08001153 va.setStartDelay(delay);
1154 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001155 return true;
1156 }
1157 return false;
1158 }
1159
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001160 void visualizeDropLocation(int cellX, int cellY, int spanX, int spanY,
1161 DropTarget.DragObject dragObject) {
1162 if (mDragCell[0] != cellX || mDragCell[1] != cellY || mDragCellSpan[0] != spanX
1163 || mDragCellSpan[1] != spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08001164 mDragCell[0] = cellX;
1165 mDragCell[1] = cellY;
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001166 mDragCellSpan[0] = spanX;
1167 mDragCellSpan[1] = spanY;
Steven Ng30dd1d62021-03-15 21:45:49 +00001168
Steven Nga999e222021-04-19 18:17:15 +01001169 // Apply color extraction on a widget when dragging.
1170 applyColorExtractionOnWidget(dragObject, mDragCell, spanX, spanY);
1171
Joe Onorato4be866d2010-10-10 11:26:02 -07001172 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001173 mDragOutlineAnims[oldIndex].animateOut();
1174 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Sunny Goyal106bf642015-07-16 12:18:06 -07001175
Sebastian Francod4682992022-10-05 13:03:09 -05001176 CellLayoutLayoutParams cell = mDragOutlines[mDragOutlineCurrent];
Sebastian Franco877088e2023-01-03 15:16:22 -07001177 cell.setCellX(cellX);
1178 cell.setCellY(cellY);
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001179 cell.cellHSpan = spanX;
1180 cell.cellVSpan = spanY;
Adam Cohen65086992020-02-19 08:40:49 -08001181
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001182 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001183 invalidate();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001184
1185 if (dragObject.stateAnnouncer != null) {
Sunny Goyalc13403c2016-11-18 23:44:48 -08001186 dragObject.stateAnnouncer.announce(getItemMoveDescription(cellX, cellY));
Sunny Goyale78e3d72015-09-24 11:23:31 -07001187 }
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001188
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001189 }
1190 }
1191
Steven Ng30dd1d62021-03-15 21:45:49 +00001192 /** Applies the local color extraction to a dragging widget object. */
Steven Nga999e222021-04-19 18:17:15 +01001193 private void applyColorExtractionOnWidget(DropTarget.DragObject dragObject, int[] targetCell,
1194 int spanX, int spanY) {
Steven Ng30dd1d62021-03-15 21:45:49 +00001195 // Apply local extracted color if the DragView is an AppWidgetHostViewDrawable.
Steven Ng32427202021-04-19 18:12:12 +01001196 View view = dragObject.dragView.getContentView();
1197 if (view instanceof LauncherAppWidgetHostView) {
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001198 int screenId = getWorkspace().getIdForScreen(this);
Steven Ng30dd1d62021-03-15 21:45:49 +00001199 cellToRect(targetCell[0], targetCell[1], spanX, spanY, mTempRect);
Jonathan Miranda21930da2021-05-03 18:44:13 +00001200
Sunny Goyal69a8eec2021-07-22 10:02:50 -07001201 ((LauncherAppWidgetHostView) view).handleDrag(mTempRect, this, screenId);
Steven Ng30dd1d62021-03-15 21:45:49 +00001202 }
1203 }
1204
Sunny Goyal726bee72018-03-05 12:54:24 -08001205 @SuppressLint("StringFormatMatches")
Sunny Goyalc13403c2016-11-18 23:44:48 -08001206 public String getItemMoveDescription(int cellX, int cellY) {
1207 if (mContainerType == HOTSEAT) {
1208 return getContext().getString(R.string.move_to_hotseat_position,
1209 Math.max(cellX, cellY) + 1);
1210 } else {
Shikha Malhotraf78da1b2022-04-11 10:23:18 +00001211 Workspace<?> workspace = getWorkspace();
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001212 int row = cellY + 1;
1213 int col = workspace.mIsRtl ? mCountX - cellX : cellX + 1;
1214 int panelCount = workspace.getPanelCount();
Sebastian Franco930531f2022-06-16 16:49:11 -07001215 int screenId = workspace.getIdForScreen(this);
1216 int pageIndex = workspace.getPageIndexForScreenId(screenId);
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001217 if (panelCount > 1) {
1218 // Increment the column if the target is on the right side of a two panel home
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001219 col += (pageIndex % panelCount) * mCountX;
1220 }
Sebastian Franco930531f2022-06-16 16:49:11 -07001221 return getContext().getString(R.string.move_to_empty_cell_description, row, col,
1222 workspace.getPageDescription(pageIndex));
Sunny Goyalc13403c2016-11-18 23:44:48 -08001223 }
1224 }
1225
Shikha Malhotraf78da1b2022-04-11 10:23:18 +00001226 private Workspace<?> getWorkspace() {
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001227 return Launcher.cast(mActivity).getWorkspace();
1228 }
1229
Adam Cohene0310962011-04-18 16:15:31 -07001230 public void clearDragOutlines() {
1231 final int oldIndex = mDragOutlineCurrent;
1232 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001233 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001234 }
1235
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001236 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001237 * Find a vacant area that will fit the given bounds nearest the requested
1238 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001239 *
Romain Guy51afc022009-05-04 18:03:43 -07001240 * @param pixelX The X location at which you want to search for a vacant area.
1241 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001242 * @param minSpanX The minimum horizontal span required
1243 * @param minSpanY The minimum vertical span required
1244 * @param spanX Horizontal span of the object.
1245 * @param spanY Vertical span of the object.
1246 * @param result Array in which to place the result, or null (in which case a new array will
1247 * be allocated)
1248 * @return The X, Y cell of a vacant area that can contain this object,
1249 * nearest the requested location.
1250 */
Sebastian Francoe4c03452022-12-27 14:50:02 -06001251 public int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
1252 int spanX, int spanY, int[] result, int[] resultSpan) {
Sebastian Francob57c0b22022-06-28 13:54:35 -07001253 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, false,
Adam Cohend41fbf52012-02-16 23:53:59 -08001254 result, resultSpan);
1255 }
1256
Adam Cohend41fbf52012-02-16 23:53:59 -08001257 /**
1258 * Find a vacant area that will fit the given bounds nearest the requested
1259 * cell location. Uses Euclidean distance to score multiple vacant areas.
Sebastian Francob57c0b22022-06-28 13:54:35 -07001260 * @param relativeXPos The X location relative to the Cell layout at which you want to search
1261 * for a vacant area.
1262 * @param relativeYPos The Y location relative to the Cell layout at which you want to search
1263 * for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001264 * @param minSpanX The minimum horizontal span required
1265 * @param minSpanY The minimum vertical span required
1266 * @param spanX Horizontal span of the object.
1267 * @param spanY Vertical span of the object.
1268 * @param ignoreOccupied If true, the result can be an occupied cell
1269 * @param result Array in which to place the result, or null (in which case a new array will
1270 * be allocated)
1271 * @return The X, Y cell of a vacant area that can contain this object,
1272 * nearest the requested location.
1273 */
Sebastian Franco96c46e72023-05-08 10:04:44 -06001274 protected int[] findNearestArea(int relativeXPos, int relativeYPos, int minSpanX, int minSpanY,
Sebastian Francob57c0b22022-06-28 13:54:35 -07001275 int spanX, int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Sebastian Francob57c0b22022-06-28 13:54:35 -07001276 // For items with a spanX / spanY > 1, the passed in point (relativeXPos, relativeYPos)
1277 // corresponds to the center of the item, but we are searching based on the top-left cell,
1278 // so we translate the point over to correspond to the top-left.
1279 relativeXPos = (int) (relativeXPos - (mCellWidth + mBorderSpace.x) * (spanX - 1) / 2f);
1280 relativeYPos = (int) (relativeYPos - (mCellHeight + mBorderSpace.y) * (spanY - 1) / 2f);
Adam Cohene3e27a82011-04-15 12:07:39 -07001281
Jeff Sharkey70864282009-04-07 21:08:40 -07001282 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001283 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001284 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001285 final Rect bestRect = new Rect(-1, -1, -1, -1);
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001286 final Stack<Rect> validRegions = new Stack<>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001287
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001288 final int countX = mCountX;
1289 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001290
Adam Cohend41fbf52012-02-16 23:53:59 -08001291 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1292 spanX < minSpanX || spanY < minSpanY) {
1293 return bestXY;
1294 }
1295
1296 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001297 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001298 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1299 int ySize = -1;
1300 int xSize = -1;
Sebastian Francob57c0b22022-06-28 13:54:35 -07001301 if (!ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001302 // First, let's see if this thing fits anywhere
1303 for (int i = 0; i < minSpanX; i++) {
1304 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001305 if (mOccupied.cells[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001306 continue inner;
1307 }
Michael Jurkac28de512010-08-13 11:27:44 -07001308 }
1309 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001310 xSize = minSpanX;
1311 ySize = minSpanY;
1312
1313 // We know that the item will fit at _some_ acceptable size, now let's see
1314 // how big we can make it. We'll alternate between incrementing x and y spans
1315 // until we hit a limit.
1316 boolean incX = true;
1317 boolean hitMaxX = xSize >= spanX;
1318 boolean hitMaxY = ySize >= spanY;
1319 while (!(hitMaxX && hitMaxY)) {
1320 if (incX && !hitMaxX) {
1321 for (int j = 0; j < ySize; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001322 if (x + xSize > countX -1 || mOccupied.cells[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001323 // We can't move out horizontally
1324 hitMaxX = true;
1325 }
1326 }
1327 if (!hitMaxX) {
1328 xSize++;
1329 }
1330 } else if (!hitMaxY) {
1331 for (int i = 0; i < xSize; i++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001332 if (y + ySize > countY - 1 || mOccupied.cells[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001333 // We can't move out vertically
1334 hitMaxY = true;
1335 }
1336 }
1337 if (!hitMaxY) {
1338 ySize++;
1339 }
1340 }
1341 hitMaxX |= xSize >= spanX;
1342 hitMaxY |= ySize >= spanY;
1343 incX = !incX;
1344 }
Michael Jurkac28de512010-08-13 11:27:44 -07001345 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001346 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001347 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001348
Adam Cohend41fbf52012-02-16 23:53:59 -08001349 // We verify that the current rect is not a sub-rect of any of our previous
1350 // candidates. In this case, the current rect is disqualified in favour of the
1351 // containing rect.
Sebastian Franco4a922672022-10-27 16:42:24 -07001352 Rect currentRect = new Rect(x, y, x + xSize, y + ySize);
Adam Cohend41fbf52012-02-16 23:53:59 -08001353 boolean contained = false;
1354 for (Rect r : validRegions) {
1355 if (r.contains(currentRect)) {
1356 contained = true;
1357 break;
1358 }
1359 }
1360 validRegions.push(currentRect);
Sebastian Francob57c0b22022-06-28 13:54:35 -07001361 double distance = Math.hypot(cellXY[0] - relativeXPos, cellXY[1] - relativeYPos);
Adam Cohen482ed822012-03-02 14:15:13 -08001362
Adam Cohend41fbf52012-02-16 23:53:59 -08001363 if ((distance <= bestDistance && !contained) ||
1364 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001365 bestDistance = distance;
1366 bestXY[0] = x;
1367 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001368 if (resultSpan != null) {
1369 resultSpan[0] = xSize;
1370 resultSpan[1] = ySize;
1371 }
1372 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001373 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001374 }
1375 }
1376
Adam Cohenc0dcf592011-06-01 15:30:43 -07001377 // Return -1, -1 if no suitable location found
1378 if (bestDistance == Double.MAX_VALUE) {
1379 bestXY[0] = -1;
1380 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001381 }
Adam Cohenc0dcf592011-06-01 15:30:43 -07001382 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001383 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001384
Sebastian Francoe4c03452022-12-27 14:50:02 -06001385 public GridOccupancy getOccupied() {
1386 return mOccupied;
1387 }
1388
Adam Cohen482ed822012-03-02 14:15:13 -08001389 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001390 mTmpOccupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001391
Michael Jurkaa52570f2012-03-20 03:18:20 -07001392 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001393 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001394 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001395 if (child == dragView) continue;
Sebastian Francod4682992022-10-05 13:03:09 -05001396 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001397 CellAndSpan c = solution.map.get(child);
1398 if (c != null) {
Sebastian Franco877088e2023-01-03 15:16:22 -07001399 lp.setTmpCellX(c.cellX);
1400 lp.setTmpCellY(c.cellY);
Adam Cohen8baab352012-03-20 17:39:21 -07001401 lp.cellHSpan = c.spanX;
1402 lp.cellVSpan = c.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001403 mTmpOccupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001404 }
1405 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001406 mTmpOccupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001407 }
1408
1409 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1410 commitDragView) {
1411
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001412 GridOccupancy occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1413 occupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001414
Michael Jurkaa52570f2012-03-20 03:18:20 -07001415 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001416 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001417 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001418 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001419 CellAndSpan c = solution.map.get(child);
1420 if (c != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001421 animateChildToPosition(child, c.cellX, c.cellY, REORDER_ANIMATION_DURATION, 0,
Adam Cohen19f37922012-03-21 11:59:11 -07001422 DESTRUCTIVE_REORDER, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001423 occupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001424 }
1425 }
1426 if (commitDragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001427 occupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001428 }
1429 }
1430
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001431
1432 // This method starts or changes the reorder preview animations
1433 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
Adam Cohen65086992020-02-19 08:40:49 -08001434 View dragView, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07001435 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07001436 for (int i = 0; i < childCount; i++) {
1437 View child = mShortcutsAndWidgets.getChildAt(i);
1438 if (child == dragView) continue;
1439 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001440 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
1441 != null && !solution.intersectingViews.contains(child);
1442
Adam Cohend9162062020-03-24 16:35:35 -07001443
Sebastian Francod4682992022-10-05 13:03:09 -05001444 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohend9162062020-03-24 16:35:35 -07001445 if (c != null && !skip && (child instanceof Reorderable)) {
Sunny Goyal82dfc152023-02-24 16:50:09 -08001446 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child,
Sebastian Franco877088e2023-01-03 15:16:22 -07001447 mode, lp.getCellX(), lp.getCellY(), c.cellX, c.cellY, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07001448 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07001449 }
1450 }
1451 }
1452
Sunny Goyal849c6a22018-08-08 16:33:46 -07001453 private static final Property<ReorderPreviewAnimation, Float> ANIMATION_PROGRESS =
1454 new Property<ReorderPreviewAnimation, Float>(float.class, "animationProgress") {
1455 @Override
1456 public Float get(ReorderPreviewAnimation anim) {
1457 return anim.animationProgress;
1458 }
1459
1460 @Override
1461 public void set(ReorderPreviewAnimation anim, Float progress) {
1462 anim.setAnimationProgress(progress);
1463 }
1464 };
1465
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001466 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07001467 // in a temporary state, and hint at where the item will return to.
Sunny Goyal82dfc152023-02-24 16:50:09 -08001468 class ReorderPreviewAnimation<T extends View & Reorderable> {
1469 final T child;
Adam Cohend024f982012-05-23 18:26:45 -07001470 float finalDeltaX;
1471 float finalDeltaY;
1472 float initDeltaX;
1473 float initDeltaY;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001474 final float finalScale;
Adam Cohend024f982012-05-23 18:26:45 -07001475 float initScale;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001476 final int mode;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001477 boolean repeating = false;
1478 private static final int PREVIEW_DURATION = 300;
1479 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
1480
Jon Miranda21266912016-12-19 14:12:05 -08001481 private static final float CHILD_DIVIDEND = 4.0f;
1482
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001483 public static final int MODE_HINT = 0;
1484 public static final int MODE_PREVIEW = 1;
1485
Sunny Goyal849c6a22018-08-08 16:33:46 -07001486 float animationProgress = 0;
Sunny Goyalf0b6db72018-08-13 16:10:14 -07001487 ValueAnimator a;
Adam Cohen19f37922012-03-21 11:59:11 -07001488
Sunny Goyal82dfc152023-02-24 16:50:09 -08001489 ReorderPreviewAnimation(View childView, int mode, int cellX0, int cellY0,
Adam Cohend9162062020-03-24 16:35:35 -07001490 int cellX1, int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07001491 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
1492 final int x0 = mTmpPoint[0];
1493 final int y0 = mTmpPoint[1];
1494 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
1495 final int x1 = mTmpPoint[0];
1496 final int y1 = mTmpPoint[1];
1497 final int dX = x1 - x0;
1498 final int dY = y1 - y0;
Jon Miranda21266912016-12-19 14:12:05 -08001499
Sunny Goyal82dfc152023-02-24 16:50:09 -08001500 this.child = (T) childView;
Jon Miranda21266912016-12-19 14:12:05 -08001501 this.mode = mode;
Adam Cohend9162062020-03-24 16:35:35 -07001502 finalDeltaX = 0;
1503 finalDeltaY = 0;
Adam Cohen65086992020-02-19 08:40:49 -08001504
Sunny Goyal82dfc152023-02-24 16:50:09 -08001505 MultiTranslateDelegate mtd = child.getTranslateDelegate();
1506 initDeltaX = mtd.getTranslationX(INDEX_REORDER_BOUNCE_OFFSET).getValue();
1507 initDeltaY = mtd.getTranslationY(INDEX_REORDER_BOUNCE_OFFSET).getValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001508 initScale = child.getReorderBounceScale();
Sunny Goyal82dfc152023-02-24 16:50:09 -08001509 finalScale = mChildScale - (CHILD_DIVIDEND / child.getWidth()) * initScale;
Adam Cohend9162062020-03-24 16:35:35 -07001510
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001511 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07001512 if (dX == dY && dX == 0) {
1513 } else {
1514 if (dY == 0) {
Adam Cohend9162062020-03-24 16:35:35 -07001515 finalDeltaX = -dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001516 } else if (dX == 0) {
Adam Cohend9162062020-03-24 16:35:35 -07001517 finalDeltaY = -dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001518 } else {
1519 double angle = Math.atan( (float) (dY) / dX);
Adam Cohend9162062020-03-24 16:35:35 -07001520 finalDeltaX = (int) (-dir * Math.signum(dX)
1521 * Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
1522 finalDeltaY = (int) (-dir * Math.signum(dY)
1523 * Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07001524 }
1525 }
Jon Miranda21266912016-12-19 14:12:05 -08001526 }
1527
Adam Cohend9162062020-03-24 16:35:35 -07001528 void setInitialAnimationValuesToBaseline() {
1529 initScale = mChildScale;
1530 initDeltaX = 0;
1531 initDeltaY = 0;
Adam Cohen19f37922012-03-21 11:59:11 -07001532 }
1533
Adam Cohend024f982012-05-23 18:26:45 -07001534 void animate() {
Adam Cohend9162062020-03-24 16:35:35 -07001535 boolean noMovement = (finalDeltaX == 0) && (finalDeltaY == 0);
Jon Miranda21266912016-12-19 14:12:05 -08001536
Adam Cohen19f37922012-03-21 11:59:11 -07001537 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001538 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohen19f37922012-03-21 11:59:11 -07001539 mShakeAnimators.remove(child);
Adam Cohend9162062020-03-24 16:35:35 -07001540
Jon Miranda21266912016-12-19 14:12:05 -08001541 if (noMovement) {
Adam Cohend9162062020-03-24 16:35:35 -07001542 // A previous animation for this item exists, and no new animation will exist.
1543 // Finish the old animation smoothly.
1544 oldAnimation.finishAnimation();
Adam Cohene7587d22012-05-24 18:50:02 -07001545 return;
Adam Cohend9162062020-03-24 16:35:35 -07001546 } else {
1547 // A previous animation for this item exists, and a new one will exist. Stop
1548 // the old animation in its tracks, and proceed with the new one.
1549 oldAnimation.cancel();
Adam Cohene7587d22012-05-24 18:50:02 -07001550 }
Adam Cohen19f37922012-03-21 11:59:11 -07001551 }
Jon Miranda21266912016-12-19 14:12:05 -08001552 if (noMovement) {
Adam Cohen19f37922012-03-21 11:59:11 -07001553 return;
1554 }
Adam Cohend9162062020-03-24 16:35:35 -07001555
Sunny Goyal849c6a22018-08-08 16:33:46 -07001556 ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS, 0, 1);
Adam Cohene7587d22012-05-24 18:50:02 -07001557 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07001558
1559 // Animations are disabled in power save mode, causing the repeated animation to jump
1560 // spastically between beginning and end states. Since this looks bad, we don't repeat
1561 // the animation in power save mode.
Sunny Goyaleaf7a952020-07-29 16:54:20 -07001562 if (areAnimatorsEnabled()) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07001563 va.setRepeatMode(ValueAnimator.REVERSE);
1564 va.setRepeatCount(ValueAnimator.INFINITE);
1565 }
1566
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001567 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07001568 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07001569 va.addListener(new AnimatorListenerAdapter() {
1570 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07001571 // We make sure to end only after a full period
Adam Cohend9162062020-03-24 16:35:35 -07001572 setInitialAnimationValuesToBaseline();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001573 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07001574 }
1575 });
Adam Cohen19f37922012-03-21 11:59:11 -07001576 mShakeAnimators.put(child, this);
1577 va.start();
1578 }
1579
Sunny Goyal849c6a22018-08-08 16:33:46 -07001580 private void setAnimationProgress(float progress) {
1581 animationProgress = progress;
1582 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : animationProgress;
1583 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
1584 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Sunny Goyal82dfc152023-02-24 16:50:09 -08001585 child.getTranslateDelegate().setTranslation(INDEX_REORDER_BOUNCE_OFFSET, x, y);
Sunny Goyal849c6a22018-08-08 16:33:46 -07001586 float s = animationProgress * finalScale + (1 - animationProgress) * initScale;
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001587 child.setReorderBounceScale(s);
Sunny Goyal849c6a22018-08-08 16:33:46 -07001588 }
1589
Adam Cohend024f982012-05-23 18:26:45 -07001590 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07001591 if (a != null) {
1592 a.cancel();
1593 }
Adam Cohen19f37922012-03-21 11:59:11 -07001594 }
Adam Cohene7587d22012-05-24 18:50:02 -07001595
Adam Cohend9162062020-03-24 16:35:35 -07001596 /**
1597 * Smoothly returns the item to its baseline position / scale
1598 */
1599 @Thunk void finishAnimation() {
Adam Cohene7587d22012-05-24 18:50:02 -07001600 if (a != null) {
1601 a.cancel();
1602 }
Brandon Keely50e6e562012-05-08 16:28:49 -07001603
Adam Cohend9162062020-03-24 16:35:35 -07001604 setInitialAnimationValuesToBaseline();
1605 ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS,
1606 animationProgress, 0);
1607 a = va;
Kateryna Ivanova71203732023-05-24 15:09:00 +00001608 a.setInterpolator(DECELERATE_1_5);
Adam Cohend9162062020-03-24 16:35:35 -07001609 a.setDuration(REORDER_ANIMATION_DURATION);
Sunny Goyal5d2fc322015-07-06 22:52:49 -07001610 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07001611 }
Adam Cohen19f37922012-03-21 11:59:11 -07001612 }
1613
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001614 private void completeAndClearReorderPreviewAnimations() {
1615 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Adam Cohend9162062020-03-24 16:35:35 -07001616 a.finishAnimation();
Adam Cohen19f37922012-03-21 11:59:11 -07001617 }
1618 mShakeAnimators.clear();
1619 }
1620
Sunny Goyal711c5962021-06-23 12:36:18 -07001621 private void commitTempPlacement(View dragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001622 mTmpOccupied.copyTo(mOccupied);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001623
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001624 int screenId = getWorkspace().getIdForScreen(this);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001625 int container = Favorites.CONTAINER_DESKTOP;
1626
Sunny Goyalc13403c2016-11-18 23:44:48 -08001627 if (mContainerType == HOTSEAT) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001628 screenId = -1;
1629 container = Favorites.CONTAINER_HOTSEAT;
1630 }
1631
Michael Jurkaa52570f2012-03-20 03:18:20 -07001632 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001633 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07001634 View child = mShortcutsAndWidgets.getChildAt(i);
Sebastian Francod4682992022-10-05 13:03:09 -05001635 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohenea889a22012-03-27 16:45:39 -07001636 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07001637 // We do a null check here because the item info can be null in the case of the
1638 // AllApps button in the hotseat.
Sunny Goyal711c5962021-06-23 12:36:18 -07001639 if (info != null && child != dragView) {
Sunny Goyal669b71f2023-01-27 14:37:07 -08001640 CellPos presenterPos = mActivity.getCellPosMapper().mapModelToPresenter(info);
1641 final boolean requiresDbUpdate = (presenterPos.cellX != lp.getTmpCellX()
1642 || presenterPos.cellY != lp.getTmpCellY() || info.spanX != lp.cellHSpan
1643 || info.spanY != lp.cellVSpan || presenterPos.screenId != screenId);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001644
Sebastian Franco877088e2023-01-03 15:16:22 -07001645 lp.setCellX(lp.getTmpCellX());
Sebastian Franco877088e2023-01-03 15:16:22 -07001646 lp.setCellY(lp.getTmpCellY());
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001647 if (requiresDbUpdate) {
Sunny Goyalab770a12018-11-14 15:17:26 -08001648 Launcher.cast(mActivity).getModelWriter().modifyItemInDatabase(info, container,
Sunny Goyal669b71f2023-01-27 14:37:07 -08001649 screenId, lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001650 }
Adam Cohen2acce882012-03-28 19:03:19 -07001651 }
Adam Cohen482ed822012-03-02 14:15:13 -08001652 }
1653 }
1654
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001655 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001656 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001657 for (int i = 0; i < childCount; i++) {
Sebastian Francod4682992022-10-05 13:03:09 -05001658 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) mShortcutsAndWidgets.getChildAt(
1659 i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08001660 lp.useTmpCoords = useTempCoords;
1661 }
1662 }
1663
Adam Cohen19f37922012-03-21 11:59:11 -07001664 // For a given cell and span, fetch the set of views intersecting the region.
Sebastian Francoe4c03452022-12-27 14:50:02 -06001665 public void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
Adam Cohen19f37922012-03-21 11:59:11 -07001666 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
1667 if (boundingRect != null) {
1668 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
1669 }
1670 intersectingViews.clear();
1671 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1672 Rect r1 = new Rect();
1673 final int count = mShortcutsAndWidgets.getChildCount();
1674 for (int i = 0; i < count; i++) {
1675 View child = mShortcutsAndWidgets.getChildAt(i);
1676 if (child == dragView) continue;
Sebastian Francod4682992022-10-05 13:03:09 -05001677 CellLayoutLayoutParams
1678 lp = (CellLayoutLayoutParams) child.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07001679 r1.set(lp.getCellX(), lp.getCellY(), lp.getCellX() + lp.cellHSpan,
1680 lp.getCellY() + lp.cellVSpan);
Adam Cohen19f37922012-03-21 11:59:11 -07001681 if (Rect.intersects(r0, r1)) {
1682 mIntersectingViews.add(child);
1683 if (boundingRect != null) {
1684 boundingRect.union(r1);
1685 }
1686 }
1687 }
1688 }
1689
Sebastian Francoe4c03452022-12-27 14:50:02 -06001690 public boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
Adam Cohen19f37922012-03-21 11:59:11 -07001691 View dragView, int[] result) {
Sebastián Francof9a6ac22022-11-15 22:56:37 +00001692 result = findNearestAreaIgnoreOccupied(pixelX, pixelY, spanX, spanY, result);
Adam Cohen19f37922012-03-21 11:59:11 -07001693 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
1694 mIntersectingViews);
1695 return !mIntersectingViews.isEmpty();
1696 }
1697
1698 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001699 completeAndClearReorderPreviewAnimations();
1700 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
1701 final int count = mShortcutsAndWidgets.getChildCount();
1702 for (int i = 0; i < count; i++) {
1703 View child = mShortcutsAndWidgets.getChildAt(i);
Sebastian Francod4682992022-10-05 13:03:09 -05001704 CellLayoutLayoutParams
1705 lp = (CellLayoutLayoutParams) child.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07001706 if (lp.getTmpCellX() != lp.getCellX() || lp.getTmpCellY() != lp.getCellY()) {
1707 lp.setTmpCellX(lp.getCellX());
1708 lp.setTmpCellY(lp.getCellY());
1709 animateChildToPosition(child, lp.getCellX(), lp.getCellY(),
1710 REORDER_ANIMATION_DURATION, 0, false, false);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001711 }
Adam Cohen19f37922012-03-21 11:59:11 -07001712 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001713 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07001714 }
Adam Cohen19f37922012-03-21 11:59:11 -07001715 }
1716
Adam Cohenbebf0422012-04-11 18:06:28 -07001717 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
1718 View dragView, int[] direction, boolean commit) {
1719 int[] pixelXY = new int[2];
1720 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
1721
1722 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001723 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Sebastian Francof153d912022-04-22 16:15:27 -05001724 spanX, spanY, direction, dragView, true, new ItemConfiguration());
Adam Cohenbebf0422012-04-11 18:06:28 -07001725
1726 setUseTempCoords(true);
1727 if (swapSolution != null && swapSolution.isSolution) {
1728 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
1729 // committing anything or animating anything as we just want to determine if a solution
1730 // exists
1731 copySolutionToTempState(swapSolution, dragView);
1732 setItemPlacementDirty(true);
1733 animateItemsToSolution(swapSolution, dragView, commit);
1734
1735 if (commit) {
Sunny Goyal711c5962021-06-23 12:36:18 -07001736 commitTempPlacement(null);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001737 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07001738 setItemPlacementDirty(false);
1739 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001740 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
Adam Cohen65086992020-02-19 08:40:49 -08001741 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07001742 }
1743 mShortcutsAndWidgets.requestLayout();
1744 }
1745 return swapSolution.isSolution;
1746 }
1747
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001748 /**
1749 * Find a vacant area that will fit the given bounds nearest the requested
1750 * cell location, and will also weigh in a suggested direction vector of the
1751 * desired location. This method computers distance based on unit grid distances,
1752 * not pixel distances.
1753 *
1754 * @param cellX The X cell nearest to which you want to search for a vacant area.
1755 * @param cellY The Y cell nearest which you want to search for a vacant area.
1756 * @param spanX Horizontal span of the object.
1757 * @param spanY Vertical span of the object.
1758 * @param direction The favored direction in which the views should move from x, y
1759 * @param occupied The array which represents which cells in the CellLayout are occupied
1760 * @param blockOccupied The array which represents which cells in the specified block (cellX,
1761 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
1762 * @param result Array in which to place the result, or null (in which case a new array will
1763 * be allocated)
1764 * @return The X, Y cell of a vacant area that can contain this object,
1765 * nearest the requested location.
1766 */
1767 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
1768 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
1769 // Keep track of best-scoring drop area
1770 final int[] bestXY = result != null ? result : new int[2];
1771 float bestDistance = Float.MAX_VALUE;
1772 int bestDirectionScore = Integer.MIN_VALUE;
Adam Cohen482ed822012-03-02 14:15:13 -08001773
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001774 final int countX = mCountX;
1775 final int countY = mCountY;
1776
1777 for (int y = 0; y < countY - (spanY - 1); y++) {
1778 inner:
1779 for (int x = 0; x < countX - (spanX - 1); x++) {
1780 // First, let's see if this thing fits anywhere
1781 for (int i = 0; i < spanX; i++) {
1782 for (int j = 0; j < spanY; j++) {
1783 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1784 continue inner;
1785 }
1786 }
1787 }
1788
1789 float distance = (float) Math.hypot(x - cellX, y - cellY);
1790 int[] curDirection = mTmpPoint;
1791 computeDirectionVector(x - cellX, y - cellY, curDirection);
1792 // The direction score is just the dot product of the two candidate direction
1793 // and that passed in.
1794 int curDirectionScore = direction[0] * curDirection[0] +
1795 direction[1] * curDirection[1];
1796 if (Float.compare(distance, bestDistance) < 0 ||
1797 (Float.compare(distance, bestDistance) == 0
1798 && curDirectionScore > bestDirectionScore)) {
1799 bestDistance = distance;
1800 bestDirectionScore = curDirectionScore;
1801 bestXY[0] = x;
1802 bestXY[1] = y;
1803 }
Adam Cohen19f37922012-03-21 11:59:11 -07001804 }
Adam Cohen19f37922012-03-21 11:59:11 -07001805 }
1806
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001807 // Return -1, -1 if no suitable location found
1808 if (bestDistance == Float.MAX_VALUE) {
1809 bestXY[0] = -1;
1810 bestXY[1] = -1;
Sebastian Franco53a15a42022-10-25 17:28:54 -07001811 }
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001812 return bestXY;
1813 }
1814
1815 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
1816 int[] direction, ItemConfiguration currentState) {
1817 CellAndSpan c = currentState.map.get(v);
1818 boolean success = false;
1819 mTmpOccupied.markCells(c, false);
1820 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
1821
1822 findNearestArea(c.cellX, c.cellY, c.spanX, c.spanY, direction,
1823 mTmpOccupied.cells, null, mTempLocation);
1824
1825 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
1826 c.cellX = mTempLocation[0];
1827 c.cellY = mTempLocation[1];
1828 success = true;
1829 }
1830 mTmpOccupied.markCells(c, true);
1831 return success;
1832 }
1833
1834 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1835 int[] direction, View dragView, ItemConfiguration currentState) {
1836
1837 ViewCluster cluster = new ViewCluster(views, currentState);
1838 Rect clusterRect = cluster.getBoundingRect();
1839 int whichEdge;
1840 int pushDistance;
1841 boolean fail = false;
1842
1843 // Determine the edge of the cluster that will be leading the push and how far
1844 // the cluster must be shifted.
1845 if (direction[0] < 0) {
1846 whichEdge = ViewCluster.LEFT;
1847 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
1848 } else if (direction[0] > 0) {
1849 whichEdge = ViewCluster.RIGHT;
1850 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1851 } else if (direction[1] < 0) {
1852 whichEdge = ViewCluster.TOP;
1853 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1854 } else {
1855 whichEdge = ViewCluster.BOTTOM;
1856 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
1857 }
1858
1859 // Break early for invalid push distance.
1860 if (pushDistance <= 0) {
1861 return false;
1862 }
1863
1864 // Mark the occupied state as false for the group of views we want to move.
1865 for (View v: views) {
1866 CellAndSpan c = currentState.map.get(v);
1867 mTmpOccupied.markCells(c, false);
1868 }
1869
1870 // We save the current configuration -- if we fail to find a solution we will revert
1871 // to the initial state. The process of finding a solution modifies the configuration
1872 // in place, hence the need for revert in the failure case.
1873 currentState.save();
1874
1875 // The pushing algorithm is simplified by considering the views in the order in which
1876 // they would be pushed by the cluster. For example, if the cluster is leading with its
1877 // left edge, we consider sort the views by their right edge, from right to left.
1878 cluster.sortConfigurationForEdgePush(whichEdge);
1879
1880 while (pushDistance > 0 && !fail) {
1881 for (View v: currentState.sortedViews) {
1882 // For each view that isn't in the cluster, we see if the leading edge of the
1883 // cluster is contacting the edge of that view. If so, we add that view to the
1884 // cluster.
1885 if (!cluster.views.contains(v) && v != dragView) {
1886 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1887 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) v.getLayoutParams();
1888 if (!lp.canReorder) {
1889 // The push solution includes the all apps button, this is not viable.
1890 fail = true;
1891 break;
1892 }
1893 cluster.addView(v);
1894 CellAndSpan c = currentState.map.get(v);
1895
1896 // Adding view to cluster, mark it as not occupied.
1897 mTmpOccupied.markCells(c, false);
1898 }
1899 }
1900 }
1901 pushDistance--;
1902
1903 // The cluster has been completed, now we move the whole thing over in the appropriate
1904 // direction.
1905 cluster.shift(whichEdge, 1);
1906 }
1907
1908 boolean foundSolution = false;
1909 clusterRect = cluster.getBoundingRect();
1910
1911 // Due to the nature of the algorithm, the only check required to verify a valid solution
1912 // is to ensure that completed shifted cluster lies completely within the cell layout.
1913 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1914 clusterRect.bottom <= mCountY) {
1915 foundSolution = true;
1916 } else {
1917 currentState.restore();
1918 }
1919
1920 // In either case, we set the occupied array as marked for the location of the views
1921 for (View v: cluster.views) {
1922 CellAndSpan c = currentState.map.get(v);
1923 mTmpOccupied.markCells(c, true);
1924 }
1925
1926 return foundSolution;
1927 }
1928
1929 /**
1930 * This helper class defines a cluster of views. It helps with defining complex edges
1931 * of the cluster and determining how those edges interact with other views. The edges
1932 * essentially define a fine-grained boundary around the cluster of views -- like a more
1933 * precise version of a bounding box.
1934 */
1935 private class ViewCluster {
1936 final static int LEFT = 1 << 0;
1937 final static int TOP = 1 << 1;
1938 final static int RIGHT = 1 << 2;
1939 final static int BOTTOM = 1 << 3;
1940
1941 final ArrayList<View> views;
1942 final ItemConfiguration config;
1943 final Rect boundingRect = new Rect();
1944
1945 final int[] leftEdge = new int[mCountY];
1946 final int[] rightEdge = new int[mCountY];
1947 final int[] topEdge = new int[mCountX];
1948 final int[] bottomEdge = new int[mCountX];
1949 int dirtyEdges;
1950 boolean boundingRectDirty;
1951
1952 @SuppressWarnings("unchecked")
1953 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1954 this.views = (ArrayList<View>) views.clone();
1955 this.config = config;
1956 resetEdges();
1957 }
1958
1959 void resetEdges() {
1960 for (int i = 0; i < mCountX; i++) {
1961 topEdge[i] = -1;
1962 bottomEdge[i] = -1;
1963 }
1964 for (int i = 0; i < mCountY; i++) {
1965 leftEdge[i] = -1;
1966 rightEdge[i] = -1;
1967 }
1968 dirtyEdges = LEFT | TOP | RIGHT | BOTTOM;
1969 boundingRectDirty = true;
1970 }
1971
1972 void computeEdge(int which) {
1973 int count = views.size();
1974 for (int i = 0; i < count; i++) {
1975 CellAndSpan cs = config.map.get(views.get(i));
1976 switch (which) {
1977 case LEFT:
1978 int left = cs.cellX;
1979 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
1980 if (left < leftEdge[j] || leftEdge[j] < 0) {
1981 leftEdge[j] = left;
1982 }
1983 }
1984 break;
1985 case RIGHT:
1986 int right = cs.cellX + cs.spanX;
1987 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
1988 if (right > rightEdge[j]) {
1989 rightEdge[j] = right;
1990 }
1991 }
1992 break;
1993 case TOP:
1994 int top = cs.cellY;
1995 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
1996 if (top < topEdge[j] || topEdge[j] < 0) {
1997 topEdge[j] = top;
1998 }
1999 }
2000 break;
2001 case BOTTOM:
2002 int bottom = cs.cellY + cs.spanY;
2003 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
2004 if (bottom > bottomEdge[j]) {
2005 bottomEdge[j] = bottom;
2006 }
2007 }
2008 break;
2009 }
2010 }
2011 }
2012
2013 boolean isViewTouchingEdge(View v, int whichEdge) {
2014 CellAndSpan cs = config.map.get(v);
2015
2016 if ((dirtyEdges & whichEdge) == whichEdge) {
2017 computeEdge(whichEdge);
2018 dirtyEdges &= ~whichEdge;
2019 }
2020
2021 switch (whichEdge) {
2022 case LEFT:
2023 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
2024 if (leftEdge[i] == cs.cellX + cs.spanX) {
2025 return true;
2026 }
2027 }
2028 break;
2029 case RIGHT:
2030 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
2031 if (rightEdge[i] == cs.cellX) {
2032 return true;
2033 }
2034 }
2035 break;
2036 case TOP:
2037 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
2038 if (topEdge[i] == cs.cellY + cs.spanY) {
2039 return true;
2040 }
2041 }
2042 break;
2043 case BOTTOM:
2044 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
2045 if (bottomEdge[i] == cs.cellY) {
2046 return true;
2047 }
2048 }
2049 break;
2050 }
2051 return false;
2052 }
2053
2054 void shift(int whichEdge, int delta) {
2055 for (View v: views) {
2056 CellAndSpan c = config.map.get(v);
2057 switch (whichEdge) {
2058 case LEFT:
2059 c.cellX -= delta;
2060 break;
2061 case RIGHT:
2062 c.cellX += delta;
2063 break;
2064 case TOP:
2065 c.cellY -= delta;
2066 break;
2067 case BOTTOM:
2068 default:
2069 c.cellY += delta;
2070 break;
2071 }
2072 }
2073 resetEdges();
2074 }
2075
2076 public void addView(View v) {
2077 views.add(v);
2078 resetEdges();
2079 }
2080
2081 public Rect getBoundingRect() {
2082 if (boundingRectDirty) {
2083 config.getBoundingRectForViews(views, boundingRect);
2084 }
2085 return boundingRect;
2086 }
2087
2088 final PositionComparator comparator = new PositionComparator();
2089 class PositionComparator implements Comparator<View> {
2090 int whichEdge = 0;
2091 public int compare(View left, View right) {
2092 CellAndSpan l = config.map.get(left);
2093 CellAndSpan r = config.map.get(right);
2094 switch (whichEdge) {
2095 case LEFT:
2096 return (r.cellX + r.spanX) - (l.cellX + l.spanX);
2097 case RIGHT:
2098 return l.cellX - r.cellX;
2099 case TOP:
2100 return (r.cellY + r.spanY) - (l.cellY + l.spanY);
2101 case BOTTOM:
2102 default:
2103 return l.cellY - r.cellY;
2104 }
2105 }
2106 }
2107
2108 public void sortConfigurationForEdgePush(int edge) {
2109 comparator.whichEdge = edge;
2110 Collections.sort(config.sortedViews, comparator);
2111 }
2112 }
2113
2114 // This method tries to find a reordering solution which satisfies the push mechanic by trying
2115 // to push items in each of the cardinal directions, in an order based on the direction vector
2116 // passed.
2117 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
2118 int[] direction, View ignoreView, ItemConfiguration solution) {
2119 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
2120 // If the direction vector has two non-zero components, we try pushing
2121 // separately in each of the components.
2122 int temp = direction[1];
2123 direction[1] = 0;
2124
2125 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2126 ignoreView, solution)) {
2127 return true;
2128 }
2129 direction[1] = temp;
2130 temp = direction[0];
2131 direction[0] = 0;
2132
2133 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2134 ignoreView, solution)) {
2135 return true;
2136 }
2137 // Revert the direction
2138 direction[0] = temp;
2139
2140 // Now we try pushing in each component of the opposite direction
2141 direction[0] *= -1;
2142 direction[1] *= -1;
2143 temp = direction[1];
2144 direction[1] = 0;
2145 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2146 ignoreView, solution)) {
2147 return true;
2148 }
2149
2150 direction[1] = temp;
2151 temp = direction[0];
2152 direction[0] = 0;
2153 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2154 ignoreView, solution)) {
2155 return true;
2156 }
2157 // revert the direction
2158 direction[0] = temp;
2159 direction[0] *= -1;
2160 direction[1] *= -1;
2161
2162 } else {
2163 // If the direction vector has a single non-zero component, we push first in the
2164 // direction of the vector
2165 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2166 ignoreView, solution)) {
2167 return true;
2168 }
2169 // Then we try the opposite direction
2170 direction[0] *= -1;
2171 direction[1] *= -1;
2172 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2173 ignoreView, solution)) {
2174 return true;
2175 }
2176 // Switch the direction back
2177 direction[0] *= -1;
2178 direction[1] *= -1;
2179
2180 // If we have failed to find a push solution with the above, then we try
2181 // to find a solution by pushing along the perpendicular axis.
2182
2183 // Swap the components
2184 int temp = direction[1];
2185 direction[1] = direction[0];
2186 direction[0] = temp;
2187 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2188 ignoreView, solution)) {
2189 return true;
2190 }
2191
2192 // Then we try the opposite direction
2193 direction[0] *= -1;
2194 direction[1] *= -1;
2195 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2196 ignoreView, solution)) {
2197 return true;
2198 }
2199 // Switch the direction back
2200 direction[0] *= -1;
2201 direction[1] *= -1;
2202
2203 // Swap the components back
2204 temp = direction[1];
2205 direction[1] = direction[0];
2206 direction[0] = temp;
2207 }
2208 return false;
2209 }
2210
2211 /*
2212 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
2213 * the provided point and the provided cell
2214 */
2215 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
2216 double angle = Math.atan(deltaY / deltaX);
2217
2218 result[0] = 0;
2219 result[1] = 0;
2220 if (Math.abs(Math.cos(angle)) > 0.5f) {
2221 result[0] = (int) Math.signum(deltaX);
2222 }
2223 if (Math.abs(Math.sin(angle)) > 0.5f) {
2224 result[1] = (int) Math.signum(deltaY);
2225 }
2226 }
2227
2228 /* This seems like it should be obvious and straight-forward, but when the direction vector
2229 needs to match with the notion of the dragView pushing other views, we have to employ
2230 a slightly more subtle notion of the direction vector. The question is what two points is
2231 the vector between? The center of the dragView and its desired destination? Not quite, as
2232 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2233 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2234 or right, which helps make pushing feel right.
2235 */
Sebastian Francoe4c03452022-12-27 14:50:02 -06002236 public void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002237 int spanY, View dragView, int[] resultDirection) {
2238
2239 //TODO(adamcohen) b/151776141 use the items visual center for the direction vector
2240 int[] targetDestination = new int[2];
2241
Sebastián Francof9a6ac22022-11-15 22:56:37 +00002242 findNearestAreaIgnoreOccupied(dragViewCenterX, dragViewCenterY, spanX, spanY,
2243 targetDestination);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002244 Rect dragRect = new Rect();
2245 cellToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2246 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2247
2248 Rect dropRegionRect = new Rect();
2249 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2250 dragView, dropRegionRect, mIntersectingViews);
2251
2252 int dropRegionSpanX = dropRegionRect.width();
2253 int dropRegionSpanY = dropRegionRect.height();
2254
2255 cellToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2256 dropRegionRect.height(), dropRegionRect);
2257
2258 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2259 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2260
2261 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2262 deltaX = 0;
2263 }
2264 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2265 deltaY = 0;
2266 }
2267
2268 if (deltaX == 0 && deltaY == 0) {
2269 // No idea what to do, give a random direction.
2270 resultDirection[0] = 1;
2271 resultDirection[1] = 0;
2272 } else {
2273 computeDirectionVector(deltaX, deltaY, resultDirection);
2274 }
2275 }
2276
2277 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
2278 int[] direction, View dragView, ItemConfiguration currentState) {
2279 if (views.size() == 0) return true;
2280
2281 boolean success = false;
2282 Rect boundingRect = new Rect();
2283 // We construct a rect which represents the entire group of views passed in
2284 currentState.getBoundingRectForViews(views, boundingRect);
2285
2286 // Mark the occupied state as false for the group of views we want to move.
2287 for (View v: views) {
2288 CellAndSpan c = currentState.map.get(v);
2289 mTmpOccupied.markCells(c, false);
2290 }
2291
2292 GridOccupancy blockOccupied = new GridOccupancy(boundingRect.width(), boundingRect.height());
2293 int top = boundingRect.top;
2294 int left = boundingRect.left;
2295 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
2296 // for interlocking.
2297 for (View v: views) {
2298 CellAndSpan c = currentState.map.get(v);
2299 blockOccupied.markCells(c.cellX - left, c.cellY - top, c.spanX, c.spanY, true);
2300 }
2301
2302 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
2303
2304 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
2305 boundingRect.height(), direction,
2306 mTmpOccupied.cells, blockOccupied.cells, mTempLocation);
2307
2308 // If we successfully found a location by pushing the block of views, we commit it
2309 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
2310 int deltaX = mTempLocation[0] - boundingRect.left;
2311 int deltaY = mTempLocation[1] - boundingRect.top;
2312 for (View v: views) {
2313 CellAndSpan c = currentState.map.get(v);
2314 c.cellX += deltaX;
2315 c.cellY += deltaY;
2316 }
2317 success = true;
2318 }
2319
2320 // In either case, we set the occupied array as marked for the location of the views
2321 for (View v: views) {
2322 CellAndSpan c = currentState.map.get(v);
2323 mTmpOccupied.markCells(c, true);
2324 }
2325 return success;
2326 }
2327
Sebastian Francoe4c03452022-12-27 14:50:02 -06002328 public boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002329 View ignoreView, ItemConfiguration solution) {
2330 // Return early if get invalid cell positions
2331 if (cellX < 0 || cellY < 0) return false;
2332
2333 mIntersectingViews.clear();
2334 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2335
2336 // Mark the desired location of the view currently being dragged.
2337 if (ignoreView != null) {
2338 CellAndSpan c = solution.map.get(ignoreView);
2339 if (c != null) {
2340 c.cellX = cellX;
2341 c.cellY = cellY;
2342 }
2343 }
2344 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2345 Rect r1 = new Rect();
Sebastian Franco45b39b52023-01-10 10:47:46 -06002346 // The views need to be sorted so that the results are deterministic on the views positions
2347 // and not by the views hash which is "random".
2348 // The views are sorted twice, once for the X position and a second time for the Y position
2349 // to ensure same order everytime.
2350 Comparator comparator = Comparator.comparing(view ->
2351 ((CellLayoutLayoutParams) ((View) view).getLayoutParams()).getCellX())
2352 .thenComparing(view ->
2353 ((CellLayoutLayoutParams) ((View) view).getLayoutParams()).getCellY());
2354 List<View> views = solution.map.keySet().stream().sorted(comparator).toList();
2355 for (View child : views) {
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002356 if (child == ignoreView) continue;
2357 CellAndSpan c = solution.map.get(child);
2358 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
2359 r1.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2360 if (Rect.intersects(r0, r1)) {
2361 if (!lp.canReorder) {
2362 return false;
2363 }
2364 mIntersectingViews.add(child);
2365 }
2366 }
2367
2368 solution.intersectingViews = new ArrayList<>(mIntersectingViews);
2369
2370 // First we try to find a solution which respects the push mechanic. That is,
2371 // we try to find a solution such that no displaced item travels through another item
2372 // without also displacing that item.
2373 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
2374 solution)) {
2375 return true;
2376 }
2377
2378 // Next we try moving the views as a block, but without requiring the push mechanic.
2379 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
2380 solution)) {
2381 return true;
2382 }
2383
2384 // Ok, they couldn't move as a block, let's move them individually
2385 for (View v : mIntersectingViews) {
2386 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
2387 return false;
2388 }
2389 }
2390 return true;
2391 }
2392
Sebastian Francoe4c03452022-12-27 14:50:02 -06002393 public ReorderAlgorithm createReorderAlgorithm() {
2394 return new ReorderAlgorithm(this);
2395 }
2396
Sebastian Franco09589322022-11-02 15:25:58 -07002397 protected ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX,
2398 int minSpanY, int spanX, int spanY, int[] direction, View dragView, boolean decX,
2399 ItemConfiguration solution) {
Sebastian Francoe4c03452022-12-27 14:50:02 -06002400 return createReorderAlgorithm().findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
2401 spanX, spanY, direction, dragView, decX, solution);
Sebastian Franco09589322022-11-02 15:25:58 -07002402 }
2403
Sebastian Francoe4c03452022-12-27 14:50:02 -06002404 public void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002405 int childCount = mShortcutsAndWidgets.getChildCount();
2406 for (int i = 0; i < childCount; i++) {
2407 View child = mShortcutsAndWidgets.getChildAt(i);
2408 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
2409 CellAndSpan c;
2410 if (temp) {
Sebastian Franco877088e2023-01-03 15:16:22 -07002411 c = new CellAndSpan(lp.getTmpCellX(), lp.getTmpCellY(), lp.cellHSpan, lp.cellVSpan);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002412 } else {
Sebastian Franco877088e2023-01-03 15:16:22 -07002413 c = new CellAndSpan(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002414 }
2415 solution.add(child, c);
2416 }
Sebastian Franco53a15a42022-10-25 17:28:54 -07002417 }
2418
2419 /**
Sebastian Franco53a15a42022-10-25 17:28:54 -07002420 * When the user drags an Item in the workspace sometimes we need to move the items already in
2421 * the workspace to make space for the new item, this function return a solution for that
2422 * reorder.
2423 *
2424 * @param pixelX X coordinate in the screen of the dragView in pixels
2425 * @param pixelY Y coordinate in the screen of the dragView in pixels
2426 * @param minSpanX minimum horizontal span the item can be shrunk to
2427 * @param minSpanY minimum vertical span the item can be shrunk to
2428 * @param spanX occupied horizontal span
2429 * @param spanY occupied vertical span
2430 * @param dragView the view of the item being draged
2431 * @return returns a solution for the given parameters, the solution contains all the icons and
2432 * the locations they should be in the given solution.
2433 */
2434 public ItemConfiguration calculateReorder(int pixelX, int pixelY, int minSpanX, int minSpanY,
2435 int spanX, int spanY, View dragView) {
Sebastian Francoe4c03452022-12-27 14:50:02 -06002436 return createReorderAlgorithm().calculateReorder(pixelX, pixelY, minSpanX, minSpanY,
2437 spanX, spanY, dragView);
Sebastian Franco53a15a42022-10-25 17:28:54 -07002438 }
Adam Cohen482ed822012-03-02 14:15:13 -08002439
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002440 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2441 View dragView, int[] result, int[] resultSpan, int mode) {
2442 if (resultSpan == null) {
2443 resultSpan = new int[]{-1, -1};
2444 }
2445 if (result == null) {
2446 result = new int[]{-1, -1};
2447 }
Sebastian Franco5d990ee2022-11-01 16:08:24 -07002448
2449 ItemConfiguration finalSolution = null;
2450 // We want the solution to match the animation of the preview and to match the drop so we
2451 // only recalculate in mode MODE_SHOW_REORDER_HINT because that the first one to run in the
2452 // reorder cycle.
2453 if (mode == MODE_SHOW_REORDER_HINT || mPreviousSolution == null) {
2454 finalSolution = calculateReorder(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY,
2455 dragView);
2456 mPreviousSolution = finalSolution;
2457 } else {
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002458 finalSolution = mPreviousSolution;
2459 // We reset this vector after drop
2460 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2461 mPreviousSolution = null;
2462 }
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002463 }
2464
2465 if (finalSolution == null || !finalSolution.isSolution) {
2466 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2467 } else {
2468 result[0] = finalSolution.cellX;
2469 result[1] = finalSolution.cellY;
2470 resultSpan[0] = finalSolution.spanX;
2471 resultSpan[1] = finalSolution.spanY;
Sebastian Franco9c743272022-11-15 15:03:25 -08002472 performReorder(finalSolution, dragView, mode);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002473 }
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002474 return result;
2475 }
2476
Sebastian Franco53a15a42022-10-25 17:28:54 -07002477 /**
2478 * Animates and submits in the DB the given ItemConfiguration depending of the mode.
2479 *
2480 * @param solution represents widgets on the screen which the Workspace will animate to and
2481 * would be submitted to the database.
2482 * @param dragView view which is being dragged over the workspace that trigger the reorder
2483 * @param mode depending on the mode different animations would be played and depending on the
2484 * mode the solution would be submitted or not the database.
2485 * The possible modes are {@link MODE_SHOW_REORDER_HINT}, {@link MODE_DRAG_OVER},
2486 * {@link MODE_ON_DROP}, {@link MODE_ON_DROP_EXTERNAL}, {@link MODE_ACCEPT_DROP}
2487 * defined in {@link CellLayout}.
2488 */
Sebastian Francoe4c03452022-12-27 14:50:02 -06002489 public void performReorder(ItemConfiguration solution, View dragView, int mode) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002490 if (mode == MODE_SHOW_REORDER_HINT) {
Sebastian Franco53a15a42022-10-25 17:28:54 -07002491 beginOrAdjustReorderPreviewAnimations(solution, dragView,
2492 ReorderPreviewAnimation.MODE_HINT);
2493 return;
2494 }
2495 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2496 // committing anything or animating anything as we just want to determine if a solution
2497 // exists
2498 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2499 if (!DESTRUCTIVE_REORDER) {
2500 setUseTempCoords(true);
2501 }
2502
2503 if (!DESTRUCTIVE_REORDER) {
2504 copySolutionToTempState(solution, dragView);
2505 }
2506 setItemPlacementDirty(true);
2507 animateItemsToSolution(solution, dragView, mode == MODE_ON_DROP);
2508
2509 if (!DESTRUCTIVE_REORDER
2510 && (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
2511 // Since the temp solution didn't update dragView, don't commit it either
2512 commitTempPlacement(dragView);
2513 completeAndClearReorderPreviewAnimations();
2514 setItemPlacementDirty(false);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002515 } else {
Sebastian Franco53a15a42022-10-25 17:28:54 -07002516 beginOrAdjustReorderPreviewAnimations(solution, dragView,
2517 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002518 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002519 }
2520
Sebastian Franco53a15a42022-10-25 17:28:54 -07002521 if (mode == MODE_ON_DROP && !DESTRUCTIVE_REORDER) {
Adam Cohen482ed822012-03-02 14:15:13 -08002522 setUseTempCoords(false);
2523 }
Adam Cohen482ed822012-03-02 14:15:13 -08002524
Michael Jurkaa52570f2012-03-20 03:18:20 -07002525 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002526 }
2527
Adam Cohen19f37922012-03-21 11:59:11 -07002528 void setItemPlacementDirty(boolean dirty) {
2529 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002530 }
Adam Cohen19f37922012-03-21 11:59:11 -07002531 boolean isItemPlacementDirty() {
2532 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002533 }
2534
Sebastian Francoe4c03452022-12-27 14:50:02 -06002535 /**
2536 * Represents the solution to a reorder of items in the Workspace.
2537 */
2538 public static class ItemConfiguration extends CellAndSpan {
2539 public final ArrayMap<View, CellAndSpan> map = new ArrayMap<>();
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002540 private final ArrayMap<View, CellAndSpan> savedMap = new ArrayMap<>();
Sebastian Francoe4c03452022-12-27 14:50:02 -06002541 public final ArrayList<View> sortedViews = new ArrayList<>();
2542 public ArrayList<View> intersectingViews;
2543 public boolean isSolution = false;
Adam Cohen482ed822012-03-02 14:15:13 -08002544
Sebastian Francoe4c03452022-12-27 14:50:02 -06002545 public void save() {
Adam Cohenf3900c22012-11-16 18:28:11 -08002546 // Copy current state into savedMap
2547 for (View v: map.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002548 savedMap.get(v).copyFrom(map.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002549 }
2550 }
2551
Sebastian Francoe4c03452022-12-27 14:50:02 -06002552 public void restore() {
Adam Cohenf3900c22012-11-16 18:28:11 -08002553 // Restore current state from savedMap
2554 for (View v: savedMap.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002555 map.get(v).copyFrom(savedMap.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002556 }
2557 }
2558
Sebastian Francoe4c03452022-12-27 14:50:02 -06002559 public void add(View v, CellAndSpan cs) {
Adam Cohenf3900c22012-11-16 18:28:11 -08002560 map.put(v, cs);
2561 savedMap.put(v, new CellAndSpan());
2562 sortedViews.add(v);
2563 }
2564
Sebastian Francoe4c03452022-12-27 14:50:02 -06002565 public int area() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002566 return spanX * spanY;
Adam Cohenf3900c22012-11-16 18:28:11 -08002567 }
2568
Sebastian Francoe4c03452022-12-27 14:50:02 -06002569 public void getBoundingRectForViews(ArrayList<View> views, Rect outRect) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002570 boolean first = true;
2571 for (View v: views) {
2572 CellAndSpan c = map.get(v);
2573 if (first) {
2574 outRect.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2575 first = false;
2576 } else {
2577 outRect.union(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2578 }
2579 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002580 }
Adam Cohen482ed822012-03-02 14:15:13 -08002581 }
2582
Adam Cohendf035382011-04-11 17:22:04 -07002583 /**
Adam Cohendf035382011-04-11 17:22:04 -07002584 * Find a starting cell position that will fit the given bounds nearest the requested
2585 * cell location. Uses Euclidean distance to score multiple vacant areas.
2586 *
2587 * @param pixelX The X location at which you want to search for a vacant area.
2588 * @param pixelY The Y location at which you want to search for a vacant area.
2589 * @param spanX Horizontal span of the object.
2590 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07002591 * @param result Previously returned value to possibly recycle.
2592 * @return The X, Y cell of a vacant area that can contain this object,
2593 * nearest the requested location.
2594 */
Sebastián Francof9a6ac22022-11-15 22:56:37 +00002595 public int[] findNearestAreaIgnoreOccupied(int pixelX, int pixelY, int spanX, int spanY,
2596 int[] result) {
Sebastian Francob57c0b22022-06-28 13:54:35 -07002597 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, true, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002598 }
2599
Michael Jurka0280c3b2010-09-17 15:00:07 -07002600 boolean existsEmptyCell() {
2601 return findCellForSpan(null, 1, 1);
2602 }
2603
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002604 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002605 * Finds the upper-left coordinate of the first rectangle in the grid that can
2606 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2607 * then this method will only return coordinates for rectangles that contain the cell
2608 * (intersectX, intersectY)
2609 *
2610 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2611 * can be found.
2612 * @param spanX The horizontal span of the cell we want to find.
2613 * @param spanY The vertical span of the cell we want to find.
2614 *
2615 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002616 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002617 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002618 if (cellXY == null) {
2619 cellXY = new int[2];
Michael Jurka0280c3b2010-09-17 15:00:07 -07002620 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002621 return mOccupied.findVacantCell(cellXY, spanX, spanY);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002622 }
2623
2624 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002625 * A drag event has begun over this layout.
2626 * It may have begun over this layout (in which case onDragChild is called first),
2627 * or it may have begun on another layout.
2628 */
2629 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002630 mDragging = true;
Sebastian Franco5aa71ce2022-12-14 12:13:19 -06002631 mPreviousSolution = null;
Winson Chungc07918d2011-07-01 15:35:26 -07002632 }
2633
2634 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002635 * Called when drag has left this CellLayout or has been completed (successfully or not)
2636 */
2637 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002638 // This can actually be called when we aren't in a drag, e.g. when adding a new
2639 // item to this layout via the customize drawer.
2640 // Guard against that case.
2641 if (mDragging) {
2642 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002643 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002644
2645 // Invalidate the drag data
Sebastian Franco5aa71ce2022-12-14 12:13:19 -06002646 mPreviousSolution = null;
Adam Cohend41fbf52012-02-16 23:53:59 -08002647 mDragCell[0] = mDragCell[1] = -1;
Adam Cohenf7ca3b42021-02-22 11:03:58 -08002648 mDragCellSpan[0] = mDragCellSpan[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002649 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2650 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002651 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002652 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002653 }
2654
2655 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002656 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002657 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002658 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002659 *
2660 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002661 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002662 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002663 if (child != null) {
Sebastian Francod4682992022-10-05 13:03:09 -05002664 CellLayoutLayoutParams
2665 lp = (CellLayoutLayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002666 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002667 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002668 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002669 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002670 }
2671
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002672 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002673 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002674 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002675 * @param cellX X coordinate of upper left corner expressed as a cell position
2676 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002677 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002678 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002679 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002680 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002681 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002682 final int cellWidth = mCellWidth;
2683 final int cellHeight = mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -07002684
Pierre Barbier de Reuille1b8bbb62021-05-19 22:45:16 +01002685 // We observe a shift of 1 pixel on the x coordinate compared to the actual cell coordinates
2686 final int hStartPadding = getPaddingLeft()
2687 + (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Winson Chung4b825dcd2011-06-19 12:41:22 -07002688 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002689
Thales Lima78d00ad2021-09-30 11:29:06 +01002690 int x = hStartPadding + (cellX * mBorderSpace.x) + (cellX * cellWidth);
2691 int y = vStartPadding + (cellY * mBorderSpace.y) + (cellY * cellHeight);
Jon Miranda228877d2021-02-09 11:05:00 -05002692
Thales Lima78d00ad2021-09-30 11:29:06 +01002693 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * mBorderSpace.x);
2694 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * mBorderSpace.y);
Winson Chungaafa03c2010-06-11 17:34:16 -07002695
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002696 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002697 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002698
Adam Cohend4844c32011-02-18 19:25:06 -08002699 public void markCellsAsOccupiedForView(View view) {
Sebastian Francof153d912022-04-22 16:15:27 -05002700 if (view instanceof LauncherAppWidgetHostView
2701 && view.getTag() instanceof LauncherAppWidgetInfo) {
2702 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
Sunny Goyal669b71f2023-01-27 14:37:07 -08002703 CellPos pos = mActivity.getCellPosMapper().mapModelToPresenter(info);
2704 mOccupied.markCells(pos.cellX, pos.cellY, info.spanX, info.spanY, true);
Sebastian Francof153d912022-04-22 16:15:27 -05002705 return;
2706 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002707 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Sebastian Francod4682992022-10-05 13:03:09 -05002708 CellLayoutLayoutParams
2709 lp = (CellLayoutLayoutParams) view.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07002710 mOccupied.markCells(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002711 }
2712
Adam Cohend4844c32011-02-18 19:25:06 -08002713 public void markCellsAsUnoccupiedForView(View view) {
Sebastian Francof153d912022-04-22 16:15:27 -05002714 if (view instanceof LauncherAppWidgetHostView
2715 && view.getTag() instanceof LauncherAppWidgetInfo) {
2716 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
Sunny Goyal669b71f2023-01-27 14:37:07 -08002717 CellPos pos = mActivity.getCellPosMapper().mapModelToPresenter(info);
2718 mOccupied.markCells(pos.cellX, pos.cellY, info.spanX, info.spanY, false);
Sebastian Francof153d912022-04-22 16:15:27 -05002719 return;
2720 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002721 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Sebastian Francod4682992022-10-05 13:03:09 -05002722 CellLayoutLayoutParams
2723 lp = (CellLayoutLayoutParams) view.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07002724 mOccupied.markCells(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002725 }
2726
Adam Cohen2801caf2011-05-13 20:57:39 -07002727 public int getDesiredWidth() {
Jon Miranda228877d2021-02-09 11:05:00 -05002728 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth)
Thales Lima78d00ad2021-09-30 11:29:06 +01002729 + ((mCountX - 1) * mBorderSpace.x);
Adam Cohen2801caf2011-05-13 20:57:39 -07002730 }
2731
2732 public int getDesiredHeight() {
Jon Miranda228877d2021-02-09 11:05:00 -05002733 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight)
Thales Lima78d00ad2021-09-30 11:29:06 +01002734 + ((mCountY - 1) * mBorderSpace.y);
Adam Cohen2801caf2011-05-13 20:57:39 -07002735 }
2736
Michael Jurka66d72172011-04-12 16:29:25 -07002737 public boolean isOccupied(int x, int y) {
2738 if (x < mCountX && y < mCountY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002739 return mOccupied.cells[x][y];
Michael Jurka66d72172011-04-12 16:29:25 -07002740 } else {
2741 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2742 }
2743 }
2744
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002745 @Override
2746 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
Sebastian Francod4682992022-10-05 13:03:09 -05002747 return new CellLayoutLayoutParams(getContext(), attrs);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002748 }
2749
2750 @Override
2751 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
Sebastian Francod4682992022-10-05 13:03:09 -05002752 return p instanceof CellLayoutLayoutParams;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002753 }
2754
2755 @Override
2756 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
Sebastian Francod4682992022-10-05 13:03:09 -05002757 return new CellLayoutLayoutParams(p);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002758 }
2759
Michael Jurka0280c3b2010-09-17 15:00:07 -07002760 // This class stores info for two purposes:
2761 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2762 // its spanX, spanY, and the screen it is on
2763 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2764 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2765 // the CellLayout that was long clicked
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002766 public static final class CellInfo extends CellAndSpan {
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002767 public final View cell;
Sunny Goyalefb7e842018-10-04 15:11:00 -07002768 final int screenId;
2769 final int container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002770
Sunny Goyal669b71f2023-01-27 14:37:07 -08002771 public CellInfo(View v, ItemInfo info, CellPos cellPos) {
2772 cellX = cellPos.cellX;
2773 cellY = cellPos.cellY;
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002774 spanX = info.spanX;
2775 spanY = info.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002776 cell = v;
Sunny Goyal669b71f2023-01-27 14:37:07 -08002777 screenId = cellPos.screenId;
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002778 container = info.container;
2779 }
2780
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002781 @Override
2782 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002783 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2784 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002785 }
2786 }
Michael Jurkad771c962011-08-09 15:00:48 -07002787
Tony Wickham86930612015-09-09 13:50:40 -07002788 /**
Samuel Fufa1e2d0042019-11-18 17:12:46 -08002789 * A Delegated cell Drawing for drawing on CellLayout
2790 */
2791 public abstract static class DelegatedCellDrawing {
2792 public int mDelegateCellX;
2793 public int mDelegateCellY;
2794
2795 /**
2796 * Draw under CellLayout
2797 */
2798 public abstract void drawUnderItem(Canvas canvas);
2799
2800 /**
2801 * Draw over CellLayout
2802 */
2803 public abstract void drawOverItem(Canvas canvas);
2804 }
2805
2806 /**
Tony Wickham86930612015-09-09 13:50:40 -07002807 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2808 * if necessary).
2809 */
2810 public boolean hasReorderSolution(ItemInfo itemInfo) {
2811 int[] cellPoint = new int[2];
2812 // Check for a solution starting at every cell.
2813 for (int cellX = 0; cellX < getCountX(); cellX++) {
2814 for (int cellY = 0; cellY < getCountY(); cellY++) {
2815 cellToPoint(cellX, cellY, cellPoint);
2816 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2817 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2818 true, new ItemConfiguration()).isSolution) {
2819 return true;
2820 }
2821 }
2822 }
2823 return false;
2824 }
2825
Samuel Fufaa4211432020-02-25 18:47:54 -08002826 /**
2827 * Finds solution to accept hotseat migration to cell layout. commits solution if commitConfig
2828 */
2829 public boolean makeSpaceForHotseatMigration(boolean commitConfig) {
Samuel Fufaa4211432020-02-25 18:47:54 -08002830 int[] cellPoint = new int[2];
2831 int[] directionVector = new int[]{0, -1};
2832 cellToPoint(0, mCountY, cellPoint);
2833 ItemConfiguration configuration = new ItemConfiguration();
2834 if (findReorderSolution(cellPoint[0], cellPoint[1], mCountX, 1, mCountX, 1,
2835 directionVector, null, false, configuration).isSolution) {
2836 if (commitConfig) {
2837 copySolutionToTempState(configuration, null);
Sunny Goyal711c5962021-06-23 12:36:18 -07002838 commitTempPlacement(null);
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002839 // undo marking cells occupied since there is actually nothing being placed yet.
2840 mOccupied.markCells(0, mCountY - 1, mCountX, 1, false);
Samuel Fufaa4211432020-02-25 18:47:54 -08002841 }
2842 return true;
2843 }
2844 return false;
2845 }
2846
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002847 /**
2848 * returns a copy of cell layout's grid occupancy
2849 */
2850 public GridOccupancy cloneGridOccupancy() {
2851 GridOccupancy occupancy = new GridOccupancy(mCountX, mCountY);
2852 mOccupied.copyTo(occupancy);
2853 return occupancy;
2854 }
2855
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002856 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002857 return mOccupied.isRegionVacant(x, y, spanX, spanY);
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002858 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002859}