blob: d283a328f232f5abc392faa2d4f1194a606f87b8 [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
Joe Onorato4be866d2010-10-10 11:26:02 -070019import android.animation.Animator;
Michael Jurka629758f2012-06-14 16:18:21 -070020import android.animation.AnimatorListenerAdapter;
Chet Haase00397b12010-10-07 11:13:10 -070021import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070022import android.animation.ValueAnimator;
23import android.animation.ValueAnimator.AnimatorUpdateListener;
Adam Cohenc9735cf2015-01-23 16:11:55 -080024import android.annotation.TargetApi;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040026import android.content.res.Resources;
Joe Onorato4be866d2010-10-10 11:26:02 -070027import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070028import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080029import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070030import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070031import android.graphics.Point;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080033import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070034import android.graphics.drawable.Drawable;
Tony Wickhame0c33232016-02-08 11:37:04 -080035import android.graphics.drawable.GradientDrawable;
Sunny Goyal2805e632015-05-20 15:35:32 -070036import android.graphics.drawable.TransitionDrawable;
Adam Cohenc9735cf2015-01-23 16:11:55 -080037import android.os.Build;
Adam Cohen1462de32012-07-24 22:34:36 -070038import android.os.Parcelable;
Adam Cohenc9735cf2015-01-23 16:11:55 -080039import android.support.v4.view.ViewCompat;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070041import android.util.Log;
Adam Cohen1462de32012-07-24 22:34:36 -070042import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.view.MotionEvent;
44import android.view.View;
45import android.view.ViewDebug;
46import android.view.ViewGroup;
Adam Cohenc9735cf2015-01-23 16:11:55 -080047import android.view.accessibility.AccessibilityEvent;
Winson Chung150fbab2010-09-29 17:14:26 -070048import android.view.animation.DecelerateInterpolator;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049
Sunny Goyal4b6eb262015-05-14 19:24:40 -070050import com.android.launcher3.BubbleTextView.BubbleTextShadowHandler;
Daniel Sandler325dc232013-06-05 22:57:57 -040051import com.android.launcher3.FolderIcon.FolderRingAnimator;
Sunny Goyalaa8ef112015-06-12 20:04:41 -070052import com.android.launcher3.LauncherSettings.Favorites;
Sunny Goyale9b651e2015-04-24 11:44:51 -070053import com.android.launcher3.accessibility.DragAndDropAccessibilityDelegate;
54import com.android.launcher3.accessibility.FolderAccessibilityHelper;
55import com.android.launcher3.accessibility.WorkspaceAccessibilityHelper;
Tony Wickhame0c33232016-02-08 11:37:04 -080056import com.android.launcher3.config.FeatureFlags;
Sunny Goyal6c56c682015-07-16 14:09:05 -070057import com.android.launcher3.config.ProviderConfig;
Sunny Goyale2fd14b2015-08-27 17:45:46 -070058import com.android.launcher3.util.ParcelableSparseArray;
Adam Cohen091440a2015-03-18 14:16:05 -070059import com.android.launcher3.util.Thunk;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070060
Adam Cohen69ce2e52011-07-03 19:25:21 -070061import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070062import java.util.Arrays;
Adam Cohenf3900c22012-11-16 18:28:11 -080063import java.util.Collections;
64import java.util.Comparator;
Adam Cohenbfbfd262011-06-13 16:55:12 -070065import java.util.HashMap;
Adam Cohend41fbf52012-02-16 23:53:59 -080066import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070067
Sunny Goyal4b6eb262015-05-14 19:24:40 -070068public class CellLayout extends ViewGroup implements BubbleTextShadowHandler {
Sunny Goyale9b651e2015-04-24 11:44:51 -070069 public static final int WORKSPACE_ACCESSIBILITY_DRAG = 2;
70 public static final int FOLDER_ACCESSIBILITY_DRAG = 1;
71
Tony Wickhama0628cc2015-10-14 15:23:04 -070072 private static final String TAG = "CellLayout";
73 private static final boolean LOGD = false;
Winson Chungaafa03c2010-06-11 17:34:16 -070074
Adam Cohen2acce882012-03-28 19:03:19 -070075 private Launcher mLauncher;
Adam Cohen091440a2015-03-18 14:16:05 -070076 @Thunk int mCellWidth;
77 @Thunk int mCellHeight;
Winson Chung11a1a532013-09-13 11:14:45 -070078 private int mFixedCellWidth;
79 private int mFixedCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070080
Adam Cohen091440a2015-03-18 14:16:05 -070081 @Thunk int mCountX;
82 @Thunk int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083
Adam Cohen234c4cd2011-07-17 21:03:04 -070084 private int mOriginalWidthGap;
85 private int mOriginalHeightGap;
Adam Cohen091440a2015-03-18 14:16:05 -070086 @Thunk int mWidthGap;
87 @Thunk int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070088 private int mMaxGap;
Adam Cohen917e3882013-10-31 15:03:35 -070089 private boolean mDropPending = false;
Adam Cohenc50438c2014-08-19 17:43:05 -070090 private boolean mIsDragTarget = true;
Sunny Goyale2fd14b2015-08-27 17:45:46 -070091 private boolean mJailContent = true;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080092
Patrick Dubroyde7658b2010-09-27 11:15:43 -070093 // These are temporary variables to prevent having to allocate a new object just to
94 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Adam Cohen091440a2015-03-18 14:16:05 -070095 @Thunk final int[] mTmpPoint = new int[2];
Sunny Goyal2805e632015-05-20 15:35:32 -070096 @Thunk final int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070097
The Android Open Source Project31dd5032009-03-03 19:32:27 -080098 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -080099 boolean[][] mTmpOccupied;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800100
Michael Jurkadee05892010-07-27 10:01:56 -0700101 private OnTouchListener mInterceptTouchListener;
Mady Melloref044dd2015-06-02 15:35:07 -0700102 private StylusEventHelper mStylusEventHelper;
Michael Jurkadee05892010-07-27 10:01:56 -0700103
Adam Cohen69ce2e52011-07-03 19:25:21 -0700104 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -0700105 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -0700106
Michael Jurka5f1c5092010-09-03 14:15:02 -0700107 private float mBackgroundAlpha;
Adam Cohenf34bab52010-09-30 14:11:56 -0700108
Sunny Goyal2805e632015-05-20 15:35:32 -0700109 private static final int BACKGROUND_ACTIVATE_DURATION = 120;
110 private final TransitionDrawable mBackground;
111
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700112 // These values allow a fixed measurement to be set on the CellLayout.
113 private int mFixedWidth = -1;
114 private int mFixedHeight = -1;
115
Michael Jurka33945b22010-12-21 18:19:38 -0800116 // If we're actively dragging something over this screen, mIsDragOverlapping is true
117 private boolean mIsDragOverlapping = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700118
Winson Chung150fbab2010-09-29 17:14:26 -0700119 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700120 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohen091440a2015-03-18 14:16:05 -0700121 @Thunk Rect[] mDragOutlines = new Rect[4];
122 @Thunk float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700123 private InterruptibleInOutAnimator[] mDragOutlineAnims =
124 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700125
126 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700127 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700128 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700129
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700130 private final ClickShadowView mTouchFeedbackView;
Patrick Dubroy96864c32011-03-10 17:17:23 -0800131
Sunny Goyal316490e2015-06-02 09:38:28 -0700132 @Thunk HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new HashMap<>();
133 @Thunk HashMap<View, ReorderPreviewAnimation> mShakeAnimators = new HashMap<>();
Adam Cohen19f37922012-03-21 11:59:11 -0700134
135 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700136
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700137 // When a drag operation is in progress, holds the nearest cell to the touch point
138 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800139
Joe Onorato4be866d2010-10-10 11:26:02 -0700140 private boolean mDragging = false;
141
Patrick Dubroyce34a972010-10-19 10:34:32 -0700142 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700143 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700144
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800145 private boolean mIsHotseat = false;
Adam Cohen307fe232012-08-16 17:55:58 -0700146 private float mHotseatScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800147
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800148 public static final int MODE_SHOW_REORDER_HINT = 0;
149 public static final int MODE_DRAG_OVER = 1;
150 public static final int MODE_ON_DROP = 2;
151 public static final int MODE_ON_DROP_EXTERNAL = 3;
152 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700153 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800154 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
155
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800156 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700157 private static final int REORDER_ANIMATION_DURATION = 150;
Adam Cohen091440a2015-03-18 14:16:05 -0700158 @Thunk float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700159
Adam Cohen482ed822012-03-02 14:15:13 -0800160 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
161 private Rect mOccupiedRect = new Rect();
162 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700163 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700164 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800165
Sunny Goyal2805e632015-05-20 15:35:32 -0700166 private final Rect mTempRect = new Rect();
Winson Chung3a6e7f32013-10-09 15:50:52 -0700167
Michael Jurkaca993832012-06-29 15:17:04 -0700168 private final static Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700169
Adam Cohenc9735cf2015-01-23 16:11:55 -0800170 // Related to accessible drag and drop
Sunny Goyale9b651e2015-04-24 11:44:51 -0700171 private DragAndDropAccessibilityDelegate mTouchHelper;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800172 private boolean mUseTouchHelper = false;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800173
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800174 public CellLayout(Context context) {
175 this(context, null);
176 }
177
178 public CellLayout(Context context, AttributeSet attrs) {
179 this(context, attrs, 0);
180 }
181
182 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
183 super(context, attrs, defStyle);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700184
185 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
186 // the user where a dragged item will land when dropped.
187 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800188 setClipToPadding(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700189 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700190
Adam Cohen2e6da152015-05-06 11:42:25 -0700191 DeviceProfile grid = mLauncher.getDeviceProfile();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800192
Winson Chung11a1a532013-09-13 11:14:45 -0700193 mCellWidth = mCellHeight = -1;
Nilesh Agrawal5f7099a2014-01-02 15:54:57 -0800194 mFixedCellWidth = mFixedCellHeight = -1;
Winson Chung5f8afe62013-08-12 16:19:28 -0700195 mWidthGap = mOriginalWidthGap = 0;
196 mHeightGap = mOriginalHeightGap = 0;
197 mMaxGap = Integer.MAX_VALUE;
Adam Cohen2e6da152015-05-06 11:42:25 -0700198 mCountX = (int) grid.inv.numColumns;
199 mCountY = (int) grid.inv.numRows;
Michael Jurka0280c3b2010-09-17 15:00:07 -0700200 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800201 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700202 mPreviousReorderDirection[0] = INVALID_DIRECTION;
203 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800204
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800205 setAlwaysDrawnWithCacheEnabled(false);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700206 final Resources res = getResources();
Winson Chung6e1c0d32013-10-25 15:24:24 -0700207 mHotseatScale = (float) grid.hotseatIconSizePx / grid.iconSizePx;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700208
Tony Wickhame0c33232016-02-08 11:37:04 -0800209 mBackground = (TransitionDrawable) res.getDrawable(
210 FeatureFlags.LAUNCHER3_LEGACY_WORKSPACE_DND ? R.drawable.bg_screenpanel
211 : R.drawable.bg_celllayout);
Sunny Goyal2805e632015-05-20 15:35:32 -0700212 mBackground.setCallback(this);
Winson Chunge8f1d042015-07-31 12:39:57 -0700213 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurka33945b22010-12-21 18:19:38 -0800214
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800215 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE *
Winson Chung5f8afe62013-08-12 16:19:28 -0700216 grid.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700217
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700218 // Initialize the data structures used for the drag visualization.
Patrick Dubroyce34a972010-10-19 10:34:32 -0700219 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700220 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700221 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800222 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700223 }
224
225 // When dragging things around the home screens, we show a green outline of
226 // where the item will land. The outlines gradually fade out, leaving a trail
227 // behind the drag path.
228 // Set up all the animations that are used to implement this fading.
229 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700230 final float fromAlphaValue = 0;
231 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700232
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700233 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700234
235 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700236 final InterruptibleInOutAnimator anim =
Michael Jurkaf1ad6082013-03-13 12:55:46 +0100237 new InterruptibleInOutAnimator(this, duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700238 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700239 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700240 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700241 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700242 final Bitmap outline = (Bitmap)anim.getTag();
243
244 // If an animation is started and then stopped very quickly, we can still
245 // get spurious updates we've cleared the tag. Guard against this.
246 if (outline == null) {
Tony Wickhama0628cc2015-10-14 15:23:04 -0700247 if (LOGD) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700248 Object val = animation.getAnimatedValue();
249 Log.d(TAG, "anim " + thisIndex + " update: " + val +
250 ", isStopped " + anim.isStopped());
251 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700252 // Try to prevent it from continuing to run
253 animation.cancel();
254 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700255 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800256 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700257 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700258 }
259 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700260 // The animation holds a reference to the drag outline bitmap as long is it's
261 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700262 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700263 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700264 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700265 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700266 anim.setTag(null);
267 }
268 }
269 });
270 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700271 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700272
Michael Jurkaa52570f2012-03-20 03:18:20 -0700273 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
Adam Cohen2374abf2013-04-16 14:56:57 -0700274 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700275 mCountX, mCountY);
Adam Cohen2374abf2013-04-16 14:56:57 -0700276
Mady Mellorbb835202015-07-15 16:34:34 -0700277 mStylusEventHelper = new StylusEventHelper(new SimpleOnStylusPressListener(this), this);
Mady Melloref044dd2015-06-02 15:35:07 -0700278
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700279 mTouchFeedbackView = new ClickShadowView(context);
280 addView(mTouchFeedbackView);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700281 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700282 }
283
Adam Cohenc9735cf2015-01-23 16:11:55 -0800284 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
Sunny Goyale9b651e2015-04-24 11:44:51 -0700285 public void enableAccessibleDrag(boolean enable, int dragType) {
Adam Cohenc9735cf2015-01-23 16:11:55 -0800286 mUseTouchHelper = enable;
287 if (!enable) {
288 ViewCompat.setAccessibilityDelegate(this, null);
289 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
290 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
291 setOnClickListener(mLauncher);
292 } else {
Sunny Goyale9b651e2015-04-24 11:44:51 -0700293 if (dragType == WORKSPACE_ACCESSIBILITY_DRAG &&
294 !(mTouchHelper instanceof WorkspaceAccessibilityHelper)) {
295 mTouchHelper = new WorkspaceAccessibilityHelper(this);
296 } else if (dragType == FOLDER_ACCESSIBILITY_DRAG &&
297 !(mTouchHelper instanceof FolderAccessibilityHelper)) {
298 mTouchHelper = new FolderAccessibilityHelper(this);
299 }
Adam Cohenc9735cf2015-01-23 16:11:55 -0800300 ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
301 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
302 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
303 setOnClickListener(mTouchHelper);
304 }
305
306 // Invalidate the accessibility hierarchy
307 if (getParent() != null) {
308 getParent().notifySubtreeAccessibilityStateChanged(
309 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
310 }
311 }
312
313 @Override
314 public boolean dispatchHoverEvent(MotionEvent event) {
315 // Always attempt to dispatch hover events to accessibility first.
316 if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
317 return true;
318 }
319 return super.dispatchHoverEvent(event);
320 }
321
322 @Override
Adam Cohenc9735cf2015-01-23 16:11:55 -0800323 public boolean onInterceptTouchEvent(MotionEvent ev) {
324 if (mUseTouchHelper ||
325 (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
326 return true;
327 }
328 return false;
329 }
330
Mady Melloref044dd2015-06-02 15:35:07 -0700331 @Override
332 public boolean onTouchEvent(MotionEvent ev) {
333 boolean handled = super.onTouchEvent(ev);
334 // Stylus button press on a home screen should not switch between overview mode and
335 // the home screen mode, however, once in overview mode stylus button press should be
336 // enabled to allow rearranging the different home screens. So check what mode
337 // the workspace is in, and only perform stylus button presses while in overview mode.
338 if (mLauncher.mWorkspace.isInOverviewMode()
Mady Mellorbb835202015-07-15 16:34:34 -0700339 && mStylusEventHelper.onMotionEvent(ev)) {
Mady Melloref044dd2015-06-02 15:35:07 -0700340 return true;
341 }
342 return handled;
343 }
344
Chris Craik01f2d7f2013-10-01 14:41:56 -0700345 public void enableHardwareLayer(boolean hasLayer) {
346 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700347 }
348
349 public void buildHardwareLayer() {
350 mShortcutsAndWidgets.buildLayer();
Adam Cohen2801caf2011-05-13 20:57:39 -0700351 }
352
Adam Cohen307fe232012-08-16 17:55:58 -0700353 public float getChildrenScale() {
354 return mIsHotseat ? mHotseatScale : 1.0f;
355 }
356
Winson Chung5f8afe62013-08-12 16:19:28 -0700357 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700358 mFixedCellWidth = mCellWidth = width;
359 mFixedCellHeight = mCellHeight = height;
Winson Chung5f8afe62013-08-12 16:19:28 -0700360 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
361 mCountX, mCountY);
362 }
363
Adam Cohen2801caf2011-05-13 20:57:39 -0700364 public void setGridSize(int x, int y) {
365 mCountX = x;
366 mCountY = y;
367 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800368 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700369 mTempRectStack.clear();
Adam Cohen2374abf2013-04-16 14:56:57 -0700370 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700371 mCountX, mCountY);
Adam Cohen76fc0852011-06-17 13:26:23 -0700372 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700373 }
374
Adam Cohen2374abf2013-04-16 14:56:57 -0700375 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
376 public void setInvertIfRtl(boolean invert) {
377 mShortcutsAndWidgets.setInvertIfRtl(invert);
378 }
379
Adam Cohen917e3882013-10-31 15:03:35 -0700380 public void setDropPending(boolean pending) {
381 mDropPending = pending;
382 }
383
384 public boolean isDropPending() {
385 return mDropPending;
386 }
387
Sunny Goyal4b6eb262015-05-14 19:24:40 -0700388 @Override
389 public void setPressedIcon(BubbleTextView icon, Bitmap background) {
Sunny Goyal508da152014-08-14 10:53:27 -0700390 if (icon == null || background == null) {
391 mTouchFeedbackView.setBitmap(null);
392 mTouchFeedbackView.animate().cancel();
393 } else {
Sunny Goyal508da152014-08-14 10:53:27 -0700394 if (mTouchFeedbackView.setBitmap(background)) {
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700395 mTouchFeedbackView.alignWithIconView(icon, mShortcutsAndWidgets);
396 mTouchFeedbackView.animateShadow();
Sunny Goyal508da152014-08-14 10:53:27 -0700397 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800398 }
399 }
400
Adam Cohenc50438c2014-08-19 17:43:05 -0700401 void disableDragTarget() {
402 mIsDragTarget = false;
403 }
404
Tony Wickham0f97b782015-12-02 17:55:07 -0800405 public boolean isDragTarget() {
406 return mIsDragTarget;
407 }
408
Adam Cohenc50438c2014-08-19 17:43:05 -0700409 void setIsDragOverlapping(boolean isDragOverlapping) {
410 if (mIsDragOverlapping != isDragOverlapping) {
411 mIsDragOverlapping = isDragOverlapping;
Sunny Goyal2805e632015-05-20 15:35:32 -0700412 if (mIsDragOverlapping) {
413 mBackground.startTransition(BACKGROUND_ACTIVATE_DURATION);
414 } else {
Winson Chunge8f1d042015-07-31 12:39:57 -0700415 if (mBackgroundAlpha > 0f) {
416 mBackground.reverseTransition(BACKGROUND_ACTIVATE_DURATION);
417 } else {
418 mBackground.resetTransition();
419 }
Sunny Goyal2805e632015-05-20 15:35:32 -0700420 }
Adam Cohenc50438c2014-08-19 17:43:05 -0700421 invalidate();
422 }
423 }
424
Sunny Goyale2fd14b2015-08-27 17:45:46 -0700425 public void disableJailContent() {
426 mJailContent = false;
427 }
428
429 @Override
430 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
431 if (mJailContent) {
432 ParcelableSparseArray jail = getJailedArray(container);
433 super.dispatchSaveInstanceState(jail);
434 container.put(R.id.cell_layout_jail_id, jail);
435 } else {
436 super.dispatchSaveInstanceState(container);
437 }
438 }
439
440 @Override
441 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
442 super.dispatchRestoreInstanceState(mJailContent ? getJailedArray(container) : container);
443 }
444
445 private ParcelableSparseArray getJailedArray(SparseArray<Parcelable> container) {
446 final Parcelable parcelable = container.get(R.id.cell_layout_jail_id);
447 return parcelable instanceof ParcelableSparseArray ?
448 (ParcelableSparseArray) parcelable : new ParcelableSparseArray();
449 }
450
Tony Wickham0f97b782015-12-02 17:55:07 -0800451 public boolean getIsDragOverlapping() {
452 return mIsDragOverlapping;
453 }
454
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700455 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700456 protected void onDraw(Canvas canvas) {
Sunny Goyal05739772015-05-19 19:59:09 -0700457 if (!mIsDragTarget) {
458 return;
459 }
460
Michael Jurka3e7c7632010-10-02 16:01:03 -0700461 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
462 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
463 // When we're small, we are either drawn normally or in the "accepts drops" state (during
464 // a drag). However, we also drag the mini hover background *over* one of those two
465 // backgrounds
Sunny Goyal05739772015-05-19 19:59:09 -0700466 if (mBackgroundAlpha > 0.0f) {
Sunny Goyal2805e632015-05-20 15:35:32 -0700467 mBackground.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700468 }
Romain Guya6abce82009-11-10 02:54:41 -0800469
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700470 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700471 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700472 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700473 if (alpha > 0) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700474 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700475 paint.setAlpha((int)(alpha + .5f));
Sunny Goyal106bf642015-07-16 12:18:06 -0700476 canvas.drawBitmap(b, null, mDragOutlines[i], paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700477 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700478 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800479
Adam Cohen482ed822012-03-02 14:15:13 -0800480 if (DEBUG_VISUALIZE_OCCUPIED) {
481 int[] pt = new int[2];
482 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700483 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800484 for (int i = 0; i < mCountX; i++) {
485 for (int j = 0; j < mCountY; j++) {
486 if (mOccupied[i][j]) {
487 cellToPoint(i, j, pt);
488 canvas.save();
489 canvas.translate(pt[0], pt[1]);
490 cd.draw(canvas);
491 canvas.restore();
492 }
493 }
494 }
495 }
496
Andrew Flynn850d2e72012-04-26 16:51:20 -0700497 int previewOffset = FolderRingAnimator.sPreviewSize;
498
Adam Cohen69ce2e52011-07-03 19:25:21 -0700499 // The folder outer / inner ring image(s)
Adam Cohen2e6da152015-05-06 11:42:25 -0700500 DeviceProfile grid = mLauncher.getDeviceProfile();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700501 for (int i = 0; i < mFolderOuterRings.size(); i++) {
502 FolderRingAnimator fra = mFolderOuterRings.get(i);
503
Adam Cohen5108bc02013-09-20 17:04:51 -0700504 Drawable d;
505 int width, height;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700506 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
Winson Chung5f8afe62013-08-12 16:19:28 -0700507 View child = getChildAt(fra.mCellX, fra.mCellY);
Adam Cohen558f1c22013-10-09 15:15:24 -0700508
Winson Chung89f97052013-09-20 11:32:26 -0700509 if (child != null) {
Adam Cohen558f1c22013-10-09 15:15:24 -0700510 int centerX = mTempLocation[0] + mCellWidth / 2;
511 int centerY = mTempLocation[1] + previewOffset / 2 +
512 child.getPaddingTop() + grid.folderBackgroundOffset;
513
Adam Cohen5108bc02013-09-20 17:04:51 -0700514 // Draw outer ring, if it exists
515 if (FolderIcon.HAS_OUTER_RING) {
516 d = FolderRingAnimator.sSharedOuterRingDrawable;
517 width = (int) (fra.getOuterRingSize() * getChildrenScale());
518 height = width;
519 canvas.save();
520 canvas.translate(centerX - width / 2, centerY - height / 2);
521 d.setBounds(0, 0, width, height);
522 d.draw(canvas);
523 canvas.restore();
524 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700525
Winson Chung89f97052013-09-20 11:32:26 -0700526 // Draw inner ring
527 d = FolderRingAnimator.sSharedInnerRingDrawable;
528 width = (int) (fra.getInnerRingSize() * getChildrenScale());
529 height = width;
Winson Chung89f97052013-09-20 11:32:26 -0700530 canvas.save();
531 canvas.translate(centerX - width / 2, centerY - width / 2);
532 d.setBounds(0, 0, width, height);
533 d.draw(canvas);
534 canvas.restore();
535 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700536 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700537
538 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
539 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
540 int width = d.getIntrinsicWidth();
541 int height = d.getIntrinsicHeight();
542
543 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
Winson Chung5f8afe62013-08-12 16:19:28 -0700544 View child = getChildAt(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1]);
Winson Chung89f97052013-09-20 11:32:26 -0700545 if (child != null) {
546 int centerX = mTempLocation[0] + mCellWidth / 2;
547 int centerY = mTempLocation[1] + previewOffset / 2 +
548 child.getPaddingTop() + grid.folderBackgroundOffset;
Adam Cohenc51934b2011-07-26 21:07:43 -0700549
Winson Chung89f97052013-09-20 11:32:26 -0700550 canvas.save();
551 canvas.translate(centerX - width / 2, centerY - width / 2);
552 d.setBounds(0, 0, width, height);
553 d.draw(canvas);
554 canvas.restore();
555 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700556 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700557 }
558
559 public void showFolderAccept(FolderRingAnimator fra) {
560 mFolderOuterRings.add(fra);
561 }
562
563 public void hideFolderAccept(FolderRingAnimator fra) {
564 if (mFolderOuterRings.contains(fra)) {
565 mFolderOuterRings.remove(fra);
566 }
567 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700568 }
569
Adam Cohenc51934b2011-07-26 21:07:43 -0700570 public void setFolderLeaveBehindCell(int x, int y) {
571 mFolderLeaveBehindCell[0] = x;
572 mFolderLeaveBehindCell[1] = y;
573 invalidate();
574 }
575
576 public void clearFolderLeaveBehind() {
577 mFolderLeaveBehindCell[0] = -1;
578 mFolderLeaveBehindCell[1] = -1;
579 invalidate();
580 }
581
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700582 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700583 public boolean shouldDelayChildPressedState() {
584 return false;
585 }
586
Adam Cohen1462de32012-07-24 22:34:36 -0700587 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700588 try {
589 dispatchRestoreInstanceState(states);
590 } catch (IllegalArgumentException ex) {
Sunny Goyal6c56c682015-07-16 14:09:05 -0700591 if (ProviderConfig.IS_DOGFOOD_BUILD) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700592 throw ex;
593 }
594 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
595 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
596 }
Adam Cohen1462de32012-07-24 22:34:36 -0700597 }
598
Michael Jurkae6235dd2011-10-04 15:02:05 -0700599 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700600 public void cancelLongPress() {
601 super.cancelLongPress();
602
603 // Cancel long press for all children
604 final int count = getChildCount();
605 for (int i = 0; i < count; i++) {
606 final View child = getChildAt(i);
607 child.cancelLongPress();
608 }
609 }
610
Michael Jurkadee05892010-07-27 10:01:56 -0700611 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
612 mInterceptTouchListener = listener;
613 }
614
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800615 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700616 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800617 }
618
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800619 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700620 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800621 }
622
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800623 public void setIsHotseat(boolean isHotseat) {
624 mIsHotseat = isHotseat;
Winson Chung5f8afe62013-08-12 16:19:28 -0700625 mShortcutsAndWidgets.setIsHotseat(isHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800626 }
627
Sunny Goyale9b651e2015-04-24 11:44:51 -0700628 public boolean isHotseat() {
629 return mIsHotseat;
630 }
631
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800632 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700633 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700634 final LayoutParams lp = params;
635
Andrew Flynnde38e422012-05-08 11:22:15 -0700636 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800637 if (child instanceof BubbleTextView) {
638 BubbleTextView bubbleChild = (BubbleTextView) child;
Winson Chung5f8afe62013-08-12 16:19:28 -0700639 bubbleChild.setTextVisibility(!mIsHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800640 }
641
Adam Cohen307fe232012-08-16 17:55:58 -0700642 child.setScaleX(getChildrenScale());
643 child.setScaleY(getChildrenScale());
644
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800645 // Generate an id for each view, this assumes we have at most 256x256 cells
646 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700647 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700648 // If the horizontal or vertical span is set to -1, it is taken to
649 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700650 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
651 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800652
Winson Chungaafa03c2010-06-11 17:34:16 -0700653 child.setId(childId);
Tony Wickhama0628cc2015-10-14 15:23:04 -0700654 if (LOGD) {
655 Log.d(TAG, "Adding view to ShortcutsAndWidgetsContainer: " + child);
656 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700657 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700658
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700659 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700660
Winson Chungaafa03c2010-06-11 17:34:16 -0700661 return true;
662 }
663 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800664 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700665
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800666 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700667 public void removeAllViews() {
668 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700669 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700670 }
671
672 @Override
673 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700674 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700675 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700676 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700677 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700678 }
679
680 @Override
681 public void removeView(View view) {
682 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700683 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700684 }
685
686 @Override
687 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700688 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
689 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700690 }
691
692 @Override
693 public void removeViewInLayout(View view) {
694 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700695 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700696 }
697
698 @Override
699 public void removeViews(int start, int count) {
700 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700701 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700702 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700703 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700704 }
705
706 @Override
707 public void removeViewsInLayout(int start, int count) {
708 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700709 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700710 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700711 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800712 }
713
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700714 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700715 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800716 * @param x X coordinate of the point
717 * @param y Y coordinate of the point
718 * @param result Array of 2 ints to hold the x and y coordinate of the cell
719 */
Sunny Goyale9b651e2015-04-24 11:44:51 -0700720 public void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700721 final int hStartPadding = getPaddingLeft();
722 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800723
724 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
725 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
726
Adam Cohend22015c2010-07-26 22:02:18 -0700727 final int xAxis = mCountX;
728 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800729
730 if (result[0] < 0) result[0] = 0;
731 if (result[0] >= xAxis) result[0] = xAxis - 1;
732 if (result[1] < 0) result[1] = 0;
733 if (result[1] >= yAxis) result[1] = yAxis - 1;
734 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700735
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800736 /**
737 * Given a point, return the cell that most closely encloses that point
738 * @param x X coordinate of the point
739 * @param y Y coordinate of the point
740 * @param result Array of 2 ints to hold the x and y coordinate of the cell
741 */
742 void pointToCellRounded(int x, int y, int[] result) {
743 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
744 }
745
746 /**
747 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700748 *
749 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800750 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700751 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800752 * @param result Array of 2 ints to hold the x and y coordinate of the point
753 */
754 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700755 final int hStartPadding = getPaddingLeft();
756 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800757
758 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
759 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
760 }
761
Adam Cohene3e27a82011-04-15 12:07:39 -0700762 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800763 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700764 *
765 * @param cellX X coordinate of the cell
766 * @param cellY Y coordinate of the cell
767 *
768 * @param result Array of 2 ints to hold the x and y coordinate of the point
769 */
770 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700771 regionToCenterPoint(cellX, cellY, 1, 1, result);
772 }
773
774 /**
775 * Given a cell coordinate and span return the point that represents the center of the regio
776 *
777 * @param cellX X coordinate of the cell
778 * @param cellY Y coordinate of the cell
779 *
780 * @param result Array of 2 ints to hold the x and y coordinate of the point
781 */
782 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700783 final int hStartPadding = getPaddingLeft();
784 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700785 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
786 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
787 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
788 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700789 }
790
Adam Cohen19f37922012-03-21 11:59:11 -0700791 /**
792 * Given a cell coordinate and span fills out a corresponding pixel rect
793 *
794 * @param cellX X coordinate of the cell
795 * @param cellY Y coordinate of the cell
796 * @param result Rect in which to write the result
797 */
798 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
799 final int hStartPadding = getPaddingLeft();
800 final int vStartPadding = getPaddingTop();
801 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
802 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
803 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
804 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
805 }
806
Adam Cohen482ed822012-03-02 14:15:13 -0800807 public float getDistanceFromCell(float x, float y, int[] cell) {
808 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
Sunny Goyalf7a29e82015-04-24 15:20:43 -0700809 return (float) Math.hypot(x - mTmpPoint[0], y - mTmpPoint[1]);
Adam Cohen482ed822012-03-02 14:15:13 -0800810 }
811
Romain Guy84f296c2009-11-04 15:00:44 -0800812 int getCellWidth() {
813 return mCellWidth;
814 }
815
816 int getCellHeight() {
817 return mCellHeight;
818 }
819
Adam Cohend4844c32011-02-18 19:25:06 -0800820 int getWidthGap() {
821 return mWidthGap;
822 }
823
824 int getHeightGap() {
825 return mHeightGap;
826 }
827
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700828 public void setFixedSize(int width, int height) {
829 mFixedWidth = width;
830 mFixedHeight = height;
831 }
832
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800833 @Override
834 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800835 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800836 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -0700837 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
838 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -0700839 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
840 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Winson Chung11a1a532013-09-13 11:14:45 -0700841 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Sunny Goyalc6205602015-05-21 20:46:33 -0700842 int cw = DeviceProfile.calculateCellWidth(childWidthSize, mCountX);
843 int ch = DeviceProfile.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -0700844 if (cw != mCellWidth || ch != mCellHeight) {
845 mCellWidth = cw;
846 mCellHeight = ch;
847 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
848 mHeightGap, mCountX, mCountY);
849 }
Winson Chung5f8afe62013-08-12 16:19:28 -0700850 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700851
Winson Chung2d75f122013-09-23 16:53:31 -0700852 int newWidth = childWidthSize;
853 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700854 if (mFixedWidth > 0 && mFixedHeight > 0) {
855 newWidth = mFixedWidth;
856 newHeight = mFixedHeight;
857 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800858 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
859 }
860
Adam Cohend22015c2010-07-26 22:02:18 -0700861 int numWidthGaps = mCountX - 1;
862 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800863
Adam Cohen234c4cd2011-07-17 21:03:04 -0700864 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -0700865 int hSpace = childWidthSize;
866 int vSpace = childHeightSize;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700867 int hFreeSpace = hSpace - (mCountX * mCellWidth);
868 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700869 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
870 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Winson Chung5f8afe62013-08-12 16:19:28 -0700871 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
872 mHeightGap, mCountX, mCountY);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700873 } else {
874 mWidthGap = mOriginalWidthGap;
875 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700876 }
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700877
878 // Make the feedback view large enough to hold the blur bitmap.
879 mTouchFeedbackView.measure(
880 MeasureSpec.makeMeasureSpec(mCellWidth + mTouchFeedbackView.getExtraSize(),
881 MeasureSpec.EXACTLY),
882 MeasureSpec.makeMeasureSpec(mCellHeight + mTouchFeedbackView.getExtraSize(),
883 MeasureSpec.EXACTLY));
884
885 mShortcutsAndWidgets.measure(
886 MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
887 MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
888
889 int maxWidth = mShortcutsAndWidgets.getMeasuredWidth();
890 int maxHeight = mShortcutsAndWidgets.getMeasuredHeight();
Winson Chung2d75f122013-09-23 16:53:31 -0700891 if (mFixedWidth > 0 && mFixedHeight > 0) {
892 setMeasuredDimension(maxWidth, maxHeight);
893 } else {
894 setMeasuredDimension(widthSize, heightSize);
895 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800896 }
897
898 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700899 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Tony Wickham26b01422015-11-10 14:44:32 -0800900 boolean isFullscreen = mShortcutsAndWidgets.getChildCount() > 0 &&
901 ((LayoutParams) mShortcutsAndWidgets.getChildAt(0).getLayoutParams()).isFullscreen;
902 int left = getPaddingLeft();
903 if (!isFullscreen) {
Tony Wickhama501d492015-11-03 18:05:01 -0800904 left += (int) Math.ceil(getUnusedHorizontalSpace() / 2f);
Tony Wickham26b01422015-11-10 14:44:32 -0800905 }
Winson Chung38848ca2013-10-08 12:03:44 -0700906 int top = getPaddingTop();
Sunny Goyal4fe5a372015-05-14 19:55:10 -0700907
908 mTouchFeedbackView.layout(left, top,
909 left + mTouchFeedbackView.getMeasuredWidth(),
910 top + mTouchFeedbackView.getMeasuredHeight());
911 mShortcutsAndWidgets.layout(left, top,
912 left + r - l,
913 top + b - t);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800914 }
915
Tony Wickhama501d492015-11-03 18:05:01 -0800916 /**
917 * Returns the amount of space left over after subtracting padding and cells. This space will be
918 * very small, a few pixels at most, and is a result of rounding down when calculating the cell
919 * width in {@link DeviceProfile#calculateCellWidth(int, int)}.
920 */
921 public int getUnusedHorizontalSpace() {
922 return getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - (mCountX * mCellWidth);
923 }
924
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800925 @Override
Michael Jurkadee05892010-07-27 10:01:56 -0700926 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
927 super.onSizeChanged(w, h, oldw, oldh);
Winson Chung82a9bd22013-10-08 16:02:34 -0700928
929 // Expand the background drawing bounds by the padding baked into the background drawable
Sunny Goyal2805e632015-05-20 15:35:32 -0700930 mBackground.getPadding(mTempRect);
931 mBackground.setBounds(-mTempRect.left, -mTempRect.top,
932 w + mTempRect.right, h + mTempRect.bottom);
Michael Jurkadee05892010-07-27 10:01:56 -0700933 }
934
935 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800936 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700937 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800938 }
939
940 @Override
941 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700942 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800943 }
944
Michael Jurka5f1c5092010-09-03 14:15:02 -0700945 public float getBackgroundAlpha() {
946 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -0700947 }
948
Michael Jurka5f1c5092010-09-03 14:15:02 -0700949 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -0800950 if (mBackgroundAlpha != alpha) {
951 mBackgroundAlpha = alpha;
Sunny Goyal2805e632015-05-20 15:35:32 -0700952 mBackground.setAlpha((int) (mBackgroundAlpha * 255));
Michael Jurkaafaa0502011-12-13 18:22:50 -0800953 }
Michael Jurkadee05892010-07-27 10:01:56 -0700954 }
955
Sunny Goyal2805e632015-05-20 15:35:32 -0700956 @Override
957 protected boolean verifyDrawable(Drawable who) {
958 return super.verifyDrawable(who) || (mIsDragTarget && who == mBackground);
959 }
960
Michael Jurkaa52570f2012-03-20 03:18:20 -0700961 public void setShortcutAndWidgetAlpha(float alpha) {
Sunny Goyal02b50812014-09-10 15:44:42 -0700962 mShortcutsAndWidgets.setAlpha(alpha);
Michael Jurkadee05892010-07-27 10:01:56 -0700963 }
964
Michael Jurkaa52570f2012-03-20 03:18:20 -0700965 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -0700966 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700967 }
968
Patrick Dubroy440c3602010-07-13 17:50:32 -0700969 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700970 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -0700971 }
972
Adam Cohen76fc0852011-06-17 13:26:23 -0700973 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -0800974 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700975 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -0800976 boolean[][] occupied = mOccupied;
977 if (!permanent) {
978 occupied = mTmpOccupied;
979 }
980
Adam Cohen19f37922012-03-21 11:59:11 -0700981 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -0700982 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
983 final ItemInfo info = (ItemInfo) child.getTag();
984
985 // We cancel any existing animations
986 if (mReorderAnimators.containsKey(lp)) {
987 mReorderAnimators.get(lp).cancel();
988 mReorderAnimators.remove(lp);
989 }
990
Adam Cohen482ed822012-03-02 14:15:13 -0800991 final int oldX = lp.x;
992 final int oldY = lp.y;
993 if (adjustOccupied) {
994 occupied[lp.cellX][lp.cellY] = false;
995 occupied[cellX][cellY] = true;
996 }
Adam Cohenbfbfd262011-06-13 16:55:12 -0700997 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -0800998 if (permanent) {
999 lp.cellX = info.cellX = cellX;
1000 lp.cellY = info.cellY = cellY;
1001 } else {
1002 lp.tmpCellX = cellX;
1003 lp.tmpCellY = cellY;
1004 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001005 clc.setupLp(lp);
1006 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001007 final int newX = lp.x;
1008 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001009
Adam Cohen76fc0852011-06-17 13:26:23 -07001010 lp.x = oldX;
1011 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001012
Adam Cohen482ed822012-03-02 14:15:13 -08001013 // Exit early if we're not actually moving the view
1014 if (oldX == newX && oldY == newY) {
1015 lp.isLockedToGrid = true;
1016 return true;
1017 }
1018
Michael Jurkaf1ad6082013-03-13 12:55:46 +01001019 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001020 va.setDuration(duration);
1021 mReorderAnimators.put(lp, va);
1022
1023 va.addUpdateListener(new AnimatorUpdateListener() {
1024 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001025 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001026 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001027 lp.x = (int) ((1 - r) * oldX + r * newX);
1028 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001029 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001030 }
1031 });
Adam Cohen482ed822012-03-02 14:15:13 -08001032 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001033 boolean cancelled = false;
1034 public void onAnimationEnd(Animator animation) {
1035 // If the animation was cancelled, it means that another animation
1036 // has interrupted this one, and we don't want to lock the item into
1037 // place just yet.
1038 if (!cancelled) {
1039 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001040 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001041 }
1042 if (mReorderAnimators.containsKey(lp)) {
1043 mReorderAnimators.remove(lp);
1044 }
1045 }
1046 public void onAnimationCancel(Animator animation) {
1047 cancelled = true;
1048 }
1049 });
Adam Cohen482ed822012-03-02 14:15:13 -08001050 va.setStartDelay(delay);
1051 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001052 return true;
1053 }
1054 return false;
1055 }
1056
Tony Wickhama501d492015-11-03 18:05:01 -08001057 void visualizeDropLocation(View v, Bitmap dragOutline, int cellX, int cellY, int spanX,
1058 int spanY, boolean resize, DropTarget.DragObject dragObject) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001059 final int oldDragCellX = mDragCell[0];
1060 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001061
Adam Cohen2801caf2011-05-13 20:57:39 -07001062 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001063 return;
1064 }
1065
Adam Cohen482ed822012-03-02 14:15:13 -08001066 if (cellX != oldDragCellX || cellY != oldDragCellY) {
Sunny Goyale78e3d72015-09-24 11:23:31 -07001067 Point dragOffset = dragObject.dragView.getDragVisualizeOffset();
1068 Rect dragRegion = dragObject.dragView.getDragRegion();
1069
Adam Cohen482ed822012-03-02 14:15:13 -08001070 mDragCell[0] = cellX;
1071 mDragCell[1] = cellY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001072
Joe Onorato4be866d2010-10-10 11:26:02 -07001073 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001074 mDragOutlineAnims[oldIndex].animateOut();
1075 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001076 Rect r = mDragOutlines[mDragOutlineCurrent];
Sunny Goyal106bf642015-07-16 12:18:06 -07001077
Adam Cohend41fbf52012-02-16 23:53:59 -08001078 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001079 cellToRect(cellX, cellY, spanX, spanY, r);
Sunny Goyal106bf642015-07-16 12:18:06 -07001080 } else {
1081 // Find the top left corner of the rect the object will occupy
1082 final int[] topLeft = mTmpPoint;
1083 cellToPoint(cellX, cellY, topLeft);
1084
1085 int left = topLeft[0];
1086 int top = topLeft[1];
1087
1088 if (v != null && dragOffset == null) {
1089 // When drawing the drag outline, it did not account for margin offsets
1090 // added by the view's parent.
1091 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1092 left += lp.leftMargin;
1093 top += lp.topMargin;
1094
1095 // Offsets due to the size difference between the View and the dragOutline.
1096 // There is a size difference to account for the outer blur, which may lie
1097 // outside the bounds of the view.
1098 top += (v.getHeight() - dragOutline.getHeight()) / 2;
1099 // We center about the x axis
1100 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1101 - dragOutline.getWidth()) / 2;
1102 } else {
1103 if (dragOffset != null && dragRegion != null) {
1104 // Center the drag region *horizontally* in the cell and apply a drag
1105 // outline offset
1106 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1107 - dragRegion.width()) / 2;
1108 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
1109 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
1110 top += dragOffset.y + cellPaddingY;
1111 } else {
1112 // Center the drag outline in the cell
1113 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1114 - dragOutline.getWidth()) / 2;
1115 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1116 - dragOutline.getHeight()) / 2;
1117 }
1118 }
1119 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
Adam Cohend41fbf52012-02-16 23:53:59 -08001120 }
Winson Chung150fbab2010-09-29 17:14:26 -07001121
Sunny Goyal106bf642015-07-16 12:18:06 -07001122 Utilities.scaleRectAboutCenter(r, getChildrenScale());
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001123 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1124 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Sunny Goyale78e3d72015-09-24 11:23:31 -07001125
1126 if (dragObject.stateAnnouncer != null) {
1127 String msg;
1128 if (isHotseat()) {
1129 msg = getContext().getString(R.string.move_to_hotseat_position,
1130 Math.max(cellX, cellY) + 1);
1131 } else {
1132 msg = getContext().getString(R.string.move_to_empty_cell,
1133 cellY + 1, cellX + 1);
1134 }
1135 dragObject.stateAnnouncer.announce(msg);
1136 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001137 }
1138 }
1139
Adam Cohene0310962011-04-18 16:15:31 -07001140 public void clearDragOutlines() {
1141 final int oldIndex = mDragOutlineCurrent;
1142 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001143 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001144 }
1145
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001146 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001147 * Find a vacant area that will fit the given bounds nearest the requested
1148 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001149 *
Romain Guy51afc022009-05-04 18:03:43 -07001150 * @param pixelX The X location at which you want to search for a vacant area.
1151 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001152 * @param minSpanX The minimum horizontal span required
1153 * @param minSpanY The minimum vertical span required
1154 * @param spanX Horizontal span of the object.
1155 * @param spanY Vertical span of the object.
1156 * @param result Array in which to place the result, or null (in which case a new array will
1157 * be allocated)
1158 * @return The X, Y cell of a vacant area that can contain this object,
1159 * nearest the requested location.
1160 */
1161 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1162 int spanY, int[] result, int[] resultSpan) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001163 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, true,
Adam Cohend41fbf52012-02-16 23:53:59 -08001164 result, resultSpan);
1165 }
1166
Adam Cohend41fbf52012-02-16 23:53:59 -08001167 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1168 private void lazyInitTempRectStack() {
1169 if (mTempRectStack.isEmpty()) {
1170 for (int i = 0; i < mCountX * mCountY; i++) {
1171 mTempRectStack.push(new Rect());
1172 }
1173 }
1174 }
Adam Cohen482ed822012-03-02 14:15:13 -08001175
Adam Cohend41fbf52012-02-16 23:53:59 -08001176 private void recycleTempRects(Stack<Rect> used) {
1177 while (!used.isEmpty()) {
1178 mTempRectStack.push(used.pop());
1179 }
1180 }
1181
1182 /**
1183 * Find a vacant area that will fit the given bounds nearest the requested
1184 * cell location. Uses Euclidean distance to score multiple vacant areas.
1185 *
1186 * @param pixelX The X location at which you want to search for a vacant area.
1187 * @param pixelY The Y location at which you want to search for a vacant area.
1188 * @param minSpanX The minimum horizontal span required
1189 * @param minSpanY The minimum vertical span required
1190 * @param spanX Horizontal span of the object.
1191 * @param spanY Vertical span of the object.
1192 * @param ignoreOccupied If true, the result can be an occupied cell
1193 * @param result Array in which to place the result, or null (in which case a new array will
1194 * be allocated)
1195 * @return The X, Y cell of a vacant area that can contain this object,
1196 * nearest the requested location.
1197 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001198 private int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1199 int spanY, boolean ignoreOccupied, int[] result, int[] resultSpan) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001200 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001201
Adam Cohene3e27a82011-04-15 12:07:39 -07001202 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1203 // to the center of the item, but we are searching based on the top-left cell, so
1204 // we translate the point over to correspond to the top-left.
1205 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1206 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1207
Jeff Sharkey70864282009-04-07 21:08:40 -07001208 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001209 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001210 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001211 final Rect bestRect = new Rect(-1, -1, -1, -1);
1212 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001213
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001214 final int countX = mCountX;
1215 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001216
Adam Cohend41fbf52012-02-16 23:53:59 -08001217 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1218 spanX < minSpanX || spanY < minSpanY) {
1219 return bestXY;
1220 }
1221
1222 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001223 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001224 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1225 int ySize = -1;
1226 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001227 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001228 // First, let's see if this thing fits anywhere
1229 for (int i = 0; i < minSpanX; i++) {
1230 for (int j = 0; j < minSpanY; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001231 if (mOccupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001232 continue inner;
1233 }
Michael Jurkac28de512010-08-13 11:27:44 -07001234 }
1235 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001236 xSize = minSpanX;
1237 ySize = minSpanY;
1238
1239 // We know that the item will fit at _some_ acceptable size, now let's see
1240 // how big we can make it. We'll alternate between incrementing x and y spans
1241 // until we hit a limit.
1242 boolean incX = true;
1243 boolean hitMaxX = xSize >= spanX;
1244 boolean hitMaxY = ySize >= spanY;
1245 while (!(hitMaxX && hitMaxY)) {
1246 if (incX && !hitMaxX) {
1247 for (int j = 0; j < ySize; j++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001248 if (x + xSize > countX -1 || mOccupied[x + xSize][y + j]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001249 // We can't move out horizontally
1250 hitMaxX = true;
1251 }
1252 }
1253 if (!hitMaxX) {
1254 xSize++;
1255 }
1256 } else if (!hitMaxY) {
1257 for (int i = 0; i < xSize; i++) {
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001258 if (y + ySize > countY - 1 || mOccupied[x + i][y + ySize]) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001259 // We can't move out vertically
1260 hitMaxY = true;
1261 }
1262 }
1263 if (!hitMaxY) {
1264 ySize++;
1265 }
1266 }
1267 hitMaxX |= xSize >= spanX;
1268 hitMaxY |= ySize >= spanY;
1269 incX = !incX;
1270 }
1271 incX = true;
1272 hitMaxX = xSize >= spanX;
1273 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001274 }
Sunny Goyal2805e632015-05-20 15:35:32 -07001275 final int[] cellXY = mTmpPoint;
Adam Cohene3e27a82011-04-15 12:07:39 -07001276 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001277
Adam Cohend41fbf52012-02-16 23:53:59 -08001278 // We verify that the current rect is not a sub-rect of any of our previous
1279 // candidates. In this case, the current rect is disqualified in favour of the
1280 // containing rect.
1281 Rect currentRect = mTempRectStack.pop();
1282 currentRect.set(x, y, x + xSize, y + ySize);
1283 boolean contained = false;
1284 for (Rect r : validRegions) {
1285 if (r.contains(currentRect)) {
1286 contained = true;
1287 break;
1288 }
1289 }
1290 validRegions.push(currentRect);
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001291 double distance = Math.hypot(cellXY[0] - pixelX, cellXY[1] - pixelY);
Adam Cohen482ed822012-03-02 14:15:13 -08001292
Adam Cohend41fbf52012-02-16 23:53:59 -08001293 if ((distance <= bestDistance && !contained) ||
1294 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001295 bestDistance = distance;
1296 bestXY[0] = x;
1297 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001298 if (resultSpan != null) {
1299 resultSpan[0] = xSize;
1300 resultSpan[1] = ySize;
1301 }
1302 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001303 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001304 }
1305 }
1306
Adam Cohenc0dcf592011-06-01 15:30:43 -07001307 // Return -1, -1 if no suitable location found
1308 if (bestDistance == Double.MAX_VALUE) {
1309 bestXY[0] = -1;
1310 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001311 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001312 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001313 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001314 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001315
Adam Cohen482ed822012-03-02 14:15:13 -08001316 /**
1317 * Find a vacant area that will fit the given bounds nearest the requested
1318 * cell location, and will also weigh in a suggested direction vector of the
1319 * desired location. This method computers distance based on unit grid distances,
1320 * not pixel distances.
1321 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001322 * @param cellX The X cell nearest to which you want to search for a vacant area.
1323 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001324 * @param spanX Horizontal span of the object.
1325 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001326 * @param direction The favored direction in which the views should move from x, y
Sunny Goyal9eba1fd2015-10-16 08:58:57 -07001327 * @param occupied The array which represents which cells in the CellLayout are occupied
Adam Cohen47a876d2012-03-19 13:21:41 -07001328 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001329 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001330 * @param result Array in which to place the result, or null (in which case a new array will
1331 * be allocated)
1332 * @return The X, Y cell of a vacant area that can contain this object,
1333 * nearest the requested location.
1334 */
1335 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001336 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001337 // Keep track of best-scoring drop area
1338 final int[] bestXY = result != null ? result : new int[2];
1339 float bestDistance = Float.MAX_VALUE;
1340 int bestDirectionScore = Integer.MIN_VALUE;
1341
1342 final int countX = mCountX;
1343 final int countY = mCountY;
1344
1345 for (int y = 0; y < countY - (spanY - 1); y++) {
1346 inner:
1347 for (int x = 0; x < countX - (spanX - 1); x++) {
1348 // First, let's see if this thing fits anywhere
1349 for (int i = 0; i < spanX; i++) {
1350 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001351 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001352 continue inner;
1353 }
1354 }
1355 }
1356
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001357 float distance = (float) Math.hypot(x - cellX, y - cellY);
Adam Cohen482ed822012-03-02 14:15:13 -08001358 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001359 computeDirectionVector(x - cellX, y - cellY, curDirection);
1360 // The direction score is just the dot product of the two candidate direction
1361 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001362 int curDirectionScore = direction[0] * curDirection[0] +
1363 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001364 boolean exactDirectionOnly = false;
1365 boolean directionMatches = direction[0] == curDirection[0] &&
1366 direction[0] == curDirection[0];
1367 if ((directionMatches || !exactDirectionOnly) &&
1368 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001369 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1370 bestDistance = distance;
1371 bestDirectionScore = curDirectionScore;
1372 bestXY[0] = x;
1373 bestXY[1] = y;
1374 }
1375 }
1376 }
1377
1378 // Return -1, -1 if no suitable location found
1379 if (bestDistance == Float.MAX_VALUE) {
1380 bestXY[0] = -1;
1381 bestXY[1] = -1;
1382 }
1383 return bestXY;
1384 }
1385
1386 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001387 int[] direction, ItemConfiguration currentState) {
1388 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001389 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001390 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001391 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1392
Adam Cohen8baab352012-03-20 17:39:21 -07001393 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001394
1395 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001396 c.x = mTempLocation[0];
1397 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001398 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001399 }
Adam Cohen8baab352012-03-20 17:39:21 -07001400 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001401 return success;
1402 }
1403
Adam Cohenf3900c22012-11-16 18:28:11 -08001404 /**
1405 * This helper class defines a cluster of views. It helps with defining complex edges
1406 * of the cluster and determining how those edges interact with other views. The edges
1407 * essentially define a fine-grained boundary around the cluster of views -- like a more
1408 * precise version of a bounding box.
1409 */
1410 private class ViewCluster {
1411 final static int LEFT = 0;
1412 final static int TOP = 1;
1413 final static int RIGHT = 2;
1414 final static int BOTTOM = 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001415
Adam Cohenf3900c22012-11-16 18:28:11 -08001416 ArrayList<View> views;
1417 ItemConfiguration config;
1418 Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001419
Adam Cohenf3900c22012-11-16 18:28:11 -08001420 int[] leftEdge = new int[mCountY];
1421 int[] rightEdge = new int[mCountY];
1422 int[] topEdge = new int[mCountX];
1423 int[] bottomEdge = new int[mCountX];
1424 boolean leftEdgeDirty, rightEdgeDirty, topEdgeDirty, bottomEdgeDirty, boundingRectDirty;
1425
1426 @SuppressWarnings("unchecked")
1427 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1428 this.views = (ArrayList<View>) views.clone();
1429 this.config = config;
1430 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001431 }
1432
Adam Cohenf3900c22012-11-16 18:28:11 -08001433 void resetEdges() {
1434 for (int i = 0; i < mCountX; i++) {
1435 topEdge[i] = -1;
1436 bottomEdge[i] = -1;
1437 }
1438 for (int i = 0; i < mCountY; i++) {
1439 leftEdge[i] = -1;
1440 rightEdge[i] = -1;
1441 }
1442 leftEdgeDirty = true;
1443 rightEdgeDirty = true;
1444 bottomEdgeDirty = true;
1445 topEdgeDirty = true;
1446 boundingRectDirty = true;
1447 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001448
Adam Cohenf3900c22012-11-16 18:28:11 -08001449 void computeEdge(int which, int[] edge) {
1450 int count = views.size();
1451 for (int i = 0; i < count; i++) {
1452 CellAndSpan cs = config.map.get(views.get(i));
1453 switch (which) {
1454 case LEFT:
1455 int left = cs.x;
1456 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1457 if (left < edge[j] || edge[j] < 0) {
1458 edge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001459 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001460 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001461 break;
1462 case RIGHT:
1463 int right = cs.x + cs.spanX;
1464 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1465 if (right > edge[j]) {
1466 edge[j] = right;
1467 }
1468 }
1469 break;
1470 case TOP:
1471 int top = cs.y;
1472 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1473 if (top < edge[j] || edge[j] < 0) {
1474 edge[j] = top;
1475 }
1476 }
1477 break;
1478 case BOTTOM:
1479 int bottom = cs.y + cs.spanY;
1480 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1481 if (bottom > edge[j]) {
1482 edge[j] = bottom;
1483 }
1484 }
1485 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001486 }
1487 }
1488 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001489
1490 boolean isViewTouchingEdge(View v, int whichEdge) {
1491 CellAndSpan cs = config.map.get(v);
1492
1493 int[] edge = getEdge(whichEdge);
1494
1495 switch (whichEdge) {
1496 case LEFT:
1497 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1498 if (edge[i] == cs.x + cs.spanX) {
1499 return true;
1500 }
1501 }
1502 break;
1503 case RIGHT:
1504 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1505 if (edge[i] == cs.x) {
1506 return true;
1507 }
1508 }
1509 break;
1510 case TOP:
1511 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1512 if (edge[i] == cs.y + cs.spanY) {
1513 return true;
1514 }
1515 }
1516 break;
1517 case BOTTOM:
1518 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1519 if (edge[i] == cs.y) {
1520 return true;
1521 }
1522 }
1523 break;
1524 }
1525 return false;
1526 }
1527
1528 void shift(int whichEdge, int delta) {
1529 for (View v: views) {
1530 CellAndSpan c = config.map.get(v);
1531 switch (whichEdge) {
1532 case LEFT:
1533 c.x -= delta;
1534 break;
1535 case RIGHT:
1536 c.x += delta;
1537 break;
1538 case TOP:
1539 c.y -= delta;
1540 break;
1541 case BOTTOM:
1542 default:
1543 c.y += delta;
1544 break;
1545 }
1546 }
1547 resetEdges();
1548 }
1549
1550 public void addView(View v) {
1551 views.add(v);
1552 resetEdges();
1553 }
1554
1555 public Rect getBoundingRect() {
1556 if (boundingRectDirty) {
1557 boolean first = true;
1558 for (View v: views) {
1559 CellAndSpan c = config.map.get(v);
1560 if (first) {
1561 boundingRect.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1562 first = false;
1563 } else {
1564 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1565 }
1566 }
1567 }
1568 return boundingRect;
1569 }
1570
1571 public int[] getEdge(int which) {
1572 switch (which) {
1573 case LEFT:
1574 return getLeftEdge();
1575 case RIGHT:
1576 return getRightEdge();
1577 case TOP:
1578 return getTopEdge();
1579 case BOTTOM:
1580 default:
1581 return getBottomEdge();
1582 }
1583 }
1584
1585 public int[] getLeftEdge() {
1586 if (leftEdgeDirty) {
1587 computeEdge(LEFT, leftEdge);
1588 }
1589 return leftEdge;
1590 }
1591
1592 public int[] getRightEdge() {
1593 if (rightEdgeDirty) {
1594 computeEdge(RIGHT, rightEdge);
1595 }
1596 return rightEdge;
1597 }
1598
1599 public int[] getTopEdge() {
1600 if (topEdgeDirty) {
1601 computeEdge(TOP, topEdge);
1602 }
1603 return topEdge;
1604 }
1605
1606 public int[] getBottomEdge() {
1607 if (bottomEdgeDirty) {
1608 computeEdge(BOTTOM, bottomEdge);
1609 }
1610 return bottomEdge;
1611 }
1612
1613 PositionComparator comparator = new PositionComparator();
1614 class PositionComparator implements Comparator<View> {
1615 int whichEdge = 0;
1616 public int compare(View left, View right) {
1617 CellAndSpan l = config.map.get(left);
1618 CellAndSpan r = config.map.get(right);
1619 switch (whichEdge) {
1620 case LEFT:
1621 return (r.x + r.spanX) - (l.x + l.spanX);
1622 case RIGHT:
1623 return l.x - r.x;
1624 case TOP:
1625 return (r.y + r.spanY) - (l.y + l.spanY);
1626 case BOTTOM:
1627 default:
1628 return l.y - r.y;
1629 }
1630 }
1631 }
1632
1633 public void sortConfigurationForEdgePush(int edge) {
1634 comparator.whichEdge = edge;
1635 Collections.sort(config.sortedViews, comparator);
1636 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001637 }
1638
Adam Cohenf3900c22012-11-16 18:28:11 -08001639 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1640 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001641
Adam Cohenf3900c22012-11-16 18:28:11 -08001642 ViewCluster cluster = new ViewCluster(views, currentState);
1643 Rect clusterRect = cluster.getBoundingRect();
1644 int whichEdge;
1645 int pushDistance;
1646 boolean fail = false;
1647
1648 // Determine the edge of the cluster that will be leading the push and how far
1649 // the cluster must be shifted.
1650 if (direction[0] < 0) {
1651 whichEdge = ViewCluster.LEFT;
1652 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001653 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001654 whichEdge = ViewCluster.RIGHT;
1655 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
1656 } else if (direction[1] < 0) {
1657 whichEdge = ViewCluster.TOP;
1658 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
1659 } else {
1660 whichEdge = ViewCluster.BOTTOM;
1661 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07001662 }
1663
Adam Cohenf3900c22012-11-16 18:28:11 -08001664 // Break early for invalid push distance.
1665 if (pushDistance <= 0) {
1666 return false;
Adam Cohene0489502012-08-27 15:18:53 -07001667 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001668
1669 // Mark the occupied state as false for the group of views we want to move.
1670 for (View v: views) {
1671 CellAndSpan c = currentState.map.get(v);
1672 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1673 }
1674
1675 // We save the current configuration -- if we fail to find a solution we will revert
1676 // to the initial state. The process of finding a solution modifies the configuration
1677 // in place, hence the need for revert in the failure case.
1678 currentState.save();
1679
1680 // The pushing algorithm is simplified by considering the views in the order in which
1681 // they would be pushed by the cluster. For example, if the cluster is leading with its
1682 // left edge, we consider sort the views by their right edge, from right to left.
1683 cluster.sortConfigurationForEdgePush(whichEdge);
1684
1685 while (pushDistance > 0 && !fail) {
1686 for (View v: currentState.sortedViews) {
1687 // For each view that isn't in the cluster, we see if the leading edge of the
1688 // cluster is contacting the edge of that view. If so, we add that view to the
1689 // cluster.
1690 if (!cluster.views.contains(v) && v != dragView) {
1691 if (cluster.isViewTouchingEdge(v, whichEdge)) {
1692 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1693 if (!lp.canReorder) {
1694 // The push solution includes the all apps button, this is not viable.
1695 fail = true;
1696 break;
1697 }
1698 cluster.addView(v);
1699 CellAndSpan c = currentState.map.get(v);
1700
1701 // Adding view to cluster, mark it as not occupied.
1702 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1703 }
1704 }
1705 }
1706 pushDistance--;
1707
1708 // The cluster has been completed, now we move the whole thing over in the appropriate
1709 // direction.
1710 cluster.shift(whichEdge, 1);
1711 }
1712
1713 boolean foundSolution = false;
1714 clusterRect = cluster.getBoundingRect();
1715
1716 // Due to the nature of the algorithm, the only check required to verify a valid solution
1717 // is to ensure that completed shifted cluster lies completely within the cell layout.
1718 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
1719 clusterRect.bottom <= mCountY) {
1720 foundSolution = true;
1721 } else {
1722 currentState.restore();
1723 }
1724
1725 // In either case, we set the occupied array as marked for the location of the views
1726 for (View v: cluster.views) {
1727 CellAndSpan c = currentState.map.get(v);
1728 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
1729 }
1730
1731 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07001732 }
1733
Adam Cohen482ed822012-03-02 14:15:13 -08001734 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08001735 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001736 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001737
Adam Cohen8baab352012-03-20 17:39:21 -07001738 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001739 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001740 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001741 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001742 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001743 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001744 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001745 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001746 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001747 }
1748 }
Adam Cohen8baab352012-03-20 17:39:21 -07001749
Adam Cohen8baab352012-03-20 17:39:21 -07001750 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08001751 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001752 CellAndSpan c = currentState.map.get(v);
1753 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1754 }
1755
Adam Cohen47a876d2012-03-19 13:21:41 -07001756 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1757 int top = boundingRect.top;
1758 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001759 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001760 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08001761 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001762 CellAndSpan c = currentState.map.get(v);
1763 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001764 }
1765
Adam Cohen482ed822012-03-02 14:15:13 -08001766 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1767
Adam Cohenf3900c22012-11-16 18:28:11 -08001768 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1769 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001770
Adam Cohen8baab352012-03-20 17:39:21 -07001771 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001772 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001773 int deltaX = mTempLocation[0] - boundingRect.left;
1774 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08001775 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001776 CellAndSpan c = currentState.map.get(v);
1777 c.x += deltaX;
1778 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001779 }
1780 success = true;
1781 }
Adam Cohen8baab352012-03-20 17:39:21 -07001782
1783 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08001784 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001785 CellAndSpan c = currentState.map.get(v);
1786 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001787 }
1788 return success;
1789 }
1790
1791 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1792 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1793 }
1794
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001795 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1796 // to push items in each of the cardinal directions, in an order based on the direction vector
1797 // passed.
1798 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1799 int[] direction, View ignoreView, ItemConfiguration solution) {
1800 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001801 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001802 // separately in each of the components.
1803 int temp = direction[1];
1804 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001805
1806 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001807 ignoreView, solution)) {
1808 return true;
1809 }
1810 direction[1] = temp;
1811 temp = direction[0];
1812 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001813
1814 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001815 ignoreView, solution)) {
1816 return true;
1817 }
1818 // Revert the direction
1819 direction[0] = temp;
1820
1821 // Now we try pushing in each component of the opposite direction
1822 direction[0] *= -1;
1823 direction[1] *= -1;
1824 temp = direction[1];
1825 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001826 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001827 ignoreView, solution)) {
1828 return true;
1829 }
1830
1831 direction[1] = temp;
1832 temp = direction[0];
1833 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08001834 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001835 ignoreView, solution)) {
1836 return true;
1837 }
1838 // revert the direction
1839 direction[0] = temp;
1840 direction[0] *= -1;
1841 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001842
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001843 } else {
1844 // If the direction vector has a single non-zero component, we push first in the
1845 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08001846 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001847 ignoreView, solution)) {
1848 return true;
1849 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001850 // Then we try the opposite direction
1851 direction[0] *= -1;
1852 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001853 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001854 ignoreView, solution)) {
1855 return true;
1856 }
1857 // Switch the direction back
1858 direction[0] *= -1;
1859 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07001860
1861 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001862 // to find a solution by pushing along the perpendicular axis.
1863
1864 // Swap the components
1865 int temp = direction[1];
1866 direction[1] = direction[0];
1867 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08001868 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001869 ignoreView, solution)) {
1870 return true;
1871 }
1872
1873 // Then we try the opposite direction
1874 direction[0] *= -1;
1875 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08001876 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001877 ignoreView, solution)) {
1878 return true;
1879 }
1880 // Switch the direction back
1881 direction[0] *= -1;
1882 direction[1] *= -1;
1883
1884 // Swap the components back
1885 temp = direction[1];
1886 direction[1] = direction[0];
1887 direction[0] = temp;
1888 }
1889 return false;
1890 }
1891
Adam Cohen482ed822012-03-02 14:15:13 -08001892 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001893 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001894 // Return early if get invalid cell positions
1895 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001896
Adam Cohen8baab352012-03-20 17:39:21 -07001897 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001898 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001899
Adam Cohen8baab352012-03-20 17:39:21 -07001900 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001901 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001902 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001903 if (c != null) {
1904 c.x = cellX;
1905 c.y = cellY;
1906 }
Adam Cohen482ed822012-03-02 14:15:13 -08001907 }
Adam Cohen482ed822012-03-02 14:15:13 -08001908 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1909 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001910 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001911 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001912 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001913 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001914 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001915 if (Rect.intersects(r0, r1)) {
1916 if (!lp.canReorder) {
1917 return false;
1918 }
1919 mIntersectingViews.add(child);
1920 }
1921 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001922
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001923 solution.intersectingViews = new ArrayList<View>(mIntersectingViews);
1924
Winson Chung5f8afe62013-08-12 16:19:28 -07001925 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001926 // we try to find a solution such that no displaced item travels through another item
1927 // without also displacing that item.
1928 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001929 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001930 return true;
1931 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001932
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001933 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08001934 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001935 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001936 return true;
1937 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001938
Adam Cohen482ed822012-03-02 14:15:13 -08001939 // Ok, they couldn't move as a block, let's move them individually
1940 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001941 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001942 return false;
1943 }
1944 }
1945 return true;
1946 }
1947
1948 /*
1949 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1950 * the provided point and the provided cell
1951 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001952 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001953 double angle = Math.atan(((float) deltaY) / deltaX);
1954
1955 result[0] = 0;
1956 result[1] = 0;
1957 if (Math.abs(Math.cos(angle)) > 0.5f) {
1958 result[0] = (int) Math.signum(deltaX);
1959 }
1960 if (Math.abs(Math.sin(angle)) > 0.5f) {
1961 result[1] = (int) Math.signum(deltaY);
1962 }
1963 }
1964
Adam Cohen8baab352012-03-20 17:39:21 -07001965 private void copyOccupiedArray(boolean[][] occupied) {
1966 for (int i = 0; i < mCountX; i++) {
1967 for (int j = 0; j < mCountY; j++) {
1968 occupied[i][j] = mOccupied[i][j];
1969 }
1970 }
1971 }
1972
Sunny Goyalf7a29e82015-04-24 15:20:43 -07001973 private ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001974 int spanX, int spanY, int[] direction, View dragView, boolean decX,
1975 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001976 // Copy the current state into the solution. This solution will be manipulated as necessary.
1977 copyCurrentStateToSolution(solution, false);
1978 // Copy the current occupied array into the temporary occupied array. This array will be
1979 // manipulated as necessary to find a solution.
1980 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001981
1982 // We find the nearest cell into which we would place the dragged item, assuming there's
1983 // nothing in its way.
1984 int result[] = new int[2];
1985 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1986
1987 boolean success = false;
1988 // First we try the exact nearest position of the item being dragged,
1989 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001990 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1991 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001992
1993 if (!success) {
1994 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1995 // x, then 1 in y etc.
1996 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08001997 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
1998 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001999 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002000 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
2001 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08002002 }
2003 solution.isSolution = false;
2004 } else {
2005 solution.isSolution = true;
2006 solution.dragViewX = result[0];
2007 solution.dragViewY = result[1];
2008 solution.dragViewSpanX = spanX;
2009 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002010 }
2011 return solution;
2012 }
2013
2014 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002015 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002016 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002017 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002018 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002019 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08002020 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07002021 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002022 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07002023 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002024 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002025 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08002026 }
2027 }
2028
2029 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
2030 for (int i = 0; i < mCountX; i++) {
2031 for (int j = 0; j < mCountY; j++) {
2032 mTmpOccupied[i][j] = false;
2033 }
2034 }
2035
Michael Jurkaa52570f2012-03-20 03:18:20 -07002036 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002037 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002038 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002039 if (child == dragView) continue;
2040 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002041 CellAndSpan c = solution.map.get(child);
2042 if (c != null) {
2043 lp.tmpCellX = c.x;
2044 lp.tmpCellY = c.y;
2045 lp.cellHSpan = c.spanX;
2046 lp.cellVSpan = c.spanY;
2047 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002048 }
2049 }
2050 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2051 solution.dragViewSpanY, mTmpOccupied, true);
2052 }
2053
2054 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
2055 commitDragView) {
2056
2057 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
2058 for (int i = 0; i < mCountX; i++) {
2059 for (int j = 0; j < mCountY; j++) {
2060 occupied[i][j] = false;
2061 }
2062 }
2063
Michael Jurkaa52570f2012-03-20 03:18:20 -07002064 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002065 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002066 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002067 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002068 CellAndSpan c = solution.map.get(child);
2069 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002070 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2071 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002072 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002073 }
2074 }
2075 if (commitDragView) {
2076 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2077 solution.dragViewSpanY, occupied, true);
2078 }
2079 }
2080
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002081
2082 // This method starts or changes the reorder preview animations
2083 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
2084 View dragView, int delay, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07002085 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002086 for (int i = 0; i < childCount; i++) {
2087 View child = mShortcutsAndWidgets.getChildAt(i);
2088 if (child == dragView) continue;
2089 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002090 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
2091 != null && !solution.intersectingViews.contains(child);
2092
Adam Cohen19f37922012-03-21 11:59:11 -07002093 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002094 if (c != null && !skip) {
2095 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
2096 lp.cellY, c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002097 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002098 }
2099 }
2100 }
2101
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002102 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07002103 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002104 class ReorderPreviewAnimation {
Adam Cohen19f37922012-03-21 11:59:11 -07002105 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002106 float finalDeltaX;
2107 float finalDeltaY;
2108 float initDeltaX;
2109 float initDeltaY;
2110 float finalScale;
2111 float initScale;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002112 int mode;
2113 boolean repeating = false;
2114 private static final int PREVIEW_DURATION = 300;
2115 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
2116
2117 public static final int MODE_HINT = 0;
2118 public static final int MODE_PREVIEW = 1;
2119
Adam Cohene7587d22012-05-24 18:50:02 -07002120 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002121
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002122 public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
2123 int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07002124 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2125 final int x0 = mTmpPoint[0];
2126 final int y0 = mTmpPoint[1];
2127 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2128 final int x1 = mTmpPoint[0];
2129 final int y1 = mTmpPoint[1];
2130 final int dX = x1 - x0;
2131 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002132 finalDeltaX = 0;
2133 finalDeltaY = 0;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002134 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07002135 if (dX == dY && dX == 0) {
2136 } else {
2137 if (dY == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002138 finalDeltaX = - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002139 } else if (dX == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002140 finalDeltaY = - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002141 } else {
2142 double angle = Math.atan( (float) (dY) / dX);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002143 finalDeltaX = (int) (- dir * Math.signum(dX) *
2144 Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
2145 finalDeltaY = (int) (- dir * Math.signum(dY) *
2146 Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002147 }
2148 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002149 this.mode = mode;
Adam Cohend024f982012-05-23 18:26:45 -07002150 initDeltaX = child.getTranslationX();
2151 initDeltaY = child.getTranslationY();
Adam Cohen307fe232012-08-16 17:55:58 -07002152 finalScale = getChildrenScale() - 4.0f / child.getWidth();
Adam Cohend024f982012-05-23 18:26:45 -07002153 initScale = child.getScaleX();
Adam Cohen19f37922012-03-21 11:59:11 -07002154 this.child = child;
2155 }
2156
Adam Cohend024f982012-05-23 18:26:45 -07002157 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002158 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002159 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002160 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002161 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002162 if (finalDeltaX == 0 && finalDeltaY == 0) {
2163 completeAnimationImmediately();
2164 return;
2165 }
Adam Cohen19f37922012-03-21 11:59:11 -07002166 }
Adam Cohend024f982012-05-23 18:26:45 -07002167 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002168 return;
2169 }
Michael Jurkaf1ad6082013-03-13 12:55:46 +01002170 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002171 a = va;
Tony Wickham9e0702f2015-09-02 14:45:39 -07002172
2173 // Animations are disabled in power save mode, causing the repeated animation to jump
2174 // spastically between beginning and end states. Since this looks bad, we don't repeat
2175 // the animation in power save mode.
Tony Wickham112ac952015-11-12 12:31:50 -08002176 if (!Utilities.isPowerSaverOn(getContext())) {
Tony Wickham9e0702f2015-09-02 14:45:39 -07002177 va.setRepeatMode(ValueAnimator.REVERSE);
2178 va.setRepeatCount(ValueAnimator.INFINITE);
2179 }
2180
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002181 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002182 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002183 va.addUpdateListener(new AnimatorUpdateListener() {
2184 @Override
2185 public void onAnimationUpdate(ValueAnimator animation) {
2186 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002187 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : r;
2188 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2189 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002190 child.setTranslationX(x);
2191 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002192 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002193 child.setScaleX(s);
2194 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002195 }
2196 });
2197 va.addListener(new AnimatorListenerAdapter() {
2198 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002199 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002200 initDeltaX = 0;
2201 initDeltaY = 0;
Adam Cohen307fe232012-08-16 17:55:58 -07002202 initScale = getChildrenScale();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002203 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002204 }
2205 });
Adam Cohen19f37922012-03-21 11:59:11 -07002206 mShakeAnimators.put(child, this);
2207 va.start();
2208 }
2209
Adam Cohend024f982012-05-23 18:26:45 -07002210 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002211 if (a != null) {
2212 a.cancel();
2213 }
Adam Cohen19f37922012-03-21 11:59:11 -07002214 }
Adam Cohene7587d22012-05-24 18:50:02 -07002215
Adam Cohen091440a2015-03-18 14:16:05 -07002216 @Thunk void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002217 if (a != null) {
2218 a.cancel();
2219 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002220
Sunny Goyal5d2fc322015-07-06 22:52:49 -07002221 a = new LauncherViewPropertyAnimator(child)
2222 .scaleX(getChildrenScale())
2223 .scaleY(getChildrenScale())
2224 .translationX(0)
2225 .translationY(0)
2226 .setDuration(REORDER_ANIMATION_DURATION);
2227 a.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2228 a.start();
Brandon Keely50e6e562012-05-08 16:28:49 -07002229 }
Adam Cohen19f37922012-03-21 11:59:11 -07002230 }
2231
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002232 private void completeAndClearReorderPreviewAnimations() {
2233 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002234 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002235 }
2236 mShakeAnimators.clear();
2237 }
2238
Adam Cohen482ed822012-03-02 14:15:13 -08002239 private void commitTempPlacement() {
2240 for (int i = 0; i < mCountX; i++) {
2241 for (int j = 0; j < mCountY; j++) {
2242 mOccupied[i][j] = mTmpOccupied[i][j];
2243 }
2244 }
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002245
2246 long screenId = mLauncher.getWorkspace().getIdForScreen(this);
2247 int container = Favorites.CONTAINER_DESKTOP;
2248
2249 if (mLauncher.isHotseatLayout(this)) {
2250 screenId = -1;
2251 container = Favorites.CONTAINER_HOTSEAT;
2252 }
2253
Michael Jurkaa52570f2012-03-20 03:18:20 -07002254 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002255 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002256 View child = mShortcutsAndWidgets.getChildAt(i);
2257 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2258 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002259 // We do a null check here because the item info can be null in the case of the
2260 // AllApps button in the hotseat.
2261 if (info != null) {
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002262 final boolean requiresDbUpdate = (info.cellX != lp.tmpCellX
2263 || info.cellY != lp.tmpCellY || info.spanX != lp.cellHSpan
2264 || info.spanY != lp.cellVSpan);
2265
Adam Cohen2acce882012-03-28 19:03:19 -07002266 info.cellX = lp.cellX = lp.tmpCellX;
2267 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002268 info.spanX = lp.cellHSpan;
2269 info.spanY = lp.cellVSpan;
Sunny Goyalaa8ef112015-06-12 20:04:41 -07002270
2271 if (requiresDbUpdate) {
2272 LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId,
2273 info.cellX, info.cellY, info.spanX, info.spanY);
2274 }
Adam Cohen2acce882012-03-28 19:03:19 -07002275 }
Adam Cohen482ed822012-03-02 14:15:13 -08002276 }
2277 }
2278
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002279 private void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002280 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002281 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002282 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002283 lp.useTmpCoords = useTempCoords;
2284 }
2285 }
2286
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002287 private ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002288 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2289 int[] result = new int[2];
2290 int[] resultSpan = new int[2];
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002291 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, result,
Adam Cohen482ed822012-03-02 14:15:13 -08002292 resultSpan);
2293 if (result[0] >= 0 && result[1] >= 0) {
2294 copyCurrentStateToSolution(solution, false);
2295 solution.dragViewX = result[0];
2296 solution.dragViewY = result[1];
2297 solution.dragViewSpanX = resultSpan[0];
2298 solution.dragViewSpanY = resultSpan[1];
2299 solution.isSolution = true;
2300 } else {
2301 solution.isSolution = false;
2302 }
2303 return solution;
2304 }
2305
2306 public void prepareChildForDrag(View child) {
2307 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002308 }
2309
Adam Cohen19f37922012-03-21 11:59:11 -07002310 /* This seems like it should be obvious and straight-forward, but when the direction vector
2311 needs to match with the notion of the dragView pushing other views, we have to employ
2312 a slightly more subtle notion of the direction vector. The question is what two points is
2313 the vector between? The center of the dragView and its desired destination? Not quite, as
2314 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2315 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2316 or right, which helps make pushing feel right.
2317 */
2318 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2319 int spanY, View dragView, int[] resultDirection) {
2320 int[] targetDestination = new int[2];
2321
2322 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2323 Rect dragRect = new Rect();
2324 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2325 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2326
2327 Rect dropRegionRect = new Rect();
2328 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2329 dragView, dropRegionRect, mIntersectingViews);
2330
2331 int dropRegionSpanX = dropRegionRect.width();
2332 int dropRegionSpanY = dropRegionRect.height();
2333
2334 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2335 dropRegionRect.height(), dropRegionRect);
2336
2337 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2338 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2339
2340 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2341 deltaX = 0;
2342 }
2343 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2344 deltaY = 0;
2345 }
2346
2347 if (deltaX == 0 && deltaY == 0) {
2348 // No idea what to do, give a random direction.
2349 resultDirection[0] = 1;
2350 resultDirection[1] = 0;
2351 } else {
2352 computeDirectionVector(deltaX, deltaY, resultDirection);
2353 }
2354 }
2355
2356 // For a given cell and span, fetch the set of views intersecting the region.
2357 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2358 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2359 if (boundingRect != null) {
2360 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2361 }
2362 intersectingViews.clear();
2363 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2364 Rect r1 = new Rect();
2365 final int count = mShortcutsAndWidgets.getChildCount();
2366 for (int i = 0; i < count; i++) {
2367 View child = mShortcutsAndWidgets.getChildAt(i);
2368 if (child == dragView) continue;
2369 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2370 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2371 if (Rect.intersects(r0, r1)) {
2372 mIntersectingViews.add(child);
2373 if (boundingRect != null) {
2374 boundingRect.union(r1);
2375 }
2376 }
2377 }
2378 }
2379
2380 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2381 View dragView, int[] result) {
2382 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2383 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2384 mIntersectingViews);
2385 return !mIntersectingViews.isEmpty();
2386 }
2387
2388 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002389 completeAndClearReorderPreviewAnimations();
2390 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2391 final int count = mShortcutsAndWidgets.getChildCount();
2392 for (int i = 0; i < count; i++) {
2393 View child = mShortcutsAndWidgets.getChildAt(i);
2394 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2395 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2396 lp.tmpCellX = lp.cellX;
2397 lp.tmpCellY = lp.cellY;
2398 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2399 0, false, false);
2400 }
Adam Cohen19f37922012-03-21 11:59:11 -07002401 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002402 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002403 }
Adam Cohen19f37922012-03-21 11:59:11 -07002404 }
2405
Adam Cohenbebf0422012-04-11 18:06:28 -07002406 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2407 View dragView, int[] direction, boolean commit) {
2408 int[] pixelXY = new int[2];
2409 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2410
2411 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002412 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002413 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2414
2415 setUseTempCoords(true);
2416 if (swapSolution != null && swapSolution.isSolution) {
2417 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2418 // committing anything or animating anything as we just want to determine if a solution
2419 // exists
2420 copySolutionToTempState(swapSolution, dragView);
2421 setItemPlacementDirty(true);
2422 animateItemsToSolution(swapSolution, dragView, commit);
2423
2424 if (commit) {
2425 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002426 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002427 setItemPlacementDirty(false);
2428 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002429 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
2430 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002431 }
2432 mShortcutsAndWidgets.requestLayout();
2433 }
2434 return swapSolution.isSolution;
2435 }
2436
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002437 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002438 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002439 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002440 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002441
2442 if (resultSpan == null) {
2443 resultSpan = new int[2];
2444 }
2445
Adam Cohen19f37922012-03-21 11:59:11 -07002446 // When we are checking drop validity or actually dropping, we don't recompute the
2447 // direction vector, since we want the solution to match the preview, and it's possible
2448 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002449 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2450 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002451 mDirectionVector[0] = mPreviousReorderDirection[0];
2452 mDirectionVector[1] = mPreviousReorderDirection[1];
2453 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002454 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2455 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2456 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002457 }
2458 } else {
2459 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2460 mPreviousReorderDirection[0] = mDirectionVector[0];
2461 mPreviousReorderDirection[1] = mDirectionVector[1];
2462 }
2463
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002464 // Find a solution involving pushing / displacing any items in the way
2465 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002466 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2467
2468 // We attempt the approach which doesn't shuffle views at all
2469 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2470 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2471
2472 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002473
2474 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2475 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002476 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2477 finalSolution = swapSolution;
2478 } else if (noShuffleSolution.isSolution) {
2479 finalSolution = noShuffleSolution;
2480 }
2481
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002482 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002483 if (finalSolution != null) {
Adam Cohenfe692872013-12-11 14:47:23 -08002484 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
2485 ReorderPreviewAnimation.MODE_HINT);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002486 result[0] = finalSolution.dragViewX;
2487 result[1] = finalSolution.dragViewY;
2488 resultSpan[0] = finalSolution.dragViewSpanX;
2489 resultSpan[1] = finalSolution.dragViewSpanY;
2490 } else {
2491 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2492 }
2493 return result;
2494 }
2495
Adam Cohen482ed822012-03-02 14:15:13 -08002496 boolean foundSolution = true;
2497 if (!DESTRUCTIVE_REORDER) {
2498 setUseTempCoords(true);
2499 }
2500
2501 if (finalSolution != null) {
2502 result[0] = finalSolution.dragViewX;
2503 result[1] = finalSolution.dragViewY;
2504 resultSpan[0] = finalSolution.dragViewSpanX;
2505 resultSpan[1] = finalSolution.dragViewSpanY;
2506
2507 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2508 // committing anything or animating anything as we just want to determine if a solution
2509 // exists
2510 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2511 if (!DESTRUCTIVE_REORDER) {
2512 copySolutionToTempState(finalSolution, dragView);
2513 }
2514 setItemPlacementDirty(true);
2515 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2516
Adam Cohen19f37922012-03-21 11:59:11 -07002517 if (!DESTRUCTIVE_REORDER &&
2518 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002519 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002520 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002521 setItemPlacementDirty(false);
2522 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002523 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
2524 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002525 }
2526 }
2527 } else {
2528 foundSolution = false;
2529 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2530 }
2531
2532 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2533 setUseTempCoords(false);
2534 }
Adam Cohen482ed822012-03-02 14:15:13 -08002535
Michael Jurkaa52570f2012-03-20 03:18:20 -07002536 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002537 return result;
2538 }
2539
Adam Cohen19f37922012-03-21 11:59:11 -07002540 void setItemPlacementDirty(boolean dirty) {
2541 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002542 }
Adam Cohen19f37922012-03-21 11:59:11 -07002543 boolean isItemPlacementDirty() {
2544 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002545 }
2546
Adam Cohen091440a2015-03-18 14:16:05 -07002547 @Thunk class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002548 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohenf3900c22012-11-16 18:28:11 -08002549 private HashMap<View, CellAndSpan> savedMap = new HashMap<View, CellAndSpan>();
2550 ArrayList<View> sortedViews = new ArrayList<View>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002551 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002552 boolean isSolution = false;
2553 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2554
Adam Cohenf3900c22012-11-16 18:28:11 -08002555 void save() {
2556 // Copy current state into savedMap
2557 for (View v: map.keySet()) {
2558 map.get(v).copy(savedMap.get(v));
2559 }
2560 }
2561
2562 void restore() {
2563 // Restore current state from savedMap
2564 for (View v: savedMap.keySet()) {
2565 savedMap.get(v).copy(map.get(v));
2566 }
2567 }
2568
2569 void add(View v, CellAndSpan cs) {
2570 map.put(v, cs);
2571 savedMap.put(v, new CellAndSpan());
2572 sortedViews.add(v);
2573 }
2574
Adam Cohen482ed822012-03-02 14:15:13 -08002575 int area() {
2576 return dragViewSpanX * dragViewSpanY;
2577 }
Adam Cohen8baab352012-03-20 17:39:21 -07002578 }
2579
2580 private class CellAndSpan {
2581 int x, y;
2582 int spanX, spanY;
2583
Adam Cohenf3900c22012-11-16 18:28:11 -08002584 public CellAndSpan() {
2585 }
2586
2587 public void copy(CellAndSpan copy) {
2588 copy.x = x;
2589 copy.y = y;
2590 copy.spanX = spanX;
2591 copy.spanY = spanY;
2592 }
2593
Adam Cohen8baab352012-03-20 17:39:21 -07002594 public CellAndSpan(int x, int y, int spanX, int spanY) {
2595 this.x = x;
2596 this.y = y;
2597 this.spanX = spanX;
2598 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002599 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002600
2601 public String toString() {
2602 return "(" + x + ", " + y + ": " + spanX + ", " + spanY + ")";
2603 }
2604
Adam Cohen482ed822012-03-02 14:15:13 -08002605 }
2606
Adam Cohendf035382011-04-11 17:22:04 -07002607 /**
Adam Cohendf035382011-04-11 17:22:04 -07002608 * Find a starting cell position that will fit the given bounds nearest the requested
2609 * cell location. Uses Euclidean distance to score multiple vacant areas.
2610 *
2611 * @param pixelX The X location at which you want to search for a vacant area.
2612 * @param pixelY The Y location at which you want to search for a vacant area.
2613 * @param spanX Horizontal span of the object.
2614 * @param spanY Vertical span of the object.
2615 * @param ignoreView Considers space occupied by this view as unoccupied
2616 * @param result Previously returned value to possibly recycle.
2617 * @return The X, Y cell of a vacant area that can contain this object,
2618 * nearest the requested location.
2619 */
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002620 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2621 return findNearestArea(pixelX, pixelY, spanX, spanY, spanX, spanY, false, result, null);
Adam Cohendf035382011-04-11 17:22:04 -07002622 }
2623
Michael Jurka0280c3b2010-09-17 15:00:07 -07002624 boolean existsEmptyCell() {
2625 return findCellForSpan(null, 1, 1);
2626 }
2627
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002628 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002629 * Finds the upper-left coordinate of the first rectangle in the grid that can
2630 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2631 * then this method will only return coordinates for rectangles that contain the cell
2632 * (intersectX, intersectY)
2633 *
2634 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2635 * can be found.
2636 * @param spanX The horizontal span of the cell we want to find.
2637 * @param spanY The vertical span of the cell we want to find.
2638 *
2639 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002640 */
Hyunyoung Song3f471442015-04-08 19:01:34 -07002641 public boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Michael Jurka28750fb2010-09-24 17:43:49 -07002642 boolean foundCell = false;
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002643 final int endX = mCountX - (spanX - 1);
2644 final int endY = mCountY - (spanY - 1);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002645
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002646 for (int y = 0; y < endY && !foundCell; y++) {
2647 inner:
2648 for (int x = 0; x < endX; x++) {
2649 for (int i = 0; i < spanX; i++) {
2650 for (int j = 0; j < spanY; j++) {
2651 if (mOccupied[x + i][y + j]) {
2652 // small optimization: we can skip to after the column we just found
2653 // an occupied cell
2654 x += i;
2655 continue inner;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002656 }
2657 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002658 }
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002659 if (cellXY != null) {
2660 cellXY[0] = x;
2661 cellXY[1] = y;
2662 }
2663 foundCell = true;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002664 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002665 }
2666 }
2667
Michael Jurka28750fb2010-09-24 17:43:49 -07002668 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002669 }
2670
2671 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002672 * A drag event has begun over this layout.
2673 * It may have begun over this layout (in which case onDragChild is called first),
2674 * or it may have begun on another layout.
2675 */
2676 void onDragEnter() {
Winson Chungc07918d2011-07-01 15:35:26 -07002677 mDragging = true;
2678 }
2679
2680 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002681 * Called when drag has left this CellLayout or has been completed (successfully or not)
2682 */
2683 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002684 // This can actually be called when we aren't in a drag, e.g. when adding a new
2685 // item to this layout via the customize drawer.
2686 // Guard against that case.
2687 if (mDragging) {
2688 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002689 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002690
2691 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002692 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002693 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2694 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002695 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002696 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002697 }
2698
2699 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002700 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002701 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002702 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002703 *
2704 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002705 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002706 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002707 if (child != null) {
2708 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002709 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002710 child.requestLayout();
Tony Wickham1cdb6d02015-09-17 11:08:27 -07002711 markCellsAsOccupiedForView(child);
Romain Guyd94533d2009-08-17 10:01:15 -07002712 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002713 }
2714
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002715 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002716 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002717 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002718 * @param cellX X coordinate of upper left corner expressed as a cell position
2719 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002720 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002721 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002722 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002723 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002724 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002725 final int cellWidth = mCellWidth;
2726 final int cellHeight = mCellHeight;
2727 final int widthGap = mWidthGap;
2728 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002729
Winson Chung4b825dcd2011-06-19 12:41:22 -07002730 final int hStartPadding = getPaddingLeft();
2731 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002732
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002733 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2734 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2735
2736 int x = hStartPadding + cellX * (cellWidth + widthGap);
2737 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002738
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002739 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002740 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002741
Michael Jurka0280c3b2010-09-17 15:00:07 -07002742 private void clearOccupiedCells() {
2743 for (int x = 0; x < mCountX; x++) {
2744 for (int y = 0; y < mCountY; y++) {
2745 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002746 }
2747 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002748 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002749
Adam Cohend4844c32011-02-18 19:25:06 -08002750 public void markCellsAsOccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002751 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002752 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002753 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002754 }
2755
Adam Cohend4844c32011-02-18 19:25:06 -08002756 public void markCellsAsUnoccupiedForView(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002757 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002758 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Sunny Goyalf7a29e82015-04-24 15:20:43 -07002759 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, mOccupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002760 }
2761
Adam Cohen482ed822012-03-02 14:15:13 -08002762 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2763 boolean value) {
2764 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002765 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2766 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002767 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002768 }
2769 }
2770 }
2771
Adam Cohen2801caf2011-05-13 20:57:39 -07002772 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002773 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002774 (Math.max((mCountX - 1), 0) * mWidthGap);
2775 }
2776
2777 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002778 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002779 (Math.max((mCountY - 1), 0) * mHeightGap);
2780 }
2781
Michael Jurka66d72172011-04-12 16:29:25 -07002782 public boolean isOccupied(int x, int y) {
2783 if (x < mCountX && y < mCountY) {
2784 return mOccupied[x][y];
2785 } else {
2786 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2787 }
2788 }
2789
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002790 @Override
2791 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2792 return new CellLayout.LayoutParams(getContext(), attrs);
2793 }
2794
2795 @Override
2796 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2797 return p instanceof CellLayout.LayoutParams;
2798 }
2799
2800 @Override
2801 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2802 return new CellLayout.LayoutParams(p);
2803 }
2804
2805 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2806 /**
2807 * Horizontal location of the item in the grid.
2808 */
2809 @ViewDebug.ExportedProperty
2810 public int cellX;
2811
2812 /**
2813 * Vertical location of the item in the grid.
2814 */
2815 @ViewDebug.ExportedProperty
2816 public int cellY;
2817
2818 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002819 * Temporary horizontal location of the item in the grid during reorder
2820 */
2821 public int tmpCellX;
2822
2823 /**
2824 * Temporary vertical location of the item in the grid during reorder
2825 */
2826 public int tmpCellY;
2827
2828 /**
2829 * Indicates that the temporary coordinates should be used to layout the items
2830 */
2831 public boolean useTmpCoords;
2832
2833 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002834 * Number of cells spanned horizontally by the item.
2835 */
2836 @ViewDebug.ExportedProperty
2837 public int cellHSpan;
2838
2839 /**
2840 * Number of cells spanned vertically by the item.
2841 */
2842 @ViewDebug.ExportedProperty
2843 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002844
Adam Cohen1b607ed2011-03-03 17:26:50 -08002845 /**
2846 * Indicates whether the item will set its x, y, width and height parameters freely,
2847 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2848 */
Adam Cohend4844c32011-02-18 19:25:06 -08002849 public boolean isLockedToGrid = true;
2850
Adam Cohen482ed822012-03-02 14:15:13 -08002851 /**
Adam Cohenec40b2b2013-07-23 15:52:40 -07002852 * Indicates that this item should use the full extents of its parent.
2853 */
2854 public boolean isFullscreen = false;
2855
2856 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002857 * Indicates whether this item can be reordered. Always true except in the case of the
2858 * the AllApps button.
2859 */
2860 public boolean canReorder = true;
2861
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002862 // X coordinate of the view in the layout.
2863 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002864 public int x;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002865 // Y coordinate of the view in the layout.
2866 @ViewDebug.ExportedProperty
Vadim Tryshevfedca432015-08-19 17:55:02 -07002867 public int y;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002868
Romain Guy84f296c2009-11-04 15:00:44 -08002869 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002870
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002871 public LayoutParams(Context c, AttributeSet attrs) {
2872 super(c, attrs);
2873 cellHSpan = 1;
2874 cellVSpan = 1;
2875 }
2876
2877 public LayoutParams(ViewGroup.LayoutParams source) {
2878 super(source);
2879 cellHSpan = 1;
2880 cellVSpan = 1;
2881 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002882
2883 public LayoutParams(LayoutParams source) {
2884 super(source);
2885 this.cellX = source.cellX;
2886 this.cellY = source.cellY;
2887 this.cellHSpan = source.cellHSpan;
2888 this.cellVSpan = source.cellVSpan;
2889 }
2890
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002891 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002892 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002893 this.cellX = cellX;
2894 this.cellY = cellY;
2895 this.cellHSpan = cellHSpan;
2896 this.cellVSpan = cellVSpan;
2897 }
2898
Adam Cohen2374abf2013-04-16 14:56:57 -07002899 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap,
2900 boolean invertHorizontally, int colCount) {
Adam Cohend4844c32011-02-18 19:25:06 -08002901 if (isLockedToGrid) {
2902 final int myCellHSpan = cellHSpan;
2903 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07002904 int myCellX = useTmpCoords ? tmpCellX : cellX;
2905 int myCellY = useTmpCoords ? tmpCellY : cellY;
2906
2907 if (invertHorizontally) {
2908 myCellX = colCount - myCellX - cellHSpan;
2909 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08002910
Adam Cohend4844c32011-02-18 19:25:06 -08002911 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2912 leftMargin - rightMargin;
2913 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2914 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002915 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2916 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002917 }
2918 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002919
Winson Chungaafa03c2010-06-11 17:34:16 -07002920 public String toString() {
2921 return "(" + this.cellX + ", " + this.cellY + ")";
2922 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002923
2924 public void setWidth(int width) {
2925 this.width = width;
2926 }
2927
2928 public int getWidth() {
2929 return width;
2930 }
2931
2932 public void setHeight(int height) {
2933 this.height = height;
2934 }
2935
2936 public int getHeight() {
2937 return height;
2938 }
2939
2940 public void setX(int x) {
2941 this.x = x;
2942 }
2943
2944 public int getX() {
2945 return x;
2946 }
2947
2948 public void setY(int y) {
2949 this.y = y;
2950 }
2951
2952 public int getY() {
2953 return y;
2954 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002955 }
2956
Michael Jurka0280c3b2010-09-17 15:00:07 -07002957 // This class stores info for two purposes:
2958 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2959 // its spanX, spanY, and the screen it is on
2960 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2961 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2962 // the CellLayout that was long clicked
Sunny Goyal83a8f042015-05-19 12:52:12 -07002963 public static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002964 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002965 int cellX = -1;
2966 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002967 int spanX;
2968 int spanY;
Adam Cohendcd297f2013-06-18 13:13:40 -07002969 long screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07002970 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002971
Sunny Goyal83a8f042015-05-19 12:52:12 -07002972 public CellInfo(View v, ItemInfo info) {
Adam Cohene0aaa0d2014-05-12 12:44:22 -07002973 cell = v;
2974 cellX = info.cellX;
2975 cellY = info.cellY;
2976 spanX = info.spanX;
2977 spanY = info.spanY;
2978 screenId = info.screenId;
2979 container = info.container;
2980 }
2981
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002982 @Override
2983 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002984 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2985 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002986 }
2987 }
Michael Jurkad771c962011-08-09 15:00:48 -07002988
Sunny Goyala9116722015-04-29 13:55:58 -07002989 public boolean findVacantCell(int spanX, int spanY, int[] outXY) {
2990 return Utilities.findVacantCell(outXY, spanX, spanY, mCountX, mCountY, mOccupied);
2991 }
Sunny Goyal9ca9c132015-04-29 14:57:22 -07002992
Tony Wickham86930612015-09-09 13:50:40 -07002993 /**
2994 * Returns whether an item can be placed in this CellLayout (after rearranging and/or resizing
2995 * if necessary).
2996 */
2997 public boolean hasReorderSolution(ItemInfo itemInfo) {
2998 int[] cellPoint = new int[2];
2999 // Check for a solution starting at every cell.
3000 for (int cellX = 0; cellX < getCountX(); cellX++) {
3001 for (int cellY = 0; cellY < getCountY(); cellY++) {
3002 cellToPoint(cellX, cellY, cellPoint);
3003 if (findReorderSolution(cellPoint[0], cellPoint[1], itemInfo.minSpanX,
3004 itemInfo.minSpanY, itemInfo.spanX, itemInfo.spanY, mDirectionVector, null,
3005 true, new ItemConfiguration()).isSolution) {
3006 return true;
3007 }
3008 }
3009 }
3010 return false;
3011 }
3012
Sunny Goyal9ca9c132015-04-29 14:57:22 -07003013 public boolean isRegionVacant(int x, int y, int spanX, int spanY) {
3014 int x2 = x + spanX - 1;
3015 int y2 = y + spanY - 1;
3016 if (x < 0 || y < 0 || x2 >= mCountX || y2 >= mCountY) {
3017 return false;
3018 }
3019 for (int i = x; i <= x2; i++) {
3020 for (int j = y; j <= y2; j++) {
3021 if (mOccupied[i][j]) {
3022 return false;
3023 }
3024 }
3025 }
3026
3027 return true;
3028 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003029}