blob: 37194b1ba6f37a08ec76a209c550bcdae613faaf [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyaleaf7a952020-07-29 16:54:20 -070019import static android.animation.ValueAnimator.areAnimatorsEnabled;
20
Sunny Goyalf0b6db72018-08-13 16:10:14 -070021import static com.android.launcher3.anim.Interpolators.DEACCEL_1_5;
Federico Baron1028a722022-10-13 14:09:38 -070022import static com.android.launcher3.config.FeatureFlags.SHOW_HOME_GARDENING;
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
Sunny Goyalaa8ef112015-06-12 20:04:41 -070063import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyale9b651e2015-04-24 11:44:51 -070064import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070065import com.android.launcher3.anim.Interpolators;
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;
Adam Cohend41fbf52012-02-16 23:53:59 -080089import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070090
Sunny Goyalc4d32012020-04-03 17:10:11 -070091public class CellLayout extends ViewGroup {
Tony Wickhama0628cc2015-10-14 15:23:04 -070092 private static final String TAG = "CellLayout";
93 private static final boolean LOGD = false;
Winson Chungaafa03c2010-06-11 17:34:16 -070094
Tony Wickhamec6fd6f2023-03-11 02:08:57 +000095 /** The color of the "leave-behind" shape when a folder is opened from Hotseat. */
96 private static final int FOLDER_LEAVE_BEHIND_COLOR = Color.argb(160, 245, 245, 245);
97
Sunny Goyalab770a12018-11-14 15:17:26 -080098 protected final ActivityContext mActivity;
Sunny Goyal4ffec482016-02-09 11:28:52 -080099 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -0700100 @Thunk int mCellWidth;
Sunny Goyal4ffec482016-02-09 11:28:52 -0800101 @ViewDebug.ExportedProperty(category = "launcher")
Adam Cohen091440a2015-03-18 14:16:05 -0700102 @Thunk int mCellHeight;
Winson Chung11a1a532013-09-13 11:14:45 -0700103 private int mFixedCellWidth;
104 private int mFixedCellHeight;
Jon Miranda228877d2021-02-09 11:05:00 -0500105 @ViewDebug.ExportedProperty(category = "launcher")
Thales Lima8cd020b2022-03-15 20:15:14 +0000106 private Point mBorderSpace;
Winson Chungaafa03c2010-06-11 17:34:16 -0700107
Sunny Goyal4ffec482016-02-09 11:28:52 -0800108 @ViewDebug.ExportedProperty(category = "launcher")
Sebastian Franco09589322022-11-02 15:25:58 -0700109 protected int mCountX;
Sunny Goyal4ffec482016-02-09 11:28:52 -0800110 @ViewDebug.ExportedProperty(category = "launcher")
Sebastian Franco09589322022-11-02 15:25:58 -0700111 protected int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112
Adam Cohen917e3882013-10-31 15:03:35 -0700113 private boolean mDropPending = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800114
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700115 // These are temporary variables to prevent having to allocate a new object just to
116 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Adam Cohen091440a2015-03-18 14:16:05 -0700117 @Thunk final int[] mTmpPoint = new int[2];
Sunny Goyal2805e632015-05-20 15:35:32 -0700118 @Thunk final int[] mTempLocation = new int[2];
Adam Cohend9162062020-03-24 16:35:35 -0700119 final PointF mTmpPointF = new PointF();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700120
Sebastian Franco09589322022-11-02 15:25:58 -0700121 protected GridOccupancy mOccupied;
Sebastian Francoe4c03452022-12-27 14:50:02 -0600122 public GridOccupancy mTmpOccupied;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800123
Michael Jurkadee05892010-07-27 10:01:56 -0700124 private OnTouchListener mInterceptTouchListener;
125
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800126 private final ArrayList<DelegatedCellDrawing> mDelegatedCellDrawings = new ArrayList<>();
Jon Mirandaa0233f72017-06-22 18:34:45 -0700127 final PreviewBackground mFolderLeaveBehind = new PreviewBackground();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700128
Sunny Goyalf5440cb2016-12-14 15:13:00 -0800129 private static final int[] BACKGROUND_STATE_ACTIVE = new int[] { android.R.attr.state_active };
Sunny Goyale15e2a82017-12-15 13:05:42 -0800130 private static final int[] BACKGROUND_STATE_DEFAULT = EMPTY_STATE_SET;
Sebastian Franco09589322022-11-02 15:25:58 -0700131 protected final Drawable mBackground;
Sunny Goyal2805e632015-05-20 15:35:32 -0700132
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700133 // These values allow a fixed measurement to be set on the CellLayout.
134 private int mFixedWidth = -1;
135 private int mFixedHeight = -1;
136
Michael Jurka33945b22010-12-21 18:19:38 -0800137 // If we're actively dragging something over this screen, mIsDragOverlapping is true
138 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700139
Winson Chung150fbab2010-09-29 17:14:26 -0700140 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700141 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Sebastian Francod4682992022-10-05 13:03:09 -0500142 @Thunk final CellLayoutLayoutParams[] mDragOutlines = new CellLayoutLayoutParams[4];
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700143 @Thunk final float[] mDragOutlineAlphas = new float[mDragOutlines.length];
144 private final InterruptibleInOutAnimator[] mDragOutlineAnims =
Joe Onorato4be866d2010-10-10 11:26:02 -0700145 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700146
147 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700148 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700149 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700150
Sebastian Francod4682992022-10-05 13:03:09 -0500151 @Thunk final ArrayMap<CellLayoutLayoutParams, Animator> mReorderAnimators = new ArrayMap<>();
Adam Cohend9162062020-03-24 16:35:35 -0700152 @Thunk final ArrayMap<Reorderable, ReorderPreviewAnimation> mShakeAnimators = new ArrayMap<>();
Adam Cohen19f37922012-03-21 11:59:11 -0700153
154 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700155
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800156 // Used to visualize the grid and drop locations
157 private boolean mVisualizeCells = false;
158 private boolean mVisualizeDropLocation = true;
159 private RectF mVisualizeGridRect = new RectF();
160 private Paint mVisualizeGridPaint = new Paint();
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800161 private int mGridVisualizationRoundingRadius;
162 private float mGridAlpha = 0f;
163 private int mGridColor = 0;
Sebastian Franco09589322022-11-02 15:25:58 -0700164 protected float mSpringLoadedProgress = 0f;
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800165 private float mScrollProgress = 0f;
166
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700167 // When a drag operation is in progress, holds the nearest cell to the touch point
168 private final int[] mDragCell = new int[2];
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800169 private final int[] mDragCellSpan = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800170
Joe Onorato4be866d2010-10-10 11:26:02 -0700171 private boolean mDragging = false;
172
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700173 private final TimeInterpolator mEaseOutInterpolator;
Sebastian Franco09589322022-11-02 15:25:58 -0700174 protected final ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700175
Sunny Goyalc13403c2016-11-18 23:44:48 -0800176 @Retention(RetentionPolicy.SOURCE)
177 @IntDef({WORKSPACE, HOTSEAT, FOLDER})
178 public @interface ContainerType{}
179 public static final int WORKSPACE = 0;
180 public static final int HOTSEAT = 1;
181 public static final int FOLDER = 2;
182
183 @ContainerType private final int mContainerType;
184
Jon Mirandab28c4fc2017-06-20 10:58:36 -0700185 private final float mChildScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800186
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800187 public static final int MODE_SHOW_REORDER_HINT = 0;
188 public static final int MODE_DRAG_OVER = 1;
189 public static final int MODE_ON_DROP = 2;
190 public static final int MODE_ON_DROP_EXTERNAL = 3;
191 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700192 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800193 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
194
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800195 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700196 private static final int REORDER_ANIMATION_DURATION = 150;
Sunny Goyalc13403c2016-11-18 23:44:48 -0800197 @Thunk final float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700198
Rajeev Kumar9962dbe2017-06-12 12:16:20 -0700199 private final ArrayList<View> mIntersectingViews = new ArrayList<>();
200 private final Rect mOccupiedRect = new Rect();
Sebastian Francoe4c03452022-12-27 14:50:02 -0600201 public final int[] mDirectionVector = new int[2];
Steven Ng30dd1d62021-03-15 21:45:49 +0000202
Sebastian Franco53a15a42022-10-25 17:28:54 -0700203 ItemConfiguration mPreviousSolution = null;
Adam Cohenb209e632012-03-27 17:09:36 -0700204 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800205
Sunny Goyal2805e632015-05-20 15:35:32 -0700206 private final Rect mTempRect = new Rect();
Jonathan Miranda21930da2021-05-03 18:44:13 +0000207 private final RectF mTempRectF = new RectF();
Jon Miranda88b7f6a2021-05-03 16:49:53 -0700208 private final float[] mTmpFloatArray = new float[4];
Winson Chung3a6e7f32013-10-09 15:50:52 -0700209
Sunny Goyal73b5a272019-12-09 14:55:56 -0800210 private static final Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700211
Adam Cohenc9735cf2015-01-23 16:11:55 -0800212 // Related to accessible drag and drop
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700213 DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800214
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800215
216 public static final FloatProperty<CellLayout> SPRING_LOADED_PROGRESS =
217 new FloatProperty<CellLayout>("spring_loaded_progress") {
218 @Override
219 public Float get(CellLayout cl) {
220 return cl.getSpringLoadedProgress();
221 }
222
223 @Override
224 public void setValue(CellLayout cl, float progress) {
225 cl.setSpringLoadedProgress(progress);
226 }
227 };
228
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800229 public CellLayout(Context context) {
230 this(context, null);
231 }
232
233 public CellLayout(Context context, AttributeSet attrs) {
234 this(context, attrs, 0);
235 }
236
237 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
238 super(context, attrs, defStyle);
Sunny Goyalc13403c2016-11-18 23:44:48 -0800239 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
240 mContainerType = a.getInteger(R.styleable.CellLayout_containerType, WORKSPACE);
241 a.recycle();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700242
243 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
244 // the user where a dragged item will land when dropped.
245 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800246 setClipToPadding(false);
Sunny Goyalab770a12018-11-14 15:17:26 -0800247 mActivity = ActivityContext.lookupContext(context);
Steven Ngcc505b82021-03-18 23:04:35 +0000248 DeviceProfile deviceProfile = mActivity.getDeviceProfile();
Michael Jurkaa63c4522010-08-19 13:52:27 -0700249
Thales Lima8cd020b2022-03-15 20:15:14 +0000250 resetCellSizeInternal(deviceProfile);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700251
Steven Ngcc505b82021-03-18 23:04:35 +0000252 mCountX = deviceProfile.inv.numColumns;
253 mCountY = deviceProfile.inv.numRows;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700254 mOccupied = new GridOccupancy(mCountX, mCountY);
255 mTmpOccupied = new GridOccupancy(mCountX, mCountY);
256
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800257 mFolderLeaveBehind.mDelegateCellX = -1;
258 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenefca0272016-02-24 19:19:06 -0800259
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800260 setAlwaysDrawnWithCacheEnabled(false);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700261
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800262 Resources res = getResources();
263
264 mBackground = getContext().getDrawable(R.drawable.bg_celllayout);
Sunny Goyal2805e632015-05-20 15:35:32 -0700265 mBackground.setCallback(this);
Sunny Goyalaeb16432017-10-16 11:46:41 -0700266 mBackground.setAlpha(0);
Michael Jurka33945b22010-12-21 18:19:38 -0800267
Yogisha Dixitc0ac1dd2021-05-29 00:26:25 +0100268 mGridColor = Themes.getAttrColor(getContext(), R.attr.workspaceAccentColor);
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800269 mGridVisualizationRoundingRadius =
270 res.getDimensionPixelSize(R.dimen.grid_visualization_rounding_radius);
Steven Ngcc505b82021-03-18 23:04:35 +0000271 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE * deviceProfile.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700272
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700273 // Initialize the data structures used for the drag visualization.
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -0700274 mEaseOutInterpolator = Interpolators.DEACCEL_2_5; // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700275 mDragCell[0] = mDragCell[1] = -1;
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800276 mDragCellSpan[0] = mDragCellSpan[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700277 for (int i = 0; i < mDragOutlines.length; i++) {
Sunny Goyal669b71f2023-01-27 14:37:07 -0800278 mDragOutlines[i] = new CellLayoutLayoutParams(0, 0, 0, 0);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700279 }
Mario Bertschler54ba6012017-06-08 10:53:53 -0700280 mDragOutlinePaint.setColor(Themes.getAttrColor(context, R.attr.workspaceTextColor));
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700281
282 // When dragging things around the home screens, we show a green outline of
283 // where the item will land. The outlines gradually fade out, leaving a trail
284 // behind the drag path.
285 // Set up all the animations that are used to implement this fading.
286 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700287 final float fromAlphaValue = 0;
288 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700289
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700290 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700291
292 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700293 final InterruptibleInOutAnimator anim =
Sebastian Francof153d912022-04-22 16:15:27 -0500294 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700295 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700296 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700297 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700298 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700299 // If an animation is started and then stopped very quickly, we can still
300 // get spurious updates we've cleared the tag. Guard against this.
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800301 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
302 CellLayout.this.invalidate();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700303 }
304 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700305 // The animation holds a reference to the drag outline bitmap as long is it's
306 // running. This way the bitmap can be GCed when the animations are complete.
Joe Onorato4be866d2010-10-10 11:26:02 -0700307 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700308 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700309
Sunny Goyalc13403c2016-11-18 23:44:48 -0800310 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context, mContainerType);
Jon Miranda228877d2021-02-09 11:05:00 -0500311 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100312 mBorderSpace);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700313 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700314 }
315
Sunny Goyal9b180102020-03-11 10:02:29 -0700316 /**
317 * Sets or clears a delegate used for accessible drag and drop
318 */
319 public void setDragAndDropAccessibilityDelegate(DragAndDropAccessibilityDelegate delegate) {
320 setOnClickListener(delegate);
Sunny Goyal9b180102020-03-11 10:02:29 -0700321 ViewCompat.setAccessibilityDelegate(this, delegate);
322
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700323 mTouchHelper = delegate;
324 int accessibilityFlag = mTouchHelper != null
Sunny Goyal9b180102020-03-11 10:02:29 -0700325 ? IMPORTANT_FOR_ACCESSIBILITY_YES : IMPORTANT_FOR_ACCESSIBILITY_NO;
326 setImportantForAccessibility(accessibilityFlag);
327 getShortcutsAndWidgets().setImportantForAccessibility(accessibilityFlag);
Adam Cohenc9735cf2015-01-23 16:11:55 -0800328
Sunny Goyal384b5782021-02-09 22:50:02 -0800329 // ExploreByTouchHelper sets focusability. Clear it when the delegate is cleared.
330 setFocusable(delegate != null);
Adam Cohenc9735cf2015-01-23 16:11:55 -0800331 // Invalidate the accessibility hierarchy
332 if (getParent() != null) {
333 getParent().notifySubtreeAccessibilityStateChanged(
334 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
335 }
336 }
337
Sunny Goyala4647b62021-02-02 13:45:34 -0800338 /**
339 * Returns the currently set accessibility delegate
340 */
341 public DragAndDropAccessibilityDelegate getDragAndDropAccessibilityDelegate() {
342 return mTouchHelper;
343 }
344
Adam Cohenc9735cf2015-01-23 16:11:55 -0800345 @Override
Adam Cohen6e7c37a2020-06-25 19:22:37 -0700346 public boolean dispatchHoverEvent(MotionEvent event) {
347 // Always attempt to dispatch hover events to accessibility first.
348 if (mTouchHelper != null && mTouchHelper.dispatchHoverEvent(event)) {
349 return true;
350 }
351 return super.dispatchHoverEvent(event);
352 }
353
354 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800355 public boolean onInterceptTouchEvent(MotionEvent ev) {
Winson Chungf9935182020-10-23 09:26:44 -0700356 return mTouchHelper != null
357 || (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev));
Adam Cohenc9735cf2015-01-23 16:11:55 -0800358 }
359
Chris Craik01f2d7f2013-10-01 14:41:56 -0700360 public void enableHardwareLayer(boolean hasLayer) {
361 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700362 }
363
vadimt04f356f2019-02-14 18:46:36 -0800364 public boolean isHardwareLayerEnabled() {
365 return mShortcutsAndWidgets.getLayerType() == LAYER_TYPE_HARDWARE;
366 }
367
Thales Lima8cd020b2022-03-15 20:15:14 +0000368 /**
369 * Change sizes of cells
370 *
371 * @param width the new width of the cells
372 * @param height the new height of the cells
373 */
Winson Chung5f8afe62013-08-12 16:19:28 -0700374 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700375 mFixedCellWidth = mCellWidth = width;
376 mFixedCellHeight = mCellHeight = height;
Jon Miranda228877d2021-02-09 11:05:00 -0500377 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100378 mBorderSpace);
Winson Chung5f8afe62013-08-12 16:19:28 -0700379 }
380
Thales Lima8cd020b2022-03-15 20:15:14 +0000381 private void resetCellSizeInternal(DeviceProfile deviceProfile) {
382 switch (mContainerType) {
383 case FOLDER:
Thales Limab35faed2022-09-05 16:30:01 -0300384 mBorderSpace = new Point(deviceProfile.folderCellLayoutBorderSpacePx,
385 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;
Federico Baron1028a722022-10-13 14:09:38 -0700560 if (!SHOW_HOME_GARDENING.get()) {
561 updateBgAlpha();
562 }
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800563 setGridAlpha(progress);
564 }
565 }
566
567 /**
568 * See setSpringLoadedProgress
569 * @return progress
570 */
571 public float getSpringLoadedProgress() {
572 return mSpringLoadedProgress;
573 }
574
Sebastian Franco09589322022-11-02 15:25:58 -0700575 protected void updateBgAlpha() {
Adam Cohen0c4d2782021-04-29 15:56:13 -0700576 mBackground.setAlpha((int) (mSpringLoadedProgress * 255));
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);
Federico Baron1028a722022-10-13 14:09:38 -0700587 if (!SHOW_HOME_GARDENING.get()) {
588 updateBgAlpha();
589 }
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800590 }
591 }
592
593 private void setGridAlpha(float gridAlpha) {
594 if (Float.compare(gridAlpha, mGridAlpha) != 0) {
595 mGridAlpha = gridAlpha;
596 invalidate();
597 }
598 }
599
Adam Cohen65086992020-02-19 08:40:49 -0800600 protected void visualizeGrid(Canvas canvas) {
Adam Cohen0c4d2782021-04-29 15:56:13 -0700601 DeviceProfile dp = mActivity.getDeviceProfile();
Alex Chau51da2192022-05-20 13:32:10 +0100602 int paddingX = Math.min((mCellWidth - dp.iconSizePx) / 2, dp.gridVisualizationPaddingX);
603 int paddingY = Math.min((mCellHeight - dp.iconSizePx) / 2, dp.gridVisualizationPaddingY);
Adam Cohen0c4d2782021-04-29 15:56:13 -0700604 mVisualizeGridRect.set(paddingX, paddingY,
605 mCellWidth - paddingX,
606 mCellHeight - paddingY);
Adam Cohen65086992020-02-19 08:40:49 -0800607
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800608 mVisualizeGridPaint.setStrokeWidth(8);
609 int paintAlpha = (int) (120 * mGridAlpha);
610 mVisualizeGridPaint.setColor(ColorUtils.setAlphaComponent(mGridColor, paintAlpha));
Adam Cohen65086992020-02-19 08:40:49 -0800611
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800612 if (mVisualizeCells) {
613 for (int i = 0; i < mCountX; i++) {
614 for (int j = 0; j < mCountY; j++) {
Thales Lima78d00ad2021-09-30 11:29:06 +0100615 int transX = i * mCellWidth + (i * mBorderSpace.x) + getPaddingLeft()
Adam Cohen0c4d2782021-04-29 15:56:13 -0700616 + paddingX;
Thales Lima78d00ad2021-09-30 11:29:06 +0100617 int transY = j * mCellHeight + (j * mBorderSpace.y) + getPaddingTop()
Adam Cohen0c4d2782021-04-29 15:56:13 -0700618 + paddingY;
Adam Cohen65086992020-02-19 08:40:49 -0800619
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800620 mVisualizeGridRect.offsetTo(transX, transY);
621 mVisualizeGridPaint.setStyle(Paint.Style.FILL);
622 canvas.drawRoundRect(mVisualizeGridRect, mGridVisualizationRoundingRadius,
623 mGridVisualizationRoundingRadius, mVisualizeGridPaint);
624 }
625 }
626 }
Adam Cohen65086992020-02-19 08:40:49 -0800627
Federico Baron1028a722022-10-13 14:09:38 -0700628 if (mVisualizeDropLocation && !SHOW_HOME_GARDENING.get()) {
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800629 for (int i = 0; i < mDragOutlines.length; i++) {
630 final float alpha = mDragOutlineAlphas[i];
631 if (alpha <= 0) continue;
Adam Cohen65086992020-02-19 08:40:49 -0800632
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800633 mVisualizeGridPaint.setAlpha(255);
Sebastian Franco877088e2023-01-03 15:16:22 -0700634 int x = mDragOutlines[i].getCellX();
635 int y = mDragOutlines[i].getCellY();
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800636 int spanX = mDragOutlines[i].cellHSpan;
637 int spanY = mDragOutlines[i].cellVSpan;
638
Adam Cohened82e0d2021-07-21 17:24:12 -0700639 // TODO b/194414754 clean this up, reconcile with cellToRect
Adam Cohen0c4d2782021-04-29 15:56:13 -0700640 mVisualizeGridRect.set(paddingX, paddingY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100641 mCellWidth * spanX + mBorderSpace.x * (spanX - 1) - paddingX,
642 mCellHeight * spanY + mBorderSpace.y * (spanY - 1) - paddingY);
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800643
Thales Lima78d00ad2021-09-30 11:29:06 +0100644 int transX = x * mCellWidth + (x * mBorderSpace.x)
Adam Cohen0c4d2782021-04-29 15:56:13 -0700645 + getPaddingLeft() + paddingX;
Thales Lima78d00ad2021-09-30 11:29:06 +0100646 int transY = y * mCellHeight + (y * mBorderSpace.y)
Adam Cohen0c4d2782021-04-29 15:56:13 -0700647 + getPaddingTop() + paddingY;
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800648
649 mVisualizeGridRect.offsetTo(transX, transY);
Adam Cohen65086992020-02-19 08:40:49 -0800650
651 mVisualizeGridPaint.setStyle(Paint.Style.STROKE);
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800652 mVisualizeGridPaint.setColor(Color.argb((int) (alpha),
653 Color.red(mGridColor), Color.green(mGridColor), Color.blue(mGridColor)));
Adam Cohen65086992020-02-19 08:40:49 -0800654
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800655 canvas.drawRoundRect(mVisualizeGridRect, mGridVisualizationRoundingRadius,
656 mGridVisualizationRoundingRadius, mVisualizeGridPaint);
Adam Cohen65086992020-02-19 08:40:49 -0800657 }
658 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700659 }
660
Adam Cohenefca0272016-02-24 19:19:06 -0800661 @Override
662 protected void dispatchDraw(Canvas canvas) {
663 super.dispatchDraw(canvas);
664
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800665 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
666 DelegatedCellDrawing bg = mDelegatedCellDrawings.get(i);
667 cellToPoint(bg.mDelegateCellX, bg.mDelegateCellY, mTempLocation);
668 canvas.save();
669 canvas.translate(mTempLocation[0], mTempLocation[1]);
670 bg.drawOverItem(canvas);
671 canvas.restore();
Adam Cohenefca0272016-02-24 19:19:06 -0800672 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700673 }
674
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800675 /**
676 * Add Delegated cell drawing
677 */
678 public void addDelegatedCellDrawing(DelegatedCellDrawing bg) {
679 mDelegatedCellDrawings.add(bg);
Adam Cohenefca0272016-02-24 19:19:06 -0800680 }
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800681
682 /**
683 * Remove item from DelegatedCellDrawings
684 */
685 public void removeDelegatedCellDrawing(DelegatedCellDrawing bg) {
686 mDelegatedCellDrawings.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700687 }
688
Adam Cohenc51934b2011-07-26 21:07:43 -0700689 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800690 View child = getChildAt(x, y);
Sunny Goyalab770a12018-11-14 15:17:26 -0800691 mFolderLeaveBehind.setup(getContext(), mActivity, null,
Adam Cohenefca0272016-02-24 19:19:06 -0800692 child.getMeasuredWidth(), child.getPaddingTop());
693
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800694 mFolderLeaveBehind.mDelegateCellX = x;
695 mFolderLeaveBehind.mDelegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700696 invalidate();
697 }
698
699 public void clearFolderLeaveBehind() {
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800700 mFolderLeaveBehind.mDelegateCellX = -1;
701 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700702 invalidate();
703 }
704
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700705 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700706 public boolean shouldDelayChildPressedState() {
707 return false;
708 }
709
Adam Cohen1462de32012-07-24 22:34:36 -0700710 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700711 try {
712 dispatchRestoreInstanceState(states);
713 } catch (IllegalArgumentException ex) {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800714 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700715 throw ex;
716 }
717 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
718 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
719 }
Adam Cohen1462de32012-07-24 22:34:36 -0700720 }
721
Michael Jurkae6235dd2011-10-04 15:02:05 -0700722 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700723 public void cancelLongPress() {
724 super.cancelLongPress();
725
726 // Cancel long press for all children
727 final int count = getChildCount();
728 for (int i = 0; i < count; i++) {
729 final View child = getChildAt(i);
730 child.cancelLongPress();
731 }
732 }
733
Michael Jurkadee05892010-07-27 10:01:56 -0700734 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
735 mInterceptTouchListener = listener;
736 }
737
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800738 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700739 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800740 }
741
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800742 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700743 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800744 }
745
Sunny Goyalc13403c2016-11-18 23:44:48 -0800746 public boolean acceptsWidget() {
747 return mContainerType == WORKSPACE;
Sunny Goyale9b651e2015-04-24 11:44:51 -0700748 }
749
Sebastian Francod4682992022-10-05 13:03:09 -0500750 /**
751 * Adds the given view to the CellLayout
752 *
753 * @param child view to add.
754 * @param index index of the CellLayout children where to add the view.
755 * @param childId id of the view.
756 * @param params represent the logic of the view on the CellLayout.
757 * @param markCells if the occupied cells should be marked or not
758 * @return if adding the view was successful
759 */
760 public boolean addViewToCellLayout(View child, int index, int childId,
761 CellLayoutLayoutParams params, boolean markCells) {
762 final CellLayoutLayoutParams lp = params;
Winson Chungaafa03c2010-06-11 17:34:16 -0700763
Andrew Flynnde38e422012-05-08 11:22:15 -0700764 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800765 if (child instanceof BubbleTextView) {
766 BubbleTextView bubbleChild = (BubbleTextView) child;
Jon Mirandaf1eae802017-10-04 11:23:33 -0700767 bubbleChild.setTextVisibility(mContainerType != HOTSEAT);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800768 }
769
Sunny Goyalc13403c2016-11-18 23:44:48 -0800770 child.setScaleX(mChildScale);
771 child.setScaleY(mChildScale);
Adam Cohen307fe232012-08-16 17:55:58 -0700772
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800773 // Generate an id for each view, this assumes we have at most 256x256 cells
774 // per workspace screen
Sebastian Franco877088e2023-01-03 15:16:22 -0700775 if (lp.getCellX() >= 0 && lp.getCellX() <= mCountX - 1
776 && lp.getCellY() >= 0 && lp.getCellY() <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700777 // If the horizontal or vertical span is set to -1, it is taken to
778 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700779 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
780 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800781
Winson Chungaafa03c2010-06-11 17:34:16 -0700782 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700783 if (LOGD) {
784 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
785 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700786 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700787
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700788 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700789
Winson Chungaafa03c2010-06-11 17:34:16 -0700790 return true;
791 }
792 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800793 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700794
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800795 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700796 public void removeAllViews() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700797 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700798 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700799 }
800
801 @Override
802 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700803 if (mShortcutsAndWidgets.getChildCount() > 0) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700804 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700805 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700806 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700807 }
808
809 @Override
810 public void removeView(View view) {
811 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700812 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700813 }
814
815 @Override
816 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700817 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
818 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700819 }
820
821 @Override
822 public void removeViewInLayout(View view) {
823 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700824 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700825 }
826
827 @Override
828 public void removeViews(int start, int count) {
829 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700830 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700831 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700832 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700833 }
834
835 @Override
836 public void removeViewsInLayout(int start, int count) {
837 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700838 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700839 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700840 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800841 }
842
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700843 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700844 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800845 * @param x X coordinate of the point
846 * @param y Y coordinate of the point
847 * @param result Array of 2 ints to hold the x and y coordinate of the cell
848 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700849 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700850 final int hStartPadding = getPaddingLeft();
851 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800852
Sebastian Francob57c0b22022-06-28 13:54:35 -0700853 result[0] = (x - hStartPadding) / (mCellWidth + mBorderSpace.x);
854 result[1] = (y - vStartPadding) / (mCellHeight + mBorderSpace.y);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800855
Adam Cohend22015c2010-07-26 22:02:18 -0700856 final int xAxis = mCountX;
857 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800858
859 if (result[0] < 0) result[0] = 0;
860 if (result[0] >= xAxis) result[0] = xAxis - 1;
861 if (result[1] < 0) result[1] = 0;
862 if (result[1] >= yAxis) result[1] = yAxis - 1;
863 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700864
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800865 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800866 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700867 *
868 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800869 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700870 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800871 * @param result Array of 2 ints to hold the x and y coordinate of the point
872 */
873 void cellToPoint(int cellX, int cellY, int[] result) {
Jon Miranda228877d2021-02-09 11:05:00 -0500874 cellToRect(cellX, cellY, 1, 1, mTempRect);
875 result[0] = mTempRect.left;
876 result[1] = mTempRect.top;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800877 }
878
Adam Cohene3e27a82011-04-15 12:07:39 -0700879 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800880 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700881 *
882 * @param cellX X coordinate of the cell
883 * @param cellY Y coordinate of the cell
884 *
885 * @param result Array of 2 ints to hold the x and y coordinate of the point
886 */
887 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700888 regionToCenterPoint(cellX, cellY, 1, 1, result);
889 }
890
891 /**
Tony Wickham0ac045f2021-11-03 13:17:02 -0700892 * Given a cell coordinate and span return the point that represents the center of the region
Adam Cohen47a876d2012-03-19 13:21:41 -0700893 *
894 * @param cellX X coordinate of the cell
895 * @param cellY Y coordinate of the cell
896 *
897 * @param result Array of 2 ints to hold the x and y coordinate of the point
898 */
899 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Jon Miranda228877d2021-02-09 11:05:00 -0500900 cellToRect(cellX, cellY, spanX, spanY, mTempRect);
901 result[0] = mTempRect.centerX();
902 result[1] = mTempRect.centerY();
Adam Cohen19f37922012-03-21 11:59:11 -0700903 }
904
Tony Wickham3cfa5ed2021-11-03 13:20:43 -0700905 /**
906 * Returns the distance between the given coordinate and the visual center of the given cell.
907 */
908 public float getDistanceFromWorkspaceCellVisualCenter(float x, float y, int[] cell) {
909 getWorkspaceCellVisualCenter(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700910 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800911 }
912
Tony Wickham3cfa5ed2021-11-03 13:20:43 -0700913 private void getWorkspaceCellVisualCenter(int cellX, int cellY, int[] outPoint) {
914 View child = getChildAt(cellX, cellY);
915 if (child instanceof DraggableView) {
916 DraggableView draggableChild = (DraggableView) child;
917 if (draggableChild.getViewType() == DRAGGABLE_ICON) {
918 cellToPoint(cellX, cellY, outPoint);
919 draggableChild.getWorkspaceVisualDragBounds(mTempRect);
920 mTempRect.offset(outPoint[0], outPoint[1]);
921 outPoint[0] = mTempRect.centerX();
922 outPoint[1] = mTempRect.centerY();
923 return;
924 }
925 }
926 cellToCenterPoint(cellX, cellY, outPoint);
927 }
928
Tony Wickham0ac045f2021-11-03 13:17:02 -0700929 /**
930 * Returns the max distance from the center of a cell that can accept a drop to create a folder.
931 */
Tony Wickham12784902021-11-03 14:02:10 -0700932 public float getFolderCreationRadius(int[] targetCell) {
Tony Wickham0ac045f2021-11-03 13:17:02 -0700933 DeviceProfile grid = mActivity.getDeviceProfile();
Tony Wickham12784902021-11-03 14:02:10 -0700934 float iconVisibleRadius = ICON_VISIBLE_AREA_FACTOR * grid.iconSizePx / 2;
935 // Halfway between reorder radius and icon.
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700936 return (getReorderRadius(targetCell, 1, 1) + iconVisibleRadius) / 2;
Tony Wickham12784902021-11-03 14:02:10 -0700937 }
938
939 /**
940 * Returns the max distance from the center of a cell that will start to reorder on drag over.
941 */
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700942 public float getReorderRadius(int[] targetCell, int spanX, int spanY) {
Tony Wickham12784902021-11-03 14:02:10 -0700943 int[] centerPoint = mTmpPoint;
944 getWorkspaceCellVisualCenter(targetCell[0], targetCell[1], centerPoint);
945
946 Rect cellBoundsWithSpacing = mTempRect;
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700947 cellToRect(targetCell[0], targetCell[1], spanX, spanY, cellBoundsWithSpacing);
Tony Wickham12784902021-11-03 14:02:10 -0700948 cellBoundsWithSpacing.inset(-mBorderSpace.x / 2, -mBorderSpace.y / 2);
949
Sebastian Francoc8392ea2022-10-28 16:38:37 -0700950 if (canCreateFolder(getChildAt(targetCell[0], targetCell[1])) && spanX == 1 && spanY == 1) {
Tony Wickham12784902021-11-03 14:02:10 -0700951 // Take only the circle in the smaller dimension, to ensure we don't start reordering
952 // too soon before accepting a folder drop.
953 int minRadius = centerPoint[0] - cellBoundsWithSpacing.left;
954 minRadius = Math.min(minRadius, centerPoint[1] - cellBoundsWithSpacing.top);
955 minRadius = Math.min(minRadius, cellBoundsWithSpacing.right - centerPoint[0]);
956 minRadius = Math.min(minRadius, cellBoundsWithSpacing.bottom - centerPoint[1]);
957 return minRadius;
958 }
959 // Take up the entire cell, including space between this cell and the adjacent ones.
Sebastian Francoc8392ea2022-10-28 16:38:37 -0700960 // Multiply by span to scale radius
961 return (float) Math.hypot(spanX * cellBoundsWithSpacing.width() / 2f,
962 spanY * cellBoundsWithSpacing.height() / 2f);
Tony Wickham0ac045f2021-11-03 13:17:02 -0700963 }
964
Adam Cohenf9c184a2016-01-15 16:47:43 -0800965 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800966 return mCellWidth;
967 }
968
Sunny Goyal0b754e52017-08-07 07:42:45 -0700969 public int getCellHeight() {
Romain Guy84f296c2009-11-04 15:00:44 -0800970 return mCellHeight;
971 }
972
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700973 public void setFixedSize(int width, int height) {
974 mFixedWidth = width;
975 mFixedHeight = height;
976 }
977
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800978 @Override
979 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800980 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800981 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700982 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
983 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700984 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
985 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -0700986
Winson Chung11a1a532013-09-13 11:14:45 -0700987 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Thales Lima78d00ad2021-09-30 11:29:06 +0100988 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mBorderSpace.x,
Jon Miranda228877d2021-02-09 11:05:00 -0500989 mCountX);
Thales Lima78d00ad2021-09-30 11:29:06 +0100990 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mBorderSpace.y,
Jon Miranda228877d2021-02-09 11:05:00 -0500991 mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700992 if (cw != mCellWidth || ch != mCellHeight) {
993 mCellWidth = cw;
994 mCellHeight = ch;
Jon Miranda228877d2021-02-09 11:05:00 -0500995 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100996 mBorderSpace);
Winson Chung11a1a532013-09-13 11:14:45 -0700997 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700998 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700999
Winson Chung2d75f122013-09-23 16:53:31 -07001000 int newWidth = childWidthSize;
1001 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -07001002 if (mFixedWidth > 0 && mFixedHeight > 0) {
1003 newWidth = mFixedWidth;
1004 newHeight = mFixedHeight;
1005 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001006 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
1007 }
1008
Sunny Goyal4fe5a372015-05-14 19:55:10 -07001009 mShortcutsAndWidgets.measure(
1010 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
1011 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
1012
1013 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
1014 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -07001015 if (mFixedWidth > 0 && mFixedHeight > 0) {
1016 setMeasuredDimension(maxWidth, maxHeight);
1017 } else {
1018 setMeasuredDimension(widthSize, heightSize);
1019 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001020 }
1021
1022 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -07001023 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -08001024 int left = getPaddingLeft();
Sunny Goyal7ce471b2017-08-02 03:37:39 -07001025 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -07001026 int right = r - l - getPaddingRight();
Sunny Goyal7ce471b2017-08-02 03:37:39 -07001027 right -= (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -07001028
Winson Chung38848ca2013-10-08 12:03:44 -07001029 int top = getPaddingTop();
Sunny Goyal7c786f72016-06-01 14:08:21 -07001030 int bottom = b - t - getPaddingBottom();
Sunny Goyal4fe5a372015-05-14 19:55:10 -07001031
Sunny Goyal7c786f72016-06-01 14:08:21 -07001032 // Expand the background drawing bounds by the padding baked into the background drawable
1033 mBackground.getPadding(mTempRect);
1034 mBackground.setBounds(
Jon Miranda28032002017-07-13 16:18:56 -07001035 left - mTempRect.left - getPaddingLeft(),
1036 top - mTempRect.top - getPaddingTop(),
1037 right + mTempRect.right + getPaddingRight(),
1038 bottom + mTempRect.bottom + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -07001039
Sunny Goyalc4d32012020-04-03 17:10:11 -07001040 mShortcutsAndWidgets.layout(left, top, right, bottom);
Sunny Goyal7c786f72016-06-01 14:08:21 -07001041 }
1042
Tony Wickhama501d492015-11-03 18:05:01 -08001043 /**
1044 * Returns the amount of space left over after subtracting padding and cells. This space will be
1045 * 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 -05001046 * width in {@link DeviceProfile#calculateCellWidth(int, int, int)}.
Tony Wickhama501d492015-11-03 18:05:01 -08001047 */
1048 public int getUnusedHorizontalSpace() {
Jon Miranda228877d2021-02-09 11:05:00 -05001049 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth)
Thales Lima78d00ad2021-09-30 11:29:06 +01001050 - ((mCountX - 1) * mBorderSpace.x);
Tony Wickhama501d492015-11-03 18:05:01 -08001051 }
1052
Sunny Goyal2805e632015-05-20 15:35:32 -07001053 @Override
1054 protected boolean verifyDrawable(Drawable who) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -07001055 return super.verifyDrawable(who) || (who == mBackground);
Sunny Goyal2805e632015-05-20 15:35:32 -07001056 }
1057
Michael Jurkaa52570f2012-03-20 03:18:20 -07001058 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -07001059 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -07001060 }
1061
Jon Miranda228877d2021-02-09 11:05:00 -05001062 public View getChildAt(int cellX, int cellY) {
1063 return mShortcutsAndWidgets.getChildAt(cellX, cellY);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001064 }
1065
Adam Cohen76fc0852011-06-17 13:26:23 -07001066 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001067 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001068 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -08001069
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001070 if (clc.indexOfChild(child) != -1 && (child instanceof Reorderable)) {
Sebastian Francod4682992022-10-05 13:03:09 -05001071 final CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001072 final ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001073 final Reorderable item = (Reorderable) child;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001074
1075 // We cancel any existing animations
1076 if (mReorderAnimators.containsKey(lp)) {
1077 mReorderAnimators.get(lp).cancel();
1078 mReorderAnimators.remove(lp);
1079 }
1080
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001081
Adam Cohen482ed822012-03-02 14:15:13 -08001082 if (adjustOccupied) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001083 GridOccupancy occupied = permanent ? mOccupied : mTmpOccupied;
Sebastian Franco877088e2023-01-03 15:16:22 -07001084 occupied.markCells(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001085 occupied.markCells(cellX, cellY, lp.cellHSpan, lp.cellVSpan, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001086 }
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001087
1088 // Compute the new x and y position based on the new cellX and cellY
1089 // We leverage the actual layout logic in the layout params and hence need to modify
1090 // state and revert that state.
1091 final int oldX = lp.x;
1092 final int oldY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001093 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001094 if (permanent) {
Sunny Goyal669b71f2023-01-27 14:37:07 -08001095 lp.setCellX(cellX);
1096 lp.setCellY(cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001097 } else {
Sebastian Franco877088e2023-01-03 15:16:22 -07001098 lp.setTmpCellX(cellX);
1099 lp.setTmpCellY(cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001100 }
Jon Mirandae96798e2016-12-07 12:10:44 -08001101 clc.setupLp(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001102 final int newX = lp.x;
1103 final int newY = lp.y;
Adam Cohen76fc0852011-06-17 13:26:23 -07001104 lp.x = oldX;
1105 lp.y = oldY;
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001106 lp.isLockedToGrid = false;
1107 // End compute new x and y
1108
Sunny Goyal82dfc152023-02-24 16:50:09 -08001109 MultiTranslateDelegate mtd = item.getTranslateDelegate();
1110 float initPreviewOffsetX = mtd.getTranslationX(INDEX_REORDER_PREVIEW_OFFSET).getValue();
1111 float initPreviewOffsetY = mtd.getTranslationY(INDEX_REORDER_PREVIEW_OFFSET).getValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001112 final float finalPreviewOffsetX = newX - oldX;
1113 final float finalPreviewOffsetY = newY - oldY;
1114
Adam Cohen482ed822012-03-02 14:15:13 -08001115 // Exit early if we're not actually moving the view
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001116 if (finalPreviewOffsetX == 0 && finalPreviewOffsetY == 0
1117 && initPreviewOffsetX == 0 && initPreviewOffsetY == 0) {
Adam Cohen482ed822012-03-02 14:15:13 -08001118 lp.isLockedToGrid = true;
1119 return true;
1120 }
1121
Sunny Goyal849c6a22018-08-08 16:33:46 -07001122 ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001123 va.setDuration(duration);
1124 mReorderAnimators.put(lp, va);
1125
1126 va.addUpdateListener(new AnimatorUpdateListener() {
1127 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001128 public void onAnimationUpdate(ValueAnimator animation) {
Jon Mirandae96798e2016-12-07 12:10:44 -08001129 float r = (Float) animation.getAnimatedValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001130 float x = (1 - r) * initPreviewOffsetX + r * finalPreviewOffsetX;
1131 float y = (1 - r) * initPreviewOffsetY + r * finalPreviewOffsetY;
Sunny Goyal82dfc152023-02-24 16:50:09 -08001132 item.getTranslateDelegate().setTranslation(INDEX_REORDER_PREVIEW_OFFSET, x, y);
Adam Cohenbfbfd262011-06-13 16:55:12 -07001133 }
1134 });
Adam Cohen482ed822012-03-02 14:15:13 -08001135 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001136 boolean cancelled = false;
1137 public void onAnimationEnd(Animator animation) {
1138 // If the animation was cancelled, it means that another animation
1139 // has interrupted this one, and we don't want to lock the item into
1140 // place just yet.
1141 if (!cancelled) {
1142 lp.isLockedToGrid = true;
Sunny Goyal82dfc152023-02-24 16:50:09 -08001143 item.getTranslateDelegate()
1144 .setTranslation(INDEX_REORDER_PREVIEW_OFFSET, 0, 0);
Adam Cohen482ed822012-03-02 14:15:13 -08001145 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001146 }
1147 if (mReorderAnimators.containsKey(lp)) {
1148 mReorderAnimators.remove(lp);
1149 }
1150 }
1151 public void onAnimationCancel(Animator animation) {
1152 cancelled = true;
1153 }
1154 });
Adam Cohen482ed822012-03-02 14:15:13 -08001155 va.setStartDelay(delay);
1156 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001157 return true;
1158 }
1159 return false;
1160 }
1161
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001162 void visualizeDropLocation(int cellX, int cellY, int spanX, int spanY,
1163 DropTarget.DragObject dragObject) {
1164 if (mDragCell[0] != cellX || mDragCell[1] != cellY || mDragCellSpan[0] != spanX
1165 || mDragCellSpan[1] != spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08001166 mDragCell[0] = cellX;
1167 mDragCell[1] = cellY;
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001168 mDragCellSpan[0] = spanX;
1169 mDragCellSpan[1] = spanY;
Steven Ng30dd1d62021-03-15 21:45:49 +00001170
Steven Nga999e222021-04-19 18:17:15 +01001171 // Apply color extraction on a widget when dragging.
1172 applyColorExtractionOnWidget(dragObject, mDragCell, spanX, spanY);
1173
Joe Onorato4be866d2010-10-10 11:26:02 -07001174 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001175 mDragOutlineAnims[oldIndex].animateOut();
1176 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Sunny Goyal106bf642015-07-16 12:18:06 -07001177
Sebastian Francod4682992022-10-05 13:03:09 -05001178 CellLayoutLayoutParams cell = mDragOutlines[mDragOutlineCurrent];
Sebastian Franco877088e2023-01-03 15:16:22 -07001179 cell.setCellX(cellX);
1180 cell.setCellY(cellY);
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001181 cell.cellHSpan = spanX;
1182 cell.cellVSpan = spanY;
Adam Cohen65086992020-02-19 08:40:49 -08001183
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001184 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001185 invalidate();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001186
1187 if (dragObject.stateAnnouncer != null) {
Sunny Goyalc13403c2016-11-18 23:44:48 -08001188 dragObject.stateAnnouncer.announce(getItemMoveDescription(cellX, cellY));
Sunny Goyale78e3d72015-09-24 11:23:31 -07001189 }
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001190
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001191 }
1192 }
1193
Steven Ng30dd1d62021-03-15 21:45:49 +00001194 /** Applies the local color extraction to a dragging widget object. */
Steven Nga999e222021-04-19 18:17:15 +01001195 private void applyColorExtractionOnWidget(DropTarget.DragObject dragObject, int[] targetCell,
1196 int spanX, int spanY) {
Steven Ng30dd1d62021-03-15 21:45:49 +00001197 // Apply local extracted color if the DragView is an AppWidgetHostViewDrawable.
Steven Ng32427202021-04-19 18:12:12 +01001198 View view = dragObject.dragView.getContentView();
1199 if (view instanceof LauncherAppWidgetHostView) {
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001200 int screenId = getWorkspace().getIdForScreen(this);
Steven Ng30dd1d62021-03-15 21:45:49 +00001201 cellToRect(targetCell[0], targetCell[1], spanX, spanY, mTempRect);
Jonathan Miranda21930da2021-05-03 18:44:13 +00001202
Sunny Goyal69a8eec2021-07-22 10:02:50 -07001203 ((LauncherAppWidgetHostView) view).handleDrag(mTempRect, this, screenId);
Steven Ng30dd1d62021-03-15 21:45:49 +00001204 }
1205 }
1206
Sunny Goyal726bee72018-03-05 12:54:24 -08001207 @SuppressLint("StringFormatMatches")
Sunny Goyalc13403c2016-11-18 23:44:48 -08001208 public String getItemMoveDescription(int cellX, int cellY) {
1209 if (mContainerType == HOTSEAT) {
1210 return getContext().getString(R.string.move_to_hotseat_position,
1211 Math.max(cellX, cellY) + 1);
1212 } else {
Shikha Malhotraf78da1b2022-04-11 10:23:18 +00001213 Workspace<?> workspace = getWorkspace();
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001214 int row = cellY + 1;
1215 int col = workspace.mIsRtl ? mCountX - cellX : cellX + 1;
1216 int panelCount = workspace.getPanelCount();
Sebastian Franco930531f2022-06-16 16:49:11 -07001217 int screenId = workspace.getIdForScreen(this);
1218 int pageIndex = workspace.getPageIndexForScreenId(screenId);
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001219 if (panelCount > 1) {
1220 // Increment the column if the target is on the right side of a two panel home
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001221 col += (pageIndex % panelCount) * mCountX;
1222 }
Sebastian Franco930531f2022-06-16 16:49:11 -07001223 return getContext().getString(R.string.move_to_empty_cell_description, row, col,
1224 workspace.getPageDescription(pageIndex));
Sunny Goyalc13403c2016-11-18 23:44:48 -08001225 }
1226 }
1227
Shikha Malhotraf78da1b2022-04-11 10:23:18 +00001228 private Workspace<?> getWorkspace() {
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001229 return Launcher.cast(mActivity).getWorkspace();
1230 }
1231
Adam Cohene0310962011-04-18 16:15:31 -07001232 public void clearDragOutlines() {
1233 final int oldIndex = mDragOutlineCurrent;
1234 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001235 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001236 }
1237
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001238 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001239 * Find a vacant area that will fit the given bounds nearest the requested
1240 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001241 *
Romain Guy51afc022009-05-04 18:03:43 -07001242 * @param pixelX The X location at which you want to search for a vacant area.
1243 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001244 * @param minSpanX The minimum horizontal span required
1245 * @param minSpanY The minimum vertical span required
1246 * @param spanX Horizontal span of the object.
1247 * @param spanY Vertical span of the object.
1248 * @param result Array in which to place the result, or null (in which case a new array will
1249 * be allocated)
1250 * @return The X, Y cell of a vacant area that can contain this object,
1251 * nearest the requested location.
1252 */
Sebastian Francoe4c03452022-12-27 14:50:02 -06001253 public int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
1254 int spanX, int spanY, int[] result, int[] resultSpan) {
Sebastian Francob57c0b22022-06-28 13:54:35 -07001255 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, false,
Adam Cohend41fbf52012-02-16 23:53:59 -08001256 result, resultSpan);
1257 }
1258
Adam Cohend41fbf52012-02-16 23:53:59 -08001259 /**
1260 * Find a vacant area that will fit the given bounds nearest the requested
1261 * cell location. Uses Euclidean distance to score multiple vacant areas.
Sebastian Francob57c0b22022-06-28 13:54:35 -07001262 * @param relativeXPos The X location relative to the Cell layout at which you want to search
1263 * for a vacant area.
1264 * @param relativeYPos The Y location relative to the Cell layout at which you want to search
1265 * for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001266 * @param minSpanX The minimum horizontal span required
1267 * @param minSpanY The minimum vertical span required
1268 * @param spanX Horizontal span of the object.
1269 * @param spanY Vertical span of the object.
1270 * @param ignoreOccupied If true, the result can be an occupied cell
1271 * @param result Array in which to place the result, or null (in which case a new array will
1272 * be allocated)
1273 * @return The X, Y cell of a vacant area that can contain this object,
1274 * nearest the requested location.
1275 */
Sebastian Francob57c0b22022-06-28 13:54:35 -07001276 private int[] findNearestArea(int relativeXPos, int relativeYPos, int minSpanX, int minSpanY,
1277 int spanX, int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Sebastian Francob57c0b22022-06-28 13:54:35 -07001278 // For items with a spanX / spanY > 1, the passed in point (relativeXPos, relativeYPos)
1279 // corresponds to the center of the item, but we are searching based on the top-left cell,
1280 // so we translate the point over to correspond to the top-left.
1281 relativeXPos = (int) (relativeXPos - (mCellWidth + mBorderSpace.x) * (spanX - 1) / 2f);
1282 relativeYPos = (int) (relativeYPos - (mCellHeight + mBorderSpace.y) * (spanY - 1) / 2f);
Adam Cohene3e27a82011-04-15 12:07:39 -07001283
Jeff Sharkey70864282009-04-07 21:08:40 -07001284 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001285 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001286 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001287 final Rect bestRect = new Rect(-1, -1, -1, -1);
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001288 final Stack<Rect> validRegions = new Stack<>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001289
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001290 final int countX = mCountX;
1291 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001292
Adam Cohend41fbf52012-02-16 23:53:59 -08001293 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1294 spanX < minSpanX || spanY < minSpanY) {
1295 return bestXY;
1296 }
1297
1298 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001299 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001300 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1301 int ySize = -1;
1302 int xSize = -1;
Sebastian Francob57c0b22022-06-28 13:54:35 -07001303 if (!ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001304 // First, let's see if this thing fits anywhere
1305 for (int i = 0; i < minSpanX; i++) {
1306 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001307 if (mOccupied.cells[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001308 continue inner;
1309 }
Michael Jurkac28de512010-08-13 11:27:44 -07001310 }
1311 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001312 xSize = minSpanX;
1313 ySize = minSpanY;
1314
1315 // We know that the item will fit at _some_ acceptable size, now let's see
1316 // how big we can make it. We'll alternate between incrementing x and y spans
1317 // until we hit a limit.
1318 boolean incX = true;
1319 boolean hitMaxX = xSize >= spanX;
1320 boolean hitMaxY = ySize >= spanY;
1321 while (!(hitMaxX && hitMaxY)) {
1322 if (incX && !hitMaxX) {
1323 for (int j = 0; j < ySize; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001324 if (x + xSize > countX -1 || mOccupied.cells[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001325 // We can't move out horizontally
1326 hitMaxX = true;
1327 }
1328 }
1329 if (!hitMaxX) {
1330 xSize++;
1331 }
1332 } else if (!hitMaxY) {
1333 for (int i = 0; i < xSize; i++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001334 if (y + ySize > countY - 1 || mOccupied.cells[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001335 // We can't move out vertically
1336 hitMaxY = true;
1337 }
1338 }
1339 if (!hitMaxY) {
1340 ySize++;
1341 }
1342 }
1343 hitMaxX |= xSize >= spanX;
1344 hitMaxY |= ySize >= spanY;
1345 incX = !incX;
1346 }
Michael Jurkac28de512010-08-13 11:27:44 -07001347 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001348 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001349 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001350
Adam Cohend41fbf52012-02-16 23:53:59 -08001351 // We verify that the current rect is not a sub-rect of any of our previous
1352 // candidates. In this case, the current rect is disqualified in favour of the
1353 // containing rect.
Sebastian Franco4a922672022-10-27 16:42:24 -07001354 Rect currentRect = new Rect(x, y, x + xSize, y + ySize);
Adam Cohend41fbf52012-02-16 23:53:59 -08001355 boolean contained = false;
1356 for (Rect r : validRegions) {
1357 if (r.contains(currentRect)) {
1358 contained = true;
1359 break;
1360 }
1361 }
1362 validRegions.push(currentRect);
Sebastian Francob57c0b22022-06-28 13:54:35 -07001363 double distance = Math.hypot(cellXY[0] - relativeXPos, cellXY[1] - relativeYPos);
Adam Cohen482ed822012-03-02 14:15:13 -08001364
Adam Cohend41fbf52012-02-16 23:53:59 -08001365 if ((distance <= bestDistance && !contained) ||
1366 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001367 bestDistance = distance;
1368 bestXY[0] = x;
1369 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001370 if (resultSpan != null) {
1371 resultSpan[0] = xSize;
1372 resultSpan[1] = ySize;
1373 }
1374 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001375 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001376 }
1377 }
1378
Adam Cohenc0dcf592011-06-01 15:30:43 -07001379 // Return -1, -1 if no suitable location found
1380 if (bestDistance == Double.MAX_VALUE) {
1381 bestXY[0] = -1;
1382 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001383 }
Adam Cohenc0dcf592011-06-01 15:30:43 -07001384 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001385 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001386
Sebastian Francoe4c03452022-12-27 14:50:02 -06001387 public GridOccupancy getOccupied() {
1388 return mOccupied;
1389 }
1390
Adam Cohen482ed822012-03-02 14:15:13 -08001391 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001392 mTmpOccupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001393
Michael Jurkaa52570f2012-03-20 03:18:20 -07001394 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001395 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001396 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001397 if (child == dragView) continue;
Sebastian Francod4682992022-10-05 13:03:09 -05001398 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001399 CellAndSpan c = solution.map.get(child);
1400 if (c != null) {
Sebastian Franco877088e2023-01-03 15:16:22 -07001401 lp.setTmpCellX(c.cellX);
1402 lp.setTmpCellY(c.cellY);
Adam Cohen8baab352012-03-20 17:39:21 -07001403 lp.cellHSpan = c.spanX;
1404 lp.cellVSpan = c.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001405 mTmpOccupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001406 }
1407 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001408 mTmpOccupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001409 }
1410
1411 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1412 commitDragView) {
1413
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001414 GridOccupancy occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1415 occupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001416
Michael Jurkaa52570f2012-03-20 03:18:20 -07001417 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001418 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001419 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001420 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001421 CellAndSpan c = solution.map.get(child);
1422 if (c != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001423 animateChildToPosition(child, c.cellX, c.cellY, REORDER_ANIMATION_DURATION, 0,
Adam Cohen19f37922012-03-21 11:59:11 -07001424 DESTRUCTIVE_REORDER, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001425 occupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001426 }
1427 }
1428 if (commitDragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001429 occupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001430 }
1431 }
1432
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001433
1434 // This method starts or changes the reorder preview animations
1435 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
Adam Cohen65086992020-02-19 08:40:49 -08001436 View dragView, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07001437 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07001438 for (int i = 0; i < childCount; i++) {
1439 View child = mShortcutsAndWidgets.getChildAt(i);
1440 if (child == dragView) continue;
1441 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001442 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
1443 != null && !solution.intersectingViews.contains(child);
1444
Adam Cohend9162062020-03-24 16:35:35 -07001445
Sebastian Francod4682992022-10-05 13:03:09 -05001446 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohend9162062020-03-24 16:35:35 -07001447 if (c != null && !skip && (child instanceof Reorderable)) {
Sunny Goyal82dfc152023-02-24 16:50:09 -08001448 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child,
Sebastian Franco877088e2023-01-03 15:16:22 -07001449 mode, lp.getCellX(), lp.getCellY(), c.cellX, c.cellY, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07001450 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07001451 }
1452 }
1453 }
1454
Sunny Goyal849c6a22018-08-08 16:33:46 -07001455 private static final Property<ReorderPreviewAnimation, Float> ANIMATION_PROGRESS =
1456 new Property<ReorderPreviewAnimation, Float>(float.class, "animationProgress") {
1457 @Override
1458 public Float get(ReorderPreviewAnimation anim) {
1459 return anim.animationProgress;
1460 }
1461
1462 @Override
1463 public void set(ReorderPreviewAnimation anim, Float progress) {
1464 anim.setAnimationProgress(progress);
1465 }
1466 };
1467
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001468 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07001469 // in a temporary state, and hint at where the item will return to.
Sunny Goyal82dfc152023-02-24 16:50:09 -08001470 class ReorderPreviewAnimation<T extends View & Reorderable> {
1471 final T child;
Adam Cohend024f982012-05-23 18:26:45 -07001472 float finalDeltaX;
1473 float finalDeltaY;
1474 float initDeltaX;
1475 float initDeltaY;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001476 final float finalScale;
Adam Cohend024f982012-05-23 18:26:45 -07001477 float initScale;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001478 final int mode;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001479 boolean repeating = false;
1480 private static final int PREVIEW_DURATION = 300;
1481 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
1482
Jon Miranda21266912016-12-19 14:12:05 -08001483 private static final float CHILD_DIVIDEND = 4.0f;
1484
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001485 public static final int MODE_HINT = 0;
1486 public static final int MODE_PREVIEW = 1;
1487
Sunny Goyal849c6a22018-08-08 16:33:46 -07001488 float animationProgress = 0;
Sunny Goyalf0b6db72018-08-13 16:10:14 -07001489 ValueAnimator a;
Adam Cohen19f37922012-03-21 11:59:11 -07001490
Sunny Goyal82dfc152023-02-24 16:50:09 -08001491 ReorderPreviewAnimation(View childView, int mode, int cellX0, int cellY0,
Adam Cohend9162062020-03-24 16:35:35 -07001492 int cellX1, int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07001493 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
1494 final int x0 = mTmpPoint[0];
1495 final int y0 = mTmpPoint[1];
1496 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
1497 final int x1 = mTmpPoint[0];
1498 final int y1 = mTmpPoint[1];
1499 final int dX = x1 - x0;
1500 final int dY = y1 - y0;
Jon Miranda21266912016-12-19 14:12:05 -08001501
Sunny Goyal82dfc152023-02-24 16:50:09 -08001502 this.child = (T) childView;
Jon Miranda21266912016-12-19 14:12:05 -08001503 this.mode = mode;
Adam Cohend9162062020-03-24 16:35:35 -07001504 finalDeltaX = 0;
1505 finalDeltaY = 0;
Adam Cohen65086992020-02-19 08:40:49 -08001506
Sunny Goyal82dfc152023-02-24 16:50:09 -08001507 MultiTranslateDelegate mtd = child.getTranslateDelegate();
1508 initDeltaX = mtd.getTranslationX(INDEX_REORDER_BOUNCE_OFFSET).getValue();
1509 initDeltaY = mtd.getTranslationY(INDEX_REORDER_BOUNCE_OFFSET).getValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001510 initScale = child.getReorderBounceScale();
Sunny Goyal82dfc152023-02-24 16:50:09 -08001511 finalScale = mChildScale - (CHILD_DIVIDEND / child.getWidth()) * initScale;
Adam Cohend9162062020-03-24 16:35:35 -07001512
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001513 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07001514 if (dX == dY && dX == 0) {
1515 } else {
1516 if (dY == 0) {
Adam Cohend9162062020-03-24 16:35:35 -07001517 finalDeltaX = -dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001518 } else if (dX == 0) {
Adam Cohend9162062020-03-24 16:35:35 -07001519 finalDeltaY = -dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001520 } else {
1521 double angle = Math.atan( (float) (dY) / dX);
Adam Cohend9162062020-03-24 16:35:35 -07001522 finalDeltaX = (int) (-dir * Math.signum(dX)
1523 * Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
1524 finalDeltaY = (int) (-dir * Math.signum(dY)
1525 * Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07001526 }
1527 }
Jon Miranda21266912016-12-19 14:12:05 -08001528 }
1529
Adam Cohend9162062020-03-24 16:35:35 -07001530 void setInitialAnimationValuesToBaseline() {
1531 initScale = mChildScale;
1532 initDeltaX = 0;
1533 initDeltaY = 0;
Adam Cohen19f37922012-03-21 11:59:11 -07001534 }
1535
Adam Cohend024f982012-05-23 18:26:45 -07001536 void animate() {
Adam Cohend9162062020-03-24 16:35:35 -07001537 boolean noMovement = (finalDeltaX == 0) && (finalDeltaY == 0);
Jon Miranda21266912016-12-19 14:12:05 -08001538
Adam Cohen19f37922012-03-21 11:59:11 -07001539 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001540 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohen19f37922012-03-21 11:59:11 -07001541 mShakeAnimators.remove(child);
Adam Cohend9162062020-03-24 16:35:35 -07001542
Jon Miranda21266912016-12-19 14:12:05 -08001543 if (noMovement) {
Adam Cohend9162062020-03-24 16:35:35 -07001544 // A previous animation for this item exists, and no new animation will exist.
1545 // Finish the old animation smoothly.
1546 oldAnimation.finishAnimation();
Adam Cohene7587d22012-05-24 18:50:02 -07001547 return;
Adam Cohend9162062020-03-24 16:35:35 -07001548 } else {
1549 // A previous animation for this item exists, and a new one will exist. Stop
1550 // the old animation in its tracks, and proceed with the new one.
1551 oldAnimation.cancel();
Adam Cohene7587d22012-05-24 18:50:02 -07001552 }
Adam Cohen19f37922012-03-21 11:59:11 -07001553 }
Jon Miranda21266912016-12-19 14:12:05 -08001554 if (noMovement) {
Adam Cohen19f37922012-03-21 11:59:11 -07001555 return;
1556 }
Adam Cohend9162062020-03-24 16:35:35 -07001557
Sunny Goyal849c6a22018-08-08 16:33:46 -07001558 ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS, 0, 1);
Adam Cohene7587d22012-05-24 18:50:02 -07001559 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07001560
1561 // Animations are disabled in power save mode, causing the repeated animation to jump
1562 // spastically between beginning and end states. Since this looks bad, we don't repeat
1563 // the animation in power save mode.
Sunny Goyaleaf7a952020-07-29 16:54:20 -07001564 if (areAnimatorsEnabled()) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07001565 va.setRepeatMode(ValueAnimator.REVERSE);
1566 va.setRepeatCount(ValueAnimator.INFINITE);
1567 }
1568
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001569 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07001570 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07001571 va.addListener(new AnimatorListenerAdapter() {
1572 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07001573 // We make sure to end only after a full period
Adam Cohend9162062020-03-24 16:35:35 -07001574 setInitialAnimationValuesToBaseline();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001575 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07001576 }
1577 });
Adam Cohen19f37922012-03-21 11:59:11 -07001578 mShakeAnimators.put(child, this);
1579 va.start();
1580 }
1581
Sunny Goyal849c6a22018-08-08 16:33:46 -07001582 private void setAnimationProgress(float progress) {
1583 animationProgress = progress;
1584 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : animationProgress;
1585 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
1586 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Sunny Goyal82dfc152023-02-24 16:50:09 -08001587 child.getTranslateDelegate().setTranslation(INDEX_REORDER_BOUNCE_OFFSET, x, y);
Sunny Goyal849c6a22018-08-08 16:33:46 -07001588 float s = animationProgress * finalScale + (1 - animationProgress) * initScale;
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001589 child.setReorderBounceScale(s);
Sunny Goyal849c6a22018-08-08 16:33:46 -07001590 }
1591
Adam Cohend024f982012-05-23 18:26:45 -07001592 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07001593 if (a != null) {
1594 a.cancel();
1595 }
Adam Cohen19f37922012-03-21 11:59:11 -07001596 }
Adam Cohene7587d22012-05-24 18:50:02 -07001597
Adam Cohend9162062020-03-24 16:35:35 -07001598 /**
1599 * Smoothly returns the item to its baseline position / scale
1600 */
1601 @Thunk void finishAnimation() {
Adam Cohene7587d22012-05-24 18:50:02 -07001602 if (a != null) {
1603 a.cancel();
1604 }
Brandon Keely50e6e562012-05-08 16:28:49 -07001605
Adam Cohend9162062020-03-24 16:35:35 -07001606 setInitialAnimationValuesToBaseline();
1607 ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS,
1608 animationProgress, 0);
1609 a = va;
Sunny Goyalf0b6db72018-08-13 16:10:14 -07001610 a.setInterpolator(DEACCEL_1_5);
Adam Cohend9162062020-03-24 16:35:35 -07001611 a.setDuration(REORDER_ANIMATION_DURATION);
Sunny Goyal5d2fc322015-07-06 22:52:49 -07001612 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07001613 }
Adam Cohen19f37922012-03-21 11:59:11 -07001614 }
1615
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001616 private void completeAndClearReorderPreviewAnimations() {
1617 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Adam Cohend9162062020-03-24 16:35:35 -07001618 a.finishAnimation();
Adam Cohen19f37922012-03-21 11:59:11 -07001619 }
1620 mShakeAnimators.clear();
1621 }
1622
Sunny Goyal711c5962021-06-23 12:36:18 -07001623 private void commitTempPlacement(View dragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001624 mTmpOccupied.copyTo(mOccupied);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001625
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001626 int screenId = getWorkspace().getIdForScreen(this);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001627 int container = Favorites.CONTAINER_DESKTOP;
1628
Sunny Goyalc13403c2016-11-18 23:44:48 -08001629 if (mContainerType == HOTSEAT) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001630 screenId = -1;
1631 container = Favorites.CONTAINER_HOTSEAT;
1632 }
1633
Michael Jurkaa52570f2012-03-20 03:18:20 -07001634 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001635 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07001636 View child = mShortcutsAndWidgets.getChildAt(i);
Sebastian Francod4682992022-10-05 13:03:09 -05001637 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohenea889a22012-03-27 16:45:39 -07001638 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07001639 // We do a null check here because the item info can be null in the case of the
1640 // AllApps button in the hotseat.
Sunny Goyal711c5962021-06-23 12:36:18 -07001641 if (info != null && child != dragView) {
Sunny Goyal669b71f2023-01-27 14:37:07 -08001642 CellPos presenterPos = mActivity.getCellPosMapper().mapModelToPresenter(info);
1643 final boolean requiresDbUpdate = (presenterPos.cellX != lp.getTmpCellX()
1644 || presenterPos.cellY != lp.getTmpCellY() || info.spanX != lp.cellHSpan
1645 || info.spanY != lp.cellVSpan || presenterPos.screenId != screenId);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001646
Sebastian Franco877088e2023-01-03 15:16:22 -07001647 lp.setCellX(lp.getTmpCellX());
Sebastian Franco877088e2023-01-03 15:16:22 -07001648 lp.setCellY(lp.getTmpCellY());
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001649 if (requiresDbUpdate) {
Sunny Goyalab770a12018-11-14 15:17:26 -08001650 Launcher.cast(mActivity).getModelWriter().modifyItemInDatabase(info, container,
Sunny Goyal669b71f2023-01-27 14:37:07 -08001651 screenId, lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001652 }
Adam Cohen2acce882012-03-28 19:03:19 -07001653 }
Adam Cohen482ed822012-03-02 14:15:13 -08001654 }
1655 }
1656
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001657 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001658 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001659 for (int i = 0; i < childCount; i++) {
Sebastian Francod4682992022-10-05 13:03:09 -05001660 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) mShortcutsAndWidgets.getChildAt(
1661 i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08001662 lp.useTmpCoords = useTempCoords;
1663 }
1664 }
1665
Adam Cohen19f37922012-03-21 11:59:11 -07001666 // For a given cell and span, fetch the set of views intersecting the region.
Sebastian Francoe4c03452022-12-27 14:50:02 -06001667 public void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
Adam Cohen19f37922012-03-21 11:59:11 -07001668 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
1669 if (boundingRect != null) {
1670 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
1671 }
1672 intersectingViews.clear();
1673 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1674 Rect r1 = new Rect();
1675 final int count = mShortcutsAndWidgets.getChildCount();
1676 for (int i = 0; i < count; i++) {
1677 View child = mShortcutsAndWidgets.getChildAt(i);
1678 if (child == dragView) continue;
Sebastian Francod4682992022-10-05 13:03:09 -05001679 CellLayoutLayoutParams
1680 lp = (CellLayoutLayoutParams) child.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07001681 r1.set(lp.getCellX(), lp.getCellY(), lp.getCellX() + lp.cellHSpan,
1682 lp.getCellY() + lp.cellVSpan);
Adam Cohen19f37922012-03-21 11:59:11 -07001683 if (Rect.intersects(r0, r1)) {
1684 mIntersectingViews.add(child);
1685 if (boundingRect != null) {
1686 boundingRect.union(r1);
1687 }
1688 }
1689 }
1690 }
1691
Sebastian Francoe4c03452022-12-27 14:50:02 -06001692 public boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
Adam Cohen19f37922012-03-21 11:59:11 -07001693 View dragView, int[] result) {
Sebastián Francof9a6ac22022-11-15 22:56:37 +00001694 result = findNearestAreaIgnoreOccupied(pixelX, pixelY, spanX, spanY, result);
Adam Cohen19f37922012-03-21 11:59:11 -07001695 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
1696 mIntersectingViews);
1697 return !mIntersectingViews.isEmpty();
1698 }
1699
1700 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001701 completeAndClearReorderPreviewAnimations();
1702 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
1703 final int count = mShortcutsAndWidgets.getChildCount();
1704 for (int i = 0; i < count; i++) {
1705 View child = mShortcutsAndWidgets.getChildAt(i);
Sebastian Francod4682992022-10-05 13:03:09 -05001706 CellLayoutLayoutParams
1707 lp = (CellLayoutLayoutParams) child.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07001708 if (lp.getTmpCellX() != lp.getCellX() || lp.getTmpCellY() != lp.getCellY()) {
1709 lp.setTmpCellX(lp.getCellX());
1710 lp.setTmpCellY(lp.getCellY());
1711 animateChildToPosition(child, lp.getCellX(), lp.getCellY(),
1712 REORDER_ANIMATION_DURATION, 0, false, false);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001713 }
Adam Cohen19f37922012-03-21 11:59:11 -07001714 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001715 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07001716 }
Adam Cohen19f37922012-03-21 11:59:11 -07001717 }
1718
Adam Cohenbebf0422012-04-11 18:06:28 -07001719 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
1720 View dragView, int[] direction, boolean commit) {
1721 int[] pixelXY = new int[2];
1722 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
1723
1724 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001725 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Sebastian Francof153d912022-04-22 16:15:27 -05001726 spanX, spanY, direction, dragView, true, new ItemConfiguration());
Adam Cohenbebf0422012-04-11 18:06:28 -07001727
1728 setUseTempCoords(true);
1729 if (swapSolution != null && swapSolution.isSolution) {
1730 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
1731 // committing anything or animating anything as we just want to determine if a solution
1732 // exists
1733 copySolutionToTempState(swapSolution, dragView);
1734 setItemPlacementDirty(true);
1735 animateItemsToSolution(swapSolution, dragView, commit);
1736
1737 if (commit) {
Sunny Goyal711c5962021-06-23 12:36:18 -07001738 commitTempPlacement(null);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001739 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07001740 setItemPlacementDirty(false);
1741 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001742 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
Adam Cohen65086992020-02-19 08:40:49 -08001743 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07001744 }
1745 mShortcutsAndWidgets.requestLayout();
1746 }
1747 return swapSolution.isSolution;
1748 }
1749
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001750 /**
1751 * Find a vacant area that will fit the given bounds nearest the requested
1752 * cell location, and will also weigh in a suggested direction vector of the
1753 * desired location. This method computers distance based on unit grid distances,
1754 * not pixel distances.
1755 *
1756 * @param cellX The X cell nearest to which you want to search for a vacant area.
1757 * @param cellY The Y cell nearest which you want to search for a vacant area.
1758 * @param spanX Horizontal span of the object.
1759 * @param spanY Vertical span of the object.
1760 * @param direction The favored direction in which the views should move from x, y
1761 * @param occupied The array which represents which cells in the CellLayout are occupied
1762 * @param blockOccupied The array which represents which cells in the specified block (cellX,
1763 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
1764 * @param result Array in which to place the result, or null (in which case a new array will
1765 * be allocated)
1766 * @return The X, Y cell of a vacant area that can contain this object,
1767 * nearest the requested location.
1768 */
1769 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
1770 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
1771 // Keep track of best-scoring drop area
1772 final int[] bestXY = result != null ? result : new int[2];
1773 float bestDistance = Float.MAX_VALUE;
1774 int bestDirectionScore = Integer.MIN_VALUE;
Adam Cohen482ed822012-03-02 14:15:13 -08001775
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001776 final int countX = mCountX;
1777 final int countY = mCountY;
1778
1779 for (int y = 0; y < countY - (spanY - 1); y++) {
1780 inner:
1781 for (int x = 0; x < countX - (spanX - 1); x++) {
1782 // First, let's see if this thing fits anywhere
1783 for (int i = 0; i < spanX; i++) {
1784 for (int j = 0; j < spanY; j++) {
1785 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1786 continue inner;
1787 }
1788 }
1789 }
1790
1791 float distance = (float) Math.hypot(x - cellX, y - cellY);
1792 int[] curDirection = mTmpPoint;
1793 computeDirectionVector(x - cellX, y - cellY, curDirection);
1794 // The direction score is just the dot product of the two candidate direction
1795 // and that passed in.
1796 int curDirectionScore = direction[0] * curDirection[0] +
1797 direction[1] * curDirection[1];
1798 if (Float.compare(distance, bestDistance) < 0 ||
1799 (Float.compare(distance, bestDistance) == 0
1800 && curDirectionScore > bestDirectionScore)) {
1801 bestDistance = distance;
1802 bestDirectionScore = curDirectionScore;
1803 bestXY[0] = x;
1804 bestXY[1] = y;
1805 }
Adam Cohen19f37922012-03-21 11:59:11 -07001806 }
Adam Cohen19f37922012-03-21 11:59:11 -07001807 }
1808
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001809 // Return -1, -1 if no suitable location found
1810 if (bestDistance == Float.MAX_VALUE) {
1811 bestXY[0] = -1;
1812 bestXY[1] = -1;
Sebastian Franco53a15a42022-10-25 17:28:54 -07001813 }
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001814 return bestXY;
1815 }
1816
1817 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
1818 int[] direction, ItemConfiguration currentState) {
1819 CellAndSpan c = currentState.map.get(v);
1820 boolean success = false;
1821 mTmpOccupied.markCells(c, false);
1822 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
1823
1824 findNearestArea(c.cellX, c.cellY, c.spanX, c.spanY, direction,
1825 mTmpOccupied.cells, null, mTempLocation);
1826
1827 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
1828 c.cellX = mTempLocation[0];
1829 c.cellY = mTempLocation[1];
1830 success = true;
1831 }
1832 mTmpOccupied.markCells(c, true);
1833 return success;
1834 }
1835
1836 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1837 int[] direction, View dragView, ItemConfiguration currentState) {
1838
1839 ViewCluster cluster = new ViewCluster(views, currentState);
1840 Rect clusterRect = cluster.getBoundingRect();
1841 int whichEdge;
1842 int pushDistance;
1843 boolean fail = false;
1844
1845 // Determine the edge of the cluster that will be leading the push and how far
1846 // the cluster must be shifted.
1847 if (direction[0] < 0) {
1848 whichEdge = ViewCluster.LEFT;
1849 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
1850 } else if (direction[0] > 0) {
1851 whichEdge = ViewCluster.RIGHT;
1852 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1853 } else if (direction[1] < 0) {
1854 whichEdge = ViewCluster.TOP;
1855 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1856 } else {
1857 whichEdge = ViewCluster.BOTTOM;
1858 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
1859 }
1860
1861 // Break early for invalid push distance.
1862 if (pushDistance <= 0) {
1863 return false;
1864 }
1865
1866 // Mark the occupied state as false for the group of views we want to move.
1867 for (View v: views) {
1868 CellAndSpan c = currentState.map.get(v);
1869 mTmpOccupied.markCells(c, false);
1870 }
1871
1872 // We save the current configuration -- if we fail to find a solution we will revert
1873 // to the initial state. The process of finding a solution modifies the configuration
1874 // in place, hence the need for revert in the failure case.
1875 currentState.save();
1876
1877 // The pushing algorithm is simplified by considering the views in the order in which
1878 // they would be pushed by the cluster. For example, if the cluster is leading with its
1879 // left edge, we consider sort the views by their right edge, from right to left.
1880 cluster.sortConfigurationForEdgePush(whichEdge);
1881
1882 while (pushDistance > 0 && !fail) {
1883 for (View v: currentState.sortedViews) {
1884 // For each view that isn't in the cluster, we see if the leading edge of the
1885 // cluster is contacting the edge of that view. If so, we add that view to the
1886 // cluster.
1887 if (!cluster.views.contains(v) && v != dragView) {
1888 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1889 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) v.getLayoutParams();
1890 if (!lp.canReorder) {
1891 // The push solution includes the all apps button, this is not viable.
1892 fail = true;
1893 break;
1894 }
1895 cluster.addView(v);
1896 CellAndSpan c = currentState.map.get(v);
1897
1898 // Adding view to cluster, mark it as not occupied.
1899 mTmpOccupied.markCells(c, false);
1900 }
1901 }
1902 }
1903 pushDistance--;
1904
1905 // The cluster has been completed, now we move the whole thing over in the appropriate
1906 // direction.
1907 cluster.shift(whichEdge, 1);
1908 }
1909
1910 boolean foundSolution = false;
1911 clusterRect = cluster.getBoundingRect();
1912
1913 // Due to the nature of the algorithm, the only check required to verify a valid solution
1914 // is to ensure that completed shifted cluster lies completely within the cell layout.
1915 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1916 clusterRect.bottom <= mCountY) {
1917 foundSolution = true;
1918 } else {
1919 currentState.restore();
1920 }
1921
1922 // In either case, we set the occupied array as marked for the location of the views
1923 for (View v: cluster.views) {
1924 CellAndSpan c = currentState.map.get(v);
1925 mTmpOccupied.markCells(c, true);
1926 }
1927
1928 return foundSolution;
1929 }
1930
1931 /**
1932 * This helper class defines a cluster of views. It helps with defining complex edges
1933 * of the cluster and determining how those edges interact with other views. The edges
1934 * essentially define a fine-grained boundary around the cluster of views -- like a more
1935 * precise version of a bounding box.
1936 */
1937 private class ViewCluster {
1938 final static int LEFT = 1 << 0;
1939 final static int TOP = 1 << 1;
1940 final static int RIGHT = 1 << 2;
1941 final static int BOTTOM = 1 << 3;
1942
1943 final ArrayList<View> views;
1944 final ItemConfiguration config;
1945 final Rect boundingRect = new Rect();
1946
1947 final int[] leftEdge = new int[mCountY];
1948 final int[] rightEdge = new int[mCountY];
1949 final int[] topEdge = new int[mCountX];
1950 final int[] bottomEdge = new int[mCountX];
1951 int dirtyEdges;
1952 boolean boundingRectDirty;
1953
1954 @SuppressWarnings("unchecked")
1955 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1956 this.views = (ArrayList<View>) views.clone();
1957 this.config = config;
1958 resetEdges();
1959 }
1960
1961 void resetEdges() {
1962 for (int i = 0; i < mCountX; i++) {
1963 topEdge[i] = -1;
1964 bottomEdge[i] = -1;
1965 }
1966 for (int i = 0; i < mCountY; i++) {
1967 leftEdge[i] = -1;
1968 rightEdge[i] = -1;
1969 }
1970 dirtyEdges = LEFT | TOP | RIGHT | BOTTOM;
1971 boundingRectDirty = true;
1972 }
1973
1974 void computeEdge(int which) {
1975 int count = views.size();
1976 for (int i = 0; i < count; i++) {
1977 CellAndSpan cs = config.map.get(views.get(i));
1978 switch (which) {
1979 case LEFT:
1980 int left = cs.cellX;
1981 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
1982 if (left < leftEdge[j] || leftEdge[j] < 0) {
1983 leftEdge[j] = left;
1984 }
1985 }
1986 break;
1987 case RIGHT:
1988 int right = cs.cellX + cs.spanX;
1989 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
1990 if (right > rightEdge[j]) {
1991 rightEdge[j] = right;
1992 }
1993 }
1994 break;
1995 case TOP:
1996 int top = cs.cellY;
1997 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
1998 if (top < topEdge[j] || topEdge[j] < 0) {
1999 topEdge[j] = top;
2000 }
2001 }
2002 break;
2003 case BOTTOM:
2004 int bottom = cs.cellY + cs.spanY;
2005 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
2006 if (bottom > bottomEdge[j]) {
2007 bottomEdge[j] = bottom;
2008 }
2009 }
2010 break;
2011 }
2012 }
2013 }
2014
2015 boolean isViewTouchingEdge(View v, int whichEdge) {
2016 CellAndSpan cs = config.map.get(v);
2017
2018 if ((dirtyEdges & whichEdge) == whichEdge) {
2019 computeEdge(whichEdge);
2020 dirtyEdges &= ~whichEdge;
2021 }
2022
2023 switch (whichEdge) {
2024 case LEFT:
2025 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
2026 if (leftEdge[i] == cs.cellX + cs.spanX) {
2027 return true;
2028 }
2029 }
2030 break;
2031 case RIGHT:
2032 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
2033 if (rightEdge[i] == cs.cellX) {
2034 return true;
2035 }
2036 }
2037 break;
2038 case TOP:
2039 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
2040 if (topEdge[i] == cs.cellY + cs.spanY) {
2041 return true;
2042 }
2043 }
2044 break;
2045 case BOTTOM:
2046 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
2047 if (bottomEdge[i] == cs.cellY) {
2048 return true;
2049 }
2050 }
2051 break;
2052 }
2053 return false;
2054 }
2055
2056 void shift(int whichEdge, int delta) {
2057 for (View v: views) {
2058 CellAndSpan c = config.map.get(v);
2059 switch (whichEdge) {
2060 case LEFT:
2061 c.cellX -= delta;
2062 break;
2063 case RIGHT:
2064 c.cellX += delta;
2065 break;
2066 case TOP:
2067 c.cellY -= delta;
2068 break;
2069 case BOTTOM:
2070 default:
2071 c.cellY += delta;
2072 break;
2073 }
2074 }
2075 resetEdges();
2076 }
2077
2078 public void addView(View v) {
2079 views.add(v);
2080 resetEdges();
2081 }
2082
2083 public Rect getBoundingRect() {
2084 if (boundingRectDirty) {
2085 config.getBoundingRectForViews(views, boundingRect);
2086 }
2087 return boundingRect;
2088 }
2089
2090 final PositionComparator comparator = new PositionComparator();
2091 class PositionComparator implements Comparator<View> {
2092 int whichEdge = 0;
2093 public int compare(View left, View right) {
2094 CellAndSpan l = config.map.get(left);
2095 CellAndSpan r = config.map.get(right);
2096 switch (whichEdge) {
2097 case LEFT:
2098 return (r.cellX + r.spanX) - (l.cellX + l.spanX);
2099 case RIGHT:
2100 return l.cellX - r.cellX;
2101 case TOP:
2102 return (r.cellY + r.spanY) - (l.cellY + l.spanY);
2103 case BOTTOM:
2104 default:
2105 return l.cellY - r.cellY;
2106 }
2107 }
2108 }
2109
2110 public void sortConfigurationForEdgePush(int edge) {
2111 comparator.whichEdge = edge;
2112 Collections.sort(config.sortedViews, comparator);
2113 }
2114 }
2115
2116 // This method tries to find a reordering solution which satisfies the push mechanic by trying
2117 // to push items in each of the cardinal directions, in an order based on the direction vector
2118 // passed.
2119 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
2120 int[] direction, View ignoreView, ItemConfiguration solution) {
2121 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
2122 // If the direction vector has two non-zero components, we try pushing
2123 // separately in each of the components.
2124 int temp = direction[1];
2125 direction[1] = 0;
2126
2127 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2128 ignoreView, solution)) {
2129 return true;
2130 }
2131 direction[1] = temp;
2132 temp = direction[0];
2133 direction[0] = 0;
2134
2135 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2136 ignoreView, solution)) {
2137 return true;
2138 }
2139 // Revert the direction
2140 direction[0] = temp;
2141
2142 // Now we try pushing in each component of the opposite direction
2143 direction[0] *= -1;
2144 direction[1] *= -1;
2145 temp = direction[1];
2146 direction[1] = 0;
2147 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2148 ignoreView, solution)) {
2149 return true;
2150 }
2151
2152 direction[1] = temp;
2153 temp = direction[0];
2154 direction[0] = 0;
2155 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2156 ignoreView, solution)) {
2157 return true;
2158 }
2159 // revert the direction
2160 direction[0] = temp;
2161 direction[0] *= -1;
2162 direction[1] *= -1;
2163
2164 } else {
2165 // If the direction vector has a single non-zero component, we push first in the
2166 // direction of the vector
2167 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2168 ignoreView, solution)) {
2169 return true;
2170 }
2171 // Then we try the opposite direction
2172 direction[0] *= -1;
2173 direction[1] *= -1;
2174 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2175 ignoreView, solution)) {
2176 return true;
2177 }
2178 // Switch the direction back
2179 direction[0] *= -1;
2180 direction[1] *= -1;
2181
2182 // If we have failed to find a push solution with the above, then we try
2183 // to find a solution by pushing along the perpendicular axis.
2184
2185 // Swap the components
2186 int temp = direction[1];
2187 direction[1] = direction[0];
2188 direction[0] = temp;
2189 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2190 ignoreView, solution)) {
2191 return true;
2192 }
2193
2194 // Then we try the opposite direction
2195 direction[0] *= -1;
2196 direction[1] *= -1;
2197 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2198 ignoreView, solution)) {
2199 return true;
2200 }
2201 // Switch the direction back
2202 direction[0] *= -1;
2203 direction[1] *= -1;
2204
2205 // Swap the components back
2206 temp = direction[1];
2207 direction[1] = direction[0];
2208 direction[0] = temp;
2209 }
2210 return false;
2211 }
2212
2213 /*
2214 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
2215 * the provided point and the provided cell
2216 */
2217 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
2218 double angle = Math.atan(deltaY / deltaX);
2219
2220 result[0] = 0;
2221 result[1] = 0;
2222 if (Math.abs(Math.cos(angle)) > 0.5f) {
2223 result[0] = (int) Math.signum(deltaX);
2224 }
2225 if (Math.abs(Math.sin(angle)) > 0.5f) {
2226 result[1] = (int) Math.signum(deltaY);
2227 }
2228 }
2229
2230 /* This seems like it should be obvious and straight-forward, but when the direction vector
2231 needs to match with the notion of the dragView pushing other views, we have to employ
2232 a slightly more subtle notion of the direction vector. The question is what two points is
2233 the vector between? The center of the dragView and its desired destination? Not quite, as
2234 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2235 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2236 or right, which helps make pushing feel right.
2237 */
Sebastian Francoe4c03452022-12-27 14:50:02 -06002238 public void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002239 int spanY, View dragView, int[] resultDirection) {
2240
2241 //TODO(adamcohen) b/151776141 use the items visual center for the direction vector
2242 int[] targetDestination = new int[2];
2243
Sebastián Francof9a6ac22022-11-15 22:56:37 +00002244 findNearestAreaIgnoreOccupied(dragViewCenterX, dragViewCenterY, spanX, spanY,
2245 targetDestination);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002246 Rect dragRect = new Rect();
2247 cellToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2248 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2249
2250 Rect dropRegionRect = new Rect();
2251 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2252 dragView, dropRegionRect, mIntersectingViews);
2253
2254 int dropRegionSpanX = dropRegionRect.width();
2255 int dropRegionSpanY = dropRegionRect.height();
2256
2257 cellToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2258 dropRegionRect.height(), dropRegionRect);
2259
2260 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2261 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2262
2263 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2264 deltaX = 0;
2265 }
2266 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2267 deltaY = 0;
2268 }
2269
2270 if (deltaX == 0 && deltaY == 0) {
2271 // No idea what to do, give a random direction.
2272 resultDirection[0] = 1;
2273 resultDirection[1] = 0;
2274 } else {
2275 computeDirectionVector(deltaX, deltaY, resultDirection);
2276 }
2277 }
2278
2279 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
2280 int[] direction, View dragView, ItemConfiguration currentState) {
2281 if (views.size() == 0) return true;
2282
2283 boolean success = false;
2284 Rect boundingRect = new Rect();
2285 // We construct a rect which represents the entire group of views passed in
2286 currentState.getBoundingRectForViews(views, boundingRect);
2287
2288 // Mark the occupied state as false for the group of views we want to move.
2289 for (View v: views) {
2290 CellAndSpan c = currentState.map.get(v);
2291 mTmpOccupied.markCells(c, false);
2292 }
2293
2294 GridOccupancy blockOccupied = new GridOccupancy(boundingRect.width(), boundingRect.height());
2295 int top = boundingRect.top;
2296 int left = boundingRect.left;
2297 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
2298 // for interlocking.
2299 for (View v: views) {
2300 CellAndSpan c = currentState.map.get(v);
2301 blockOccupied.markCells(c.cellX - left, c.cellY - top, c.spanX, c.spanY, true);
2302 }
2303
2304 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
2305
2306 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
2307 boundingRect.height(), direction,
2308 mTmpOccupied.cells, blockOccupied.cells, mTempLocation);
2309
2310 // If we successfully found a location by pushing the block of views, we commit it
2311 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
2312 int deltaX = mTempLocation[0] - boundingRect.left;
2313 int deltaY = mTempLocation[1] - boundingRect.top;
2314 for (View v: views) {
2315 CellAndSpan c = currentState.map.get(v);
2316 c.cellX += deltaX;
2317 c.cellY += deltaY;
2318 }
2319 success = true;
2320 }
2321
2322 // In either case, we set the occupied array as marked for the location of the views
2323 for (View v: views) {
2324 CellAndSpan c = currentState.map.get(v);
2325 mTmpOccupied.markCells(c, true);
2326 }
2327 return success;
2328 }
2329
Sebastian Francoe4c03452022-12-27 14:50:02 -06002330 public boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002331 View ignoreView, ItemConfiguration solution) {
2332 // Return early if get invalid cell positions
2333 if (cellX < 0 || cellY < 0) return false;
2334
2335 mIntersectingViews.clear();
2336 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2337
2338 // Mark the desired location of the view currently being dragged.
2339 if (ignoreView != null) {
2340 CellAndSpan c = solution.map.get(ignoreView);
2341 if (c != null) {
2342 c.cellX = cellX;
2343 c.cellY = cellY;
2344 }
2345 }
2346 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2347 Rect r1 = new Rect();
2348 for (View child: solution.map.keySet()) {
2349 if (child == ignoreView) continue;
2350 CellAndSpan c = solution.map.get(child);
2351 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
2352 r1.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2353 if (Rect.intersects(r0, r1)) {
2354 if (!lp.canReorder) {
2355 return false;
2356 }
2357 mIntersectingViews.add(child);
2358 }
2359 }
2360
2361 solution.intersectingViews = new ArrayList<>(mIntersectingViews);
2362
2363 // First we try to find a solution which respects the push mechanic. That is,
2364 // we try to find a solution such that no displaced item travels through another item
2365 // without also displacing that item.
2366 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
2367 solution)) {
2368 return true;
2369 }
2370
2371 // Next we try moving the views as a block, but without requiring the push mechanic.
2372 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
2373 solution)) {
2374 return true;
2375 }
2376
2377 // Ok, they couldn't move as a block, let's move them individually
2378 for (View v : mIntersectingViews) {
2379 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
2380 return false;
2381 }
2382 }
2383 return true;
2384 }
2385
Sebastian Francoe4c03452022-12-27 14:50:02 -06002386 public ReorderAlgorithm createReorderAlgorithm() {
2387 return new ReorderAlgorithm(this);
2388 }
2389
Sebastian Franco09589322022-11-02 15:25:58 -07002390 protected ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX,
2391 int minSpanY, int spanX, int spanY, int[] direction, View dragView, boolean decX,
2392 ItemConfiguration solution) {
Sebastian Francoe4c03452022-12-27 14:50:02 -06002393 return createReorderAlgorithm().findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
2394 spanX, spanY, direction, dragView, decX, solution);
Sebastian Franco09589322022-11-02 15:25:58 -07002395 }
2396
Sebastian Francoe4c03452022-12-27 14:50:02 -06002397 public void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002398 int childCount = mShortcutsAndWidgets.getChildCount();
2399 for (int i = 0; i < childCount; i++) {
2400 View child = mShortcutsAndWidgets.getChildAt(i);
2401 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
2402 CellAndSpan c;
2403 if (temp) {
Sebastian Franco877088e2023-01-03 15:16:22 -07002404 c = new CellAndSpan(lp.getTmpCellX(), lp.getTmpCellY(), lp.cellHSpan, lp.cellVSpan);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002405 } else {
Sebastian Franco877088e2023-01-03 15:16:22 -07002406 c = new CellAndSpan(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002407 }
2408 solution.add(child, c);
2409 }
Sebastian Franco53a15a42022-10-25 17:28:54 -07002410 }
2411
2412 /**
Sebastian Franco53a15a42022-10-25 17:28:54 -07002413 * When the user drags an Item in the workspace sometimes we need to move the items already in
2414 * the workspace to make space for the new item, this function return a solution for that
2415 * reorder.
2416 *
2417 * @param pixelX X coordinate in the screen of the dragView in pixels
2418 * @param pixelY Y coordinate in the screen of the dragView in pixels
2419 * @param minSpanX minimum horizontal span the item can be shrunk to
2420 * @param minSpanY minimum vertical span the item can be shrunk to
2421 * @param spanX occupied horizontal span
2422 * @param spanY occupied vertical span
2423 * @param dragView the view of the item being draged
2424 * @return returns a solution for the given parameters, the solution contains all the icons and
2425 * the locations they should be in the given solution.
2426 */
2427 public ItemConfiguration calculateReorder(int pixelX, int pixelY, int minSpanX, int minSpanY,
2428 int spanX, int spanY, View dragView) {
Sebastian Francoe4c03452022-12-27 14:50:02 -06002429 return createReorderAlgorithm().calculateReorder(pixelX, pixelY, minSpanX, minSpanY,
2430 spanX, spanY, dragView);
Sebastian Franco53a15a42022-10-25 17:28:54 -07002431 }
Adam Cohen482ed822012-03-02 14:15:13 -08002432
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002433 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2434 View dragView, int[] result, int[] resultSpan, int mode) {
2435 if (resultSpan == null) {
2436 resultSpan = new int[]{-1, -1};
2437 }
2438 if (result == null) {
2439 result = new int[]{-1, -1};
2440 }
Sebastian Franco5d990ee2022-11-01 16:08:24 -07002441
2442 ItemConfiguration finalSolution = null;
2443 // We want the solution to match the animation of the preview and to match the drop so we
2444 // only recalculate in mode MODE_SHOW_REORDER_HINT because that the first one to run in the
2445 // reorder cycle.
2446 if (mode == MODE_SHOW_REORDER_HINT || mPreviousSolution == null) {
2447 finalSolution = calculateReorder(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY,
2448 dragView);
2449 mPreviousSolution = finalSolution;
2450 } else {
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002451 finalSolution = mPreviousSolution;
2452 // We reset this vector after drop
2453 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2454 mPreviousSolution = null;
2455 }
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002456 }
2457
2458 if (finalSolution == null || !finalSolution.isSolution) {
2459 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2460 } else {
2461 result[0] = finalSolution.cellX;
2462 result[1] = finalSolution.cellY;
2463 resultSpan[0] = finalSolution.spanX;
2464 resultSpan[1] = finalSolution.spanY;
Sebastian Franco9c743272022-11-15 15:03:25 -08002465 performReorder(finalSolution, dragView, mode);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002466 }
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002467 return result;
2468 }
2469
Sebastian Franco53a15a42022-10-25 17:28:54 -07002470 /**
2471 * Animates and submits in the DB the given ItemConfiguration depending of the mode.
2472 *
2473 * @param solution represents widgets on the screen which the Workspace will animate to and
2474 * would be submitted to the database.
2475 * @param dragView view which is being dragged over the workspace that trigger the reorder
2476 * @param mode depending on the mode different animations would be played and depending on the
2477 * mode the solution would be submitted or not the database.
2478 * The possible modes are {@link MODE_SHOW_REORDER_HINT}, {@link MODE_DRAG_OVER},
2479 * {@link MODE_ON_DROP}, {@link MODE_ON_DROP_EXTERNAL}, {@link MODE_ACCEPT_DROP}
2480 * defined in {@link CellLayout}.
2481 */
Sebastian Francoe4c03452022-12-27 14:50:02 -06002482 public void performReorder(ItemConfiguration solution, View dragView, int mode) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002483 if (mode == MODE_SHOW_REORDER_HINT) {
Sebastian Franco53a15a42022-10-25 17:28:54 -07002484 beginOrAdjustReorderPreviewAnimations(solution, dragView,
2485 ReorderPreviewAnimation.MODE_HINT);
2486 return;
2487 }
2488 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2489 // committing anything or animating anything as we just want to determine if a solution
2490 // exists
2491 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2492 if (!DESTRUCTIVE_REORDER) {
2493 setUseTempCoords(true);
2494 }
2495
2496 if (!DESTRUCTIVE_REORDER) {
2497 copySolutionToTempState(solution, dragView);
2498 }
2499 setItemPlacementDirty(true);
2500 animateItemsToSolution(solution, dragView, mode == MODE_ON_DROP);
2501
2502 if (!DESTRUCTIVE_REORDER
2503 && (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
2504 // Since the temp solution didn't update dragView, don't commit it either
2505 commitTempPlacement(dragView);
2506 completeAndClearReorderPreviewAnimations();
2507 setItemPlacementDirty(false);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002508 } else {
Sebastian Franco53a15a42022-10-25 17:28:54 -07002509 beginOrAdjustReorderPreviewAnimations(solution, dragView,
2510 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002511 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002512 }
2513
Sebastian Franco53a15a42022-10-25 17:28:54 -07002514 if (mode == MODE_ON_DROP && !DESTRUCTIVE_REORDER) {
Adam Cohen482ed822012-03-02 14:15:13 -08002515 setUseTempCoords(false);
2516 }
Adam Cohen482ed822012-03-02 14:15:13 -08002517
Michael Jurkaa52570f2012-03-20 03:18:20 -07002518 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002519 }
2520
Adam Cohen19f37922012-03-21 11:59:11 -07002521 void setItemPlacementDirty(boolean dirty) {
2522 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002523 }
Adam Cohen19f37922012-03-21 11:59:11 -07002524 boolean isItemPlacementDirty() {
2525 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002526 }
2527
Sebastian Francoe4c03452022-12-27 14:50:02 -06002528 /**
2529 * Represents the solution to a reorder of items in the Workspace.
2530 */
2531 public static class ItemConfiguration extends CellAndSpan {
2532 public final ArrayMap<View, CellAndSpan> map = new ArrayMap<>();
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002533 private final ArrayMap<View, CellAndSpan> savedMap = new ArrayMap<>();
Sebastian Francoe4c03452022-12-27 14:50:02 -06002534 public final ArrayList<View> sortedViews = new ArrayList<>();
2535 public ArrayList<View> intersectingViews;
2536 public boolean isSolution = false;
Adam Cohen482ed822012-03-02 14:15:13 -08002537
Sebastian Francoe4c03452022-12-27 14:50:02 -06002538 public void save() {
Adam Cohenf3900c22012-11-16 18:28:11 -08002539 // Copy current state into savedMap
2540 for (View v: map.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002541 savedMap.get(v).copyFrom(map.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002542 }
2543 }
2544
Sebastian Francoe4c03452022-12-27 14:50:02 -06002545 public void restore() {
Adam Cohenf3900c22012-11-16 18:28:11 -08002546 // Restore current state from savedMap
2547 for (View v: savedMap.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002548 map.get(v).copyFrom(savedMap.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002549 }
2550 }
2551
Sebastian Francoe4c03452022-12-27 14:50:02 -06002552 public void add(View v, CellAndSpan cs) {
Adam Cohenf3900c22012-11-16 18:28:11 -08002553 map.put(v, cs);
2554 savedMap.put(v, new CellAndSpan());
2555 sortedViews.add(v);
2556 }
2557
Sebastian Francoe4c03452022-12-27 14:50:02 -06002558 public int area() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002559 return spanX * spanY;
Adam Cohenf3900c22012-11-16 18:28:11 -08002560 }
2561
Sebastian Francoe4c03452022-12-27 14:50:02 -06002562 public void getBoundingRectForViews(ArrayList<View> views, Rect outRect) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002563 boolean first = true;
2564 for (View v: views) {
2565 CellAndSpan c = map.get(v);
2566 if (first) {
2567 outRect.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2568 first = false;
2569 } else {
2570 outRect.union(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2571 }
2572 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002573 }
Adam Cohen482ed822012-03-02 14:15:13 -08002574 }
2575
Adam Cohendf035382011-04-11 17:22:04 -07002576 /**
Adam Cohendf035382011-04-11 17:22:04 -07002577 * Find a starting cell position that will fit the given bounds nearest the requested
2578 * cell location. Uses Euclidean distance to score multiple vacant areas.
2579 *
2580 * @param pixelX The X location at which you want to search for a vacant area.
2581 * @param pixelY The Y location at which you want to search for a vacant area.
2582 * @param spanX Horizontal span of the object.
2583 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07002584 * @param result Previously returned value to possibly recycle.
2585 * @return The X, Y cell of a vacant area that can contain this object,
2586 * nearest the requested location.
2587 */
Sebastián Francof9a6ac22022-11-15 22:56:37 +00002588 public int[] findNearestAreaIgnoreOccupied(int pixelX, int pixelY, int spanX, int spanY,
2589 int[] result) {
Sebastian Francob57c0b22022-06-28 13:54:35 -07002590 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, true, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002591 }
2592
Michael Jurka0280c3b2010-09-17 15:00:07 -07002593 boolean existsEmptyCell() {
2594 return findCellForSpan(null, 1, 1);
2595 }
2596
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002597 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002598 * Finds the upper-left coordinate of the first rectangle in the grid that can
2599 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2600 * then this method will only return coordinates for rectangles that contain the cell
2601 * (intersectX, intersectY)
2602 *
2603 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2604 * can be found.
2605 * @param spanX The horizontal span of the cell we want to find.
2606 * @param spanY The vertical span of the cell we want to find.
2607 *
2608 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002609 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002610 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002611 if (cellXY == null) {
2612 cellXY = new int[2];
Michael Jurka0280c3b2010-09-17 15:00:07 -07002613 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002614 return mOccupied.findVacantCell(cellXY, spanX, spanY);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002615 }
2616
2617 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002618 * A drag event has begun over this layout.
2619 * It may have begun over this layout (in which case onDragChild is called first),
2620 * or it may have begun on another layout.
2621 */
2622 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002623 mDragging = true;
Sebastian Franco5aa71ce2022-12-14 12:13:19 -06002624 mPreviousSolution = null;
Winson Chungc07918d2011-07-01 15:35:26 -07002625 }
2626
2627 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002628 * Called when drag has left this CellLayout or has been completed (successfully or not)
2629 */
2630 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002631 // This can actually be called when we aren't in a drag, e.g. when adding a new
2632 // item to this layout via the customize drawer.
2633 // Guard against that case.
2634 if (mDragging) {
2635 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002636 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002637
2638 // Invalidate the drag data
Sebastian Franco5aa71ce2022-12-14 12:13:19 -06002639 mPreviousSolution = null;
Adam Cohend41fbf52012-02-16 23:53:59 -08002640 mDragCell[0] = mDragCell[1] = -1;
Adam Cohenf7ca3b42021-02-22 11:03:58 -08002641 mDragCellSpan[0] = mDragCellSpan[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002642 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2643 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002644 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002645 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002646 }
2647
2648 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002649 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002650 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002651 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002652 *
2653 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002654 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002655 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002656 if (child != null) {
Sebastian Francod4682992022-10-05 13:03:09 -05002657 CellLayoutLayoutParams
2658 lp = (CellLayoutLayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002659 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002660 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002661 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002662 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002663 }
2664
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002665 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002666 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002667 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002668 * @param cellX X coordinate of upper left corner expressed as a cell position
2669 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002670 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002671 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002672 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002673 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002674 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002675 final int cellWidth = mCellWidth;
2676 final int cellHeight = mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -07002677
Pierre Barbier de Reuille1b8bbb62021-05-19 22:45:16 +01002678 // We observe a shift of 1 pixel on the x coordinate compared to the actual cell coordinates
2679 final int hStartPadding = getPaddingLeft()
2680 + (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Winson Chung4b825dcd2011-06-19 12:41:22 -07002681 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002682
Thales Lima78d00ad2021-09-30 11:29:06 +01002683 int x = hStartPadding + (cellX * mBorderSpace.x) + (cellX * cellWidth);
2684 int y = vStartPadding + (cellY * mBorderSpace.y) + (cellY * cellHeight);
Jon Miranda228877d2021-02-09 11:05:00 -05002685
Thales Lima78d00ad2021-09-30 11:29:06 +01002686 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * mBorderSpace.x);
2687 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * mBorderSpace.y);
Winson Chungaafa03c2010-06-11 17:34:16 -07002688
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002689 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002690 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002691
Adam Cohend4844c32011-02-18 19:25:06 -08002692 public void markCellsAsOccupiedForView(View view) {
Sebastian Francof153d912022-04-22 16:15:27 -05002693 if (view instanceof LauncherAppWidgetHostView
2694 && view.getTag() instanceof LauncherAppWidgetInfo) {
2695 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
Sunny Goyal669b71f2023-01-27 14:37:07 -08002696 CellPos pos = mActivity.getCellPosMapper().mapModelToPresenter(info);
2697 mOccupied.markCells(pos.cellX, pos.cellY, info.spanX, info.spanY, true);
Sebastian Francof153d912022-04-22 16:15:27 -05002698 return;
2699 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002700 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Sebastian Francod4682992022-10-05 13:03:09 -05002701 CellLayoutLayoutParams
2702 lp = (CellLayoutLayoutParams) view.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07002703 mOccupied.markCells(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002704 }
2705
Adam Cohend4844c32011-02-18 19:25:06 -08002706 public void markCellsAsUnoccupiedForView(View view) {
Sebastian Francof153d912022-04-22 16:15:27 -05002707 if (view instanceof LauncherAppWidgetHostView
2708 && view.getTag() instanceof LauncherAppWidgetInfo) {
2709 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
Sunny Goyal669b71f2023-01-27 14:37:07 -08002710 CellPos pos = mActivity.getCellPosMapper().mapModelToPresenter(info);
2711 mOccupied.markCells(pos.cellX, pos.cellY, info.spanX, info.spanY, false);
Sebastian Francof153d912022-04-22 16:15:27 -05002712 return;
2713 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002714 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Sebastian Francod4682992022-10-05 13:03:09 -05002715 CellLayoutLayoutParams
2716 lp = (CellLayoutLayoutParams) view.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07002717 mOccupied.markCells(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002718 }
2719
Adam Cohen2801caf2011-05-13 20:57:39 -07002720 public int getDesiredWidth() {
Jon Miranda228877d2021-02-09 11:05:00 -05002721 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth)
Thales Lima78d00ad2021-09-30 11:29:06 +01002722 + ((mCountX - 1) * mBorderSpace.x);
Adam Cohen2801caf2011-05-13 20:57:39 -07002723 }
2724
2725 public int getDesiredHeight() {
Jon Miranda228877d2021-02-09 11:05:00 -05002726 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight)
Thales Lima78d00ad2021-09-30 11:29:06 +01002727 + ((mCountY - 1) * mBorderSpace.y);
Adam Cohen2801caf2011-05-13 20:57:39 -07002728 }
2729
Michael Jurka66d72172011-04-12 16:29:25 -07002730 public boolean isOccupied(int x, int y) {
2731 if (x < mCountX && y < mCountY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002732 return mOccupied.cells[x][y];
Michael Jurka66d72172011-04-12 16:29:25 -07002733 } else {
2734 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2735 }
2736 }
2737
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002738 @Override
2739 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
Sebastian Francod4682992022-10-05 13:03:09 -05002740 return new CellLayoutLayoutParams(getContext(), attrs);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002741 }
2742
2743 @Override
2744 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
Sebastian Francod4682992022-10-05 13:03:09 -05002745 return p instanceof CellLayoutLayoutParams;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002746 }
2747
2748 @Override
2749 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
Sebastian Francod4682992022-10-05 13:03:09 -05002750 return new CellLayoutLayoutParams(p);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002751 }
2752
Michael Jurka0280c3b2010-09-17 15:00:07 -07002753 // This class stores info for two purposes:
2754 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2755 // its spanX, spanY, and the screen it is on
2756 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2757 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2758 // the CellLayout that was long clicked
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002759 public static final class CellInfo extends CellAndSpan {
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002760 public final View cell;
Sunny Goyalefb7e842018-10-04 15:11:00 -07002761 final int screenId;
2762 final int container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002763
Sunny Goyal669b71f2023-01-27 14:37:07 -08002764 public CellInfo(View v, ItemInfo info, CellPos cellPos) {
2765 cellX = cellPos.cellX;
2766 cellY = cellPos.cellY;
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002767 spanX = info.spanX;
2768 spanY = info.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002769 cell = v;
Sunny Goyal669b71f2023-01-27 14:37:07 -08002770 screenId = cellPos.screenId;
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002771 container = info.container;
2772 }
2773
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002774 @Override
2775 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002776 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2777 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002778 }
2779 }
Michael Jurkad771c962011-08-09 15:00:48 -07002780
Tony Wickham86930612015-09-09 13:50:40 -07002781 /**
Samuel Fufa1e2d0042019-11-18 17:12:46 -08002782 * A Delegated cell Drawing for drawing on CellLayout
2783 */
2784 public abstract static class DelegatedCellDrawing {
2785 public int mDelegateCellX;
2786 public int mDelegateCellY;
2787
2788 /**
2789 * Draw under CellLayout
2790 */
2791 public abstract void drawUnderItem(Canvas canvas);
2792
2793 /**
2794 * Draw over CellLayout
2795 */
2796 public abstract void drawOverItem(Canvas canvas);
2797 }
2798
2799 /**
Tony Wickham86930612015-09-09 13:50:40 -07002800 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2801 * if necessary).
2802 */
2803 public boolean hasReorderSolution(ItemInfo itemInfo) {
2804 int[] cellPoint = new int[2];
2805 // Check for a solution starting at every cell.
2806 for (int cellX = 0; cellX < getCountX(); cellX++) {
2807 for (int cellY = 0; cellY < getCountY(); cellY++) {
2808 cellToPoint(cellX, cellY, cellPoint);
2809 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2810 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2811 true, new ItemConfiguration()).isSolution) {
2812 return true;
2813 }
2814 }
2815 }
2816 return false;
2817 }
2818
Samuel Fufaa4211432020-02-25 18:47:54 -08002819 /**
2820 * Finds solution to accept hotseat migration to cell layout. commits solution if commitConfig
2821 */
2822 public boolean makeSpaceForHotseatMigration(boolean commitConfig) {
Samuel Fufaa4211432020-02-25 18:47:54 -08002823 int[] cellPoint = new int[2];
2824 int[] directionVector = new int[]{0, -1};
2825 cellToPoint(0, mCountY, cellPoint);
2826 ItemConfiguration configuration = new ItemConfiguration();
2827 if (findReorderSolution(cellPoint[0], cellPoint[1], mCountX, 1, mCountX, 1,
2828 directionVector, null, false, configuration).isSolution) {
2829 if (commitConfig) {
2830 copySolutionToTempState(configuration, null);
Sunny Goyal711c5962021-06-23 12:36:18 -07002831 commitTempPlacement(null);
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002832 // undo marking cells occupied since there is actually nothing being placed yet.
2833 mOccupied.markCells(0, mCountY - 1, mCountX, 1, false);
Samuel Fufaa4211432020-02-25 18:47:54 -08002834 }
2835 return true;
2836 }
2837 return false;
2838 }
2839
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002840 /**
2841 * returns a copy of cell layout's grid occupancy
2842 */
2843 public GridOccupancy cloneGridOccupancy() {
2844 GridOccupancy occupancy = new GridOccupancy(mCountX, mCountY);
2845 mOccupied.copyTo(occupancy);
2846 return occupancy;
2847 }
2848
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002849 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002850 return mOccupied.isRegionVacant(x, y, spanX, spanY);
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002851 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002852}