blob: 5163ede509eb1b0bb6afaf7246d3641fbdce875f [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;
Tony Wickham0ac045f2021-11-03 13:17:02 -070022import static com.android.launcher3.dragndrop.DraggableView.DRAGGABLE_ICON;
Tony Wickham12784902021-11-03 14:02:10 -070023import static com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR;
Sunny Goyal82dfc152023-02-24 16:50:09 -080024import static com.android.launcher3.util.MultiTranslateDelegate.INDEX_REORDER_BOUNCE_OFFSET;
25import static com.android.launcher3.util.MultiTranslateDelegate.INDEX_REORDER_PREVIEW_OFFSET;
Sunny Goyalf0b6db72018-08-13 16:10:14 -070026
Joe Onorato4be866d2010-10-10 11:26:02 -070027import android.animation.Animator;
Michael Jurka629758f2012-06-14 16:18:21 -070028import android.animation.AnimatorListenerAdapter;
Sunny Goyal849c6a22018-08-08 16:33:46 -070029import android.animation.ObjectAnimator;
Chet Haase00397b12010-10-07 11:13:10 -070030import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070031import android.animation.ValueAnimator;
32import android.animation.ValueAnimator.AnimatorUpdateListener;
Sunny Goyal726bee72018-03-05 12:54:24 -080033import android.annotation.SuppressLint;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040035import android.content.res.Resources;
Sunny Goyalc13403c2016-11-18 23:44:48 -080036import android.content.res.TypedArray;
Winson Chungaafa03c2010-06-11 17:34:16 -070037import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080038import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070039import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070040import android.graphics.Point;
Adam Cohend9162062020-03-24 16:35:35 -070041import android.graphics.PointF;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080042import android.graphics.Rect;
Adam Cohenf7ca3b42021-02-22 11:03:58 -080043import android.graphics.RectF;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070044import android.graphics.drawable.Drawable;
Adam Cohen1462de32012-07-24 22:34:36 -070045import android.os.Parcelable;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -070046import android.util.ArrayMap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080047import android.util.AttributeSet;
Adam Cohenf7ca3b42021-02-22 11:03:58 -080048import android.util.FloatProperty;
Joe Onorato4be866d2010-10-10 11:26:02 -070049import android.util.Log;
Sunny Goyal849c6a22018-08-08 16:33:46 -070050import android.util.Property;
Adam Cohen1462de32012-07-24 22:34:36 -070051import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080052import android.view.MotionEvent;
53import android.view.View;
54import android.view.ViewDebug;
55import android.view.ViewGroup;
Adam Cohenc9735cf2015-01-23 16:11:55 -080056import android.view.accessibility.AccessibilityEvent;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070057
vadimt04f356f2019-02-14 18:46:36 -080058import androidx.annotation.IntDef;
Adam Cohenf7ca3b42021-02-22 11:03:58 -080059import androidx.core.graphics.ColorUtils;
vadimt04f356f2019-02-14 18:46:36 -080060import androidx.core.view.ViewCompat;
61
Sunny Goyalaa8ef112015-06-12 20:04:41 -070062import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyale9b651e2015-04-24 11:44:51 -070063import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070064import com.android.launcher3.anim.Interpolators;
Sebastian Francod4682992022-10-05 13:03:09 -050065import com.android.launcher3.celllayout.CellLayoutLayoutParams;
Sunny Goyal669b71f2023-01-27 14:37:07 -080066import com.android.launcher3.celllayout.CellPosMapper.CellPos;
Sebastian Francoe4c03452022-12-27 14:50:02 -060067import com.android.launcher3.celllayout.ReorderAlgorithm;
Sunny Goyal3d706ad2017-03-06 16:56:39 -080068import com.android.launcher3.config.FeatureFlags;
Tony Wickham0ac045f2021-11-03 13:17:02 -070069import com.android.launcher3.dragndrop.DraggableView;
Jon Mirandaa0233f72017-06-22 18:34:45 -070070import com.android.launcher3.folder.PreviewBackground;
Sunny Goyale396abf2020-04-06 15:11:17 -070071import com.android.launcher3.model.data.ItemInfo;
Sebastian Francof153d912022-04-22 16:15:27 -050072import com.android.launcher3.model.data.LauncherAppWidgetInfo;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -070073import com.android.launcher3.util.CellAndSpan;
74import com.android.launcher3.util.GridOccupancy;
Sunny Goyal82dfc152023-02-24 16:50:09 -080075import com.android.launcher3.util.MultiTranslateDelegate;
Sunny Goyale2fd14b2015-08-27 17:45:46 -070076import com.android.launcher3.util.ParcelableSparseArray;
Sunny Goyal9b29ca52017-02-17 10:39:44 -080077import com.android.launcher3.util.Themes;
Adam Cohen091440a2015-03-18 14:16:05 -070078import com.android.launcher3.util.Thunk;
Sunny Goyalab770a12018-11-14 15:17:26 -080079import com.android.launcher3.views.ActivityContext;
Steven Ng32427202021-04-19 18:12:12 +010080import com.android.launcher3.widget.LauncherAppWidgetHostView;
Sunny Goyal5bc6b6f2017-10-26 15:36:10 -070081
Sunny Goyalc13403c2016-11-18 23:44:48 -080082import java.lang.annotation.Retention;
83import java.lang.annotation.RetentionPolicy;
Adam Cohen69ce2e52011-07-03 19:25:21 -070084import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070085import java.util.Arrays;
Adam Cohenf3900c22012-11-16 18:28:11 -080086import java.util.Collections;
87import java.util.Comparator;
Sebastian Franco45b39b52023-01-10 10:47:46 -060088import java.util.List;
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")
Sebastian Franco25423862023-03-10 10:50:37 -0800106 protected 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;
fbarone74256b2023-04-10 14:50:31 -0700560 updateBgAlpha();
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800561 setGridAlpha(progress);
562 }
563 }
564
565 /**
566 * See setSpringLoadedProgress
567 * @return progress
568 */
569 public float getSpringLoadedProgress() {
570 return mSpringLoadedProgress;
571 }
572
Sebastian Franco09589322022-11-02 15:25:58 -0700573 protected void updateBgAlpha() {
Adam Cohen0c4d2782021-04-29 15:56:13 -0700574 mBackground.setAlpha((int) (mSpringLoadedProgress * 255));
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800575 }
576
577 /**
578 * Set the progress of this page's scroll
579 *
580 * @param progress 0 if the screen is centered, +/-1 if it is to the right / left respectively
581 */
582 public void setScrollProgress(float progress) {
583 if (Float.compare(Math.abs(progress), mScrollProgress) != 0) {
584 mScrollProgress = Math.abs(progress);
fbarone74256b2023-04-10 14:50:31 -0700585 updateBgAlpha();
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800586 }
587 }
588
589 private void setGridAlpha(float gridAlpha) {
590 if (Float.compare(gridAlpha, mGridAlpha) != 0) {
591 mGridAlpha = gridAlpha;
592 invalidate();
593 }
594 }
595
Adam Cohen65086992020-02-19 08:40:49 -0800596 protected void visualizeGrid(Canvas canvas) {
Adam Cohen0c4d2782021-04-29 15:56:13 -0700597 DeviceProfile dp = mActivity.getDeviceProfile();
Alex Chau51da2192022-05-20 13:32:10 +0100598 int paddingX = Math.min((mCellWidth - dp.iconSizePx) / 2, dp.gridVisualizationPaddingX);
599 int paddingY = Math.min((mCellHeight - dp.iconSizePx) / 2, dp.gridVisualizationPaddingY);
Adam Cohen0c4d2782021-04-29 15:56:13 -0700600 mVisualizeGridRect.set(paddingX, paddingY,
601 mCellWidth - paddingX,
602 mCellHeight - paddingY);
Adam Cohen65086992020-02-19 08:40:49 -0800603
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800604 mVisualizeGridPaint.setStrokeWidth(8);
605 int paintAlpha = (int) (120 * mGridAlpha);
606 mVisualizeGridPaint.setColor(ColorUtils.setAlphaComponent(mGridColor, paintAlpha));
Adam Cohen65086992020-02-19 08:40:49 -0800607
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800608 if (mVisualizeCells) {
609 for (int i = 0; i < mCountX; i++) {
610 for (int j = 0; j < mCountY; j++) {
Thales Lima78d00ad2021-09-30 11:29:06 +0100611 int transX = i * mCellWidth + (i * mBorderSpace.x) + getPaddingLeft()
Adam Cohen0c4d2782021-04-29 15:56:13 -0700612 + paddingX;
Thales Lima78d00ad2021-09-30 11:29:06 +0100613 int transY = j * mCellHeight + (j * mBorderSpace.y) + getPaddingTop()
Adam Cohen0c4d2782021-04-29 15:56:13 -0700614 + paddingY;
Adam Cohen65086992020-02-19 08:40:49 -0800615
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800616 mVisualizeGridRect.offsetTo(transX, transY);
617 mVisualizeGridPaint.setStyle(Paint.Style.FILL);
618 canvas.drawRoundRect(mVisualizeGridRect, mGridVisualizationRoundingRadius,
619 mGridVisualizationRoundingRadius, mVisualizeGridPaint);
620 }
621 }
622 }
Adam Cohen65086992020-02-19 08:40:49 -0800623
fbarone74256b2023-04-10 14:50:31 -0700624 if (mVisualizeDropLocation) {
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800625 for (int i = 0; i < mDragOutlines.length; i++) {
626 final float alpha = mDragOutlineAlphas[i];
627 if (alpha <= 0) continue;
Adam Cohen65086992020-02-19 08:40:49 -0800628
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800629 mVisualizeGridPaint.setAlpha(255);
Sebastian Franco877088e2023-01-03 15:16:22 -0700630 int x = mDragOutlines[i].getCellX();
631 int y = mDragOutlines[i].getCellY();
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800632 int spanX = mDragOutlines[i].cellHSpan;
633 int spanY = mDragOutlines[i].cellVSpan;
634
Adam Cohened82e0d2021-07-21 17:24:12 -0700635 // TODO b/194414754 clean this up, reconcile with cellToRect
Adam Cohen0c4d2782021-04-29 15:56:13 -0700636 mVisualizeGridRect.set(paddingX, paddingY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100637 mCellWidth * spanX + mBorderSpace.x * (spanX - 1) - paddingX,
638 mCellHeight * spanY + mBorderSpace.y * (spanY - 1) - paddingY);
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800639
Thales Lima78d00ad2021-09-30 11:29:06 +0100640 int transX = x * mCellWidth + (x * mBorderSpace.x)
Adam Cohen0c4d2782021-04-29 15:56:13 -0700641 + getPaddingLeft() + paddingX;
Thales Lima78d00ad2021-09-30 11:29:06 +0100642 int transY = y * mCellHeight + (y * mBorderSpace.y)
Adam Cohen0c4d2782021-04-29 15:56:13 -0700643 + getPaddingTop() + paddingY;
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800644
645 mVisualizeGridRect.offsetTo(transX, transY);
Adam Cohen65086992020-02-19 08:40:49 -0800646
647 mVisualizeGridPaint.setStyle(Paint.Style.STROKE);
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800648 mVisualizeGridPaint.setColor(Color.argb((int) (alpha),
649 Color.red(mGridColor), Color.green(mGridColor), Color.blue(mGridColor)));
Adam Cohen65086992020-02-19 08:40:49 -0800650
Adam Cohenf7ca3b42021-02-22 11:03:58 -0800651 canvas.drawRoundRect(mVisualizeGridRect, mGridVisualizationRoundingRadius,
652 mGridVisualizationRoundingRadius, mVisualizeGridPaint);
Adam Cohen65086992020-02-19 08:40:49 -0800653 }
654 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700655 }
656
Adam Cohenefca0272016-02-24 19:19:06 -0800657 @Override
658 protected void dispatchDraw(Canvas canvas) {
659 super.dispatchDraw(canvas);
660
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800661 for (int i = 0; i < mDelegatedCellDrawings.size(); i++) {
662 DelegatedCellDrawing bg = mDelegatedCellDrawings.get(i);
663 cellToPoint(bg.mDelegateCellX, bg.mDelegateCellY, mTempLocation);
664 canvas.save();
665 canvas.translate(mTempLocation[0], mTempLocation[1]);
666 bg.drawOverItem(canvas);
667 canvas.restore();
Adam Cohenefca0272016-02-24 19:19:06 -0800668 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700669 }
670
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800671 /**
672 * Add Delegated cell drawing
673 */
674 public void addDelegatedCellDrawing(DelegatedCellDrawing bg) {
675 mDelegatedCellDrawings.add(bg);
Adam Cohenefca0272016-02-24 19:19:06 -0800676 }
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800677
678 /**
679 * Remove item from DelegatedCellDrawings
680 */
681 public void removeDelegatedCellDrawing(DelegatedCellDrawing bg) {
682 mDelegatedCellDrawings.remove(bg);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700683 }
684
Adam Cohenc51934b2011-07-26 21:07:43 -0700685 public void setFolderLeaveBehindCell(int x, int y) {
Adam Cohenefca0272016-02-24 19:19:06 -0800686 View child = getChildAt(x, y);
Sunny Goyalab770a12018-11-14 15:17:26 -0800687 mFolderLeaveBehind.setup(getContext(), mActivity, null,
Adam Cohenefca0272016-02-24 19:19:06 -0800688 child.getMeasuredWidth(), child.getPaddingTop());
689
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800690 mFolderLeaveBehind.mDelegateCellX = x;
691 mFolderLeaveBehind.mDelegateCellY = y;
Adam Cohenc51934b2011-07-26 21:07:43 -0700692 invalidate();
693 }
694
695 public void clearFolderLeaveBehind() {
Samuel Fufa1e2d0042019-11-18 17:12:46 -0800696 mFolderLeaveBehind.mDelegateCellX = -1;
697 mFolderLeaveBehind.mDelegateCellY = -1;
Adam Cohenc51934b2011-07-26 21:07:43 -0700698 invalidate();
699 }
700
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700701 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700702 public boolean shouldDelayChildPressedState() {
703 return false;
704 }
705
Adam Cohen1462de32012-07-24 22:34:36 -0700706 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700707 try {
708 dispatchRestoreInstanceState(states);
709 } catch (IllegalArgumentException ex) {
Zak Cohen3eeb41d2020-02-14 14:15:13 -0800710 if (FeatureFlags.IS_STUDIO_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700711 throw ex;
712 }
713 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
714 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
715 }
Adam Cohen1462de32012-07-24 22:34:36 -0700716 }
717
Michael Jurkae6235dd2011-10-04 15:02:05 -0700718 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700719 public void cancelLongPress() {
720 super.cancelLongPress();
721
722 // Cancel long press for all children
723 final int count = getChildCount();
724 for (int i = 0; i < count; i++) {
725 final View child = getChildAt(i);
726 child.cancelLongPress();
727 }
728 }
729
Michael Jurkadee05892010-07-27 10:01:56 -0700730 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
731 mInterceptTouchListener = listener;
732 }
733
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800734 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700735 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800736 }
737
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800738 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700739 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800740 }
741
Sunny Goyalc13403c2016-11-18 23:44:48 -0800742 public boolean acceptsWidget() {
743 return mContainerType == WORKSPACE;
Sunny Goyale9b651e2015-04-24 11:44:51 -0700744 }
745
Sebastian Francod4682992022-10-05 13:03:09 -0500746 /**
747 * Adds the given view to the CellLayout
748 *
749 * @param child view to add.
750 * @param index index of the CellLayout children where to add the view.
751 * @param childId id of the view.
752 * @param params represent the logic of the view on the CellLayout.
753 * @param markCells if the occupied cells should be marked or not
754 * @return if adding the view was successful
755 */
756 public boolean addViewToCellLayout(View child, int index, int childId,
757 CellLayoutLayoutParams params, boolean markCells) {
758 final CellLayoutLayoutParams lp = params;
Winson Chungaafa03c2010-06-11 17:34:16 -0700759
Andrew Flynnde38e422012-05-08 11:22:15 -0700760 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800761 if (child instanceof BubbleTextView) {
762 BubbleTextView bubbleChild = (BubbleTextView) child;
Jon Mirandaf1eae802017-10-04 11:23:33 -0700763 bubbleChild.setTextVisibility(mContainerType != HOTSEAT);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800764 }
765
Sunny Goyalc13403c2016-11-18 23:44:48 -0800766 child.setScaleX(mChildScale);
767 child.setScaleY(mChildScale);
Adam Cohen307fe232012-08-16 17:55:58 -0700768
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800769 // Generate an id for each view, this assumes we have at most 256x256 cells
770 // per workspace screen
Sebastian Franco877088e2023-01-03 15:16:22 -0700771 if (lp.getCellX() >= 0 && lp.getCellX() <= mCountX - 1
772 && lp.getCellY() >= 0 && lp.getCellY() <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700773 // If the horizontal or vertical span is set to -1, it is taken to
774 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700775 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
776 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800777
Winson Chungaafa03c2010-06-11 17:34:16 -0700778 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700779 if (LOGD) {
780 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
781 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700782 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700783
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700784 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700785
Winson Chungaafa03c2010-06-11 17:34:16 -0700786 return true;
787 }
788 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800789 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700790
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800791 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700792 public void removeAllViews() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700793 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700794 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700795 }
796
797 @Override
798 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700799 if (mShortcutsAndWidgets.getChildCount() > 0) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -0700800 mOccupied.clear();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700801 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700802 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700803 }
804
805 @Override
806 public void removeView(View view) {
807 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700808 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700809 }
810
811 @Override
812 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700813 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
814 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700815 }
816
817 @Override
818 public void removeViewInLayout(View view) {
819 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700820 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700821 }
822
823 @Override
824 public void removeViews(int start, int count) {
825 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700826 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700827 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700828 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700829 }
830
831 @Override
832 public void removeViewsInLayout(int start, int count) {
833 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700834 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700835 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700836 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800837 }
838
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700839 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700840 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800841 * @param x X coordinate of the point
842 * @param y Y coordinate of the point
843 * @param result Array of 2 ints to hold the x and y coordinate of the cell
844 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700845 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700846 final int hStartPadding = getPaddingLeft();
847 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800848
Sebastian Francob57c0b22022-06-28 13:54:35 -0700849 result[0] = (x - hStartPadding) / (mCellWidth + mBorderSpace.x);
850 result[1] = (y - vStartPadding) / (mCellHeight + mBorderSpace.y);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800851
Adam Cohend22015c2010-07-26 22:02:18 -0700852 final int xAxis = mCountX;
853 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800854
855 if (result[0] < 0) result[0] = 0;
856 if (result[0] >= xAxis) result[0] = xAxis - 1;
857 if (result[1] < 0) result[1] = 0;
858 if (result[1] >= yAxis) result[1] = yAxis - 1;
859 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700860
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800861 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800862 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700863 *
864 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800865 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700866 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800867 * @param result Array of 2 ints to hold the x and y coordinate of the point
868 */
869 void cellToPoint(int cellX, int cellY, int[] result) {
Jon Miranda228877d2021-02-09 11:05:00 -0500870 cellToRect(cellX, cellY, 1, 1, mTempRect);
871 result[0] = mTempRect.left;
872 result[1] = mTempRect.top;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800873 }
874
Adam Cohene3e27a82011-04-15 12:07:39 -0700875 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800876 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700877 *
878 * @param cellX X coordinate of the cell
879 * @param cellY Y coordinate of the cell
880 *
881 * @param result Array of 2 ints to hold the x and y coordinate of the point
882 */
883 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700884 regionToCenterPoint(cellX, cellY, 1, 1, result);
885 }
886
887 /**
Tony Wickham0ac045f2021-11-03 13:17:02 -0700888 * Given a cell coordinate and span return the point that represents the center of the region
Adam Cohen47a876d2012-03-19 13:21:41 -0700889 *
890 * @param cellX X coordinate of the cell
891 * @param cellY Y coordinate of the cell
892 *
893 * @param result Array of 2 ints to hold the x and y coordinate of the point
894 */
Sebastian Franco45b39b52023-01-10 10:47:46 -0600895 public void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Jon Miranda228877d2021-02-09 11:05:00 -0500896 cellToRect(cellX, cellY, spanX, spanY, mTempRect);
897 result[0] = mTempRect.centerX();
898 result[1] = mTempRect.centerY();
Adam Cohen19f37922012-03-21 11:59:11 -0700899 }
900
Tony Wickham3cfa5ed2021-11-03 13:20:43 -0700901 /**
902 * Returns the distance between the given coordinate and the visual center of the given cell.
903 */
904 public float getDistanceFromWorkspaceCellVisualCenter(float x, float y, int[] cell) {
905 getWorkspaceCellVisualCenter(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700906 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800907 }
908
Tony Wickham3cfa5ed2021-11-03 13:20:43 -0700909 private void getWorkspaceCellVisualCenter(int cellX, int cellY, int[] outPoint) {
910 View child = getChildAt(cellX, cellY);
911 if (child instanceof DraggableView) {
912 DraggableView draggableChild = (DraggableView) child;
913 if (draggableChild.getViewType() == DRAGGABLE_ICON) {
914 cellToPoint(cellX, cellY, outPoint);
915 draggableChild.getWorkspaceVisualDragBounds(mTempRect);
916 mTempRect.offset(outPoint[0], outPoint[1]);
917 outPoint[0] = mTempRect.centerX();
918 outPoint[1] = mTempRect.centerY();
919 return;
920 }
921 }
922 cellToCenterPoint(cellX, cellY, outPoint);
923 }
924
Tony Wickham0ac045f2021-11-03 13:17:02 -0700925 /**
926 * Returns the max distance from the center of a cell that can accept a drop to create a folder.
927 */
Tony Wickham12784902021-11-03 14:02:10 -0700928 public float getFolderCreationRadius(int[] targetCell) {
Tony Wickham0ac045f2021-11-03 13:17:02 -0700929 DeviceProfile grid = mActivity.getDeviceProfile();
Tony Wickham12784902021-11-03 14:02:10 -0700930 float iconVisibleRadius = ICON_VISIBLE_AREA_FACTOR * grid.iconSizePx / 2;
931 // Halfway between reorder radius and icon.
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700932 return (getReorderRadius(targetCell, 1, 1) + iconVisibleRadius) / 2;
Tony Wickham12784902021-11-03 14:02:10 -0700933 }
934
935 /**
936 * Returns the max distance from the center of a cell that will start to reorder on drag over.
937 */
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700938 public float getReorderRadius(int[] targetCell, int spanX, int spanY) {
Tony Wickham12784902021-11-03 14:02:10 -0700939 int[] centerPoint = mTmpPoint;
940 getWorkspaceCellVisualCenter(targetCell[0], targetCell[1], centerPoint);
941
942 Rect cellBoundsWithSpacing = mTempRect;
Sebastian Franco6e1024e2022-07-29 13:46:49 -0700943 cellToRect(targetCell[0], targetCell[1], spanX, spanY, cellBoundsWithSpacing);
Tony Wickham12784902021-11-03 14:02:10 -0700944 cellBoundsWithSpacing.inset(-mBorderSpace.x / 2, -mBorderSpace.y / 2);
945
Sebastian Francoc8392ea2022-10-28 16:38:37 -0700946 if (canCreateFolder(getChildAt(targetCell[0], targetCell[1])) && spanX == 1 && spanY == 1) {
Tony Wickham12784902021-11-03 14:02:10 -0700947 // Take only the circle in the smaller dimension, to ensure we don't start reordering
948 // too soon before accepting a folder drop.
949 int minRadius = centerPoint[0] - cellBoundsWithSpacing.left;
950 minRadius = Math.min(minRadius, centerPoint[1] - cellBoundsWithSpacing.top);
951 minRadius = Math.min(minRadius, cellBoundsWithSpacing.right - centerPoint[0]);
952 minRadius = Math.min(minRadius, cellBoundsWithSpacing.bottom - centerPoint[1]);
953 return minRadius;
954 }
955 // Take up the entire cell, including space between this cell and the adjacent ones.
Sebastian Francoc8392ea2022-10-28 16:38:37 -0700956 // Multiply by span to scale radius
957 return (float) Math.hypot(spanX * cellBoundsWithSpacing.width() / 2f,
958 spanY * cellBoundsWithSpacing.height() / 2f);
Tony Wickham0ac045f2021-11-03 13:17:02 -0700959 }
960
Adam Cohenf9c184a2016-01-15 16:47:43 -0800961 public int getCellWidth() {
Romain Guy84f296c2009-11-04 15:00:44 -0800962 return mCellWidth;
963 }
964
Sunny Goyal0b754e52017-08-07 07:42:45 -0700965 public int getCellHeight() {
Romain Guy84f296c2009-11-04 15:00:44 -0800966 return mCellHeight;
967 }
968
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700969 public void setFixedSize(int width, int height) {
970 mFixedWidth = width;
971 mFixedHeight = height;
972 }
973
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800974 @Override
975 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800976 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800977 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700978 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
979 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700980 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
981 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -0700982
Winson Chung11a1a532013-09-13 11:14:45 -0700983 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Thales Lima78d00ad2021-09-30 11:29:06 +0100984 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mBorderSpace.x,
Jon Miranda228877d2021-02-09 11:05:00 -0500985 mCountX);
Thales Lima78d00ad2021-09-30 11:29:06 +0100986 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mBorderSpace.y,
Jon Miranda228877d2021-02-09 11:05:00 -0500987 mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700988 if (cw != mCellWidth || ch != mCellHeight) {
989 mCellWidth = cw;
990 mCellHeight = ch;
Jon Miranda228877d2021-02-09 11:05:00 -0500991 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mCountX, mCountY,
Thales Lima78d00ad2021-09-30 11:29:06 +0100992 mBorderSpace);
Winson Chung11a1a532013-09-13 11:14:45 -0700993 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700994 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700995
Winson Chung2d75f122013-09-23 16:53:31 -0700996 int newWidth = childWidthSize;
997 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700998 if (mFixedWidth > 0 && mFixedHeight > 0) {
999 newWidth = mFixedWidth;
1000 newHeight = mFixedHeight;
1001 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001002 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
1003 }
1004
Sunny Goyal4fe5a372015-05-14 19:55:10 -07001005 mShortcutsAndWidgets.measure(
1006 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
1007 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
1008
1009 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
1010 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -07001011 if (mFixedWidth > 0 && mFixedHeight > 0) {
1012 setMeasuredDimension(maxWidth, maxHeight);
1013 } else {
1014 setMeasuredDimension(widthSize, heightSize);
1015 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001016 }
1017
1018 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -07001019 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -08001020 int left = getPaddingLeft();
Sunny Goyal7ce471b2017-08-02 03:37:39 -07001021 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -07001022 int right = r - l - getPaddingRight();
Sunny Goyal7ce471b2017-08-02 03:37:39 -07001023 right -= (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Sunny Goyal7c786f72016-06-01 14:08:21 -07001024
Winson Chung38848ca2013-10-08 12:03:44 -07001025 int top = getPaddingTop();
Sunny Goyal7c786f72016-06-01 14:08:21 -07001026 int bottom = b - t - getPaddingBottom();
Sunny Goyal4fe5a372015-05-14 19:55:10 -07001027
Sunny Goyal7c786f72016-06-01 14:08:21 -07001028 // Expand the background drawing bounds by the padding baked into the background drawable
1029 mBackground.getPadding(mTempRect);
1030 mBackground.setBounds(
Jon Miranda28032002017-07-13 16:18:56 -07001031 left - mTempRect.left - getPaddingLeft(),
1032 top - mTempRect.top - getPaddingTop(),
1033 right + mTempRect.right + getPaddingRight(),
1034 bottom + mTempRect.bottom + getPaddingBottom());
Sunny Goyalae6e3182019-04-30 12:04:37 -07001035
Sunny Goyalc4d32012020-04-03 17:10:11 -07001036 mShortcutsAndWidgets.layout(left, top, right, bottom);
Sunny Goyal7c786f72016-06-01 14:08:21 -07001037 }
1038
Tony Wickhama501d492015-11-03 18:05:01 -08001039 /**
1040 * Returns the amount of space left over after subtracting padding and cells. This space will be
1041 * 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 -05001042 * width in {@link DeviceProfile#calculateCellWidth(int, int, int)}.
Tony Wickhama501d492015-11-03 18:05:01 -08001043 */
1044 public int getUnusedHorizontalSpace() {
Jon Miranda228877d2021-02-09 11:05:00 -05001045 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth)
Thales Lima78d00ad2021-09-30 11:29:06 +01001046 - ((mCountX - 1) * mBorderSpace.x);
Tony Wickhama501d492015-11-03 18:05:01 -08001047 }
1048
Sunny Goyal2805e632015-05-20 15:35:32 -07001049 @Override
1050 protected boolean verifyDrawable(Drawable who) {
Sunny Goyal7ce471b2017-08-02 03:37:39 -07001051 return super.verifyDrawable(who) || (who == mBackground);
Sunny Goyal2805e632015-05-20 15:35:32 -07001052 }
1053
Michael Jurkaa52570f2012-03-20 03:18:20 -07001054 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -07001055 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -07001056 }
1057
Jon Miranda228877d2021-02-09 11:05:00 -05001058 public View getChildAt(int cellX, int cellY) {
1059 return mShortcutsAndWidgets.getChildAt(cellX, cellY);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001060 }
1061
Adam Cohen76fc0852011-06-17 13:26:23 -07001062 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001063 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001064 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -08001065
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001066 if (clc.indexOfChild(child) != -1 && (child instanceof Reorderable)) {
Sebastian Francod4682992022-10-05 13:03:09 -05001067 final CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001068 final ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001069 final Reorderable item = (Reorderable) child;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001070
1071 // We cancel any existing animations
1072 if (mReorderAnimators.containsKey(lp)) {
1073 mReorderAnimators.get(lp).cancel();
1074 mReorderAnimators.remove(lp);
1075 }
1076
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001077
Adam Cohen482ed822012-03-02 14:15:13 -08001078 if (adjustOccupied) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001079 GridOccupancy occupied = permanent ? mOccupied : mTmpOccupied;
Sebastian Franco877088e2023-01-03 15:16:22 -07001080 occupied.markCells(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001081 occupied.markCells(cellX, cellY, lp.cellHSpan, lp.cellVSpan, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001082 }
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001083
1084 // Compute the new x and y position based on the new cellX and cellY
1085 // We leverage the actual layout logic in the layout params and hence need to modify
1086 // state and revert that state.
1087 final int oldX = lp.x;
1088 final int oldY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001089 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001090 if (permanent) {
Sunny Goyal669b71f2023-01-27 14:37:07 -08001091 lp.setCellX(cellX);
1092 lp.setCellY(cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001093 } else {
Sebastian Franco877088e2023-01-03 15:16:22 -07001094 lp.setTmpCellX(cellX);
1095 lp.setTmpCellY(cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001096 }
Jon Mirandae96798e2016-12-07 12:10:44 -08001097 clc.setupLp(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001098 final int newX = lp.x;
1099 final int newY = lp.y;
Adam Cohen76fc0852011-06-17 13:26:23 -07001100 lp.x = oldX;
1101 lp.y = oldY;
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001102 lp.isLockedToGrid = false;
1103 // End compute new x and y
1104
Sunny Goyal82dfc152023-02-24 16:50:09 -08001105 MultiTranslateDelegate mtd = item.getTranslateDelegate();
1106 float initPreviewOffsetX = mtd.getTranslationX(INDEX_REORDER_PREVIEW_OFFSET).getValue();
1107 float initPreviewOffsetY = mtd.getTranslationY(INDEX_REORDER_PREVIEW_OFFSET).getValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001108 final float finalPreviewOffsetX = newX - oldX;
1109 final float finalPreviewOffsetY = newY - oldY;
1110
Adam Cohen482ed822012-03-02 14:15:13 -08001111 // Exit early if we're not actually moving the view
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001112 if (finalPreviewOffsetX == 0 && finalPreviewOffsetY == 0
1113 && initPreviewOffsetX == 0 && initPreviewOffsetY == 0) {
Adam Cohen482ed822012-03-02 14:15:13 -08001114 lp.isLockedToGrid = true;
1115 return true;
1116 }
1117
Sunny Goyal849c6a22018-08-08 16:33:46 -07001118 ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001119 va.setDuration(duration);
1120 mReorderAnimators.put(lp, va);
1121
1122 va.addUpdateListener(new AnimatorUpdateListener() {
1123 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001124 public void onAnimationUpdate(ValueAnimator animation) {
Jon Mirandae96798e2016-12-07 12:10:44 -08001125 float r = (Float) animation.getAnimatedValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001126 float x = (1 - r) * initPreviewOffsetX + r * finalPreviewOffsetX;
1127 float y = (1 - r) * initPreviewOffsetY + r * finalPreviewOffsetY;
Sunny Goyal82dfc152023-02-24 16:50:09 -08001128 item.getTranslateDelegate().setTranslation(INDEX_REORDER_PREVIEW_OFFSET, x, y);
Adam Cohenbfbfd262011-06-13 16:55:12 -07001129 }
1130 });
Adam Cohen482ed822012-03-02 14:15:13 -08001131 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001132 boolean cancelled = false;
1133 public void onAnimationEnd(Animator animation) {
1134 // If the animation was cancelled, it means that another animation
1135 // has interrupted this one, and we don't want to lock the item into
1136 // place just yet.
1137 if (!cancelled) {
1138 lp.isLockedToGrid = true;
Sunny Goyal82dfc152023-02-24 16:50:09 -08001139 item.getTranslateDelegate()
1140 .setTranslation(INDEX_REORDER_PREVIEW_OFFSET, 0, 0);
Adam Cohen482ed822012-03-02 14:15:13 -08001141 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001142 }
1143 if (mReorderAnimators.containsKey(lp)) {
1144 mReorderAnimators.remove(lp);
1145 }
1146 }
1147 public void onAnimationCancel(Animator animation) {
1148 cancelled = true;
1149 }
1150 });
Adam Cohen482ed822012-03-02 14:15:13 -08001151 va.setStartDelay(delay);
1152 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001153 return true;
1154 }
1155 return false;
1156 }
1157
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001158 void visualizeDropLocation(int cellX, int cellY, int spanX, int spanY,
1159 DropTarget.DragObject dragObject) {
1160 if (mDragCell[0] != cellX || mDragCell[1] != cellY || mDragCellSpan[0] != spanX
1161 || mDragCellSpan[1] != spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08001162 mDragCell[0] = cellX;
1163 mDragCell[1] = cellY;
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001164 mDragCellSpan[0] = spanX;
1165 mDragCellSpan[1] = spanY;
Steven Ng30dd1d62021-03-15 21:45:49 +00001166
Steven Nga999e222021-04-19 18:17:15 +01001167 // Apply color extraction on a widget when dragging.
1168 applyColorExtractionOnWidget(dragObject, mDragCell, spanX, spanY);
1169
Joe Onorato4be866d2010-10-10 11:26:02 -07001170 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001171 mDragOutlineAnims[oldIndex].animateOut();
1172 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Sunny Goyal106bf642015-07-16 12:18:06 -07001173
Sebastian Francod4682992022-10-05 13:03:09 -05001174 CellLayoutLayoutParams cell = mDragOutlines[mDragOutlineCurrent];
Sebastian Franco877088e2023-01-03 15:16:22 -07001175 cell.setCellX(cellX);
1176 cell.setCellY(cellY);
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001177 cell.cellHSpan = spanX;
1178 cell.cellVSpan = spanY;
Adam Cohen65086992020-02-19 08:40:49 -08001179
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001180 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001181 invalidate();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001182
1183 if (dragObject.stateAnnouncer != null) {
Sunny Goyalc13403c2016-11-18 23:44:48 -08001184 dragObject.stateAnnouncer.announce(getItemMoveDescription(cellX, cellY));
Sunny Goyale78e3d72015-09-24 11:23:31 -07001185 }
Adam Cohenf7ca3b42021-02-22 11:03:58 -08001186
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001187 }
1188 }
1189
Steven Ng30dd1d62021-03-15 21:45:49 +00001190 /** Applies the local color extraction to a dragging widget object. */
Steven Nga999e222021-04-19 18:17:15 +01001191 private void applyColorExtractionOnWidget(DropTarget.DragObject dragObject, int[] targetCell,
1192 int spanX, int spanY) {
Steven Ng30dd1d62021-03-15 21:45:49 +00001193 // Apply local extracted color if the DragView is an AppWidgetHostViewDrawable.
Steven Ng32427202021-04-19 18:12:12 +01001194 View view = dragObject.dragView.getContentView();
1195 if (view instanceof LauncherAppWidgetHostView) {
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001196 int screenId = getWorkspace().getIdForScreen(this);
Steven Ng30dd1d62021-03-15 21:45:49 +00001197 cellToRect(targetCell[0], targetCell[1], spanX, spanY, mTempRect);
Jonathan Miranda21930da2021-05-03 18:44:13 +00001198
Sunny Goyal69a8eec2021-07-22 10:02:50 -07001199 ((LauncherAppWidgetHostView) view).handleDrag(mTempRect, this, screenId);
Steven Ng30dd1d62021-03-15 21:45:49 +00001200 }
1201 }
1202
Sunny Goyal726bee72018-03-05 12:54:24 -08001203 @SuppressLint("StringFormatMatches")
Sunny Goyalc13403c2016-11-18 23:44:48 -08001204 public String getItemMoveDescription(int cellX, int cellY) {
1205 if (mContainerType == HOTSEAT) {
1206 return getContext().getString(R.string.move_to_hotseat_position,
1207 Math.max(cellX, cellY) + 1);
1208 } else {
Shikha Malhotraf78da1b2022-04-11 10:23:18 +00001209 Workspace<?> workspace = getWorkspace();
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001210 int row = cellY + 1;
1211 int col = workspace.mIsRtl ? mCountX - cellX : cellX + 1;
1212 int panelCount = workspace.getPanelCount();
Sebastian Franco930531f2022-06-16 16:49:11 -07001213 int screenId = workspace.getIdForScreen(this);
1214 int pageIndex = workspace.getPageIndexForScreenId(screenId);
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001215 if (panelCount > 1) {
1216 // Increment the column if the target is on the right side of a two panel home
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001217 col += (pageIndex % panelCount) * mCountX;
1218 }
Sebastian Franco930531f2022-06-16 16:49:11 -07001219 return getContext().getString(R.string.move_to_empty_cell_description, row, col,
1220 workspace.getPageDescription(pageIndex));
Sunny Goyalc13403c2016-11-18 23:44:48 -08001221 }
1222 }
1223
Shikha Malhotraf78da1b2022-04-11 10:23:18 +00001224 private Workspace<?> getWorkspace() {
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001225 return Launcher.cast(mActivity).getWorkspace();
1226 }
1227
Adam Cohene0310962011-04-18 16:15:31 -07001228 public void clearDragOutlines() {
1229 final int oldIndex = mDragOutlineCurrent;
1230 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001231 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001232 }
1233
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001234 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001235 * Find a vacant area that will fit the given bounds nearest the requested
1236 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001237 *
Romain Guy51afc022009-05-04 18:03:43 -07001238 * @param pixelX The X location at which you want to search for a vacant area.
1239 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001240 * @param minSpanX The minimum horizontal span required
1241 * @param minSpanY The minimum vertical span required
1242 * @param spanX Horizontal span of the object.
1243 * @param spanY Vertical span of the object.
1244 * @param result Array in which to place the result, or null (in which case a new array will
1245 * be allocated)
1246 * @return The X, Y cell of a vacant area that can contain this object,
1247 * nearest the requested location.
1248 */
Sebastian Francoe4c03452022-12-27 14:50:02 -06001249 public int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
1250 int spanX, int spanY, int[] result, int[] resultSpan) {
Sebastian Francob57c0b22022-06-28 13:54:35 -07001251 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, false,
Adam Cohend41fbf52012-02-16 23:53:59 -08001252 result, resultSpan);
1253 }
1254
Adam Cohend41fbf52012-02-16 23:53:59 -08001255 /**
1256 * Find a vacant area that will fit the given bounds nearest the requested
1257 * cell location. Uses Euclidean distance to score multiple vacant areas.
Sebastian Francob57c0b22022-06-28 13:54:35 -07001258 * @param relativeXPos The X location relative to the Cell layout at which you want to search
1259 * for a vacant area.
1260 * @param relativeYPos The Y location relative to the Cell layout at which you want to search
1261 * for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001262 * @param minSpanX The minimum horizontal span required
1263 * @param minSpanY The minimum vertical span required
1264 * @param spanX Horizontal span of the object.
1265 * @param spanY Vertical span of the object.
1266 * @param ignoreOccupied If true, the result can be an occupied cell
1267 * @param result Array in which to place the result, or null (in which case a new array will
1268 * be allocated)
1269 * @return The X, Y cell of a vacant area that can contain this object,
1270 * nearest the requested location.
1271 */
Sebastian Francob57c0b22022-06-28 13:54:35 -07001272 private int[] findNearestArea(int relativeXPos, int relativeYPos, int minSpanX, int minSpanY,
1273 int spanX, int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Sebastian Francob57c0b22022-06-28 13:54:35 -07001274 // For items with a spanX / spanY > 1, the passed in point (relativeXPos, relativeYPos)
1275 // corresponds to the center of the item, but we are searching based on the top-left cell,
1276 // so we translate the point over to correspond to the top-left.
1277 relativeXPos = (int) (relativeXPos - (mCellWidth + mBorderSpace.x) * (spanX - 1) / 2f);
1278 relativeYPos = (int) (relativeYPos - (mCellHeight + mBorderSpace.y) * (spanY - 1) / 2f);
Adam Cohene3e27a82011-04-15 12:07:39 -07001279
Jeff Sharkey70864282009-04-07 21:08:40 -07001280 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001281 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001282 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001283 final Rect bestRect = new Rect(-1, -1, -1, -1);
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001284 final Stack<Rect> validRegions = new Stack<>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001285
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001286 final int countX = mCountX;
1287 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001288
Adam Cohend41fbf52012-02-16 23:53:59 -08001289 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1290 spanX < minSpanX || spanY < minSpanY) {
1291 return bestXY;
1292 }
1293
1294 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001295 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001296 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1297 int ySize = -1;
1298 int xSize = -1;
Sebastian Francob57c0b22022-06-28 13:54:35 -07001299 if (!ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001300 // First, let's see if this thing fits anywhere
1301 for (int i = 0; i < minSpanX; i++) {
1302 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001303 if (mOccupied.cells[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001304 continue inner;
1305 }
Michael Jurkac28de512010-08-13 11:27:44 -07001306 }
1307 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001308 xSize = minSpanX;
1309 ySize = minSpanY;
1310
1311 // We know that the item will fit at _some_ acceptable size, now let's see
1312 // how big we can make it. We'll alternate between incrementing x and y spans
1313 // until we hit a limit.
1314 boolean incX = true;
1315 boolean hitMaxX = xSize >= spanX;
1316 boolean hitMaxY = ySize >= spanY;
1317 while (!(hitMaxX && hitMaxY)) {
1318 if (incX && !hitMaxX) {
1319 for (int j = 0; j < ySize; j++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001320 if (x + xSize > countX -1 || mOccupied.cells[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001321 // We can't move out horizontally
1322 hitMaxX = true;
1323 }
1324 }
1325 if (!hitMaxX) {
1326 xSize++;
1327 }
1328 } else if (!hitMaxY) {
1329 for (int i = 0; i < xSize; i++) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001330 if (y + ySize > countY - 1 || mOccupied.cells[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001331 // We can't move out vertically
1332 hitMaxY = true;
1333 }
1334 }
1335 if (!hitMaxY) {
1336 ySize++;
1337 }
1338 }
1339 hitMaxX |= xSize >= spanX;
1340 hitMaxY |= ySize >= spanY;
1341 incX = !incX;
1342 }
Michael Jurkac28de512010-08-13 11:27:44 -07001343 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001344 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001345 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001346
Adam Cohend41fbf52012-02-16 23:53:59 -08001347 // We verify that the current rect is not a sub-rect of any of our previous
1348 // candidates. In this case, the current rect is disqualified in favour of the
1349 // containing rect.
Sebastian Franco4a922672022-10-27 16:42:24 -07001350 Rect currentRect = new Rect(x, y, x + xSize, y + ySize);
Adam Cohend41fbf52012-02-16 23:53:59 -08001351 boolean contained = false;
1352 for (Rect r : validRegions) {
1353 if (r.contains(currentRect)) {
1354 contained = true;
1355 break;
1356 }
1357 }
1358 validRegions.push(currentRect);
Sebastian Francob57c0b22022-06-28 13:54:35 -07001359 double distance = Math.hypot(cellXY[0] - relativeXPos, cellXY[1] - relativeYPos);
Adam Cohen482ed822012-03-02 14:15:13 -08001360
Adam Cohend41fbf52012-02-16 23:53:59 -08001361 if ((distance <= bestDistance && !contained) ||
1362 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001363 bestDistance = distance;
1364 bestXY[0] = x;
1365 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001366 if (resultSpan != null) {
1367 resultSpan[0] = xSize;
1368 resultSpan[1] = ySize;
1369 }
1370 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001371 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001372 }
1373 }
1374
Adam Cohenc0dcf592011-06-01 15:30:43 -07001375 // Return -1, -1 if no suitable location found
1376 if (bestDistance == Double.MAX_VALUE) {
1377 bestXY[0] = -1;
1378 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001379 }
Adam Cohenc0dcf592011-06-01 15:30:43 -07001380 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001381 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001382
Sebastian Francoe4c03452022-12-27 14:50:02 -06001383 public GridOccupancy getOccupied() {
1384 return mOccupied;
1385 }
1386
Adam Cohen482ed822012-03-02 14:15:13 -08001387 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001388 mTmpOccupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001389
Michael Jurkaa52570f2012-03-20 03:18:20 -07001390 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001391 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001392 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001393 if (child == dragView) continue;
Sebastian Francod4682992022-10-05 13:03:09 -05001394 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001395 CellAndSpan c = solution.map.get(child);
1396 if (c != null) {
Sebastian Franco877088e2023-01-03 15:16:22 -07001397 lp.setTmpCellX(c.cellX);
1398 lp.setTmpCellY(c.cellY);
Adam Cohen8baab352012-03-20 17:39:21 -07001399 lp.cellHSpan = c.spanX;
1400 lp.cellVSpan = c.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001401 mTmpOccupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001402 }
1403 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001404 mTmpOccupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001405 }
1406
1407 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1408 commitDragView) {
1409
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001410 GridOccupancy occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1411 occupied.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001412
Michael Jurkaa52570f2012-03-20 03:18:20 -07001413 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001414 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001415 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001416 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001417 CellAndSpan c = solution.map.get(child);
1418 if (c != null) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001419 animateChildToPosition(child, c.cellX, c.cellY, REORDER_ANIMATION_DURATION, 0,
Adam Cohen19f37922012-03-21 11:59:11 -07001420 DESTRUCTIVE_REORDER, false);
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001421 occupied.markCells(c, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001422 }
1423 }
1424 if (commitDragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001425 occupied.markCells(solution, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001426 }
1427 }
1428
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001429
1430 // This method starts or changes the reorder preview animations
1431 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
Adam Cohen65086992020-02-19 08:40:49 -08001432 View dragView, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07001433 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07001434 for (int i = 0; i < childCount; i++) {
1435 View child = mShortcutsAndWidgets.getChildAt(i);
1436 if (child == dragView) continue;
1437 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001438 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
1439 != null && !solution.intersectingViews.contains(child);
1440
Adam Cohend9162062020-03-24 16:35:35 -07001441
Sebastian Francod4682992022-10-05 13:03:09 -05001442 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohend9162062020-03-24 16:35:35 -07001443 if (c != null && !skip && (child instanceof Reorderable)) {
Sunny Goyal82dfc152023-02-24 16:50:09 -08001444 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child,
Sebastian Franco877088e2023-01-03 15:16:22 -07001445 mode, lp.getCellX(), lp.getCellY(), c.cellX, c.cellY, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07001446 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07001447 }
1448 }
1449 }
1450
Sunny Goyal849c6a22018-08-08 16:33:46 -07001451 private static final Property<ReorderPreviewAnimation, Float> ANIMATION_PROGRESS =
1452 new Property<ReorderPreviewAnimation, Float>(float.class, "animationProgress") {
1453 @Override
1454 public Float get(ReorderPreviewAnimation anim) {
1455 return anim.animationProgress;
1456 }
1457
1458 @Override
1459 public void set(ReorderPreviewAnimation anim, Float progress) {
1460 anim.setAnimationProgress(progress);
1461 }
1462 };
1463
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001464 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07001465 // in a temporary state, and hint at where the item will return to.
Sunny Goyal82dfc152023-02-24 16:50:09 -08001466 class ReorderPreviewAnimation<T extends View & Reorderable> {
1467 final T child;
Adam Cohend024f982012-05-23 18:26:45 -07001468 float finalDeltaX;
1469 float finalDeltaY;
1470 float initDeltaX;
1471 float initDeltaY;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001472 final float finalScale;
Adam Cohend024f982012-05-23 18:26:45 -07001473 float initScale;
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07001474 final int mode;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001475 boolean repeating = false;
1476 private static final int PREVIEW_DURATION = 300;
1477 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
1478
Jon Miranda21266912016-12-19 14:12:05 -08001479 private static final float CHILD_DIVIDEND = 4.0f;
1480
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001481 public static final int MODE_HINT = 0;
1482 public static final int MODE_PREVIEW = 1;
1483
Sunny Goyal849c6a22018-08-08 16:33:46 -07001484 float animationProgress = 0;
Sunny Goyalf0b6db72018-08-13 16:10:14 -07001485 ValueAnimator a;
Adam Cohen19f37922012-03-21 11:59:11 -07001486
Sunny Goyal82dfc152023-02-24 16:50:09 -08001487 ReorderPreviewAnimation(View childView, int mode, int cellX0, int cellY0,
Adam Cohend9162062020-03-24 16:35:35 -07001488 int cellX1, int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07001489 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
1490 final int x0 = mTmpPoint[0];
1491 final int y0 = mTmpPoint[1];
1492 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
1493 final int x1 = mTmpPoint[0];
1494 final int y1 = mTmpPoint[1];
1495 final int dX = x1 - x0;
1496 final int dY = y1 - y0;
Jon Miranda21266912016-12-19 14:12:05 -08001497
Sunny Goyal82dfc152023-02-24 16:50:09 -08001498 this.child = (T) childView;
Jon Miranda21266912016-12-19 14:12:05 -08001499 this.mode = mode;
Adam Cohend9162062020-03-24 16:35:35 -07001500 finalDeltaX = 0;
1501 finalDeltaY = 0;
Adam Cohen65086992020-02-19 08:40:49 -08001502
Sunny Goyal82dfc152023-02-24 16:50:09 -08001503 MultiTranslateDelegate mtd = child.getTranslateDelegate();
1504 initDeltaX = mtd.getTranslationX(INDEX_REORDER_BOUNCE_OFFSET).getValue();
1505 initDeltaY = mtd.getTranslationY(INDEX_REORDER_BOUNCE_OFFSET).getValue();
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001506 initScale = child.getReorderBounceScale();
Sunny Goyal82dfc152023-02-24 16:50:09 -08001507 finalScale = mChildScale - (CHILD_DIVIDEND / child.getWidth()) * initScale;
Adam Cohend9162062020-03-24 16:35:35 -07001508
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001509 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07001510 if (dX == dY && dX == 0) {
1511 } else {
1512 if (dY == 0) {
Adam Cohend9162062020-03-24 16:35:35 -07001513 finalDeltaX = -dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001514 } else if (dX == 0) {
Adam Cohend9162062020-03-24 16:35:35 -07001515 finalDeltaY = -dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07001516 } else {
1517 double angle = Math.atan( (float) (dY) / dX);
Adam Cohend9162062020-03-24 16:35:35 -07001518 finalDeltaX = (int) (-dir * Math.signum(dX)
1519 * Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
1520 finalDeltaY = (int) (-dir * Math.signum(dY)
1521 * Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07001522 }
1523 }
Jon Miranda21266912016-12-19 14:12:05 -08001524 }
1525
Adam Cohend9162062020-03-24 16:35:35 -07001526 void setInitialAnimationValuesToBaseline() {
1527 initScale = mChildScale;
1528 initDeltaX = 0;
1529 initDeltaY = 0;
Adam Cohen19f37922012-03-21 11:59:11 -07001530 }
1531
Adam Cohend024f982012-05-23 18:26:45 -07001532 void animate() {
Adam Cohend9162062020-03-24 16:35:35 -07001533 boolean noMovement = (finalDeltaX == 0) && (finalDeltaY == 0);
Jon Miranda21266912016-12-19 14:12:05 -08001534
Adam Cohen19f37922012-03-21 11:59:11 -07001535 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001536 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohen19f37922012-03-21 11:59:11 -07001537 mShakeAnimators.remove(child);
Adam Cohend9162062020-03-24 16:35:35 -07001538
Jon Miranda21266912016-12-19 14:12:05 -08001539 if (noMovement) {
Adam Cohend9162062020-03-24 16:35:35 -07001540 // A previous animation for this item exists, and no new animation will exist.
1541 // Finish the old animation smoothly.
1542 oldAnimation.finishAnimation();
Adam Cohene7587d22012-05-24 18:50:02 -07001543 return;
Adam Cohend9162062020-03-24 16:35:35 -07001544 } else {
1545 // A previous animation for this item exists, and a new one will exist. Stop
1546 // the old animation in its tracks, and proceed with the new one.
1547 oldAnimation.cancel();
Adam Cohene7587d22012-05-24 18:50:02 -07001548 }
Adam Cohen19f37922012-03-21 11:59:11 -07001549 }
Jon Miranda21266912016-12-19 14:12:05 -08001550 if (noMovement) {
Adam Cohen19f37922012-03-21 11:59:11 -07001551 return;
1552 }
Adam Cohend9162062020-03-24 16:35:35 -07001553
Sunny Goyal849c6a22018-08-08 16:33:46 -07001554 ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS, 0, 1);
Adam Cohene7587d22012-05-24 18:50:02 -07001555 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07001556
1557 // Animations are disabled in power save mode, causing the repeated animation to jump
1558 // spastically between beginning and end states. Since this looks bad, we don't repeat
1559 // the animation in power save mode.
Sunny Goyaleaf7a952020-07-29 16:54:20 -07001560 if (areAnimatorsEnabled()) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07001561 va.setRepeatMode(ValueAnimator.REVERSE);
1562 va.setRepeatCount(ValueAnimator.INFINITE);
1563 }
1564
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001565 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07001566 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07001567 va.addListener(new AnimatorListenerAdapter() {
1568 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07001569 // We make sure to end only after a full period
Adam Cohend9162062020-03-24 16:35:35 -07001570 setInitialAnimationValuesToBaseline();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001571 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07001572 }
1573 });
Adam Cohen19f37922012-03-21 11:59:11 -07001574 mShakeAnimators.put(child, this);
1575 va.start();
1576 }
1577
Sunny Goyal849c6a22018-08-08 16:33:46 -07001578 private void setAnimationProgress(float progress) {
1579 animationProgress = progress;
1580 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : animationProgress;
1581 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
1582 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Sunny Goyal82dfc152023-02-24 16:50:09 -08001583 child.getTranslateDelegate().setTranslation(INDEX_REORDER_BOUNCE_OFFSET, x, y);
Sunny Goyal849c6a22018-08-08 16:33:46 -07001584 float s = animationProgress * finalScale + (1 - animationProgress) * initScale;
Adam Cohen1d13c0b2020-04-21 16:29:12 -07001585 child.setReorderBounceScale(s);
Sunny Goyal849c6a22018-08-08 16:33:46 -07001586 }
1587
Adam Cohend024f982012-05-23 18:26:45 -07001588 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07001589 if (a != null) {
1590 a.cancel();
1591 }
Adam Cohen19f37922012-03-21 11:59:11 -07001592 }
Adam Cohene7587d22012-05-24 18:50:02 -07001593
Adam Cohend9162062020-03-24 16:35:35 -07001594 /**
1595 * Smoothly returns the item to its baseline position / scale
1596 */
1597 @Thunk void finishAnimation() {
Adam Cohene7587d22012-05-24 18:50:02 -07001598 if (a != null) {
1599 a.cancel();
1600 }
Brandon Keely50e6e562012-05-08 16:28:49 -07001601
Adam Cohend9162062020-03-24 16:35:35 -07001602 setInitialAnimationValuesToBaseline();
1603 ValueAnimator va = ObjectAnimator.ofFloat(this, ANIMATION_PROGRESS,
1604 animationProgress, 0);
1605 a = va;
Sunny Goyalf0b6db72018-08-13 16:10:14 -07001606 a.setInterpolator(DEACCEL_1_5);
Adam Cohend9162062020-03-24 16:35:35 -07001607 a.setDuration(REORDER_ANIMATION_DURATION);
Sunny Goyal5d2fc322015-07-06 22:52:49 -07001608 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07001609 }
Adam Cohen19f37922012-03-21 11:59:11 -07001610 }
1611
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001612 private void completeAndClearReorderPreviewAnimations() {
1613 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Adam Cohend9162062020-03-24 16:35:35 -07001614 a.finishAnimation();
Adam Cohen19f37922012-03-21 11:59:11 -07001615 }
1616 mShakeAnimators.clear();
1617 }
1618
Sunny Goyal711c5962021-06-23 12:36:18 -07001619 private void commitTempPlacement(View dragView) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07001620 mTmpOccupied.copyTo(mOccupied);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001621
Andras Kloczl2dacbee2022-02-21 16:53:28 +00001622 int screenId = getWorkspace().getIdForScreen(this);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001623 int container = Favorites.CONTAINER_DESKTOP;
1624
Sunny Goyalc13403c2016-11-18 23:44:48 -08001625 if (mContainerType == HOTSEAT) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001626 screenId = -1;
1627 container = Favorites.CONTAINER_HOTSEAT;
1628 }
1629
Michael Jurkaa52570f2012-03-20 03:18:20 -07001630 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001631 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07001632 View child = mShortcutsAndWidgets.getChildAt(i);
Sebastian Francod4682992022-10-05 13:03:09 -05001633 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
Adam Cohenea889a22012-03-27 16:45:39 -07001634 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07001635 // We do a null check here because the item info can be null in the case of the
1636 // AllApps button in the hotseat.
Sunny Goyal711c5962021-06-23 12:36:18 -07001637 if (info != null && child != dragView) {
Sunny Goyal669b71f2023-01-27 14:37:07 -08001638 CellPos presenterPos = mActivity.getCellPosMapper().mapModelToPresenter(info);
1639 final boolean requiresDbUpdate = (presenterPos.cellX != lp.getTmpCellX()
1640 || presenterPos.cellY != lp.getTmpCellY() || info.spanX != lp.cellHSpan
1641 || info.spanY != lp.cellVSpan || presenterPos.screenId != screenId);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001642
Sebastian Franco877088e2023-01-03 15:16:22 -07001643 lp.setCellX(lp.getTmpCellX());
Sebastian Franco877088e2023-01-03 15:16:22 -07001644 lp.setCellY(lp.getTmpCellY());
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001645 if (requiresDbUpdate) {
Sunny Goyalab770a12018-11-14 15:17:26 -08001646 Launcher.cast(mActivity).getModelWriter().modifyItemInDatabase(info, container,
Sunny Goyal669b71f2023-01-27 14:37:07 -08001647 screenId, lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan);
Sunny Goyalaa8ef112015-06-12 20:04:41 -07001648 }
Adam Cohen2acce882012-03-28 19:03:19 -07001649 }
Adam Cohen482ed822012-03-02 14:15:13 -08001650 }
1651 }
1652
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001653 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001654 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001655 for (int i = 0; i < childCount; i++) {
Sebastian Francod4682992022-10-05 13:03:09 -05001656 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) mShortcutsAndWidgets.getChildAt(
1657 i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08001658 lp.useTmpCoords = useTempCoords;
1659 }
1660 }
1661
Adam Cohen19f37922012-03-21 11:59:11 -07001662 // For a given cell and span, fetch the set of views intersecting the region.
Sebastian Francoe4c03452022-12-27 14:50:02 -06001663 public void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
Adam Cohen19f37922012-03-21 11:59:11 -07001664 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
1665 if (boundingRect != null) {
1666 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
1667 }
1668 intersectingViews.clear();
1669 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1670 Rect r1 = new Rect();
1671 final int count = mShortcutsAndWidgets.getChildCount();
1672 for (int i = 0; i < count; i++) {
1673 View child = mShortcutsAndWidgets.getChildAt(i);
1674 if (child == dragView) continue;
Sebastian Francod4682992022-10-05 13:03:09 -05001675 CellLayoutLayoutParams
1676 lp = (CellLayoutLayoutParams) child.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07001677 r1.set(lp.getCellX(), lp.getCellY(), lp.getCellX() + lp.cellHSpan,
1678 lp.getCellY() + lp.cellVSpan);
Adam Cohen19f37922012-03-21 11:59:11 -07001679 if (Rect.intersects(r0, r1)) {
1680 mIntersectingViews.add(child);
1681 if (boundingRect != null) {
1682 boundingRect.union(r1);
1683 }
1684 }
1685 }
1686 }
1687
Sebastian Francoe4c03452022-12-27 14:50:02 -06001688 public boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
Adam Cohen19f37922012-03-21 11:59:11 -07001689 View dragView, int[] result) {
Sebastián Francof9a6ac22022-11-15 22:56:37 +00001690 result = findNearestAreaIgnoreOccupied(pixelX, pixelY, spanX, spanY, result);
Adam Cohen19f37922012-03-21 11:59:11 -07001691 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
1692 mIntersectingViews);
1693 return !mIntersectingViews.isEmpty();
1694 }
1695
1696 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001697 completeAndClearReorderPreviewAnimations();
1698 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
1699 final int count = mShortcutsAndWidgets.getChildCount();
1700 for (int i = 0; i < count; i++) {
1701 View child = mShortcutsAndWidgets.getChildAt(i);
Sebastian Francod4682992022-10-05 13:03:09 -05001702 CellLayoutLayoutParams
1703 lp = (CellLayoutLayoutParams) child.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07001704 if (lp.getTmpCellX() != lp.getCellX() || lp.getTmpCellY() != lp.getCellY()) {
1705 lp.setTmpCellX(lp.getCellX());
1706 lp.setTmpCellY(lp.getCellY());
1707 animateChildToPosition(child, lp.getCellX(), lp.getCellY(),
1708 REORDER_ANIMATION_DURATION, 0, false, false);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001709 }
Adam Cohen19f37922012-03-21 11:59:11 -07001710 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001711 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07001712 }
Adam Cohen19f37922012-03-21 11:59:11 -07001713 }
1714
Adam Cohenbebf0422012-04-11 18:06:28 -07001715 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
1716 View dragView, int[] direction, boolean commit) {
1717 int[] pixelXY = new int[2];
1718 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
1719
1720 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001721 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Sebastian Francof153d912022-04-22 16:15:27 -05001722 spanX, spanY, direction, dragView, true, new ItemConfiguration());
Adam Cohenbebf0422012-04-11 18:06:28 -07001723
1724 setUseTempCoords(true);
1725 if (swapSolution != null && swapSolution.isSolution) {
1726 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
1727 // committing anything or animating anything as we just want to determine if a solution
1728 // exists
1729 copySolutionToTempState(swapSolution, dragView);
1730 setItemPlacementDirty(true);
1731 animateItemsToSolution(swapSolution, dragView, commit);
1732
1733 if (commit) {
Sunny Goyal711c5962021-06-23 12:36:18 -07001734 commitTempPlacement(null);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001735 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07001736 setItemPlacementDirty(false);
1737 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001738 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
Adam Cohen65086992020-02-19 08:40:49 -08001739 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07001740 }
1741 mShortcutsAndWidgets.requestLayout();
1742 }
1743 return swapSolution.isSolution;
1744 }
1745
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001746 /**
1747 * Find a vacant area that will fit the given bounds nearest the requested
1748 * cell location, and will also weigh in a suggested direction vector of the
1749 * desired location. This method computers distance based on unit grid distances,
1750 * not pixel distances.
1751 *
1752 * @param cellX The X cell nearest to which you want to search for a vacant area.
1753 * @param cellY The Y cell nearest which you want to search for a vacant area.
1754 * @param spanX Horizontal span of the object.
1755 * @param spanY Vertical span of the object.
1756 * @param direction The favored direction in which the views should move from x, y
1757 * @param occupied The array which represents which cells in the CellLayout are occupied
1758 * @param blockOccupied The array which represents which cells in the specified block (cellX,
1759 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
1760 * @param result Array in which to place the result, or null (in which case a new array will
1761 * be allocated)
1762 * @return The X, Y cell of a vacant area that can contain this object,
1763 * nearest the requested location.
1764 */
1765 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
1766 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
1767 // Keep track of best-scoring drop area
1768 final int[] bestXY = result != null ? result : new int[2];
1769 float bestDistance = Float.MAX_VALUE;
1770 int bestDirectionScore = Integer.MIN_VALUE;
Adam Cohen482ed822012-03-02 14:15:13 -08001771
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001772 final int countX = mCountX;
1773 final int countY = mCountY;
1774
1775 for (int y = 0; y < countY - (spanY - 1); y++) {
1776 inner:
1777 for (int x = 0; x < countX - (spanX - 1); x++) {
1778 // First, let's see if this thing fits anywhere
1779 for (int i = 0; i < spanX; i++) {
1780 for (int j = 0; j < spanY; j++) {
1781 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1782 continue inner;
1783 }
1784 }
1785 }
1786
1787 float distance = (float) Math.hypot(x - cellX, y - cellY);
1788 int[] curDirection = mTmpPoint;
1789 computeDirectionVector(x - cellX, y - cellY, curDirection);
1790 // The direction score is just the dot product of the two candidate direction
1791 // and that passed in.
1792 int curDirectionScore = direction[0] * curDirection[0] +
1793 direction[1] * curDirection[1];
1794 if (Float.compare(distance, bestDistance) < 0 ||
1795 (Float.compare(distance, bestDistance) == 0
1796 && curDirectionScore > bestDirectionScore)) {
1797 bestDistance = distance;
1798 bestDirectionScore = curDirectionScore;
1799 bestXY[0] = x;
1800 bestXY[1] = y;
1801 }
Adam Cohen19f37922012-03-21 11:59:11 -07001802 }
Adam Cohen19f37922012-03-21 11:59:11 -07001803 }
1804
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001805 // Return -1, -1 if no suitable location found
1806 if (bestDistance == Float.MAX_VALUE) {
1807 bestXY[0] = -1;
1808 bestXY[1] = -1;
Sebastian Franco53a15a42022-10-25 17:28:54 -07001809 }
Sebastian Franco9cab1c32022-10-25 17:28:54 -07001810 return bestXY;
1811 }
1812
1813 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
1814 int[] direction, ItemConfiguration currentState) {
1815 CellAndSpan c = currentState.map.get(v);
1816 boolean success = false;
1817 mTmpOccupied.markCells(c, false);
1818 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
1819
1820 findNearestArea(c.cellX, c.cellY, c.spanX, c.spanY, direction,
1821 mTmpOccupied.cells, null, mTempLocation);
1822
1823 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
1824 c.cellX = mTempLocation[0];
1825 c.cellY = mTempLocation[1];
1826 success = true;
1827 }
1828 mTmpOccupied.markCells(c, true);
1829 return success;
1830 }
1831
1832 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1833 int[] direction, View dragView, ItemConfiguration currentState) {
1834
1835 ViewCluster cluster = new ViewCluster(views, currentState);
1836 Rect clusterRect = cluster.getBoundingRect();
1837 int whichEdge;
1838 int pushDistance;
1839 boolean fail = false;
1840
1841 // Determine the edge of the cluster that will be leading the push and how far
1842 // the cluster must be shifted.
1843 if (direction[0] < 0) {
1844 whichEdge = ViewCluster.LEFT;
1845 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
1846 } else if (direction[0] > 0) {
1847 whichEdge = ViewCluster.RIGHT;
1848 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1849 } else if (direction[1] < 0) {
1850 whichEdge = ViewCluster.TOP;
1851 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1852 } else {
1853 whichEdge = ViewCluster.BOTTOM;
1854 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
1855 }
1856
1857 // Break early for invalid push distance.
1858 if (pushDistance <= 0) {
1859 return false;
1860 }
1861
1862 // Mark the occupied state as false for the group of views we want to move.
1863 for (View v: views) {
1864 CellAndSpan c = currentState.map.get(v);
1865 mTmpOccupied.markCells(c, false);
1866 }
1867
1868 // We save the current configuration -- if we fail to find a solution we will revert
1869 // to the initial state. The process of finding a solution modifies the configuration
1870 // in place, hence the need for revert in the failure case.
1871 currentState.save();
1872
1873 // The pushing algorithm is simplified by considering the views in the order in which
1874 // they would be pushed by the cluster. For example, if the cluster is leading with its
1875 // left edge, we consider sort the views by their right edge, from right to left.
1876 cluster.sortConfigurationForEdgePush(whichEdge);
1877
1878 while (pushDistance > 0 && !fail) {
1879 for (View v: currentState.sortedViews) {
1880 // For each view that isn't in the cluster, we see if the leading edge of the
1881 // cluster is contacting the edge of that view. If so, we add that view to the
1882 // cluster.
1883 if (!cluster.views.contains(v) && v != dragView) {
1884 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1885 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) v.getLayoutParams();
1886 if (!lp.canReorder) {
1887 // The push solution includes the all apps button, this is not viable.
1888 fail = true;
1889 break;
1890 }
1891 cluster.addView(v);
1892 CellAndSpan c = currentState.map.get(v);
1893
1894 // Adding view to cluster, mark it as not occupied.
1895 mTmpOccupied.markCells(c, false);
1896 }
1897 }
1898 }
1899 pushDistance--;
1900
1901 // The cluster has been completed, now we move the whole thing over in the appropriate
1902 // direction.
1903 cluster.shift(whichEdge, 1);
1904 }
1905
1906 boolean foundSolution = false;
1907 clusterRect = cluster.getBoundingRect();
1908
1909 // Due to the nature of the algorithm, the only check required to verify a valid solution
1910 // is to ensure that completed shifted cluster lies completely within the cell layout.
1911 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1912 clusterRect.bottom <= mCountY) {
1913 foundSolution = true;
1914 } else {
1915 currentState.restore();
1916 }
1917
1918 // In either case, we set the occupied array as marked for the location of the views
1919 for (View v: cluster.views) {
1920 CellAndSpan c = currentState.map.get(v);
1921 mTmpOccupied.markCells(c, true);
1922 }
1923
1924 return foundSolution;
1925 }
1926
1927 /**
1928 * This helper class defines a cluster of views. It helps with defining complex edges
1929 * of the cluster and determining how those edges interact with other views. The edges
1930 * essentially define a fine-grained boundary around the cluster of views -- like a more
1931 * precise version of a bounding box.
1932 */
1933 private class ViewCluster {
1934 final static int LEFT = 1 << 0;
1935 final static int TOP = 1 << 1;
1936 final static int RIGHT = 1 << 2;
1937 final static int BOTTOM = 1 << 3;
1938
1939 final ArrayList<View> views;
1940 final ItemConfiguration config;
1941 final Rect boundingRect = new Rect();
1942
1943 final int[] leftEdge = new int[mCountY];
1944 final int[] rightEdge = new int[mCountY];
1945 final int[] topEdge = new int[mCountX];
1946 final int[] bottomEdge = new int[mCountX];
1947 int dirtyEdges;
1948 boolean boundingRectDirty;
1949
1950 @SuppressWarnings("unchecked")
1951 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1952 this.views = (ArrayList<View>) views.clone();
1953 this.config = config;
1954 resetEdges();
1955 }
1956
1957 void resetEdges() {
1958 for (int i = 0; i < mCountX; i++) {
1959 topEdge[i] = -1;
1960 bottomEdge[i] = -1;
1961 }
1962 for (int i = 0; i < mCountY; i++) {
1963 leftEdge[i] = -1;
1964 rightEdge[i] = -1;
1965 }
1966 dirtyEdges = LEFT | TOP | RIGHT | BOTTOM;
1967 boundingRectDirty = true;
1968 }
1969
1970 void computeEdge(int which) {
1971 int count = views.size();
1972 for (int i = 0; i < count; i++) {
1973 CellAndSpan cs = config.map.get(views.get(i));
1974 switch (which) {
1975 case LEFT:
1976 int left = cs.cellX;
1977 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
1978 if (left < leftEdge[j] || leftEdge[j] < 0) {
1979 leftEdge[j] = left;
1980 }
1981 }
1982 break;
1983 case RIGHT:
1984 int right = cs.cellX + cs.spanX;
1985 for (int j = cs.cellY; j < cs.cellY + cs.spanY; j++) {
1986 if (right > rightEdge[j]) {
1987 rightEdge[j] = right;
1988 }
1989 }
1990 break;
1991 case TOP:
1992 int top = cs.cellY;
1993 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
1994 if (top < topEdge[j] || topEdge[j] < 0) {
1995 topEdge[j] = top;
1996 }
1997 }
1998 break;
1999 case BOTTOM:
2000 int bottom = cs.cellY + cs.spanY;
2001 for (int j = cs.cellX; j < cs.cellX + cs.spanX; j++) {
2002 if (bottom > bottomEdge[j]) {
2003 bottomEdge[j] = bottom;
2004 }
2005 }
2006 break;
2007 }
2008 }
2009 }
2010
2011 boolean isViewTouchingEdge(View v, int whichEdge) {
2012 CellAndSpan cs = config.map.get(v);
2013
2014 if ((dirtyEdges & whichEdge) == whichEdge) {
2015 computeEdge(whichEdge);
2016 dirtyEdges &= ~whichEdge;
2017 }
2018
2019 switch (whichEdge) {
2020 case LEFT:
2021 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
2022 if (leftEdge[i] == cs.cellX + cs.spanX) {
2023 return true;
2024 }
2025 }
2026 break;
2027 case RIGHT:
2028 for (int i = cs.cellY; i < cs.cellY + cs.spanY; i++) {
2029 if (rightEdge[i] == cs.cellX) {
2030 return true;
2031 }
2032 }
2033 break;
2034 case TOP:
2035 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
2036 if (topEdge[i] == cs.cellY + cs.spanY) {
2037 return true;
2038 }
2039 }
2040 break;
2041 case BOTTOM:
2042 for (int i = cs.cellX; i < cs.cellX + cs.spanX; i++) {
2043 if (bottomEdge[i] == cs.cellY) {
2044 return true;
2045 }
2046 }
2047 break;
2048 }
2049 return false;
2050 }
2051
2052 void shift(int whichEdge, int delta) {
2053 for (View v: views) {
2054 CellAndSpan c = config.map.get(v);
2055 switch (whichEdge) {
2056 case LEFT:
2057 c.cellX -= delta;
2058 break;
2059 case RIGHT:
2060 c.cellX += delta;
2061 break;
2062 case TOP:
2063 c.cellY -= delta;
2064 break;
2065 case BOTTOM:
2066 default:
2067 c.cellY += delta;
2068 break;
2069 }
2070 }
2071 resetEdges();
2072 }
2073
2074 public void addView(View v) {
2075 views.add(v);
2076 resetEdges();
2077 }
2078
2079 public Rect getBoundingRect() {
2080 if (boundingRectDirty) {
2081 config.getBoundingRectForViews(views, boundingRect);
2082 }
2083 return boundingRect;
2084 }
2085
2086 final PositionComparator comparator = new PositionComparator();
2087 class PositionComparator implements Comparator<View> {
2088 int whichEdge = 0;
2089 public int compare(View left, View right) {
2090 CellAndSpan l = config.map.get(left);
2091 CellAndSpan r = config.map.get(right);
2092 switch (whichEdge) {
2093 case LEFT:
2094 return (r.cellX + r.spanX) - (l.cellX + l.spanX);
2095 case RIGHT:
2096 return l.cellX - r.cellX;
2097 case TOP:
2098 return (r.cellY + r.spanY) - (l.cellY + l.spanY);
2099 case BOTTOM:
2100 default:
2101 return l.cellY - r.cellY;
2102 }
2103 }
2104 }
2105
2106 public void sortConfigurationForEdgePush(int edge) {
2107 comparator.whichEdge = edge;
2108 Collections.sort(config.sortedViews, comparator);
2109 }
2110 }
2111
2112 // This method tries to find a reordering solution which satisfies the push mechanic by trying
2113 // to push items in each of the cardinal directions, in an order based on the direction vector
2114 // passed.
2115 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
2116 int[] direction, View ignoreView, ItemConfiguration solution) {
2117 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
2118 // If the direction vector has two non-zero components, we try pushing
2119 // separately in each of the components.
2120 int temp = direction[1];
2121 direction[1] = 0;
2122
2123 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2124 ignoreView, solution)) {
2125 return true;
2126 }
2127 direction[1] = temp;
2128 temp = direction[0];
2129 direction[0] = 0;
2130
2131 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2132 ignoreView, solution)) {
2133 return true;
2134 }
2135 // Revert the direction
2136 direction[0] = temp;
2137
2138 // Now we try pushing in each component of the opposite direction
2139 direction[0] *= -1;
2140 direction[1] *= -1;
2141 temp = direction[1];
2142 direction[1] = 0;
2143 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2144 ignoreView, solution)) {
2145 return true;
2146 }
2147
2148 direction[1] = temp;
2149 temp = direction[0];
2150 direction[0] = 0;
2151 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2152 ignoreView, solution)) {
2153 return true;
2154 }
2155 // revert the direction
2156 direction[0] = temp;
2157 direction[0] *= -1;
2158 direction[1] *= -1;
2159
2160 } else {
2161 // If the direction vector has a single non-zero component, we push first in the
2162 // direction of the vector
2163 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2164 ignoreView, solution)) {
2165 return true;
2166 }
2167 // Then we try the opposite direction
2168 direction[0] *= -1;
2169 direction[1] *= -1;
2170 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2171 ignoreView, solution)) {
2172 return true;
2173 }
2174 // Switch the direction back
2175 direction[0] *= -1;
2176 direction[1] *= -1;
2177
2178 // If we have failed to find a push solution with the above, then we try
2179 // to find a solution by pushing along the perpendicular axis.
2180
2181 // Swap the components
2182 int temp = direction[1];
2183 direction[1] = direction[0];
2184 direction[0] = temp;
2185 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2186 ignoreView, solution)) {
2187 return true;
2188 }
2189
2190 // Then we try the opposite direction
2191 direction[0] *= -1;
2192 direction[1] *= -1;
2193 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
2194 ignoreView, solution)) {
2195 return true;
2196 }
2197 // Switch the direction back
2198 direction[0] *= -1;
2199 direction[1] *= -1;
2200
2201 // Swap the components back
2202 temp = direction[1];
2203 direction[1] = direction[0];
2204 direction[0] = temp;
2205 }
2206 return false;
2207 }
2208
2209 /*
2210 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
2211 * the provided point and the provided cell
2212 */
2213 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
2214 double angle = Math.atan(deltaY / deltaX);
2215
2216 result[0] = 0;
2217 result[1] = 0;
2218 if (Math.abs(Math.cos(angle)) > 0.5f) {
2219 result[0] = (int) Math.signum(deltaX);
2220 }
2221 if (Math.abs(Math.sin(angle)) > 0.5f) {
2222 result[1] = (int) Math.signum(deltaY);
2223 }
2224 }
2225
2226 /* This seems like it should be obvious and straight-forward, but when the direction vector
2227 needs to match with the notion of the dragView pushing other views, we have to employ
2228 a slightly more subtle notion of the direction vector. The question is what two points is
2229 the vector between? The center of the dragView and its desired destination? Not quite, as
2230 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2231 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2232 or right, which helps make pushing feel right.
2233 */
Sebastian Francoe4c03452022-12-27 14:50:02 -06002234 public void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002235 int spanY, View dragView, int[] resultDirection) {
2236
2237 //TODO(adamcohen) b/151776141 use the items visual center for the direction vector
2238 int[] targetDestination = new int[2];
2239
Sebastián Francof9a6ac22022-11-15 22:56:37 +00002240 findNearestAreaIgnoreOccupied(dragViewCenterX, dragViewCenterY, spanX, spanY,
2241 targetDestination);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002242 Rect dragRect = new Rect();
2243 cellToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2244 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2245
2246 Rect dropRegionRect = new Rect();
2247 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2248 dragView, dropRegionRect, mIntersectingViews);
2249
2250 int dropRegionSpanX = dropRegionRect.width();
2251 int dropRegionSpanY = dropRegionRect.height();
2252
2253 cellToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2254 dropRegionRect.height(), dropRegionRect);
2255
2256 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2257 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2258
2259 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2260 deltaX = 0;
2261 }
2262 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2263 deltaY = 0;
2264 }
2265
2266 if (deltaX == 0 && deltaY == 0) {
2267 // No idea what to do, give a random direction.
2268 resultDirection[0] = 1;
2269 resultDirection[1] = 0;
2270 } else {
2271 computeDirectionVector(deltaX, deltaY, resultDirection);
2272 }
2273 }
2274
2275 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
2276 int[] direction, View dragView, ItemConfiguration currentState) {
2277 if (views.size() == 0) return true;
2278
2279 boolean success = false;
2280 Rect boundingRect = new Rect();
2281 // We construct a rect which represents the entire group of views passed in
2282 currentState.getBoundingRectForViews(views, boundingRect);
2283
2284 // Mark the occupied state as false for the group of views we want to move.
2285 for (View v: views) {
2286 CellAndSpan c = currentState.map.get(v);
2287 mTmpOccupied.markCells(c, false);
2288 }
2289
2290 GridOccupancy blockOccupied = new GridOccupancy(boundingRect.width(), boundingRect.height());
2291 int top = boundingRect.top;
2292 int left = boundingRect.left;
2293 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
2294 // for interlocking.
2295 for (View v: views) {
2296 CellAndSpan c = currentState.map.get(v);
2297 blockOccupied.markCells(c.cellX - left, c.cellY - top, c.spanX, c.spanY, true);
2298 }
2299
2300 mTmpOccupied.markCells(rectOccupiedByPotentialDrop, true);
2301
2302 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
2303 boundingRect.height(), direction,
2304 mTmpOccupied.cells, blockOccupied.cells, mTempLocation);
2305
2306 // If we successfully found a location by pushing the block of views, we commit it
2307 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
2308 int deltaX = mTempLocation[0] - boundingRect.left;
2309 int deltaY = mTempLocation[1] - boundingRect.top;
2310 for (View v: views) {
2311 CellAndSpan c = currentState.map.get(v);
2312 c.cellX += deltaX;
2313 c.cellY += deltaY;
2314 }
2315 success = true;
2316 }
2317
2318 // In either case, we set the occupied array as marked for the location of the views
2319 for (View v: views) {
2320 CellAndSpan c = currentState.map.get(v);
2321 mTmpOccupied.markCells(c, true);
2322 }
2323 return success;
2324 }
2325
Sebastian Francoe4c03452022-12-27 14:50:02 -06002326 public boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002327 View ignoreView, ItemConfiguration solution) {
2328 // Return early if get invalid cell positions
2329 if (cellX < 0 || cellY < 0) return false;
2330
2331 mIntersectingViews.clear();
2332 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2333
2334 // Mark the desired location of the view currently being dragged.
2335 if (ignoreView != null) {
2336 CellAndSpan c = solution.map.get(ignoreView);
2337 if (c != null) {
2338 c.cellX = cellX;
2339 c.cellY = cellY;
2340 }
2341 }
2342 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2343 Rect r1 = new Rect();
Sebastian Franco45b39b52023-01-10 10:47:46 -06002344 // The views need to be sorted so that the results are deterministic on the views positions
2345 // and not by the views hash which is "random".
2346 // The views are sorted twice, once for the X position and a second time for the Y position
2347 // to ensure same order everytime.
2348 Comparator comparator = Comparator.comparing(view ->
2349 ((CellLayoutLayoutParams) ((View) view).getLayoutParams()).getCellX())
2350 .thenComparing(view ->
2351 ((CellLayoutLayoutParams) ((View) view).getLayoutParams()).getCellY());
2352 List<View> views = solution.map.keySet().stream().sorted(comparator).toList();
2353 for (View child : views) {
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002354 if (child == ignoreView) continue;
2355 CellAndSpan c = solution.map.get(child);
2356 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
2357 r1.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2358 if (Rect.intersects(r0, r1)) {
2359 if (!lp.canReorder) {
2360 return false;
2361 }
2362 mIntersectingViews.add(child);
2363 }
2364 }
2365
2366 solution.intersectingViews = new ArrayList<>(mIntersectingViews);
2367
2368 // First we try to find a solution which respects the push mechanic. That is,
2369 // we try to find a solution such that no displaced item travels through another item
2370 // without also displacing that item.
2371 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
2372 solution)) {
2373 return true;
2374 }
2375
2376 // Next we try moving the views as a block, but without requiring the push mechanic.
2377 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
2378 solution)) {
2379 return true;
2380 }
2381
2382 // Ok, they couldn't move as a block, let's move them individually
2383 for (View v : mIntersectingViews) {
2384 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
2385 return false;
2386 }
2387 }
2388 return true;
2389 }
2390
Sebastian Francoe4c03452022-12-27 14:50:02 -06002391 public ReorderAlgorithm createReorderAlgorithm() {
2392 return new ReorderAlgorithm(this);
2393 }
2394
Sebastian Franco09589322022-11-02 15:25:58 -07002395 protected ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX,
2396 int minSpanY, int spanX, int spanY, int[] direction, View dragView, boolean decX,
2397 ItemConfiguration solution) {
Sebastian Francoe4c03452022-12-27 14:50:02 -06002398 return createReorderAlgorithm().findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
2399 spanX, spanY, direction, dragView, decX, solution);
Sebastian Franco09589322022-11-02 15:25:58 -07002400 }
2401
Sebastian Francoe4c03452022-12-27 14:50:02 -06002402 public void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002403 int childCount = mShortcutsAndWidgets.getChildCount();
2404 for (int i = 0; i < childCount; i++) {
2405 View child = mShortcutsAndWidgets.getChildAt(i);
2406 CellLayoutLayoutParams lp = (CellLayoutLayoutParams) child.getLayoutParams();
2407 CellAndSpan c;
2408 if (temp) {
Sebastian Franco877088e2023-01-03 15:16:22 -07002409 c = new CellAndSpan(lp.getTmpCellX(), lp.getTmpCellY(), lp.cellHSpan, lp.cellVSpan);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002410 } else {
Sebastian Franco877088e2023-01-03 15:16:22 -07002411 c = new CellAndSpan(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002412 }
2413 solution.add(child, c);
2414 }
Sebastian Franco53a15a42022-10-25 17:28:54 -07002415 }
2416
2417 /**
Sebastian Franco53a15a42022-10-25 17:28:54 -07002418 * When the user drags an Item in the workspace sometimes we need to move the items already in
2419 * the workspace to make space for the new item, this function return a solution for that
2420 * reorder.
2421 *
2422 * @param pixelX X coordinate in the screen of the dragView in pixels
2423 * @param pixelY Y coordinate in the screen of the dragView in pixels
2424 * @param minSpanX minimum horizontal span the item can be shrunk to
2425 * @param minSpanY minimum vertical span the item can be shrunk to
2426 * @param spanX occupied horizontal span
2427 * @param spanY occupied vertical span
2428 * @param dragView the view of the item being draged
2429 * @return returns a solution for the given parameters, the solution contains all the icons and
2430 * the locations they should be in the given solution.
2431 */
2432 public ItemConfiguration calculateReorder(int pixelX, int pixelY, int minSpanX, int minSpanY,
2433 int spanX, int spanY, View dragView) {
Sebastian Francoe4c03452022-12-27 14:50:02 -06002434 return createReorderAlgorithm().calculateReorder(pixelX, pixelY, minSpanX, minSpanY,
2435 spanX, spanY, dragView);
Sebastian Franco53a15a42022-10-25 17:28:54 -07002436 }
Adam Cohen482ed822012-03-02 14:15:13 -08002437
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002438 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2439 View dragView, int[] result, int[] resultSpan, int mode) {
2440 if (resultSpan == null) {
2441 resultSpan = new int[]{-1, -1};
2442 }
2443 if (result == null) {
2444 result = new int[]{-1, -1};
2445 }
Sebastian Franco5d990ee2022-11-01 16:08:24 -07002446
2447 ItemConfiguration finalSolution = null;
2448 // We want the solution to match the animation of the preview and to match the drop so we
2449 // only recalculate in mode MODE_SHOW_REORDER_HINT because that the first one to run in the
2450 // reorder cycle.
2451 if (mode == MODE_SHOW_REORDER_HINT || mPreviousSolution == null) {
2452 finalSolution = calculateReorder(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY,
2453 dragView);
2454 mPreviousSolution = finalSolution;
2455 } else {
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002456 finalSolution = mPreviousSolution;
2457 // We reset this vector after drop
2458 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2459 mPreviousSolution = null;
2460 }
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002461 }
2462
2463 if (finalSolution == null || !finalSolution.isSolution) {
2464 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2465 } else {
2466 result[0] = finalSolution.cellX;
2467 result[1] = finalSolution.cellY;
2468 resultSpan[0] = finalSolution.spanX;
2469 resultSpan[1] = finalSolution.spanY;
Sebastian Franco9c743272022-11-15 15:03:25 -08002470 performReorder(finalSolution, dragView, mode);
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002471 }
Sebastian Franco9cab1c32022-10-25 17:28:54 -07002472 return result;
2473 }
2474
Sebastian Franco53a15a42022-10-25 17:28:54 -07002475 /**
2476 * Animates and submits in the DB the given ItemConfiguration depending of the mode.
2477 *
2478 * @param solution represents widgets on the screen which the Workspace will animate to and
2479 * would be submitted to the database.
2480 * @param dragView view which is being dragged over the workspace that trigger the reorder
2481 * @param mode depending on the mode different animations would be played and depending on the
2482 * mode the solution would be submitted or not the database.
2483 * The possible modes are {@link MODE_SHOW_REORDER_HINT}, {@link MODE_DRAG_OVER},
2484 * {@link MODE_ON_DROP}, {@link MODE_ON_DROP_EXTERNAL}, {@link MODE_ACCEPT_DROP}
2485 * defined in {@link CellLayout}.
2486 */
Sebastian Francoe4c03452022-12-27 14:50:02 -06002487 public void performReorder(ItemConfiguration solution, View dragView, int mode) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002488 if (mode == MODE_SHOW_REORDER_HINT) {
Sebastian Franco53a15a42022-10-25 17:28:54 -07002489 beginOrAdjustReorderPreviewAnimations(solution, dragView,
2490 ReorderPreviewAnimation.MODE_HINT);
2491 return;
2492 }
2493 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2494 // committing anything or animating anything as we just want to determine if a solution
2495 // exists
2496 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2497 if (!DESTRUCTIVE_REORDER) {
2498 setUseTempCoords(true);
2499 }
2500
2501 if (!DESTRUCTIVE_REORDER) {
2502 copySolutionToTempState(solution, dragView);
2503 }
2504 setItemPlacementDirty(true);
2505 animateItemsToSolution(solution, dragView, mode == MODE_ON_DROP);
2506
2507 if (!DESTRUCTIVE_REORDER
2508 && (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
2509 // Since the temp solution didn't update dragView, don't commit it either
2510 commitTempPlacement(dragView);
2511 completeAndClearReorderPreviewAnimations();
2512 setItemPlacementDirty(false);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002513 } else {
Sebastian Franco53a15a42022-10-25 17:28:54 -07002514 beginOrAdjustReorderPreviewAnimations(solution, dragView,
2515 ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002516 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002517 }
2518
Sebastian Franco53a15a42022-10-25 17:28:54 -07002519 if (mode == MODE_ON_DROP && !DESTRUCTIVE_REORDER) {
Adam Cohen482ed822012-03-02 14:15:13 -08002520 setUseTempCoords(false);
2521 }
Adam Cohen482ed822012-03-02 14:15:13 -08002522
Michael Jurkaa52570f2012-03-20 03:18:20 -07002523 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002524 }
2525
Adam Cohen19f37922012-03-21 11:59:11 -07002526 void setItemPlacementDirty(boolean dirty) {
2527 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002528 }
Adam Cohen19f37922012-03-21 11:59:11 -07002529 boolean isItemPlacementDirty() {
2530 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002531 }
2532
Sebastian Francoe4c03452022-12-27 14:50:02 -06002533 /**
2534 * Represents the solution to a reorder of items in the Workspace.
2535 */
2536 public static class ItemConfiguration extends CellAndSpan {
2537 public final ArrayMap<View, CellAndSpan> map = new ArrayMap<>();
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002538 private final ArrayMap<View, CellAndSpan> savedMap = new ArrayMap<>();
Sebastian Francoe4c03452022-12-27 14:50:02 -06002539 public final ArrayList<View> sortedViews = new ArrayList<>();
2540 public ArrayList<View> intersectingViews;
2541 public boolean isSolution = false;
Adam Cohen482ed822012-03-02 14:15:13 -08002542
Sebastian Francoe4c03452022-12-27 14:50:02 -06002543 public void save() {
Adam Cohenf3900c22012-11-16 18:28:11 -08002544 // Copy current state into savedMap
2545 for (View v: map.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002546 savedMap.get(v).copyFrom(map.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002547 }
2548 }
2549
Sebastian Francoe4c03452022-12-27 14:50:02 -06002550 public void restore() {
Adam Cohenf3900c22012-11-16 18:28:11 -08002551 // Restore current state from savedMap
2552 for (View v: savedMap.keySet()) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002553 map.get(v).copyFrom(savedMap.get(v));
Adam Cohenf3900c22012-11-16 18:28:11 -08002554 }
2555 }
2556
Sebastian Francoe4c03452022-12-27 14:50:02 -06002557 public void add(View v, CellAndSpan cs) {
Adam Cohenf3900c22012-11-16 18:28:11 -08002558 map.put(v, cs);
2559 savedMap.put(v, new CellAndSpan());
2560 sortedViews.add(v);
2561 }
2562
Sebastian Francoe4c03452022-12-27 14:50:02 -06002563 public int area() {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002564 return spanX * spanY;
Adam Cohenf3900c22012-11-16 18:28:11 -08002565 }
2566
Sebastian Francoe4c03452022-12-27 14:50:02 -06002567 public void getBoundingRectForViews(ArrayList<View> views, Rect outRect) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002568 boolean first = true;
2569 for (View v: views) {
2570 CellAndSpan c = map.get(v);
2571 if (first) {
2572 outRect.set(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2573 first = false;
2574 } else {
2575 outRect.union(c.cellX, c.cellY, c.cellX + c.spanX, c.cellY + c.spanY);
2576 }
2577 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002578 }
Adam Cohen482ed822012-03-02 14:15:13 -08002579 }
2580
Adam Cohendf035382011-04-11 17:22:04 -07002581 /**
Adam Cohendf035382011-04-11 17:22:04 -07002582 * Find a starting cell position that will fit the given bounds nearest the requested
2583 * cell location. Uses Euclidean distance to score multiple vacant areas.
2584 *
2585 * @param pixelX The X location at which you want to search for a vacant area.
2586 * @param pixelY The Y location at which you want to search for a vacant area.
2587 * @param spanX Horizontal span of the object.
2588 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07002589 * @param result Previously returned value to possibly recycle.
2590 * @return The X, Y cell of a vacant area that can contain this object,
2591 * nearest the requested location.
2592 */
Sebastián Francof9a6ac22022-11-15 22:56:37 +00002593 public int[] findNearestAreaIgnoreOccupied(int pixelX, int pixelY, int spanX, int spanY,
2594 int[] result) {
Sebastian Francob57c0b22022-06-28 13:54:35 -07002595 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, true, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002596 }
2597
Michael Jurka0280c3b2010-09-17 15:00:07 -07002598 boolean existsEmptyCell() {
2599 return findCellForSpan(null, 1, 1);
2600 }
2601
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002602 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002603 * Finds the upper-left coordinate of the first rectangle in the grid that can
2604 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2605 * then this method will only return coordinates for rectangles that contain the cell
2606 * (intersectX, intersectY)
2607 *
2608 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2609 * can be found.
2610 * @param spanX The horizontal span of the cell we want to find.
2611 * @param spanY The vertical span of the cell we want to find.
2612 *
2613 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002614 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002615 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002616 if (cellXY == null) {
2617 cellXY = new int[2];
Michael Jurka0280c3b2010-09-17 15:00:07 -07002618 }
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002619 return mOccupied.findVacantCell(cellXY, spanX, spanY);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002620 }
2621
2622 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002623 * A drag event has begun over this layout.
2624 * It may have begun over this layout (in which case onDragChild is called first),
2625 * or it may have begun on another layout.
2626 */
2627 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002628 mDragging = true;
Sebastian Franco5aa71ce2022-12-14 12:13:19 -06002629 mPreviousSolution = null;
Winson Chungc07918d2011-07-01 15:35:26 -07002630 }
2631
2632 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002633 * Called when drag has left this CellLayout or has been completed (successfully or not)
2634 */
2635 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002636 // This can actually be called when we aren't in a drag, e.g. when adding a new
2637 // item to this layout via the customize drawer.
2638 // Guard against that case.
2639 if (mDragging) {
2640 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002641 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002642
2643 // Invalidate the drag data
Sebastian Franco5aa71ce2022-12-14 12:13:19 -06002644 mPreviousSolution = null;
Adam Cohend41fbf52012-02-16 23:53:59 -08002645 mDragCell[0] = mDragCell[1] = -1;
Adam Cohenf7ca3b42021-02-22 11:03:58 -08002646 mDragCellSpan[0] = mDragCellSpan[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002647 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2648 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002649 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002650 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002651 }
2652
2653 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002654 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002655 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002656 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002657 *
2658 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002659 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002660 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002661 if (child != null) {
Sebastian Francod4682992022-10-05 13:03:09 -05002662 CellLayoutLayoutParams
2663 lp = (CellLayoutLayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002664 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002665 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002666 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002667 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002668 }
2669
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002670 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002671 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002672 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002673 * @param cellX X coordinate of upper left corner expressed as a cell position
2674 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002675 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002676 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002677 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002678 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002679 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002680 final int cellWidth = mCellWidth;
2681 final int cellHeight = mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -07002682
Pierre Barbier de Reuille1b8bbb62021-05-19 22:45:16 +01002683 // We observe a shift of 1 pixel on the x coordinate compared to the actual cell coordinates
2684 final int hStartPadding = getPaddingLeft()
2685 + (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Winson Chung4b825dcd2011-06-19 12:41:22 -07002686 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002687
Thales Lima78d00ad2021-09-30 11:29:06 +01002688 int x = hStartPadding + (cellX * mBorderSpace.x) + (cellX * cellWidth);
2689 int y = vStartPadding + (cellY * mBorderSpace.y) + (cellY * cellHeight);
Jon Miranda228877d2021-02-09 11:05:00 -05002690
Thales Lima78d00ad2021-09-30 11:29:06 +01002691 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * mBorderSpace.x);
2692 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * mBorderSpace.y);
Winson Chungaafa03c2010-06-11 17:34:16 -07002693
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002694 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002695 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002696
Adam Cohend4844c32011-02-18 19:25:06 -08002697 public void markCellsAsOccupiedForView(View view) {
Sebastian Francof153d912022-04-22 16:15:27 -05002698 if (view instanceof LauncherAppWidgetHostView
2699 && view.getTag() instanceof LauncherAppWidgetInfo) {
2700 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
Sunny Goyal669b71f2023-01-27 14:37:07 -08002701 CellPos pos = mActivity.getCellPosMapper().mapModelToPresenter(info);
2702 mOccupied.markCells(pos.cellX, pos.cellY, info.spanX, info.spanY, true);
Sebastian Francof153d912022-04-22 16:15:27 -05002703 return;
2704 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002705 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Sebastian Francod4682992022-10-05 13:03:09 -05002706 CellLayoutLayoutParams
2707 lp = (CellLayoutLayoutParams) view.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07002708 mOccupied.markCells(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002709 }
2710
Adam Cohend4844c32011-02-18 19:25:06 -08002711 public void markCellsAsUnoccupiedForView(View view) {
Sebastian Francof153d912022-04-22 16:15:27 -05002712 if (view instanceof LauncherAppWidgetHostView
2713 && view.getTag() instanceof LauncherAppWidgetInfo) {
2714 LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) view.getTag();
Sunny Goyal669b71f2023-01-27 14:37:07 -08002715 CellPos pos = mActivity.getCellPosMapper().mapModelToPresenter(info);
2716 mOccupied.markCells(pos.cellX, pos.cellY, info.spanX, info.spanY, false);
Sebastian Francof153d912022-04-22 16:15:27 -05002717 return;
2718 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002719 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Sebastian Francod4682992022-10-05 13:03:09 -05002720 CellLayoutLayoutParams
2721 lp = (CellLayoutLayoutParams) view.getLayoutParams();
Sebastian Franco877088e2023-01-03 15:16:22 -07002722 mOccupied.markCells(lp.getCellX(), lp.getCellY(), lp.cellHSpan, lp.cellVSpan, false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002723 }
2724
Adam Cohen2801caf2011-05-13 20:57:39 -07002725 public int getDesiredWidth() {
Jon Miranda228877d2021-02-09 11:05:00 -05002726 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth)
Thales Lima78d00ad2021-09-30 11:29:06 +01002727 + ((mCountX - 1) * mBorderSpace.x);
Adam Cohen2801caf2011-05-13 20:57:39 -07002728 }
2729
2730 public int getDesiredHeight() {
Jon Miranda228877d2021-02-09 11:05:00 -05002731 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight)
Thales Lima78d00ad2021-09-30 11:29:06 +01002732 + ((mCountY - 1) * mBorderSpace.y);
Adam Cohen2801caf2011-05-13 20:57:39 -07002733 }
2734
Michael Jurka66d72172011-04-12 16:29:25 -07002735 public boolean isOccupied(int x, int y) {
2736 if (x < mCountX && y < mCountY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002737 return mOccupied.cells[x][y];
Michael Jurka66d72172011-04-12 16:29:25 -07002738 } else {
2739 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2740 }
2741 }
2742
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002743 @Override
2744 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
Sebastian Francod4682992022-10-05 13:03:09 -05002745 return new CellLayoutLayoutParams(getContext(), attrs);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002746 }
2747
2748 @Override
2749 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
Sebastian Francod4682992022-10-05 13:03:09 -05002750 return p instanceof CellLayoutLayoutParams;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002751 }
2752
2753 @Override
2754 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
Sebastian Francod4682992022-10-05 13:03:09 -05002755 return new CellLayoutLayoutParams(p);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002756 }
2757
Michael Jurka0280c3b2010-09-17 15:00:07 -07002758 // This class stores info for two purposes:
2759 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2760 // its spanX, spanY, and the screen it is on
2761 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2762 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2763 // the CellLayout that was long clicked
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002764 public static final class CellInfo extends CellAndSpan {
Rajeev Kumar9962dbe2017-06-12 12:16:20 -07002765 public final View cell;
Sunny Goyalefb7e842018-10-04 15:11:00 -07002766 final int screenId;
2767 final int container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002768
Sunny Goyal669b71f2023-01-27 14:37:07 -08002769 public CellInfo(View v, ItemInfo info, CellPos cellPos) {
2770 cellX = cellPos.cellX;
2771 cellY = cellPos.cellY;
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002772 spanX = info.spanX;
2773 spanY = info.spanY;
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002774 cell = v;
Sunny Goyal669b71f2023-01-27 14:37:07 -08002775 screenId = cellPos.screenId;
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002776 container = info.container;
2777 }
2778
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002779 @Override
2780 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002781 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2782 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002783 }
2784 }
Michael Jurkad771c962011-08-09 15:00:48 -07002785
Tony Wickham86930612015-09-09 13:50:40 -07002786 /**
Samuel Fufa1e2d0042019-11-18 17:12:46 -08002787 * A Delegated cell Drawing for drawing on CellLayout
2788 */
2789 public abstract static class DelegatedCellDrawing {
2790 public int mDelegateCellX;
2791 public int mDelegateCellY;
2792
2793 /**
2794 * Draw under CellLayout
2795 */
2796 public abstract void drawUnderItem(Canvas canvas);
2797
2798 /**
2799 * Draw over CellLayout
2800 */
2801 public abstract void drawOverItem(Canvas canvas);
2802 }
2803
2804 /**
Tony Wickham86930612015-09-09 13:50:40 -07002805 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2806 * if necessary).
2807 */
2808 public boolean hasReorderSolution(ItemInfo itemInfo) {
2809 int[] cellPoint = new int[2];
2810 // Check for a solution starting at every cell.
2811 for (int cellX = 0; cellX < getCountX(); cellX++) {
2812 for (int cellY = 0; cellY < getCountY(); cellY++) {
2813 cellToPoint(cellX, cellY, cellPoint);
2814 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
2815 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
2816 true, new ItemConfiguration()).isSolution) {
2817 return true;
2818 }
2819 }
2820 }
2821 return false;
2822 }
2823
Samuel Fufaa4211432020-02-25 18:47:54 -08002824 /**
2825 * Finds solution to accept hotseat migration to cell layout. commits solution if commitConfig
2826 */
2827 public boolean makeSpaceForHotseatMigration(boolean commitConfig) {
Samuel Fufaa4211432020-02-25 18:47:54 -08002828 int[] cellPoint = new int[2];
2829 int[] directionVector = new int[]{0, -1};
2830 cellToPoint(0, mCountY, cellPoint);
2831 ItemConfiguration configuration = new ItemConfiguration();
2832 if (findReorderSolution(cellPoint[0], cellPoint[1], mCountX, 1, mCountX, 1,
2833 directionVector, null, false, configuration).isSolution) {
2834 if (commitConfig) {
2835 copySolutionToTempState(configuration, null);
Sunny Goyal711c5962021-06-23 12:36:18 -07002836 commitTempPlacement(null);
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002837 // undo marking cells occupied since there is actually nothing being placed yet.
2838 mOccupied.markCells(0, mCountY - 1, mCountX, 1, false);
Samuel Fufaa4211432020-02-25 18:47:54 -08002839 }
2840 return true;
2841 }
2842 return false;
2843 }
2844
Samuel Fufa82bbdac2020-03-09 18:24:47 -07002845 /**
2846 * returns a copy of cell layout's grid occupancy
2847 */
2848 public GridOccupancy cloneGridOccupancy() {
2849 GridOccupancy occupancy = new GridOccupancy(mCountX, mCountY);
2850 mOccupied.copyTo(occupancy);
2851 return occupancy;
2852 }
2853
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002854 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
Sunny Goyalff4ba2d2016-04-02 14:12:34 -07002855 return mOccupied.isRegionVacant(x, y, spanX, spanY);
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002856 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002857}