blob: eb2aa547db8d9cf5c114fa0cc4355887c937f3b0 [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;
Brandon Keely50e6e562012-05-08 16:28:49 -070021import android.animation.AnimatorSet;
Chet Haase00397b12010-10-07 11:13:10 -070022import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070023import android.animation.ValueAnimator;
24import android.animation.ValueAnimator.AnimatorUpdateListener;
Adam Cohenc9735cf2015-01-23 16:11:55 -080025import android.annotation.TargetApi;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040027import android.content.res.Resources;
Winson Chungaafa03c2010-06-11 17:34:16 -070028import android.content.res.TypedArray;
Joe Onorato4be866d2010-10-10 11:26:02 -070029import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070030import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080031import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070032import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070033import android.graphics.Point;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080035import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070036import android.graphics.drawable.Drawable;
Adam Cohenc9735cf2015-01-23 16:11:55 -080037import android.os.Build;
38import android.os.Bundle;
Adam Cohen1462de32012-07-24 22:34:36 -070039import android.os.Parcelable;
Adam Cohenc9735cf2015-01-23 16:11:55 -080040import android.support.v4.view.ViewCompat;
41import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
42import android.support.v4.widget.ExploreByTouchHelper;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070044import android.util.Log;
Adam Cohen1462de32012-07-24 22:34:36 -070045import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080046import android.view.MotionEvent;
47import android.view.View;
Adam Cohenc9735cf2015-01-23 16:11:55 -080048import android.view.View.OnClickListener;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080049import android.view.ViewDebug;
50import android.view.ViewGroup;
Adam Cohenc9735cf2015-01-23 16:11:55 -080051import android.view.accessibility.AccessibilityEvent;
Winson Chungaafa03c2010-06-11 17:34:16 -070052import android.view.animation.Animation;
Winson Chung150fbab2010-09-29 17:14:26 -070053import android.view.animation.DecelerateInterpolator;
Winson Chungaafa03c2010-06-11 17:34:16 -070054import android.view.animation.LayoutAnimationController;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080055
Daniel Sandler325dc232013-06-05 22:57:57 -040056import com.android.launcher3.FolderIcon.FolderRingAnimator;
Adam Cohenc9735cf2015-01-23 16:11:55 -080057import com.android.launcher3.LauncherAccessibilityDelegate.DragType;
Adam Cohen091440a2015-03-18 14:16:05 -070058import com.android.launcher3.util.Thunk;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070059
Adam Cohen69ce2e52011-07-03 19:25:21 -070060import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070061import java.util.Arrays;
Adam Cohenf3900c22012-11-16 18:28:11 -080062import java.util.Collections;
63import java.util.Comparator;
Adam Cohenbfbfd262011-06-13 16:55:12 -070064import java.util.HashMap;
Adam Cohenc9735cf2015-01-23 16:11:55 -080065import java.util.List;
Adam Cohend41fbf52012-02-16 23:53:59 -080066import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070067
Michael Jurkabdb5c532011-02-01 15:05:06 -080068public class CellLayout extends ViewGroup {
Winson Chungaafa03c2010-06-11 17:34:16 -070069 static final String TAG = "CellLayout";
70
Adam Cohen2acce882012-03-28 19:03:19 -070071 private Launcher mLauncher;
Adam Cohen091440a2015-03-18 14:16:05 -070072 @Thunk int mCellWidth;
73 @Thunk int mCellHeight;
Winson Chung11a1a532013-09-13 11:14:45 -070074 private int mFixedCellWidth;
75 private int mFixedCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070076
Adam Cohen091440a2015-03-18 14:16:05 -070077 @Thunk int mCountX;
78 @Thunk int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080079
Adam Cohen234c4cd2011-07-17 21:03:04 -070080 private int mOriginalWidthGap;
81 private int mOriginalHeightGap;
Adam Cohen091440a2015-03-18 14:16:05 -070082 @Thunk int mWidthGap;
83 @Thunk int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070084 private int mMaxGap;
Adam Cohen917e3882013-10-31 15:03:35 -070085 private boolean mDropPending = false;
Adam Cohenc50438c2014-08-19 17:43:05 -070086 private boolean mIsDragTarget = true;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Patrick Dubroyde7658b2010-09-27 11:15:43 -070088 // These are temporary variables to prevent having to allocate a new object just to
89 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Winson Chung0be025d2011-05-23 17:45:09 -070090 private final int[] mTmpXY = new int[2];
Adam Cohen091440a2015-03-18 14:16:05 -070091 @Thunk final int[] mTmpPoint = new int[2];
Adam Cohen69ce2e52011-07-03 19:25:21 -070092 int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070093
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -080095 boolean[][] mTmpOccupied;
Michael Jurkad771c962011-08-09 15:00:48 -070096 private boolean mLastDownOnOccupiedCell = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080097
Michael Jurkadee05892010-07-27 10:01:56 -070098 private OnTouchListener mInterceptTouchListener;
99
Adam Cohen69ce2e52011-07-03 19:25:21 -0700100 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -0700101 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -0700102
Adam Cohen02dcfcc2013-10-01 12:37:33 -0700103 private float FOREGROUND_ALPHA_DAMPER = 0.65f;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700104 private int mForegroundAlpha = 0;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700105 private float mBackgroundAlpha;
Adam Cohen1b0aaac2010-10-28 11:11:18 -0700106 private float mBackgroundAlphaMultiplier = 1.0f;
Winson Chung59a488a2013-12-10 12:32:14 -0800107 private boolean mDrawBackground = true;
Adam Cohenf34bab52010-09-30 14:11:56 -0700108
Michael Jurka33945b22010-12-21 18:19:38 -0800109 private Drawable mNormalBackground;
Michael Jurka33945b22010-12-21 18:19:38 -0800110 private Drawable mActiveGlowBackground;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700111 private Drawable mOverScrollForegroundDrawable;
112 private Drawable mOverScrollLeft;
113 private Drawable mOverScrollRight;
Michael Jurka18014792010-10-14 09:01:34 -0700114 private Rect mBackgroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700115 private Rect mForegroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700116 private int mForegroundPadding;
Patrick Dubroy1262e362010-10-06 15:49:50 -0700117
Adam Cohenf0f4eda2013-06-06 21:27:03 -0700118 // These values allow a fixed measurement to be set on the CellLayout.
119 private int mFixedWidth = -1;
120 private int mFixedHeight = -1;
121
Michael Jurka33945b22010-12-21 18:19:38 -0800122 // If we're actively dragging something over this screen, mIsDragOverlapping is true
123 private boolean mIsDragOverlapping = false;
Adam Cohendedbd962013-07-11 14:21:49 -0700124 boolean mUseActiveGlowBackground = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700125
Winson Chung150fbab2010-09-29 17:14:26 -0700126 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700127 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohen091440a2015-03-18 14:16:05 -0700128 @Thunk Rect[] mDragOutlines = new Rect[4];
129 @Thunk float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700130 private InterruptibleInOutAnimator[] mDragOutlineAnims =
131 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700132
133 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700134 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700135 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700136
Sunny Goyal508da152014-08-14 10:53:27 -0700137 private final FastBitmapView mTouchFeedbackView;
Patrick Dubroy96864c32011-03-10 17:17:23 -0800138
Adam Cohen091440a2015-03-18 14:16:05 -0700139 @Thunk HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new
Adam Cohen482ed822012-03-02 14:15:13 -0800140 HashMap<CellLayout.LayoutParams, Animator>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800141 private HashMap<View, ReorderPreviewAnimation>
142 mShakeAnimators = new HashMap<View, ReorderPreviewAnimation>();
Adam Cohen19f37922012-03-21 11:59:11 -0700143
144 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700145
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700146 // When a drag operation is in progress, holds the nearest cell to the touch point
147 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800148
Joe Onorato4be866d2010-10-10 11:26:02 -0700149 private boolean mDragging = false;
150
Patrick Dubroyce34a972010-10-19 10:34:32 -0700151 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700152 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700153
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800154 private boolean mIsHotseat = false;
Adam Cohen307fe232012-08-16 17:55:58 -0700155 private float mHotseatScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800156
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800157 public static final int MODE_SHOW_REORDER_HINT = 0;
158 public static final int MODE_DRAG_OVER = 1;
159 public static final int MODE_ON_DROP = 2;
160 public static final int MODE_ON_DROP_EXTERNAL = 3;
161 public static final int MODE_ACCEPT_DROP = 4;
Adam Cohen19f37922012-03-21 11:59:11 -0700162 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800163 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
164
Adam Cohena897f392012-04-27 18:12:05 -0700165 static final int LANDSCAPE = 0;
166 static final int PORTRAIT = 1;
167
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800168 private static final float REORDER_PREVIEW_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700169 private static final int REORDER_ANIMATION_DURATION = 150;
Adam Cohen091440a2015-03-18 14:16:05 -0700170 @Thunk float mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -0700171
Adam Cohen482ed822012-03-02 14:15:13 -0800172 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
173 private Rect mOccupiedRect = new Rect();
174 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700175 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700176 private static final int INVALID_DIRECTION = -100;
Adam Cohenc6cc61d2012-04-04 12:47:08 -0700177 private DropTarget.DragEnforcer mDragEnforcer;
Adam Cohen482ed822012-03-02 14:15:13 -0800178
Winson Chung3a6e7f32013-10-09 15:50:52 -0700179 private Rect mTempRect = new Rect();
180
Michael Jurkaca993832012-06-29 15:17:04 -0700181 private final static Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700182
Adam Cohenc9735cf2015-01-23 16:11:55 -0800183 // Related to accessible drag and drop
184 DragAndDropAccessibilityDelegate mTouchHelper = new DragAndDropAccessibilityDelegate(this);
185 private boolean mUseTouchHelper = false;
186 OnClickListener mOldClickListener = null;
187 OnClickListener mOldWorkspaceListener = null;
Adam Cohen091440a2015-03-18 14:16:05 -0700188 @Thunk int mDownX = 0;
189 @Thunk int mDownY = 0;
Adam Cohenc9735cf2015-01-23 16:11:55 -0800190
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800191 public CellLayout(Context context) {
192 this(context, null);
193 }
194
195 public CellLayout(Context context, AttributeSet attrs) {
196 this(context, attrs, 0);
197 }
198
199 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
200 super(context, attrs, defStyle);
Michael Jurka8b805b12012-04-18 14:23:14 -0700201 mDragEnforcer = new DropTarget.DragEnforcer(context);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700202
203 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
204 // the user where a dragged item will land when dropped.
205 setWillNotDraw(false);
Romain Guyce3cbd12013-02-25 15:00:36 -0800206 setClipToPadding(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700207 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700208
Winson Chung892c74d2013-08-22 16:15:50 -0700209 LauncherAppState app = LauncherAppState.getInstance();
210 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800211 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
212
Winson Chung11a1a532013-09-13 11:14:45 -0700213 mCellWidth = mCellHeight = -1;
Nilesh Agrawal5f7099a2014-01-02 15:54:57 -0800214 mFixedCellWidth = mFixedCellHeight = -1;
Winson Chung5f8afe62013-08-12 16:19:28 -0700215 mWidthGap = mOriginalWidthGap = 0;
216 mHeightGap = mOriginalHeightGap = 0;
217 mMaxGap = Integer.MAX_VALUE;
Winson Chung892c74d2013-08-22 16:15:50 -0700218 mCountX = (int) grid.numColumns;
219 mCountY = (int) grid.numRows;
Michael Jurka0280c3b2010-09-17 15:00:07 -0700220 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800221 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700222 mPreviousReorderDirection[0] = INVALID_DIRECTION;
223 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800224
225 a.recycle();
226
227 setAlwaysDrawnWithCacheEnabled(false);
228
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700229 final Resources res = getResources();
Winson Chung6e1c0d32013-10-25 15:24:24 -0700230 mHotseatScale = (float) grid.hotseatIconSizePx / grid.iconSizePx;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700231
Adam Cohen410f3cd2013-09-22 12:09:32 -0700232 mNormalBackground = res.getDrawable(R.drawable.screenpanel);
233 mActiveGlowBackground = res.getDrawable(R.drawable.screenpanel_hover);
Michael Jurka33945b22010-12-21 18:19:38 -0800234
Adam Cohenb5ba0972011-09-07 18:02:31 -0700235 mOverScrollLeft = res.getDrawable(R.drawable.overscroll_glow_left);
236 mOverScrollRight = res.getDrawable(R.drawable.overscroll_glow_right);
237 mForegroundPadding =
238 res.getDimensionPixelSize(R.dimen.workspace_overscroll_drawable_padding);
Michael Jurka33945b22010-12-21 18:19:38 -0800239
Adam Cohenfa3c58f2013-12-06 16:10:55 -0800240 mReorderPreviewAnimationMagnitude = (REORDER_PREVIEW_MAGNITUDE *
Winson Chung5f8afe62013-08-12 16:19:28 -0700241 grid.iconSizePx);
Adam Cohen19f37922012-03-21 11:59:11 -0700242
Winson Chungb26f3d62011-06-02 10:49:29 -0700243 mNormalBackground.setFilterBitmap(true);
Winson Chungb26f3d62011-06-02 10:49:29 -0700244 mActiveGlowBackground.setFilterBitmap(true);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700245
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700246 // Initialize the data structures used for the drag visualization.
Patrick Dubroyce34a972010-10-19 10:34:32 -0700247 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Winson Chungb8c69f32011-10-19 21:36:08 -0700248 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700249 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800250 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700251 }
252
253 // When dragging things around the home screens, we show a green outline of
254 // where the item will land. The outlines gradually fade out, leaving a trail
255 // behind the drag path.
256 // Set up all the animations that are used to implement this fading.
257 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700258 final float fromAlphaValue = 0;
259 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700260
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700261 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700262
263 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700264 final InterruptibleInOutAnimator anim =
Michael Jurkaf1ad6082013-03-13 12:55:46 +0100265 new InterruptibleInOutAnimator(this, duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700266 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700267 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700268 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700269 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700270 final Bitmap outline = (Bitmap)anim.getTag();
271
272 // If an animation is started and then stopped very quickly, we can still
273 // get spurious updates we've cleared the tag. Guard against this.
274 if (outline == null) {
Michael Jurka3a9fced2012-04-13 14:44:29 -0700275 @SuppressWarnings("all") // suppress dead code warning
276 final boolean debug = false;
277 if (debug) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700278 Object val = animation.getAnimatedValue();
279 Log.d(TAG, "anim " + thisIndex + " update: " + val +
280 ", isStopped " + anim.isStopped());
281 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700282 // Try to prevent it from continuing to run
283 animation.cancel();
284 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700285 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800286 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700287 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700288 }
289 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700290 // The animation holds a reference to the drag outline bitmap as long is it's
291 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700292 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700293 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700294 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700295 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700296 anim.setTag(null);
297 }
298 }
299 });
300 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700301 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700302
Michael Jurka18014792010-10-14 09:01:34 -0700303 mBackgroundRect = new Rect();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700304 mForegroundRect = new Rect();
Michael Jurkabea15192010-11-17 12:33:46 -0800305
Michael Jurkaa52570f2012-03-20 03:18:20 -0700306 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
Adam Cohen2374abf2013-04-16 14:56:57 -0700307 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700308 mCountX, mCountY);
Adam Cohen2374abf2013-04-16 14:56:57 -0700309
Sunny Goyal508da152014-08-14 10:53:27 -0700310 mTouchFeedbackView = new FastBitmapView(context);
311 // Make the feedback view large enough to hold the blur bitmap.
312 addView(mTouchFeedbackView, (int) (grid.cellWidthPx * 1.5), (int) (grid.cellHeightPx * 1.5));
Michael Jurkaa52570f2012-03-20 03:18:20 -0700313 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700314 }
315
Adam Cohenc9735cf2015-01-23 16:11:55 -0800316 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
317 public void enableAccessibleDrag(boolean enable) {
318 mUseTouchHelper = enable;
319 if (!enable) {
320 ViewCompat.setAccessibilityDelegate(this, null);
321 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
322 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
323 setOnClickListener(mLauncher);
324 } else {
325 ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
326 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
327 getShortcutsAndWidgets().setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
328 setOnClickListener(mTouchHelper);
329 }
330
331 // Invalidate the accessibility hierarchy
332 if (getParent() != null) {
333 getParent().notifySubtreeAccessibilityStateChanged(
334 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE);
335 }
336 }
337
338 @Override
339 public boolean dispatchHoverEvent(MotionEvent event) {
340 // Always attempt to dispatch hover events to accessibility first.
341 if (mUseTouchHelper && mTouchHelper.dispatchHoverEvent(event)) {
342 return true;
343 }
344 return super.dispatchHoverEvent(event);
345 }
346
347 @Override
348 public boolean dispatchTouchEvent(MotionEvent event) {
349 if (event.getAction() == MotionEvent.ACTION_DOWN) {
350 mDownX = (int) event.getX();
351 mDownY = (int) event.getY();
352 }
353 return super.dispatchTouchEvent(event);
354 }
355
356 @Override
357 public boolean onInterceptTouchEvent(MotionEvent ev) {
358 if (mUseTouchHelper ||
359 (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev))) {
360 return true;
361 }
362 return false;
363 }
364
365 class DragAndDropAccessibilityDelegate extends ExploreByTouchHelper implements OnClickListener {
366 private final Rect mTempRect = new Rect();
367
368 public DragAndDropAccessibilityDelegate(View forView) {
369 super(forView);
370 }
371
372 private int getViewIdAt(float x, float y) {
373 if (x < 0 || y < 0 || x > getMeasuredWidth() || y > getMeasuredHeight()) {
374 return ExploreByTouchHelper.INVALID_ID;
375 }
376
377 // Map coords to cell
378 int cellX = (int) Math.floor(x / (mCellWidth + mWidthGap));
379 int cellY = (int) Math.floor(y / (mCellHeight + mHeightGap));
380
381 // Map cell to id
382 int id = cellX * mCountY + cellY;
383 return id;
384 }
385
386 @Override
387 protected int getVirtualViewAt(float x, float y) {
388 return nearestDropLocation(getViewIdAt(x, y));
389 }
390
391 protected int nearestDropLocation(int id) {
392 int count = mCountX * mCountY;
393 for (int delta = 0; delta < count; delta++) {
394 if (id + delta <= (count - 1)) {
395 int target = intersectsValidDropTarget(id + delta);
396 if (target >= 0) {
397 return target;
398 }
399 } else if (id - delta >= 0) {
400 int target = intersectsValidDropTarget(id - delta);
401 if (target >= 0) {
402 return target;
403 }
404 }
405 }
406 return ExploreByTouchHelper.INVALID_ID;
407 }
408
409 /**
410 * Find the virtual view id corresponding to the top left corner of any drop region by which
411 * the passed id is contained. For an icon, this is simply
412 *
413 * @param id the id we're interested examining (ie. does it fit there?)
414 * @return the view id of the top left corner of a valid drop region or -1 if there is no
415 * such valid region. For the icon, this can just be -1 or id.
416 */
417 protected int intersectsValidDropTarget(int id) {
418 LauncherAccessibilityDelegate delegate =
419 LauncherAppState.getInstance().getAccessibilityDelegate();
420 LauncherAccessibilityDelegate.DragInfo dragInfo = delegate.getDragInfo();
421
422 int y = id % mCountY;
423 int x = id / mCountY;
424
425 if (dragInfo.dragType == DragType.WIDGET) {
426 // For a widget, every cell must be vacant. In addition, we will return any valid
427 // drop target by which the passed id is contained.
428 boolean fits = false;
429
430 // These represent the amount that we can back off if we hit a problem. They
431 // get consumed as we move up and to the right, trying new regions.
432 int spanX = dragInfo.info.spanX;
433 int spanY = dragInfo.info.spanY;
434
435 for (int m = 0; m < spanX; m++) {
436 for (int n = 0; n < spanY; n++) {
437
438 fits = true;
439 int x0 = x - m;
440 int y0 = y - n;
441
442 if (x0 < 0 || y0 < 0) continue;
443
444 for (int i = x0; i < x0 + spanX; i++) {
445 if (!fits) break;
446 for (int j = y0; j < y0 + spanY; j++) {
447 if (i >= mCountX || j >= mCountY || mOccupied[i][j]) {
448 fits = false;
449 break;
450 }
451 }
452 }
453 if (fits) {
454 return x0 * mCountY + y0;
455 }
456 }
457 }
458 return -1;
459 } else {
460 // For an icon, we simply check the view directly below
461 View child = getChildAt(x, y);
462 if (child == null || child == dragInfo.item) {
463 // Empty cell. Good for an icon or folder.
464 return id;
465 } else if (dragInfo.dragType != DragType.FOLDER) {
466 // For icons, we can consider cells that have another icon or a folder.
467 ItemInfo info = (ItemInfo) child.getTag();
468 if (info instanceof AppInfo || info instanceof FolderInfo ||
469 info instanceof ShortcutInfo) {
470 return id;
471 }
472 }
473 return -1;
474 }
475 }
476
477 @Override
478 protected void getVisibleVirtualViews(List<Integer> virtualViews) {
479 // We create a virtual view for each cell of the grid
480 // The cell ids correspond to cells in reading order.
481 int nCells = mCountX * mCountY;
482
483 for (int i = 0; i < nCells; i++) {
484 if (intersectsValidDropTarget(i) >= 0) {
485 virtualViews.add(i);
486 }
487 }
488 }
489
490 @Override
491 protected boolean onPerformActionForVirtualView(int viewId, int action, Bundle args) {
492 if (action == AccessibilityNodeInfoCompat.ACTION_CLICK) {
493 String confirmation = getConfirmationForIconDrop(viewId);
494 LauncherAppState.getInstance().getAccessibilityDelegate()
495 .handleAccessibleDrop(CellLayout.this, getItemBounds(viewId), confirmation);
496 return true;
497 }
498 return false;
499 }
500
501 @Override
502 public void onClick(View arg0) {
503 int viewId = getViewIdAt(mDownX, mDownY);
504
505 String confirmation = getConfirmationForIconDrop(viewId);
506 LauncherAppState.getInstance().getAccessibilityDelegate()
507 .handleAccessibleDrop(CellLayout.this, getItemBounds(viewId), confirmation);
508 }
509
510 @Override
511 protected void onPopulateEventForVirtualView(int id, AccessibilityEvent event) {
512 if (id == ExploreByTouchHelper.INVALID_ID) {
513 throw new IllegalArgumentException("Invalid virtual view id");
514 }
515 // We're required to set something here.
516 event.setContentDescription("");
517 }
518
519 @Override
520 protected void onPopulateNodeForVirtualView(int id, AccessibilityNodeInfoCompat node) {
521 if (id == ExploreByTouchHelper.INVALID_ID) {
522 throw new IllegalArgumentException("Invalid virtual view id");
523 }
524
525 node.setContentDescription(getLocationDescriptionForIconDrop(id));
526 node.setBoundsInParent(getItemBounds(id));
527
528 node.addAction(AccessibilityNodeInfoCompat.ACTION_CLICK);
529 node.setClickable(true);
530 node.setFocusable(true);
531 }
532
533 private String getLocationDescriptionForIconDrop(int id) {
534 LauncherAccessibilityDelegate delegate =
535 LauncherAppState.getInstance().getAccessibilityDelegate();
536 LauncherAccessibilityDelegate.DragInfo dragInfo = delegate.getDragInfo();
537
538 int y = id % mCountY;
539 int x = id / mCountY;
540
541 Resources res = getContext().getResources();
542 View child = getChildAt(x, y);
543 if (child == null || child == dragInfo.item) {
544 return res.getString(R.string.move_to_empty_cell, x, y);
545 } else {
546 ItemInfo info = (ItemInfo) child.getTag();
547 if (info instanceof AppInfo || info instanceof ShortcutInfo) {
548 return res.getString(R.string.create_folder_with, info.title);
549 } else if (info instanceof FolderInfo) {
550 return res.getString(R.string.add_to_folder, info.title);
551 }
552 }
553 return "";
554 }
555
556 private String getConfirmationForIconDrop(int id) {
557 LauncherAccessibilityDelegate delegate =
558 LauncherAppState.getInstance().getAccessibilityDelegate();
559 LauncherAccessibilityDelegate.DragInfo dragInfo = delegate.getDragInfo();
560
561 int y = id % mCountY;
562 int x = id / mCountY;
563
564 Resources res = getContext().getResources();
565 View child = getChildAt(x, y);
566 if (child == null || child == dragInfo.item) {
567 return res.getString(R.string.item_moved);
568 } else {
569 ItemInfo info = (ItemInfo) child.getTag();
570 if (info instanceof AppInfo || info instanceof ShortcutInfo) {
571 return res.getString(R.string.folder_created);
572
573 } else if (info instanceof FolderInfo) {
574 return res.getString(R.string.added_to_folder);
575 }
576 }
577 return "";
578 }
579
580 private Rect getItemBounds(int id) {
581 int cellY = id % mCountY;
582 int cellX = id / mCountY;
583 int x = getPaddingLeft() + (int) (cellX * (mCellWidth + mWidthGap));
584 int y = getPaddingTop() + (int) (cellY * (mCellHeight + mHeightGap));
585
586 Rect bounds = mTempRect;
587 bounds.set(x, y, x + mCellWidth, y + mCellHeight);
588 return bounds;
589 }
590 }
591
Chris Craik01f2d7f2013-10-01 14:41:56 -0700592 public void enableHardwareLayer(boolean hasLayer) {
593 mShortcutsAndWidgets.setLayerType(hasLayer ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700594 }
595
596 public void buildHardwareLayer() {
597 mShortcutsAndWidgets.buildLayer();
Adam Cohen2801caf2011-05-13 20:57:39 -0700598 }
599
Adam Cohen307fe232012-08-16 17:55:58 -0700600 public float getChildrenScale() {
601 return mIsHotseat ? mHotseatScale : 1.0f;
602 }
603
Winson Chung5f8afe62013-08-12 16:19:28 -0700604 public void setCellDimensions(int width, int height) {
Winson Chung11a1a532013-09-13 11:14:45 -0700605 mFixedCellWidth = mCellWidth = width;
606 mFixedCellHeight = mCellHeight = height;
Winson Chung5f8afe62013-08-12 16:19:28 -0700607 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
608 mCountX, mCountY);
609 }
610
Adam Cohen2801caf2011-05-13 20:57:39 -0700611 public void setGridSize(int x, int y) {
612 mCountX = x;
613 mCountY = y;
614 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800615 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700616 mTempRectStack.clear();
Adam Cohen2374abf2013-04-16 14:56:57 -0700617 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap,
Winson Chung5f8afe62013-08-12 16:19:28 -0700618 mCountX, mCountY);
Adam Cohen76fc0852011-06-17 13:26:23 -0700619 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700620 }
621
Adam Cohen2374abf2013-04-16 14:56:57 -0700622 // Set whether or not to invert the layout horizontally if the layout is in RTL mode.
623 public void setInvertIfRtl(boolean invert) {
624 mShortcutsAndWidgets.setInvertIfRtl(invert);
625 }
626
Adam Cohen917e3882013-10-31 15:03:35 -0700627 public void setDropPending(boolean pending) {
628 mDropPending = pending;
629 }
630
631 public boolean isDropPending() {
632 return mDropPending;
633 }
634
Adam Cohenb5ba0972011-09-07 18:02:31 -0700635 void setOverScrollAmount(float r, boolean left) {
636 if (left && mOverScrollForegroundDrawable != mOverScrollLeft) {
637 mOverScrollForegroundDrawable = mOverScrollLeft;
638 } else if (!left && mOverScrollForegroundDrawable != mOverScrollRight) {
639 mOverScrollForegroundDrawable = mOverScrollRight;
640 }
641
Adam Cohen02dcfcc2013-10-01 12:37:33 -0700642 r *= FOREGROUND_ALPHA_DAMPER;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700643 mForegroundAlpha = (int) Math.round((r * 255));
644 mOverScrollForegroundDrawable.setAlpha(mForegroundAlpha);
645 invalidate();
646 }
647
Sunny Goyal508da152014-08-14 10:53:27 -0700648 void setPressedIcon(BubbleTextView icon, Bitmap background, int padding) {
649 if (icon == null || background == null) {
650 mTouchFeedbackView.setBitmap(null);
651 mTouchFeedbackView.animate().cancel();
652 } else {
653 int offset = getMeasuredWidth() - getPaddingLeft() - getPaddingRight()
654 - (mCountX * mCellWidth);
655 mTouchFeedbackView.setTranslationX(icon.getLeft() + (int) Math.ceil(offset / 2f)
656 - padding);
657 mTouchFeedbackView.setTranslationY(icon.getTop() - padding);
658 if (mTouchFeedbackView.setBitmap(background)) {
659 mTouchFeedbackView.setAlpha(0);
660 mTouchFeedbackView.animate().alpha(1)
661 .setDuration(FastBitmapDrawable.CLICK_FEEDBACK_DURATION)
662 .setInterpolator(FastBitmapDrawable.CLICK_FEEDBACK_INTERPOLATOR)
663 .start();
664 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800665 }
666 }
667
Adam Cohendedbd962013-07-11 14:21:49 -0700668 void setUseActiveGlowBackground(boolean use) {
669 mUseActiveGlowBackground = use;
670 }
671
Winson Chung59a488a2013-12-10 12:32:14 -0800672 void disableBackground() {
673 mDrawBackground = false;
674 }
675
Adam Cohenc50438c2014-08-19 17:43:05 -0700676 void disableDragTarget() {
677 mIsDragTarget = false;
678 }
679
680 boolean isDragTarget() {
681 return mIsDragTarget;
682 }
683
684 void setIsDragOverlapping(boolean isDragOverlapping) {
685 if (mIsDragOverlapping != isDragOverlapping) {
686 mIsDragOverlapping = isDragOverlapping;
687 setUseActiveGlowBackground(mIsDragOverlapping);
688 invalidate();
689 }
690 }
691
Michael Jurka33945b22010-12-21 18:19:38 -0800692 boolean getIsDragOverlapping() {
693 return mIsDragOverlapping;
694 }
695
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700696 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700697 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700698 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
699 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
700 // When we're small, we are either drawn normally or in the "accepts drops" state (during
701 // a drag). However, we also drag the mini hover background *over* one of those two
702 // backgrounds
Winson Chung59a488a2013-12-10 12:32:14 -0800703 if (mDrawBackground && mBackgroundAlpha > 0.0f) {
Adam Cohenf34bab52010-09-30 14:11:56 -0700704 Drawable bg;
Michael Jurka33945b22010-12-21 18:19:38 -0800705
Adam Cohendedbd962013-07-11 14:21:49 -0700706 if (mUseActiveGlowBackground) {
Michael Jurka33945b22010-12-21 18:19:38 -0800707 // In the mini case, we draw the active_glow bg *over* the active background
Michael Jurkabdf78552011-10-31 14:34:25 -0700708 bg = mActiveGlowBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700709 } else {
Michael Jurkabdf78552011-10-31 14:34:25 -0700710 bg = mNormalBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700711 }
Michael Jurka33945b22010-12-21 18:19:38 -0800712
713 bg.setAlpha((int) (mBackgroundAlpha * mBackgroundAlphaMultiplier * 255));
714 bg.setBounds(mBackgroundRect);
715 bg.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700716 }
Romain Guya6abce82009-11-10 02:54:41 -0800717
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700718 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700719 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700720 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700721 if (alpha > 0) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800722 final Rect r = mDragOutlines[i];
Winson Chung3a6e7f32013-10-09 15:50:52 -0700723 mTempRect.set(r);
724 Utilities.scaleRectAboutCenter(mTempRect, getChildrenScale());
Joe Onorato4be866d2010-10-10 11:26:02 -0700725 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700726 paint.setAlpha((int)(alpha + .5f));
Winson Chung3a6e7f32013-10-09 15:50:52 -0700727 canvas.drawBitmap(b, null, mTempRect, paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700728 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700729 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800730
Adam Cohen482ed822012-03-02 14:15:13 -0800731 if (DEBUG_VISUALIZE_OCCUPIED) {
732 int[] pt = new int[2];
733 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700734 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800735 for (int i = 0; i < mCountX; i++) {
736 for (int j = 0; j < mCountY; j++) {
737 if (mOccupied[i][j]) {
738 cellToPoint(i, j, pt);
739 canvas.save();
740 canvas.translate(pt[0], pt[1]);
741 cd.draw(canvas);
742 canvas.restore();
743 }
744 }
745 }
746 }
747
Andrew Flynn850d2e72012-04-26 16:51:20 -0700748 int previewOffset = FolderRingAnimator.sPreviewSize;
749
Adam Cohen69ce2e52011-07-03 19:25:21 -0700750 // The folder outer / inner ring image(s)
Winson Chung5f8afe62013-08-12 16:19:28 -0700751 LauncherAppState app = LauncherAppState.getInstance();
752 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Adam Cohen69ce2e52011-07-03 19:25:21 -0700753 for (int i = 0; i < mFolderOuterRings.size(); i++) {
754 FolderRingAnimator fra = mFolderOuterRings.get(i);
755
Adam Cohen5108bc02013-09-20 17:04:51 -0700756 Drawable d;
757 int width, height;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700758 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
Winson Chung5f8afe62013-08-12 16:19:28 -0700759 View child = getChildAt(fra.mCellX, fra.mCellY);
Adam Cohen558f1c22013-10-09 15:15:24 -0700760
Winson Chung89f97052013-09-20 11:32:26 -0700761 if (child != null) {
Adam Cohen558f1c22013-10-09 15:15:24 -0700762 int centerX = mTempLocation[0] + mCellWidth / 2;
763 int centerY = mTempLocation[1] + previewOffset / 2 +
764 child.getPaddingTop() + grid.folderBackgroundOffset;
765
Adam Cohen5108bc02013-09-20 17:04:51 -0700766 // Draw outer ring, if it exists
767 if (FolderIcon.HAS_OUTER_RING) {
768 d = FolderRingAnimator.sSharedOuterRingDrawable;
769 width = (int) (fra.getOuterRingSize() * getChildrenScale());
770 height = width;
771 canvas.save();
772 canvas.translate(centerX - width / 2, centerY - height / 2);
773 d.setBounds(0, 0, width, height);
774 d.draw(canvas);
775 canvas.restore();
776 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700777
Winson Chung89f97052013-09-20 11:32:26 -0700778 // Draw inner ring
779 d = FolderRingAnimator.sSharedInnerRingDrawable;
780 width = (int) (fra.getInnerRingSize() * getChildrenScale());
781 height = width;
Winson Chung89f97052013-09-20 11:32:26 -0700782 canvas.save();
783 canvas.translate(centerX - width / 2, centerY - width / 2);
784 d.setBounds(0, 0, width, height);
785 d.draw(canvas);
786 canvas.restore();
787 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700788 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700789
790 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
791 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
792 int width = d.getIntrinsicWidth();
793 int height = d.getIntrinsicHeight();
794
795 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
Winson Chung5f8afe62013-08-12 16:19:28 -0700796 View child = getChildAt(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1]);
Winson Chung89f97052013-09-20 11:32:26 -0700797 if (child != null) {
798 int centerX = mTempLocation[0] + mCellWidth / 2;
799 int centerY = mTempLocation[1] + previewOffset / 2 +
800 child.getPaddingTop() + grid.folderBackgroundOffset;
Adam Cohenc51934b2011-07-26 21:07:43 -0700801
Winson Chung89f97052013-09-20 11:32:26 -0700802 canvas.save();
803 canvas.translate(centerX - width / 2, centerY - width / 2);
804 d.setBounds(0, 0, width, height);
805 d.draw(canvas);
806 canvas.restore();
807 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700808 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700809 }
810
Adam Cohenb5ba0972011-09-07 18:02:31 -0700811 @Override
812 protected void dispatchDraw(Canvas canvas) {
813 super.dispatchDraw(canvas);
814 if (mForegroundAlpha > 0) {
815 mOverScrollForegroundDrawable.setBounds(mForegroundRect);
Adam Cohenb5ba0972011-09-07 18:02:31 -0700816 mOverScrollForegroundDrawable.draw(canvas);
Adam Cohenb5ba0972011-09-07 18:02:31 -0700817 }
818 }
819
Adam Cohen69ce2e52011-07-03 19:25:21 -0700820 public void showFolderAccept(FolderRingAnimator fra) {
821 mFolderOuterRings.add(fra);
822 }
823
824 public void hideFolderAccept(FolderRingAnimator fra) {
825 if (mFolderOuterRings.contains(fra)) {
826 mFolderOuterRings.remove(fra);
827 }
828 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700829 }
830
Adam Cohenc51934b2011-07-26 21:07:43 -0700831 public void setFolderLeaveBehindCell(int x, int y) {
832 mFolderLeaveBehindCell[0] = x;
833 mFolderLeaveBehindCell[1] = y;
834 invalidate();
835 }
836
837 public void clearFolderLeaveBehind() {
838 mFolderLeaveBehindCell[0] = -1;
839 mFolderLeaveBehindCell[1] = -1;
840 invalidate();
841 }
842
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700843 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700844 public boolean shouldDelayChildPressedState() {
845 return false;
846 }
847
Adam Cohen1462de32012-07-24 22:34:36 -0700848 public void restoreInstanceState(SparseArray<Parcelable> states) {
Sunny Goyal33a152f2014-07-22 12:13:14 -0700849 try {
850 dispatchRestoreInstanceState(states);
851 } catch (IllegalArgumentException ex) {
852 if (LauncherAppState.isDogfoodBuild()) {
853 throw ex;
854 }
855 // Mismatched viewId / viewType preventing restore. Skip restore on production builds.
856 Log.e(TAG, "Ignoring an error while restoring a view instance state", ex);
857 }
Adam Cohen1462de32012-07-24 22:34:36 -0700858 }
859
Michael Jurkae6235dd2011-10-04 15:02:05 -0700860 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700861 public void cancelLongPress() {
862 super.cancelLongPress();
863
864 // Cancel long press for all children
865 final int count = getChildCount();
866 for (int i = 0; i < count; i++) {
867 final View child = getChildAt(i);
868 child.cancelLongPress();
869 }
870 }
871
Michael Jurkadee05892010-07-27 10:01:56 -0700872 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
873 mInterceptTouchListener = listener;
874 }
875
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800876 public int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700877 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800878 }
879
Hyunyoung Songee3e6a72015-02-20 14:25:27 -0800880 public int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700881 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800882 }
883
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800884 public void setIsHotseat(boolean isHotseat) {
885 mIsHotseat = isHotseat;
Winson Chung5f8afe62013-08-12 16:19:28 -0700886 mShortcutsAndWidgets.setIsHotseat(isHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800887 }
888
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800889 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Adam Cohen59400422014-03-05 18:07:04 -0800890 boolean markCells, boolean inLayout) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700891 final LayoutParams lp = params;
892
Andrew Flynnde38e422012-05-08 11:22:15 -0700893 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800894 if (child instanceof BubbleTextView) {
895 BubbleTextView bubbleChild = (BubbleTextView) child;
Winson Chung5f8afe62013-08-12 16:19:28 -0700896 bubbleChild.setTextVisibility(!mIsHotseat);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800897 }
898
Adam Cohen307fe232012-08-16 17:55:58 -0700899 child.setScaleX(getChildrenScale());
900 child.setScaleY(getChildrenScale());
901
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800902 // Generate an id for each view, this assumes we have at most 256x256 cells
903 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700904 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700905 // If the horizontal or vertical span is set to -1, it is taken to
906 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700907 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
908 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800909
Winson Chungaafa03c2010-06-11 17:34:16 -0700910 child.setId(childId);
Sunny Goyal1587d532015-01-29 09:57:16 -0800911 mShortcutsAndWidgets.addView(child, index, lp, inLayout);
Michael Jurkadee05892010-07-27 10:01:56 -0700912
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700913 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700914
Winson Chungaafa03c2010-06-11 17:34:16 -0700915 return true;
916 }
917 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800918 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700919
Adam Cohen59400422014-03-05 18:07:04 -0800920 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
921 boolean markCells) {
922 return addViewToCellLayout(child, index, childId, params, markCells, false);
923 }
924
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800925 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700926 public void removeAllViews() {
927 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700928 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700929 }
930
931 @Override
932 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700933 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700934 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700935 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700936 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700937 }
938
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700939 public void removeViewWithoutMarkingCells(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700940 mShortcutsAndWidgets.removeView(view);
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700941 }
942
Michael Jurka0280c3b2010-09-17 15:00:07 -0700943 @Override
944 public void removeView(View view) {
945 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700946 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700947 }
948
949 @Override
950 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700951 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
952 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700953 }
954
955 @Override
956 public void removeViewInLayout(View view) {
957 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700958 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700959 }
960
961 @Override
962 public void removeViews(int start, int count) {
963 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700964 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700965 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700966 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700967 }
968
969 @Override
970 public void removeViewsInLayout(int start, int count) {
971 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700972 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700973 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700974 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800975 }
976
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700977 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700978 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800979 * @param x X coordinate of the point
980 * @param y Y coordinate of the point
981 * @param result Array of 2 ints to hold the x and y coordinate of the cell
982 */
983 void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700984 final int hStartPadding = getPaddingLeft();
985 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800986
987 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
988 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
989
Adam Cohend22015c2010-07-26 22:02:18 -0700990 final int xAxis = mCountX;
991 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800992
993 if (result[0] < 0) result[0] = 0;
994 if (result[0] >= xAxis) result[0] = xAxis - 1;
995 if (result[1] < 0) result[1] = 0;
996 if (result[1] >= yAxis) result[1] = yAxis - 1;
997 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700998
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800999 /**
1000 * Given a point, return the cell that most closely encloses that point
1001 * @param x X coordinate of the point
1002 * @param y Y coordinate of the point
1003 * @param result Array of 2 ints to hold the x and y coordinate of the cell
1004 */
1005 void pointToCellRounded(int x, int y, int[] result) {
1006 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
1007 }
1008
1009 /**
1010 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -07001011 *
1012 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001013 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -07001014 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001015 * @param result Array of 2 ints to hold the x and y coordinate of the point
1016 */
1017 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -07001018 final int hStartPadding = getPaddingLeft();
1019 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001020
1021 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
1022 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
1023 }
1024
Adam Cohene3e27a82011-04-15 12:07:39 -07001025 /**
Adam Cohen482ed822012-03-02 14:15:13 -08001026 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -07001027 *
1028 * @param cellX X coordinate of the cell
1029 * @param cellY Y coordinate of the cell
1030 *
1031 * @param result Array of 2 ints to hold the x and y coordinate of the point
1032 */
1033 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001034 regionToCenterPoint(cellX, cellY, 1, 1, result);
1035 }
1036
1037 /**
1038 * Given a cell coordinate and span return the point that represents the center of the regio
1039 *
1040 * @param cellX X coordinate of the cell
1041 * @param cellY Y coordinate of the cell
1042 *
1043 * @param result Array of 2 ints to hold the x and y coordinate of the point
1044 */
1045 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -07001046 final int hStartPadding = getPaddingLeft();
1047 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -07001048 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
1049 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
1050 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
1051 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -07001052 }
1053
Adam Cohen19f37922012-03-21 11:59:11 -07001054 /**
1055 * Given a cell coordinate and span fills out a corresponding pixel rect
1056 *
1057 * @param cellX X coordinate of the cell
1058 * @param cellY Y coordinate of the cell
1059 * @param result Rect in which to write the result
1060 */
1061 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
1062 final int hStartPadding = getPaddingLeft();
1063 final int vStartPadding = getPaddingTop();
1064 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
1065 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
1066 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
1067 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
1068 }
1069
Adam Cohen482ed822012-03-02 14:15:13 -08001070 public float getDistanceFromCell(float x, float y, int[] cell) {
1071 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
1072 float distance = (float) Math.sqrt( Math.pow(x - mTmpPoint[0], 2) +
1073 Math.pow(y - mTmpPoint[1], 2));
1074 return distance;
1075 }
1076
Romain Guy84f296c2009-11-04 15:00:44 -08001077 int getCellWidth() {
1078 return mCellWidth;
1079 }
1080
1081 int getCellHeight() {
1082 return mCellHeight;
1083 }
1084
Adam Cohend4844c32011-02-18 19:25:06 -08001085 int getWidthGap() {
1086 return mWidthGap;
1087 }
1088
1089 int getHeightGap() {
1090 return mHeightGap;
1091 }
1092
Adam Cohen7f4eabe2011-04-21 16:19:16 -07001093 Rect getContentRect(Rect r) {
1094 if (r == null) {
1095 r = new Rect();
1096 }
1097 int left = getPaddingLeft();
1098 int top = getPaddingTop();
Michael Jurka8b805b12012-04-18 14:23:14 -07001099 int right = left + getWidth() - getPaddingLeft() - getPaddingRight();
1100 int bottom = top + getHeight() - getPaddingTop() - getPaddingBottom();
Adam Cohen7f4eabe2011-04-21 16:19:16 -07001101 r.set(left, top, right, bottom);
1102 return r;
1103 }
1104
Winson Chungfe411c82013-09-26 16:07:17 -07001105 /** Return a rect that has the cellWidth/cellHeight (left, top), and
1106 * widthGap/heightGap (right, bottom) */
Winson Chung66700732013-08-20 16:56:15 -07001107 static void getMetrics(Rect metrics, int paddedMeasureWidth,
1108 int paddedMeasureHeight, int countX, int countY) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001109 LauncherAppState app = LauncherAppState.getInstance();
1110 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chung66700732013-08-20 16:56:15 -07001111 metrics.set(grid.calculateCellWidth(paddedMeasureWidth, countX),
1112 grid.calculateCellHeight(paddedMeasureHeight, countY), 0, 0);
Adam Cohenf4bd5792012-04-27 11:35:29 -07001113 }
1114
Adam Cohenf0f4eda2013-06-06 21:27:03 -07001115 public void setFixedSize(int width, int height) {
1116 mFixedWidth = width;
1117 mFixedHeight = height;
1118 }
1119
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001120 @Override
1121 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Winson Chung5f8afe62013-08-12 16:19:28 -07001122 LauncherAppState app = LauncherAppState.getInstance();
1123 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
1124
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001125 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001126 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -07001127 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
1128 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chung2d75f122013-09-23 16:53:31 -07001129 int childWidthSize = widthSize - (getPaddingLeft() + getPaddingRight());
1130 int childHeightSize = heightSize - (getPaddingTop() + getPaddingBottom());
Winson Chung11a1a532013-09-13 11:14:45 -07001131 if (mFixedCellWidth < 0 || mFixedCellHeight < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -07001132 int cw = grid.calculateCellWidth(childWidthSize, mCountX);
1133 int ch = grid.calculateCellHeight(childHeightSize, mCountY);
Winson Chung11a1a532013-09-13 11:14:45 -07001134 if (cw != mCellWidth || ch != mCellHeight) {
1135 mCellWidth = cw;
1136 mCellHeight = ch;
1137 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
1138 mHeightGap, mCountX, mCountY);
1139 }
Winson Chung5f8afe62013-08-12 16:19:28 -07001140 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001141
Winson Chung2d75f122013-09-23 16:53:31 -07001142 int newWidth = childWidthSize;
1143 int newHeight = childHeightSize;
Adam Cohenf0f4eda2013-06-06 21:27:03 -07001144 if (mFixedWidth > 0 && mFixedHeight > 0) {
1145 newWidth = mFixedWidth;
1146 newHeight = mFixedHeight;
1147 } else if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001148 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
1149 }
1150
Adam Cohend22015c2010-07-26 22:02:18 -07001151 int numWidthGaps = mCountX - 1;
1152 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001153
Adam Cohen234c4cd2011-07-17 21:03:04 -07001154 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung2d75f122013-09-23 16:53:31 -07001155 int hSpace = childWidthSize;
1156 int vSpace = childHeightSize;
Adam Cohenf4bd5792012-04-27 11:35:29 -07001157 int hFreeSpace = hSpace - (mCountX * mCellWidth);
1158 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -07001159 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
1160 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Winson Chung5f8afe62013-08-12 16:19:28 -07001161 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap,
1162 mHeightGap, mCountX, mCountY);
Adam Cohen234c4cd2011-07-17 21:03:04 -07001163 } else {
1164 mWidthGap = mOriginalWidthGap;
1165 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -07001166 }
Michael Jurka8c920dd2011-01-20 14:16:56 -08001167 int count = getChildCount();
Winson Chung5f8afe62013-08-12 16:19:28 -07001168 int maxWidth = 0;
1169 int maxHeight = 0;
Michael Jurka8c920dd2011-01-20 14:16:56 -08001170 for (int i = 0; i < count; i++) {
1171 View child = getChildAt(i);
Winson Chung2d75f122013-09-23 16:53:31 -07001172 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth,
1173 MeasureSpec.EXACTLY);
1174 int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight,
1175 MeasureSpec.EXACTLY);
Michael Jurka8c920dd2011-01-20 14:16:56 -08001176 child.measure(childWidthMeasureSpec, childheightMeasureSpec);
Winson Chung5f8afe62013-08-12 16:19:28 -07001177 maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
1178 maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
Michael Jurka8c920dd2011-01-20 14:16:56 -08001179 }
Winson Chung2d75f122013-09-23 16:53:31 -07001180 if (mFixedWidth > 0 && mFixedHeight > 0) {
1181 setMeasuredDimension(maxWidth, maxHeight);
1182 } else {
1183 setMeasuredDimension(widthSize, heightSize);
1184 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001185 }
1186
1187 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -07001188 protected void onLayout(boolean changed, int l, int t, int r, int b) {
Winson Chung38848ca2013-10-08 12:03:44 -07001189 int offset = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() -
1190 (mCountX * mCellWidth);
1191 int left = getPaddingLeft() + (int) Math.ceil(offset / 2f);
1192 int top = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001193 int count = getChildCount();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001194 for (int i = 0; i < count; i++) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08001195 View child = getChildAt(i);
Winson Chung2d75f122013-09-23 16:53:31 -07001196 child.layout(left, top,
1197 left + r - l,
1198 top + b - t);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001199 }
1200 }
1201
1202 @Override
Michael Jurkadee05892010-07-27 10:01:56 -07001203 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1204 super.onSizeChanged(w, h, oldw, oldh);
Winson Chung82a9bd22013-10-08 16:02:34 -07001205
1206 // Expand the background drawing bounds by the padding baked into the background drawable
1207 Rect padding = new Rect();
1208 mNormalBackground.getPadding(padding);
1209 mBackgroundRect.set(-padding.left, -padding.top, w + padding.right, h + padding.bottom);
1210
Adam Cohenb5ba0972011-09-07 18:02:31 -07001211 mForegroundRect.set(mForegroundPadding, mForegroundPadding,
Adam Cohen215b4162012-08-30 13:14:08 -07001212 w - mForegroundPadding, h - mForegroundPadding);
Michael Jurkadee05892010-07-27 10:01:56 -07001213 }
1214
1215 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001216 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001217 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001218 }
1219
1220 @Override
1221 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001222 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001223 }
1224
Michael Jurka5f1c5092010-09-03 14:15:02 -07001225 public float getBackgroundAlpha() {
1226 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -07001227 }
1228
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001229 public void setBackgroundAlphaMultiplier(float multiplier) {
Adam Cohenc50438c2014-08-19 17:43:05 -07001230
Michael Jurkaa3d30ad2012-05-08 13:43:43 -07001231 if (mBackgroundAlphaMultiplier != multiplier) {
1232 mBackgroundAlphaMultiplier = multiplier;
1233 invalidate();
1234 }
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001235 }
1236
Adam Cohenddb82192010-11-10 16:32:54 -08001237 public float getBackgroundAlphaMultiplier() {
1238 return mBackgroundAlphaMultiplier;
1239 }
1240
Michael Jurka5f1c5092010-09-03 14:15:02 -07001241 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -08001242 if (mBackgroundAlpha != alpha) {
1243 mBackgroundAlpha = alpha;
1244 invalidate();
1245 }
Michael Jurkadee05892010-07-27 10:01:56 -07001246 }
1247
Michael Jurkaa52570f2012-03-20 03:18:20 -07001248 public void setShortcutAndWidgetAlpha(float alpha) {
Sunny Goyal02b50812014-09-10 15:44:42 -07001249 mShortcutsAndWidgets.setAlpha(alpha);
Michael Jurkadee05892010-07-27 10:01:56 -07001250 }
1251
Michael Jurkaa52570f2012-03-20 03:18:20 -07001252 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
Sunny Goyaldcbcc862014-08-12 15:58:36 -07001253 return mShortcutsAndWidgets;
Michael Jurkaa52570f2012-03-20 03:18:20 -07001254 }
1255
Patrick Dubroy440c3602010-07-13 17:50:32 -07001256 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001257 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001258 }
1259
Adam Cohen76fc0852011-06-17 13:26:23 -07001260 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001261 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001262 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -08001263 boolean[][] occupied = mOccupied;
1264 if (!permanent) {
1265 occupied = mTmpOccupied;
1266 }
1267
Adam Cohen19f37922012-03-21 11:59:11 -07001268 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001269 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
1270 final ItemInfo info = (ItemInfo) child.getTag();
1271
1272 // We cancel any existing animations
1273 if (mReorderAnimators.containsKey(lp)) {
1274 mReorderAnimators.get(lp).cancel();
1275 mReorderAnimators.remove(lp);
1276 }
1277
Adam Cohen482ed822012-03-02 14:15:13 -08001278 final int oldX = lp.x;
1279 final int oldY = lp.y;
1280 if (adjustOccupied) {
1281 occupied[lp.cellX][lp.cellY] = false;
1282 occupied[cellX][cellY] = true;
1283 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001284 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001285 if (permanent) {
1286 lp.cellX = info.cellX = cellX;
1287 lp.cellY = info.cellY = cellY;
1288 } else {
1289 lp.tmpCellX = cellX;
1290 lp.tmpCellY = cellY;
1291 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001292 clc.setupLp(lp);
1293 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001294 final int newX = lp.x;
1295 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001296
Adam Cohen76fc0852011-06-17 13:26:23 -07001297 lp.x = oldX;
1298 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001299
Adam Cohen482ed822012-03-02 14:15:13 -08001300 // Exit early if we're not actually moving the view
1301 if (oldX == newX && oldY == newY) {
1302 lp.isLockedToGrid = true;
1303 return true;
1304 }
1305
Michael Jurkaf1ad6082013-03-13 12:55:46 +01001306 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001307 va.setDuration(duration);
1308 mReorderAnimators.put(lp, va);
1309
1310 va.addUpdateListener(new AnimatorUpdateListener() {
1311 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001312 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001313 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001314 lp.x = (int) ((1 - r) * oldX + r * newX);
1315 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001316 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001317 }
1318 });
Adam Cohen482ed822012-03-02 14:15:13 -08001319 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001320 boolean cancelled = false;
1321 public void onAnimationEnd(Animator animation) {
1322 // If the animation was cancelled, it means that another animation
1323 // has interrupted this one, and we don't want to lock the item into
1324 // place just yet.
1325 if (!cancelled) {
1326 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001327 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001328 }
1329 if (mReorderAnimators.containsKey(lp)) {
1330 mReorderAnimators.remove(lp);
1331 }
1332 }
1333 public void onAnimationCancel(Animator animation) {
1334 cancelled = true;
1335 }
1336 });
Adam Cohen482ed822012-03-02 14:15:13 -08001337 va.setStartDelay(delay);
1338 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001339 return true;
1340 }
1341 return false;
1342 }
1343
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001344 /**
1345 * Estimate where the top left cell of the dragged item will land if it is dropped.
1346 *
1347 * @param originX The X value of the top left corner of the item
1348 * @param originY The Y value of the top left corner of the item
1349 * @param spanX The number of horizontal cells that the item spans
1350 * @param spanY The number of vertical cells that the item spans
1351 * @param result The estimated drop cell X and Y.
1352 */
1353 void estimateDropCell(int originX, int originY, int spanX, int spanY, int[] result) {
Adam Cohend22015c2010-07-26 22:02:18 -07001354 final int countX = mCountX;
1355 final int countY = mCountY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001356
Michael Jurkaa63c4522010-08-19 13:52:27 -07001357 // pointToCellRounded takes the top left of a cell but will pad that with
1358 // cellWidth/2 and cellHeight/2 when finding the matching cell
1359 pointToCellRounded(originX, originY, result);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001360
1361 // If the item isn't fully on this screen, snap to the edges
1362 int rightOverhang = result[0] + spanX - countX;
1363 if (rightOverhang > 0) {
1364 result[0] -= rightOverhang; // Snap to right
1365 }
1366 result[0] = Math.max(0, result[0]); // Snap to left
1367 int bottomOverhang = result[1] + spanY - countY;
1368 if (bottomOverhang > 0) {
1369 result[1] -= bottomOverhang; // Snap to bottom
1370 }
1371 result[1] = Math.max(0, result[1]); // Snap to top
1372 }
1373
Adam Cohen482ed822012-03-02 14:15:13 -08001374 void visualizeDropLocation(View v, Bitmap dragOutline, int originX, int originY, int cellX,
1375 int cellY, int spanX, int spanY, boolean resize, Point dragOffset, Rect dragRegion) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001376 final int oldDragCellX = mDragCell[0];
1377 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001378
Adam Cohen2801caf2011-05-13 20:57:39 -07001379 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001380 return;
1381 }
1382
Adam Cohen482ed822012-03-02 14:15:13 -08001383 if (cellX != oldDragCellX || cellY != oldDragCellY) {
1384 mDragCell[0] = cellX;
1385 mDragCell[1] = cellY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001386 // Find the top left corner of the rect the object will occupy
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001387 final int[] topLeft = mTmpPoint;
Adam Cohen482ed822012-03-02 14:15:13 -08001388 cellToPoint(cellX, cellY, topLeft);
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001389
Joe Onorato4be866d2010-10-10 11:26:02 -07001390 int left = topLeft[0];
1391 int top = topLeft[1];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001392
Winson Chungb8c69f32011-10-19 21:36:08 -07001393 if (v != null && dragOffset == null) {
Adam Cohen99e8b402011-03-25 19:23:43 -07001394 // When drawing the drag outline, it did not account for margin offsets
1395 // added by the view's parent.
1396 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1397 left += lp.leftMargin;
1398 top += lp.topMargin;
Winson Chung150fbab2010-09-29 17:14:26 -07001399
Adam Cohen99e8b402011-03-25 19:23:43 -07001400 // Offsets due to the size difference between the View and the dragOutline.
1401 // There is a size difference to account for the outer blur, which may lie
1402 // outside the bounds of the view.
Winson Chunga9abd0e2010-10-27 17:18:37 -07001403 top += (v.getHeight() - dragOutline.getHeight()) / 2;
Adam Cohenae915ce2011-08-25 13:47:22 -07001404 // We center about the x axis
1405 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1406 - dragOutline.getWidth()) / 2;
Adam Cohen66396872011-04-15 17:50:36 -07001407 } else {
Winson Chungb8c69f32011-10-19 21:36:08 -07001408 if (dragOffset != null && dragRegion != null) {
1409 // Center the drag region *horizontally* in the cell and apply a drag
1410 // outline offset
1411 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1412 - dragRegion.width()) / 2;
Winson Chung69737c32013-10-08 17:00:19 -07001413 int cHeight = getShortcutsAndWidgets().getCellContentHeight();
1414 int cellPaddingY = (int) Math.max(0, ((mCellHeight - cHeight) / 2f));
1415 top += dragOffset.y + cellPaddingY;
Winson Chungb8c69f32011-10-19 21:36:08 -07001416 } else {
1417 // Center the drag outline in the cell
1418 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1419 - dragOutline.getWidth()) / 2;
1420 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1421 - dragOutline.getHeight()) / 2;
1422 }
Winson Chunga9abd0e2010-10-27 17:18:37 -07001423 }
Joe Onorato4be866d2010-10-10 11:26:02 -07001424 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001425 mDragOutlineAnims[oldIndex].animateOut();
1426 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001427 Rect r = mDragOutlines[mDragOutlineCurrent];
1428 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
1429 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001430 cellToRect(cellX, cellY, spanX, spanY, r);
Adam Cohend41fbf52012-02-16 23:53:59 -08001431 }
Winson Chung150fbab2010-09-29 17:14:26 -07001432
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001433 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1434 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001435 }
1436 }
1437
Adam Cohene0310962011-04-18 16:15:31 -07001438 public void clearDragOutlines() {
1439 final int oldIndex = mDragOutlineCurrent;
1440 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001441 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001442 }
1443
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001444 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001445 * Find a vacant area that will fit the given bounds nearest the requested
1446 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001447 *
Romain Guy51afc022009-05-04 18:03:43 -07001448 * @param pixelX The X location at which you want to search for a vacant area.
1449 * @param pixelY The Y location at which you want to search for a vacant area.
Jeff Sharkey70864282009-04-07 21:08:40 -07001450 * @param spanX Horizontal span of the object.
1451 * @param spanY Vertical span of the object.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001452 * @param result Array in which to place the result, or null (in which case a new array will
1453 * be allocated)
Jeff Sharkey70864282009-04-07 21:08:40 -07001454 * @return The X, Y cell of a vacant area that can contain this object,
1455 * nearest the requested location.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001456 */
Adam Cohend41fbf52012-02-16 23:53:59 -08001457 int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY,
1458 int[] result) {
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001459 return findNearestVacantArea(pixelX, pixelY, spanX, spanY, null, result);
Michael Jurka6a1435d2010-09-27 17:35:12 -07001460 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001461
Michael Jurka6a1435d2010-09-27 17:35:12 -07001462 /**
1463 * Find a vacant area that will fit the given bounds nearest the requested
1464 * cell location. Uses Euclidean distance to score multiple vacant areas.
1465 *
1466 * @param pixelX The X location at which you want to search for a vacant area.
1467 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001468 * @param minSpanX The minimum horizontal span required
1469 * @param minSpanY The minimum vertical span required
1470 * @param spanX Horizontal span of the object.
1471 * @param spanY Vertical span of the object.
1472 * @param result Array in which to place the result, or null (in which case a new array will
1473 * be allocated)
1474 * @return The X, Y cell of a vacant area that can contain this object,
1475 * nearest the requested location.
1476 */
1477 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1478 int spanY, int[] result, int[] resultSpan) {
1479 return findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null,
1480 result, resultSpan);
1481 }
1482
1483 /**
1484 * Find a vacant area that will fit the given bounds nearest the requested
1485 * cell location. Uses Euclidean distance to score multiple vacant areas.
1486 *
1487 * @param pixelX The X location at which you want to search for a vacant area.
1488 * @param pixelY The Y location at which you want to search for a vacant area.
Michael Jurka6a1435d2010-09-27 17:35:12 -07001489 * @param spanX Horizontal span of the object.
1490 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07001491 * @param ignoreOccupied If true, the result can be an occupied cell
1492 * @param result Array in which to place the result, or null (in which case a new array will
1493 * be allocated)
Michael Jurka6a1435d2010-09-27 17:35:12 -07001494 * @return The X, Y cell of a vacant area that can contain this object,
1495 * nearest the requested location.
1496 */
Adam Cohendf035382011-04-11 17:22:04 -07001497 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, View ignoreView,
1498 boolean ignoreOccupied, int[] result) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001499 return findNearestArea(pixelX, pixelY, spanX, spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001500 spanX, spanY, ignoreView, ignoreOccupied, result, null, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08001501 }
1502
1503 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1504 private void lazyInitTempRectStack() {
1505 if (mTempRectStack.isEmpty()) {
1506 for (int i = 0; i < mCountX * mCountY; i++) {
1507 mTempRectStack.push(new Rect());
1508 }
1509 }
1510 }
Adam Cohen482ed822012-03-02 14:15:13 -08001511
Adam Cohend41fbf52012-02-16 23:53:59 -08001512 private void recycleTempRects(Stack<Rect> used) {
1513 while (!used.isEmpty()) {
1514 mTempRectStack.push(used.pop());
1515 }
1516 }
1517
1518 /**
1519 * Find a vacant area that will fit the given bounds nearest the requested
1520 * cell location. Uses Euclidean distance to score multiple vacant areas.
1521 *
1522 * @param pixelX The X location at which you want to search for a vacant area.
1523 * @param pixelY The Y location at which you want to search for a vacant area.
1524 * @param minSpanX The minimum horizontal span required
1525 * @param minSpanY The minimum vertical span required
1526 * @param spanX Horizontal span of the object.
1527 * @param spanY Vertical span of the object.
1528 * @param ignoreOccupied If true, the result can be an occupied cell
1529 * @param result Array in which to place the result, or null (in which case a new array will
1530 * be allocated)
1531 * @return The X, Y cell of a vacant area that can contain this object,
1532 * nearest the requested location.
1533 */
1534 int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001535 View ignoreView, boolean ignoreOccupied, int[] result, int[] resultSpan,
1536 boolean[][] occupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001537 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001538 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08001539 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001540
Adam Cohene3e27a82011-04-15 12:07:39 -07001541 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1542 // to the center of the item, but we are searching based on the top-left cell, so
1543 // we translate the point over to correspond to the top-left.
1544 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1545 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1546
Jeff Sharkey70864282009-04-07 21:08:40 -07001547 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001548 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001549 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001550 final Rect bestRect = new Rect(-1, -1, -1, -1);
1551 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001552
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001553 final int countX = mCountX;
1554 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001555
Adam Cohend41fbf52012-02-16 23:53:59 -08001556 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1557 spanX < minSpanX || spanY < minSpanY) {
1558 return bestXY;
1559 }
1560
1561 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001562 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001563 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1564 int ySize = -1;
1565 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001566 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001567 // First, let's see if this thing fits anywhere
1568 for (int i = 0; i < minSpanX; i++) {
1569 for (int j = 0; j < minSpanY; j++) {
Adam Cohendf035382011-04-11 17:22:04 -07001570 if (occupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001571 continue inner;
1572 }
Michael Jurkac28de512010-08-13 11:27:44 -07001573 }
1574 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001575 xSize = minSpanX;
1576 ySize = minSpanY;
1577
1578 // We know that the item will fit at _some_ acceptable size, now let's see
1579 // how big we can make it. We'll alternate between incrementing x and y spans
1580 // until we hit a limit.
1581 boolean incX = true;
1582 boolean hitMaxX = xSize >= spanX;
1583 boolean hitMaxY = ySize >= spanY;
1584 while (!(hitMaxX && hitMaxY)) {
1585 if (incX && !hitMaxX) {
1586 for (int j = 0; j < ySize; j++) {
1587 if (x + xSize > countX -1 || occupied[x + xSize][y + j]) {
1588 // We can't move out horizontally
1589 hitMaxX = true;
1590 }
1591 }
1592 if (!hitMaxX) {
1593 xSize++;
1594 }
1595 } else if (!hitMaxY) {
1596 for (int i = 0; i < xSize; i++) {
1597 if (y + ySize > countY - 1 || occupied[x + i][y + ySize]) {
1598 // We can't move out vertically
1599 hitMaxY = true;
1600 }
1601 }
1602 if (!hitMaxY) {
1603 ySize++;
1604 }
1605 }
1606 hitMaxX |= xSize >= spanX;
1607 hitMaxY |= ySize >= spanY;
1608 incX = !incX;
1609 }
1610 incX = true;
1611 hitMaxX = xSize >= spanX;
1612 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001613 }
Winson Chung0be025d2011-05-23 17:45:09 -07001614 final int[] cellXY = mTmpXY;
Adam Cohene3e27a82011-04-15 12:07:39 -07001615 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001616
Adam Cohend41fbf52012-02-16 23:53:59 -08001617 // We verify that the current rect is not a sub-rect of any of our previous
1618 // candidates. In this case, the current rect is disqualified in favour of the
1619 // containing rect.
1620 Rect currentRect = mTempRectStack.pop();
1621 currentRect.set(x, y, x + xSize, y + ySize);
1622 boolean contained = false;
1623 for (Rect r : validRegions) {
1624 if (r.contains(currentRect)) {
1625 contained = true;
1626 break;
1627 }
1628 }
1629 validRegions.push(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001630 double distance = Math.sqrt(Math.pow(cellXY[0] - pixelX, 2)
1631 + Math.pow(cellXY[1] - pixelY, 2));
Adam Cohen482ed822012-03-02 14:15:13 -08001632
Adam Cohend41fbf52012-02-16 23:53:59 -08001633 if ((distance <= bestDistance && !contained) ||
1634 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001635 bestDistance = distance;
1636 bestXY[0] = x;
1637 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001638 if (resultSpan != null) {
1639 resultSpan[0] = xSize;
1640 resultSpan[1] = ySize;
1641 }
1642 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001643 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001644 }
1645 }
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001646 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08001647 markCellsAsOccupiedForView(ignoreView, occupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001648
Adam Cohenc0dcf592011-06-01 15:30:43 -07001649 // Return -1, -1 if no suitable location found
1650 if (bestDistance == Double.MAX_VALUE) {
1651 bestXY[0] = -1;
1652 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001653 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001654 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001655 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001656 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001657
Adam Cohen482ed822012-03-02 14:15:13 -08001658 /**
1659 * Find a vacant area that will fit the given bounds nearest the requested
1660 * cell location, and will also weigh in a suggested direction vector of the
1661 * desired location. This method computers distance based on unit grid distances,
1662 * not pixel distances.
1663 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001664 * @param cellX The X cell nearest to which you want to search for a vacant area.
1665 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001666 * @param spanX Horizontal span of the object.
1667 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001668 * @param direction The favored direction in which the views should move from x, y
1669 * @param exactDirectionOnly If this parameter is true, then only solutions where the direction
1670 * matches exactly. Otherwise we find the best matching direction.
1671 * @param occoupied The array which represents which cells in the CellLayout are occupied
1672 * @param blockOccupied The array which represents which cells in the specified block (cellX,
Winson Chung5f8afe62013-08-12 16:19:28 -07001673 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001674 * @param result Array in which to place the result, or null (in which case a new array will
1675 * be allocated)
1676 * @return The X, Y cell of a vacant area that can contain this object,
1677 * nearest the requested location.
1678 */
1679 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001680 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001681 // Keep track of best-scoring drop area
1682 final int[] bestXY = result != null ? result : new int[2];
1683 float bestDistance = Float.MAX_VALUE;
1684 int bestDirectionScore = Integer.MIN_VALUE;
1685
1686 final int countX = mCountX;
1687 final int countY = mCountY;
1688
1689 for (int y = 0; y < countY - (spanY - 1); y++) {
1690 inner:
1691 for (int x = 0; x < countX - (spanX - 1); x++) {
1692 // First, let's see if this thing fits anywhere
1693 for (int i = 0; i < spanX; i++) {
1694 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001695 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001696 continue inner;
1697 }
1698 }
1699 }
1700
1701 float distance = (float)
1702 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1703 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001704 computeDirectionVector(x - cellX, y - cellY, curDirection);
1705 // The direction score is just the dot product of the two candidate direction
1706 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001707 int curDirectionScore = direction[0] * curDirection[0] +
1708 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001709 boolean exactDirectionOnly = false;
1710 boolean directionMatches = direction[0] == curDirection[0] &&
1711 direction[0] == curDirection[0];
1712 if ((directionMatches || !exactDirectionOnly) &&
1713 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001714 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1715 bestDistance = distance;
1716 bestDirectionScore = curDirectionScore;
1717 bestXY[0] = x;
1718 bestXY[1] = y;
1719 }
1720 }
1721 }
1722
1723 // Return -1, -1 if no suitable location found
1724 if (bestDistance == Float.MAX_VALUE) {
1725 bestXY[0] = -1;
1726 bestXY[1] = -1;
1727 }
1728 return bestXY;
1729 }
1730
1731 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001732 int[] direction, ItemConfiguration currentState) {
1733 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001734 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001735 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001736 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1737
Adam Cohen8baab352012-03-20 17:39:21 -07001738 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001739
1740 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001741 c.x = mTempLocation[0];
1742 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001743 success = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001744 }
Adam Cohen8baab352012-03-20 17:39:21 -07001745 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001746 return success;
1747 }
1748
Adam Cohenf3900c22012-11-16 18:28:11 -08001749 /**
1750 * This helper class defines a cluster of views. It helps with defining complex edges
1751 * of the cluster and determining how those edges interact with other views. The edges
1752 * essentially define a fine-grained boundary around the cluster of views -- like a more
1753 * precise version of a bounding box.
1754 */
1755 private class ViewCluster {
1756 final static int LEFT = 0;
1757 final static int TOP = 1;
1758 final static int RIGHT = 2;
1759 final static int BOTTOM = 3;
Adam Cohen47a876d2012-03-19 13:21:41 -07001760
Adam Cohenf3900c22012-11-16 18:28:11 -08001761 ArrayList<View> views;
1762 ItemConfiguration config;
1763 Rect boundingRect = new Rect();
Adam Cohen47a876d2012-03-19 13:21:41 -07001764
Adam Cohenf3900c22012-11-16 18:28:11 -08001765 int[] leftEdge = new int[mCountY];
1766 int[] rightEdge = new int[mCountY];
1767 int[] topEdge = new int[mCountX];
1768 int[] bottomEdge = new int[mCountX];
1769 boolean leftEdgeDirty, rightEdgeDirty, topEdgeDirty, bottomEdgeDirty, boundingRectDirty;
1770
1771 @SuppressWarnings("unchecked")
1772 public ViewCluster(ArrayList<View> views, ItemConfiguration config) {
1773 this.views = (ArrayList<View>) views.clone();
1774 this.config = config;
1775 resetEdges();
Adam Cohen47a876d2012-03-19 13:21:41 -07001776 }
1777
Adam Cohenf3900c22012-11-16 18:28:11 -08001778 void resetEdges() {
1779 for (int i = 0; i < mCountX; i++) {
1780 topEdge[i] = -1;
1781 bottomEdge[i] = -1;
1782 }
1783 for (int i = 0; i < mCountY; i++) {
1784 leftEdge[i] = -1;
1785 rightEdge[i] = -1;
1786 }
1787 leftEdgeDirty = true;
1788 rightEdgeDirty = true;
1789 bottomEdgeDirty = true;
1790 topEdgeDirty = true;
1791 boundingRectDirty = true;
1792 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001793
Adam Cohenf3900c22012-11-16 18:28:11 -08001794 void computeEdge(int which, int[] edge) {
1795 int count = views.size();
1796 for (int i = 0; i < count; i++) {
1797 CellAndSpan cs = config.map.get(views.get(i));
1798 switch (which) {
1799 case LEFT:
1800 int left = cs.x;
1801 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1802 if (left < edge[j] || edge[j] < 0) {
1803 edge[j] = left;
Adam Cohena56dc102012-07-13 13:41:42 -07001804 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001805 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001806 break;
1807 case RIGHT:
1808 int right = cs.x + cs.spanX;
1809 for (int j = cs.y; j < cs.y + cs.spanY; j++) {
1810 if (right > edge[j]) {
1811 edge[j] = right;
1812 }
1813 }
1814 break;
1815 case TOP:
1816 int top = cs.y;
1817 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1818 if (top < edge[j] || edge[j] < 0) {
1819 edge[j] = top;
1820 }
1821 }
1822 break;
1823 case BOTTOM:
1824 int bottom = cs.y + cs.spanY;
1825 for (int j = cs.x; j < cs.x + cs.spanX; j++) {
1826 if (bottom > edge[j]) {
1827 edge[j] = bottom;
1828 }
1829 }
1830 break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001831 }
1832 }
1833 }
Adam Cohenf3900c22012-11-16 18:28:11 -08001834
1835 boolean isViewTouchingEdge(View v, int whichEdge) {
1836 CellAndSpan cs = config.map.get(v);
1837
1838 int[] edge = getEdge(whichEdge);
1839
1840 switch (whichEdge) {
1841 case LEFT:
1842 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1843 if (edge[i] == cs.x + cs.spanX) {
1844 return true;
1845 }
1846 }
1847 break;
1848 case RIGHT:
1849 for (int i = cs.y; i < cs.y + cs.spanY; i++) {
1850 if (edge[i] == cs.x) {
1851 return true;
1852 }
1853 }
1854 break;
1855 case TOP:
1856 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1857 if (edge[i] == cs.y + cs.spanY) {
1858 return true;
1859 }
1860 }
1861 break;
1862 case BOTTOM:
1863 for (int i = cs.x; i < cs.x + cs.spanX; i++) {
1864 if (edge[i] == cs.y) {
1865 return true;
1866 }
1867 }
1868 break;
1869 }
1870 return false;
1871 }
1872
1873 void shift(int whichEdge, int delta) {
1874 for (View v: views) {
1875 CellAndSpan c = config.map.get(v);
1876 switch (whichEdge) {
1877 case LEFT:
1878 c.x -= delta;
1879 break;
1880 case RIGHT:
1881 c.x += delta;
1882 break;
1883 case TOP:
1884 c.y -= delta;
1885 break;
1886 case BOTTOM:
1887 default:
1888 c.y += delta;
1889 break;
1890 }
1891 }
1892 resetEdges();
1893 }
1894
1895 public void addView(View v) {
1896 views.add(v);
1897 resetEdges();
1898 }
1899
1900 public Rect getBoundingRect() {
1901 if (boundingRectDirty) {
1902 boolean first = true;
1903 for (View v: views) {
1904 CellAndSpan c = config.map.get(v);
1905 if (first) {
1906 boundingRect.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1907 first = false;
1908 } else {
1909 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1910 }
1911 }
1912 }
1913 return boundingRect;
1914 }
1915
1916 public int[] getEdge(int which) {
1917 switch (which) {
1918 case LEFT:
1919 return getLeftEdge();
1920 case RIGHT:
1921 return getRightEdge();
1922 case TOP:
1923 return getTopEdge();
1924 case BOTTOM:
1925 default:
1926 return getBottomEdge();
1927 }
1928 }
1929
1930 public int[] getLeftEdge() {
1931 if (leftEdgeDirty) {
1932 computeEdge(LEFT, leftEdge);
1933 }
1934 return leftEdge;
1935 }
1936
1937 public int[] getRightEdge() {
1938 if (rightEdgeDirty) {
1939 computeEdge(RIGHT, rightEdge);
1940 }
1941 return rightEdge;
1942 }
1943
1944 public int[] getTopEdge() {
1945 if (topEdgeDirty) {
1946 computeEdge(TOP, topEdge);
1947 }
1948 return topEdge;
1949 }
1950
1951 public int[] getBottomEdge() {
1952 if (bottomEdgeDirty) {
1953 computeEdge(BOTTOM, bottomEdge);
1954 }
1955 return bottomEdge;
1956 }
1957
1958 PositionComparator comparator = new PositionComparator();
1959 class PositionComparator implements Comparator<View> {
1960 int whichEdge = 0;
1961 public int compare(View left, View right) {
1962 CellAndSpan l = config.map.get(left);
1963 CellAndSpan r = config.map.get(right);
1964 switch (whichEdge) {
1965 case LEFT:
1966 return (r.x + r.spanX) - (l.x + l.spanX);
1967 case RIGHT:
1968 return l.x - r.x;
1969 case TOP:
1970 return (r.y + r.spanY) - (l.y + l.spanY);
1971 case BOTTOM:
1972 default:
1973 return l.y - r.y;
1974 }
1975 }
1976 }
1977
1978 public void sortConfigurationForEdgePush(int edge) {
1979 comparator.whichEdge = edge;
1980 Collections.sort(config.sortedViews, comparator);
1981 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001982 }
1983
Adam Cohenf3900c22012-11-16 18:28:11 -08001984 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1985 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohene0489502012-08-27 15:18:53 -07001986
Adam Cohenf3900c22012-11-16 18:28:11 -08001987 ViewCluster cluster = new ViewCluster(views, currentState);
1988 Rect clusterRect = cluster.getBoundingRect();
1989 int whichEdge;
1990 int pushDistance;
1991 boolean fail = false;
1992
1993 // Determine the edge of the cluster that will be leading the push and how far
1994 // the cluster must be shifted.
1995 if (direction[0] < 0) {
1996 whichEdge = ViewCluster.LEFT;
1997 pushDistance = clusterRect.right - rectOccupiedByPotentialDrop.left;
Adam Cohene0489502012-08-27 15:18:53 -07001998 } else if (direction[0] > 0) {
Adam Cohenf3900c22012-11-16 18:28:11 -08001999 whichEdge = ViewCluster.RIGHT;
2000 pushDistance = rectOccupiedByPotentialDrop.right - clusterRect.left;
2001 } else if (direction[1] < 0) {
2002 whichEdge = ViewCluster.TOP;
2003 pushDistance = clusterRect.bottom - rectOccupiedByPotentialDrop.top;
2004 } else {
2005 whichEdge = ViewCluster.BOTTOM;
2006 pushDistance = rectOccupiedByPotentialDrop.bottom - clusterRect.top;
Adam Cohene0489502012-08-27 15:18:53 -07002007 }
2008
Adam Cohenf3900c22012-11-16 18:28:11 -08002009 // Break early for invalid push distance.
2010 if (pushDistance <= 0) {
2011 return false;
Adam Cohene0489502012-08-27 15:18:53 -07002012 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002013
2014 // Mark the occupied state as false for the group of views we want to move.
2015 for (View v: views) {
2016 CellAndSpan c = currentState.map.get(v);
2017 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
2018 }
2019
2020 // We save the current configuration -- if we fail to find a solution we will revert
2021 // to the initial state. The process of finding a solution modifies the configuration
2022 // in place, hence the need for revert in the failure case.
2023 currentState.save();
2024
2025 // The pushing algorithm is simplified by considering the views in the order in which
2026 // they would be pushed by the cluster. For example, if the cluster is leading with its
2027 // left edge, we consider sort the views by their right edge, from right to left.
2028 cluster.sortConfigurationForEdgePush(whichEdge);
2029
2030 while (pushDistance > 0 && !fail) {
2031 for (View v: currentState.sortedViews) {
2032 // For each view that isn't in the cluster, we see if the leading edge of the
2033 // cluster is contacting the edge of that view. If so, we add that view to the
2034 // cluster.
2035 if (!cluster.views.contains(v) && v != dragView) {
2036 if (cluster.isViewTouchingEdge(v, whichEdge)) {
2037 LayoutParams lp = (LayoutParams) v.getLayoutParams();
2038 if (!lp.canReorder) {
2039 // The push solution includes the all apps button, this is not viable.
2040 fail = true;
2041 break;
2042 }
2043 cluster.addView(v);
2044 CellAndSpan c = currentState.map.get(v);
2045
2046 // Adding view to cluster, mark it as not occupied.
2047 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
2048 }
2049 }
2050 }
2051 pushDistance--;
2052
2053 // The cluster has been completed, now we move the whole thing over in the appropriate
2054 // direction.
2055 cluster.shift(whichEdge, 1);
2056 }
2057
2058 boolean foundSolution = false;
2059 clusterRect = cluster.getBoundingRect();
2060
2061 // Due to the nature of the algorithm, the only check required to verify a valid solution
2062 // is to ensure that completed shifted cluster lies completely within the cell layout.
2063 if (!fail && clusterRect.left >= 0 && clusterRect.right <= mCountX && clusterRect.top >= 0 &&
2064 clusterRect.bottom <= mCountY) {
2065 foundSolution = true;
2066 } else {
2067 currentState.restore();
2068 }
2069
2070 // In either case, we set the occupied array as marked for the location of the views
2071 for (View v: cluster.views) {
2072 CellAndSpan c = currentState.map.get(v);
2073 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
2074 }
2075
2076 return foundSolution;
Adam Cohene0489502012-08-27 15:18:53 -07002077 }
2078
Adam Cohen482ed822012-03-02 14:15:13 -08002079 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohenf3900c22012-11-16 18:28:11 -08002080 int[] direction, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08002081 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08002082
Adam Cohen8baab352012-03-20 17:39:21 -07002083 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08002084 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07002085 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08002086 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07002087 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08002088 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07002089 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08002090 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07002091 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08002092 }
2093 }
Adam Cohen8baab352012-03-20 17:39:21 -07002094
Adam Cohen8baab352012-03-20 17:39:21 -07002095 // Mark the occupied state as false for the group of views we want to move.
Adam Cohenf3900c22012-11-16 18:28:11 -08002096 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07002097 CellAndSpan c = currentState.map.get(v);
2098 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
2099 }
2100
Adam Cohen47a876d2012-03-19 13:21:41 -07002101 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
2102 int top = boundingRect.top;
2103 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07002104 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07002105 // for interlocking.
Adam Cohenf3900c22012-11-16 18:28:11 -08002106 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07002107 CellAndSpan c = currentState.map.get(v);
2108 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07002109 }
2110
Adam Cohen482ed822012-03-02 14:15:13 -08002111 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
2112
Adam Cohenf3900c22012-11-16 18:28:11 -08002113 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
2114 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08002115
Adam Cohen8baab352012-03-20 17:39:21 -07002116 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08002117 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07002118 int deltaX = mTempLocation[0] - boundingRect.left;
2119 int deltaY = mTempLocation[1] - boundingRect.top;
Adam Cohenf3900c22012-11-16 18:28:11 -08002120 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07002121 CellAndSpan c = currentState.map.get(v);
2122 c.x += deltaX;
2123 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08002124 }
2125 success = true;
2126 }
Adam Cohen8baab352012-03-20 17:39:21 -07002127
2128 // In either case, we set the occupied array as marked for the location of the views
Adam Cohenf3900c22012-11-16 18:28:11 -08002129 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07002130 CellAndSpan c = currentState.map.get(v);
2131 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002132 }
2133 return success;
2134 }
2135
2136 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
2137 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
2138 }
2139
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002140 // This method tries to find a reordering solution which satisfies the push mechanic by trying
2141 // to push items in each of the cardinal directions, in an order based on the direction vector
2142 // passed.
2143 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
2144 int[] direction, View ignoreView, ItemConfiguration solution) {
2145 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
Winson Chung5f8afe62013-08-12 16:19:28 -07002146 // If the direction vector has two non-zero components, we try pushing
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002147 // separately in each of the components.
2148 int temp = direction[1];
2149 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08002150
2151 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002152 ignoreView, solution)) {
2153 return true;
2154 }
2155 direction[1] = temp;
2156 temp = direction[0];
2157 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08002158
2159 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002160 ignoreView, solution)) {
2161 return true;
2162 }
2163 // Revert the direction
2164 direction[0] = temp;
2165
2166 // Now we try pushing in each component of the opposite direction
2167 direction[0] *= -1;
2168 direction[1] *= -1;
2169 temp = direction[1];
2170 direction[1] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08002171 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002172 ignoreView, solution)) {
2173 return true;
2174 }
2175
2176 direction[1] = temp;
2177 temp = direction[0];
2178 direction[0] = 0;
Adam Cohenf3900c22012-11-16 18:28:11 -08002179 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002180 ignoreView, solution)) {
2181 return true;
2182 }
2183 // revert the direction
2184 direction[0] = temp;
2185 direction[0] *= -1;
2186 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07002187
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002188 } else {
2189 // If the direction vector has a single non-zero component, we push first in the
2190 // direction of the vector
Adam Cohenf3900c22012-11-16 18:28:11 -08002191 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002192 ignoreView, solution)) {
2193 return true;
2194 }
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002195 // Then we try the opposite direction
2196 direction[0] *= -1;
2197 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08002198 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002199 ignoreView, solution)) {
2200 return true;
2201 }
2202 // Switch the direction back
2203 direction[0] *= -1;
2204 direction[1] *= -1;
Winson Chung5f8afe62013-08-12 16:19:28 -07002205
2206 // If we have failed to find a push solution with the above, then we try
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002207 // to find a solution by pushing along the perpendicular axis.
2208
2209 // Swap the components
2210 int temp = direction[1];
2211 direction[1] = direction[0];
2212 direction[0] = temp;
Adam Cohenf3900c22012-11-16 18:28:11 -08002213 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002214 ignoreView, solution)) {
2215 return true;
2216 }
2217
2218 // Then we try the opposite direction
2219 direction[0] *= -1;
2220 direction[1] *= -1;
Adam Cohenf3900c22012-11-16 18:28:11 -08002221 if (pushViewsToTempLocation(intersectingViews, occupied, direction,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002222 ignoreView, solution)) {
2223 return true;
2224 }
2225 // Switch the direction back
2226 direction[0] *= -1;
2227 direction[1] *= -1;
2228
2229 // Swap the components back
2230 temp = direction[1];
2231 direction[1] = direction[0];
2232 direction[0] = temp;
2233 }
2234 return false;
2235 }
2236
Adam Cohen482ed822012-03-02 14:15:13 -08002237 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07002238 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07002239 // Return early if get invalid cell positions
2240 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08002241
Adam Cohen8baab352012-03-20 17:39:21 -07002242 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08002243 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08002244
Adam Cohen8baab352012-03-20 17:39:21 -07002245 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08002246 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07002247 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07002248 if (c != null) {
2249 c.x = cellX;
2250 c.y = cellY;
2251 }
Adam Cohen482ed822012-03-02 14:15:13 -08002252 }
Adam Cohen482ed822012-03-02 14:15:13 -08002253 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2254 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07002255 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08002256 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002257 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002258 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002259 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08002260 if (Rect.intersects(r0, r1)) {
2261 if (!lp.canReorder) {
2262 return false;
2263 }
2264 mIntersectingViews.add(child);
2265 }
2266 }
Adam Cohen47a876d2012-03-19 13:21:41 -07002267
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002268 solution.intersectingViews = new ArrayList<View>(mIntersectingViews);
2269
Winson Chung5f8afe62013-08-12 16:19:28 -07002270 // First we try to find a solution which respects the push mechanic. That is,
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002271 // we try to find a solution such that no displaced item travels through another item
2272 // without also displacing that item.
2273 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07002274 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07002275 return true;
2276 }
Adam Cohen47a876d2012-03-19 13:21:41 -07002277
Adam Cohen4abc5bd2012-05-29 21:06:03 -07002278 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohenf3900c22012-11-16 18:28:11 -08002279 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07002280 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002281 return true;
2282 }
Adam Cohen47a876d2012-03-19 13:21:41 -07002283
Adam Cohen482ed822012-03-02 14:15:13 -08002284 // Ok, they couldn't move as a block, let's move them individually
2285 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07002286 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002287 return false;
2288 }
2289 }
2290 return true;
2291 }
2292
2293 /*
2294 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
2295 * the provided point and the provided cell
2296 */
Adam Cohen47a876d2012-03-19 13:21:41 -07002297 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08002298 double angle = Math.atan(((float) deltaY) / deltaX);
2299
2300 result[0] = 0;
2301 result[1] = 0;
2302 if (Math.abs(Math.cos(angle)) > 0.5f) {
2303 result[0] = (int) Math.signum(deltaX);
2304 }
2305 if (Math.abs(Math.sin(angle)) > 0.5f) {
2306 result[1] = (int) Math.signum(deltaY);
2307 }
2308 }
2309
Adam Cohen8baab352012-03-20 17:39:21 -07002310 private void copyOccupiedArray(boolean[][] occupied) {
2311 for (int i = 0; i < mCountX; i++) {
2312 for (int j = 0; j < mCountY; j++) {
2313 occupied[i][j] = mOccupied[i][j];
2314 }
2315 }
2316 }
2317
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002318 ItemConfiguration findReorderSolution(int pixelX, int pixelY, int minSpanX, int minSpanY,
2319 int spanX, int spanY, int[] direction, View dragView, boolean decX,
2320 ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07002321 // Copy the current state into the solution. This solution will be manipulated as necessary.
2322 copyCurrentStateToSolution(solution, false);
2323 // Copy the current occupied array into the temporary occupied array. This array will be
2324 // manipulated as necessary to find a solution.
2325 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08002326
2327 // We find the nearest cell into which we would place the dragged item, assuming there's
2328 // nothing in its way.
2329 int result[] = new int[2];
2330 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2331
2332 boolean success = false;
2333 // First we try the exact nearest position of the item being dragged,
2334 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07002335 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
2336 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08002337
2338 if (!success) {
2339 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
2340 // x, then 1 in y etc.
2341 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002342 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY,
2343 direction, dragView, false, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08002344 } else if (spanY > minSpanY) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002345 return findReorderSolution(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1,
2346 direction, dragView, true, solution);
Adam Cohen482ed822012-03-02 14:15:13 -08002347 }
2348 solution.isSolution = false;
2349 } else {
2350 solution.isSolution = true;
2351 solution.dragViewX = result[0];
2352 solution.dragViewY = result[1];
2353 solution.dragViewSpanX = spanX;
2354 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002355 }
2356 return solution;
2357 }
2358
2359 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002360 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002361 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002362 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002363 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002364 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08002365 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07002366 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002367 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07002368 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08002369 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002370 solution.add(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08002371 }
2372 }
2373
2374 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
2375 for (int i = 0; i < mCountX; i++) {
2376 for (int j = 0; j < mCountY; j++) {
2377 mTmpOccupied[i][j] = false;
2378 }
2379 }
2380
Michael Jurkaa52570f2012-03-20 03:18:20 -07002381 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002382 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002383 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002384 if (child == dragView) continue;
2385 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002386 CellAndSpan c = solution.map.get(child);
2387 if (c != null) {
2388 lp.tmpCellX = c.x;
2389 lp.tmpCellY = c.y;
2390 lp.cellHSpan = c.spanX;
2391 lp.cellVSpan = c.spanY;
2392 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002393 }
2394 }
2395 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2396 solution.dragViewSpanY, mTmpOccupied, true);
2397 }
2398
2399 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
2400 commitDragView) {
2401
2402 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
2403 for (int i = 0; i < mCountX; i++) {
2404 for (int j = 0; j < mCountY; j++) {
2405 occupied[i][j] = false;
2406 }
2407 }
2408
Michael Jurkaa52570f2012-03-20 03:18:20 -07002409 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002410 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002411 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002412 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002413 CellAndSpan c = solution.map.get(child);
2414 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002415 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2416 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002417 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002418 }
2419 }
2420 if (commitDragView) {
2421 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2422 solution.dragViewSpanY, occupied, true);
2423 }
2424 }
2425
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002426
2427 // This method starts or changes the reorder preview animations
2428 private void beginOrAdjustReorderPreviewAnimations(ItemConfiguration solution,
2429 View dragView, int delay, int mode) {
Adam Cohen19f37922012-03-21 11:59:11 -07002430 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002431 for (int i = 0; i < childCount; i++) {
2432 View child = mShortcutsAndWidgets.getChildAt(i);
2433 if (child == dragView) continue;
2434 CellAndSpan c = solution.map.get(child);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002435 boolean skip = mode == ReorderPreviewAnimation.MODE_HINT && solution.intersectingViews
2436 != null && !solution.intersectingViews.contains(child);
2437
Adam Cohen19f37922012-03-21 11:59:11 -07002438 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002439 if (c != null && !skip) {
2440 ReorderPreviewAnimation rha = new ReorderPreviewAnimation(child, mode, lp.cellX,
2441 lp.cellY, c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002442 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002443 }
2444 }
2445 }
2446
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002447 // Class which represents the reorder preview animations. These animations show that an item is
Adam Cohen19f37922012-03-21 11:59:11 -07002448 // in a temporary state, and hint at where the item will return to.
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002449 class ReorderPreviewAnimation {
Adam Cohen19f37922012-03-21 11:59:11 -07002450 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002451 float finalDeltaX;
2452 float finalDeltaY;
2453 float initDeltaX;
2454 float initDeltaY;
2455 float finalScale;
2456 float initScale;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002457 int mode;
2458 boolean repeating = false;
2459 private static final int PREVIEW_DURATION = 300;
2460 private static final int HINT_DURATION = Workspace.REORDER_TIMEOUT;
2461
2462 public static final int MODE_HINT = 0;
2463 public static final int MODE_PREVIEW = 1;
2464
Adam Cohene7587d22012-05-24 18:50:02 -07002465 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002466
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002467 public ReorderPreviewAnimation(View child, int mode, int cellX0, int cellY0, int cellX1,
2468 int cellY1, int spanX, int spanY) {
Adam Cohen19f37922012-03-21 11:59:11 -07002469 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2470 final int x0 = mTmpPoint[0];
2471 final int y0 = mTmpPoint[1];
2472 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2473 final int x1 = mTmpPoint[0];
2474 final int y1 = mTmpPoint[1];
2475 final int dX = x1 - x0;
2476 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002477 finalDeltaX = 0;
2478 finalDeltaY = 0;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002479 int dir = mode == MODE_HINT ? -1 : 1;
Adam Cohen19f37922012-03-21 11:59:11 -07002480 if (dX == dY && dX == 0) {
2481 } else {
2482 if (dY == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002483 finalDeltaX = - dir * Math.signum(dX) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002484 } else if (dX == 0) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002485 finalDeltaY = - dir * Math.signum(dY) * mReorderPreviewAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002486 } else {
2487 double angle = Math.atan( (float) (dY) / dX);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002488 finalDeltaX = (int) (- dir * Math.signum(dX) *
2489 Math.abs(Math.cos(angle) * mReorderPreviewAnimationMagnitude));
2490 finalDeltaY = (int) (- dir * Math.signum(dY) *
2491 Math.abs(Math.sin(angle) * mReorderPreviewAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002492 }
2493 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002494 this.mode = mode;
Adam Cohend024f982012-05-23 18:26:45 -07002495 initDeltaX = child.getTranslationX();
2496 initDeltaY = child.getTranslationY();
Adam Cohen307fe232012-08-16 17:55:58 -07002497 finalScale = getChildrenScale() - 4.0f / child.getWidth();
Adam Cohend024f982012-05-23 18:26:45 -07002498 initScale = child.getScaleX();
Adam Cohen19f37922012-03-21 11:59:11 -07002499 this.child = child;
2500 }
2501
Adam Cohend024f982012-05-23 18:26:45 -07002502 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002503 if (mShakeAnimators.containsKey(child)) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002504 ReorderPreviewAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002505 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002506 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002507 if (finalDeltaX == 0 && finalDeltaY == 0) {
2508 completeAnimationImmediately();
2509 return;
2510 }
Adam Cohen19f37922012-03-21 11:59:11 -07002511 }
Adam Cohend024f982012-05-23 18:26:45 -07002512 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002513 return;
2514 }
Michael Jurkaf1ad6082013-03-13 12:55:46 +01002515 ValueAnimator va = LauncherAnimUtils.ofFloat(child, 0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002516 a = va;
Adam Cohen19f37922012-03-21 11:59:11 -07002517 va.setRepeatMode(ValueAnimator.REVERSE);
2518 va.setRepeatCount(ValueAnimator.INFINITE);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002519 va.setDuration(mode == MODE_HINT ? HINT_DURATION : PREVIEW_DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002520 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002521 va.addUpdateListener(new AnimatorUpdateListener() {
2522 @Override
2523 public void onAnimationUpdate(ValueAnimator animation) {
2524 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002525 float r1 = (mode == MODE_HINT && repeating) ? 1.0f : r;
2526 float x = r1 * finalDeltaX + (1 - r1) * initDeltaX;
2527 float y = r1 * finalDeltaY + (1 - r1) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002528 child.setTranslationX(x);
2529 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002530 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002531 child.setScaleX(s);
2532 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002533 }
2534 });
2535 va.addListener(new AnimatorListenerAdapter() {
2536 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002537 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002538 initDeltaX = 0;
2539 initDeltaY = 0;
Adam Cohen307fe232012-08-16 17:55:58 -07002540 initScale = getChildrenScale();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002541 repeating = true;
Adam Cohen19f37922012-03-21 11:59:11 -07002542 }
2543 });
Adam Cohen19f37922012-03-21 11:59:11 -07002544 mShakeAnimators.put(child, this);
2545 va.start();
2546 }
2547
Adam Cohend024f982012-05-23 18:26:45 -07002548 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002549 if (a != null) {
2550 a.cancel();
2551 }
Adam Cohen19f37922012-03-21 11:59:11 -07002552 }
Adam Cohene7587d22012-05-24 18:50:02 -07002553
Adam Cohen091440a2015-03-18 14:16:05 -07002554 @Thunk void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002555 if (a != null) {
2556 a.cancel();
2557 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002558
Michael Jurka2ecf9952012-06-18 12:52:28 -07002559 AnimatorSet s = LauncherAnimUtils.createAnimatorSet();
Adam Cohene7587d22012-05-24 18:50:02 -07002560 a = s;
Brandon Keely50e6e562012-05-08 16:28:49 -07002561 s.playTogether(
Adam Cohen307fe232012-08-16 17:55:58 -07002562 LauncherAnimUtils.ofFloat(child, "scaleX", getChildrenScale()),
2563 LauncherAnimUtils.ofFloat(child, "scaleY", getChildrenScale()),
Michael Jurka2ecf9952012-06-18 12:52:28 -07002564 LauncherAnimUtils.ofFloat(child, "translationX", 0f),
2565 LauncherAnimUtils.ofFloat(child, "translationY", 0f)
Brandon Keely50e6e562012-05-08 16:28:49 -07002566 );
2567 s.setDuration(REORDER_ANIMATION_DURATION);
2568 s.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2569 s.start();
2570 }
Adam Cohen19f37922012-03-21 11:59:11 -07002571 }
2572
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002573 private void completeAndClearReorderPreviewAnimations() {
2574 for (ReorderPreviewAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002575 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002576 }
2577 mShakeAnimators.clear();
2578 }
2579
Adam Cohen482ed822012-03-02 14:15:13 -08002580 private void commitTempPlacement() {
2581 for (int i = 0; i < mCountX; i++) {
2582 for (int j = 0; j < mCountY; j++) {
2583 mOccupied[i][j] = mTmpOccupied[i][j];
2584 }
2585 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002586 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002587 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002588 View child = mShortcutsAndWidgets.getChildAt(i);
2589 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2590 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002591 // We do a null check here because the item info can be null in the case of the
2592 // AllApps button in the hotseat.
2593 if (info != null) {
Adam Cohen487f7dd2012-06-28 18:12:10 -07002594 if (info.cellX != lp.tmpCellX || info.cellY != lp.tmpCellY ||
2595 info.spanX != lp.cellHSpan || info.spanY != lp.cellVSpan) {
2596 info.requiresDbUpdate = true;
2597 }
Adam Cohen2acce882012-03-28 19:03:19 -07002598 info.cellX = lp.cellX = lp.tmpCellX;
2599 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002600 info.spanX = lp.cellHSpan;
2601 info.spanY = lp.cellVSpan;
Adam Cohen2acce882012-03-28 19:03:19 -07002602 }
Adam Cohen482ed822012-03-02 14:15:13 -08002603 }
Adam Cohen2acce882012-03-28 19:03:19 -07002604 mLauncher.getWorkspace().updateItemLocationsInDatabase(this);
Adam Cohen482ed822012-03-02 14:15:13 -08002605 }
2606
2607 public void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002608 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002609 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002610 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002611 lp.useTmpCoords = useTempCoords;
2612 }
2613 }
2614
Adam Cohen482ed822012-03-02 14:15:13 -08002615 ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
2616 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2617 int[] result = new int[2];
2618 int[] resultSpan = new int[2];
2619 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null, result,
2620 resultSpan);
2621 if (result[0] >= 0 && result[1] >= 0) {
2622 copyCurrentStateToSolution(solution, false);
2623 solution.dragViewX = result[0];
2624 solution.dragViewY = result[1];
2625 solution.dragViewSpanX = resultSpan[0];
2626 solution.dragViewSpanY = resultSpan[1];
2627 solution.isSolution = true;
2628 } else {
2629 solution.isSolution = false;
2630 }
2631 return solution;
2632 }
2633
2634 public void prepareChildForDrag(View child) {
2635 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002636 }
2637
Adam Cohen19f37922012-03-21 11:59:11 -07002638 /* This seems like it should be obvious and straight-forward, but when the direction vector
2639 needs to match with the notion of the dragView pushing other views, we have to employ
2640 a slightly more subtle notion of the direction vector. The question is what two points is
2641 the vector between? The center of the dragView and its desired destination? Not quite, as
2642 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2643 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2644 or right, which helps make pushing feel right.
2645 */
2646 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2647 int spanY, View dragView, int[] resultDirection) {
2648 int[] targetDestination = new int[2];
2649
2650 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2651 Rect dragRect = new Rect();
2652 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2653 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2654
2655 Rect dropRegionRect = new Rect();
2656 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2657 dragView, dropRegionRect, mIntersectingViews);
2658
2659 int dropRegionSpanX = dropRegionRect.width();
2660 int dropRegionSpanY = dropRegionRect.height();
2661
2662 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2663 dropRegionRect.height(), dropRegionRect);
2664
2665 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2666 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2667
2668 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2669 deltaX = 0;
2670 }
2671 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2672 deltaY = 0;
2673 }
2674
2675 if (deltaX == 0 && deltaY == 0) {
2676 // No idea what to do, give a random direction.
2677 resultDirection[0] = 1;
2678 resultDirection[1] = 0;
2679 } else {
2680 computeDirectionVector(deltaX, deltaY, resultDirection);
2681 }
2682 }
2683
2684 // For a given cell and span, fetch the set of views intersecting the region.
2685 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2686 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2687 if (boundingRect != null) {
2688 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2689 }
2690 intersectingViews.clear();
2691 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2692 Rect r1 = new Rect();
2693 final int count = mShortcutsAndWidgets.getChildCount();
2694 for (int i = 0; i < count; i++) {
2695 View child = mShortcutsAndWidgets.getChildAt(i);
2696 if (child == dragView) continue;
2697 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2698 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2699 if (Rect.intersects(r0, r1)) {
2700 mIntersectingViews.add(child);
2701 if (boundingRect != null) {
2702 boundingRect.union(r1);
2703 }
2704 }
2705 }
2706 }
2707
2708 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2709 View dragView, int[] result) {
2710 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2711 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2712 mIntersectingViews);
2713 return !mIntersectingViews.isEmpty();
2714 }
2715
2716 void revertTempState() {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002717 completeAndClearReorderPreviewAnimations();
2718 if (isItemPlacementDirty() && !DESTRUCTIVE_REORDER) {
2719 final int count = mShortcutsAndWidgets.getChildCount();
2720 for (int i = 0; i < count; i++) {
2721 View child = mShortcutsAndWidgets.getChildAt(i);
2722 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2723 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2724 lp.tmpCellX = lp.cellX;
2725 lp.tmpCellY = lp.cellY;
2726 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2727 0, false, false);
2728 }
Adam Cohen19f37922012-03-21 11:59:11 -07002729 }
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002730 setItemPlacementDirty(false);
Adam Cohen19f37922012-03-21 11:59:11 -07002731 }
Adam Cohen19f37922012-03-21 11:59:11 -07002732 }
2733
Adam Cohenbebf0422012-04-11 18:06:28 -07002734 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2735 View dragView, int[] direction, boolean commit) {
2736 int[] pixelXY = new int[2];
2737 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2738
2739 // First we determine if things have moved enough to cause a different layout
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002740 ItemConfiguration swapSolution = findReorderSolution(pixelXY[0], pixelXY[1], spanX, spanY,
Adam Cohenbebf0422012-04-11 18:06:28 -07002741 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2742
2743 setUseTempCoords(true);
2744 if (swapSolution != null && swapSolution.isSolution) {
2745 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2746 // committing anything or animating anything as we just want to determine if a solution
2747 // exists
2748 copySolutionToTempState(swapSolution, dragView);
2749 setItemPlacementDirty(true);
2750 animateItemsToSolution(swapSolution, dragView, commit);
2751
2752 if (commit) {
2753 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002754 completeAndClearReorderPreviewAnimations();
Adam Cohenbebf0422012-04-11 18:06:28 -07002755 setItemPlacementDirty(false);
2756 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002757 beginOrAdjustReorderPreviewAnimations(swapSolution, dragView,
2758 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohenbebf0422012-04-11 18:06:28 -07002759 }
2760 mShortcutsAndWidgets.requestLayout();
2761 }
2762 return swapSolution.isSolution;
2763 }
2764
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002765 int[] performReorder(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002766 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002767 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002768 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002769
2770 if (resultSpan == null) {
2771 resultSpan = new int[2];
2772 }
2773
Adam Cohen19f37922012-03-21 11:59:11 -07002774 // When we are checking drop validity or actually dropping, we don't recompute the
2775 // direction vector, since we want the solution to match the preview, and it's possible
2776 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002777 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2778 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002779 mDirectionVector[0] = mPreviousReorderDirection[0];
2780 mDirectionVector[1] = mPreviousReorderDirection[1];
2781 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002782 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2783 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2784 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002785 }
2786 } else {
2787 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2788 mPreviousReorderDirection[0] = mDirectionVector[0];
2789 mPreviousReorderDirection[1] = mDirectionVector[1];
2790 }
2791
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002792 // Find a solution involving pushing / displacing any items in the way
2793 ItemConfiguration swapSolution = findReorderSolution(pixelX, pixelY, minSpanX, minSpanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002794 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2795
2796 // We attempt the approach which doesn't shuffle views at all
2797 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2798 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2799
2800 ItemConfiguration finalSolution = null;
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002801
2802 // If the reorder solution requires resizing (shrinking) the item being dropped, we instead
2803 // favor a solution in which the item is not resized, but
Adam Cohen482ed822012-03-02 14:15:13 -08002804 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2805 finalSolution = swapSolution;
2806 } else if (noShuffleSolution.isSolution) {
2807 finalSolution = noShuffleSolution;
2808 }
2809
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002810 if (mode == MODE_SHOW_REORDER_HINT) {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002811 if (finalSolution != null) {
Adam Cohenfe692872013-12-11 14:47:23 -08002812 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView, 0,
2813 ReorderPreviewAnimation.MODE_HINT);
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002814 result[0] = finalSolution.dragViewX;
2815 result[1] = finalSolution.dragViewY;
2816 resultSpan[0] = finalSolution.dragViewSpanX;
2817 resultSpan[1] = finalSolution.dragViewSpanY;
2818 } else {
2819 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2820 }
2821 return result;
2822 }
2823
Adam Cohen482ed822012-03-02 14:15:13 -08002824 boolean foundSolution = true;
2825 if (!DESTRUCTIVE_REORDER) {
2826 setUseTempCoords(true);
2827 }
2828
2829 if (finalSolution != null) {
2830 result[0] = finalSolution.dragViewX;
2831 result[1] = finalSolution.dragViewY;
2832 resultSpan[0] = finalSolution.dragViewSpanX;
2833 resultSpan[1] = finalSolution.dragViewSpanY;
2834
2835 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2836 // committing anything or animating anything as we just want to determine if a solution
2837 // exists
2838 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2839 if (!DESTRUCTIVE_REORDER) {
2840 copySolutionToTempState(finalSolution, dragView);
2841 }
2842 setItemPlacementDirty(true);
2843 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2844
Adam Cohen19f37922012-03-21 11:59:11 -07002845 if (!DESTRUCTIVE_REORDER &&
2846 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002847 commitTempPlacement();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002848 completeAndClearReorderPreviewAnimations();
Adam Cohen19f37922012-03-21 11:59:11 -07002849 setItemPlacementDirty(false);
2850 } else {
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002851 beginOrAdjustReorderPreviewAnimations(finalSolution, dragView,
2852 REORDER_ANIMATION_DURATION, ReorderPreviewAnimation.MODE_PREVIEW);
Adam Cohen482ed822012-03-02 14:15:13 -08002853 }
2854 }
2855 } else {
2856 foundSolution = false;
2857 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2858 }
2859
2860 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2861 setUseTempCoords(false);
2862 }
Adam Cohen482ed822012-03-02 14:15:13 -08002863
Michael Jurkaa52570f2012-03-20 03:18:20 -07002864 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002865 return result;
2866 }
2867
Adam Cohen19f37922012-03-21 11:59:11 -07002868 void setItemPlacementDirty(boolean dirty) {
2869 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002870 }
Adam Cohen19f37922012-03-21 11:59:11 -07002871 boolean isItemPlacementDirty() {
2872 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002873 }
2874
Adam Cohen091440a2015-03-18 14:16:05 -07002875 @Thunk class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002876 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohenf3900c22012-11-16 18:28:11 -08002877 private HashMap<View, CellAndSpan> savedMap = new HashMap<View, CellAndSpan>();
2878 ArrayList<View> sortedViews = new ArrayList<View>();
Adam Cohenfa3c58f2013-12-06 16:10:55 -08002879 ArrayList<View> intersectingViews;
Adam Cohen482ed822012-03-02 14:15:13 -08002880 boolean isSolution = false;
2881 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2882
Adam Cohenf3900c22012-11-16 18:28:11 -08002883 void save() {
2884 // Copy current state into savedMap
2885 for (View v: map.keySet()) {
2886 map.get(v).copy(savedMap.get(v));
2887 }
2888 }
2889
2890 void restore() {
2891 // Restore current state from savedMap
2892 for (View v: savedMap.keySet()) {
2893 savedMap.get(v).copy(map.get(v));
2894 }
2895 }
2896
2897 void add(View v, CellAndSpan cs) {
2898 map.put(v, cs);
2899 savedMap.put(v, new CellAndSpan());
2900 sortedViews.add(v);
2901 }
2902
Adam Cohen482ed822012-03-02 14:15:13 -08002903 int area() {
2904 return dragViewSpanX * dragViewSpanY;
2905 }
Adam Cohen8baab352012-03-20 17:39:21 -07002906 }
2907
2908 private class CellAndSpan {
2909 int x, y;
2910 int spanX, spanY;
2911
Adam Cohenf3900c22012-11-16 18:28:11 -08002912 public CellAndSpan() {
2913 }
2914
2915 public void copy(CellAndSpan copy) {
2916 copy.x = x;
2917 copy.y = y;
2918 copy.spanX = spanX;
2919 copy.spanY = spanY;
2920 }
2921
Adam Cohen8baab352012-03-20 17:39:21 -07002922 public CellAndSpan(int x, int y, int spanX, int spanY) {
2923 this.x = x;
2924 this.y = y;
2925 this.spanX = spanX;
2926 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002927 }
Adam Cohenf3900c22012-11-16 18:28:11 -08002928
2929 public String toString() {
2930 return "(" + x + ", " + y + ": " + spanX + ", " + spanY + ")";
2931 }
2932
Adam Cohen482ed822012-03-02 14:15:13 -08002933 }
2934
Adam Cohendf035382011-04-11 17:22:04 -07002935 /**
2936 * Find a vacant area that will fit the given bounds nearest the requested
2937 * cell location. Uses Euclidean distance to score multiple vacant areas.
2938 *
2939 * @param pixelX The X location at which you want to search for a vacant area.
2940 * @param pixelY The Y location at which you want to search for a vacant area.
2941 * @param spanX Horizontal span of the object.
2942 * @param spanY Vertical span of the object.
2943 * @param ignoreView Considers space occupied by this view as unoccupied
2944 * @param result Previously returned value to possibly recycle.
2945 * @return The X, Y cell of a vacant area that can contain this object,
2946 * nearest the requested location.
2947 */
2948 int[] findNearestVacantArea(
2949 int pixelX, int pixelY, int spanX, int spanY, View ignoreView, int[] result) {
2950 return findNearestArea(pixelX, pixelY, spanX, spanY, ignoreView, true, result);
2951 }
2952
2953 /**
Adam Cohend41fbf52012-02-16 23:53:59 -08002954 * Find a vacant area that will fit the given bounds nearest the requested
2955 * cell location. Uses Euclidean distance to score multiple vacant areas.
2956 *
2957 * @param pixelX The X location at which you want to search for a vacant area.
2958 * @param pixelY The Y location at which you want to search for a vacant area.
2959 * @param minSpanX The minimum horizontal span required
2960 * @param minSpanY The minimum vertical span required
2961 * @param spanX Horizontal span of the object.
2962 * @param spanY Vertical span of the object.
2963 * @param ignoreView Considers space occupied by this view as unoccupied
2964 * @param result Previously returned value to possibly recycle.
2965 * @return The X, Y cell of a vacant area that can contain this object,
2966 * nearest the requested location.
2967 */
2968 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
2969 int spanX, int spanY, View ignoreView, int[] result, int[] resultSpan) {
Adam Cohen482ed822012-03-02 14:15:13 -08002970 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, true,
2971 result, resultSpan, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08002972 }
2973
2974 /**
Adam Cohendf035382011-04-11 17:22:04 -07002975 * Find a starting cell position that will fit the given bounds nearest the requested
2976 * cell location. Uses Euclidean distance to score multiple vacant areas.
2977 *
2978 * @param pixelX The X location at which you want to search for a vacant area.
2979 * @param pixelY The Y location at which you want to search for a vacant area.
2980 * @param spanX Horizontal span of the object.
2981 * @param spanY Vertical span of the object.
2982 * @param ignoreView Considers space occupied by this view as unoccupied
2983 * @param result Previously returned value to possibly recycle.
2984 * @return The X, Y cell of a vacant area that can contain this object,
2985 * nearest the requested location.
2986 */
2987 int[] findNearestArea(
2988 int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2989 return findNearestArea(pixelX, pixelY, spanX, spanY, null, false, result);
2990 }
2991
Michael Jurka0280c3b2010-09-17 15:00:07 -07002992 boolean existsEmptyCell() {
2993 return findCellForSpan(null, 1, 1);
2994 }
2995
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002996 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002997 * Finds the upper-left coordinate of the first rectangle in the grid that can
2998 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2999 * then this method will only return coordinates for rectangles that contain the cell
3000 * (intersectX, intersectY)
3001 *
3002 * @param cellXY The array that will contain the position of a vacant cell if such a cell
3003 * can be found.
3004 * @param spanX The horizontal span of the cell we want to find.
3005 * @param spanY The vertical span of the cell we want to find.
3006 *
3007 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07003008 */
Michael Jurka0280c3b2010-09-17 15:00:07 -07003009 boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08003010 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07003011 }
3012
3013 /**
3014 * Like above, but ignores any cells occupied by the item "ignoreView"
3015 *
3016 * @param cellXY The array that will contain the position of a vacant cell if such a cell
3017 * can be found.
3018 * @param spanX The horizontal span of the cell we want to find.
3019 * @param spanY The vertical span of the cell we want to find.
3020 * @param ignoreView The home screen item we should treat as not occupying any space
3021 * @return
3022 */
3023 boolean findCellForSpanIgnoring(int[] cellXY, int spanX, int spanY, View ignoreView) {
Adam Cohen482ed822012-03-02 14:15:13 -08003024 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1,
3025 ignoreView, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07003026 }
3027
3028 /**
3029 * Like above, but if intersectX and intersectY are not -1, then this method will try to
3030 * return coordinates for rectangles that contain the cell [intersectX, intersectY]
3031 *
3032 * @param spanX The horizontal span of the cell we want to find.
3033 * @param spanY The vertical span of the cell we want to find.
3034 * @param ignoreView The home screen item we should treat as not occupying any space
3035 * @param intersectX The X coordinate of the cell that we should try to overlap
3036 * @param intersectX The Y coordinate of the cell that we should try to overlap
3037 *
3038 * @return True if a vacant cell of the specified dimension was found, false otherwise.
3039 */
3040 boolean findCellForSpanThatIntersects(int[] cellXY, int spanX, int spanY,
3041 int intersectX, int intersectY) {
3042 return findCellForSpanThatIntersectsIgnoring(
Adam Cohen482ed822012-03-02 14:15:13 -08003043 cellXY, spanX, spanY, intersectX, intersectY, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07003044 }
3045
3046 /**
3047 * The superset of the above two methods
3048 */
3049 boolean findCellForSpanThatIntersectsIgnoring(int[] cellXY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08003050 int intersectX, int intersectY, View ignoreView, boolean occupied[][]) {
Michael Jurkac6ee42e2010-09-30 12:04:50 -07003051 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08003052 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07003053
Michael Jurka28750fb2010-09-24 17:43:49 -07003054 boolean foundCell = false;
Michael Jurka0280c3b2010-09-17 15:00:07 -07003055 while (true) {
3056 int startX = 0;
3057 if (intersectX >= 0) {
3058 startX = Math.max(startX, intersectX - (spanX - 1));
3059 }
3060 int endX = mCountX - (spanX - 1);
3061 if (intersectX >= 0) {
3062 endX = Math.min(endX, intersectX + (spanX - 1) + (spanX == 1 ? 1 : 0));
3063 }
3064 int startY = 0;
3065 if (intersectY >= 0) {
3066 startY = Math.max(startY, intersectY - (spanY - 1));
3067 }
3068 int endY = mCountY - (spanY - 1);
3069 if (intersectY >= 0) {
3070 endY = Math.min(endY, intersectY + (spanY - 1) + (spanY == 1 ? 1 : 0));
3071 }
3072
Winson Chungbbc60d82010-11-11 16:34:41 -08003073 for (int y = startY; y < endY && !foundCell; y++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07003074 inner:
Winson Chungbbc60d82010-11-11 16:34:41 -08003075 for (int x = startX; x < endX; x++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07003076 for (int i = 0; i < spanX; i++) {
3077 for (int j = 0; j < spanY; j++) {
Adam Cohen482ed822012-03-02 14:15:13 -08003078 if (occupied[x + i][y + j]) {
Winson Chungbbc60d82010-11-11 16:34:41 -08003079 // small optimization: we can skip to after the column we just found
Michael Jurka0280c3b2010-09-17 15:00:07 -07003080 // an occupied cell
Winson Chungbbc60d82010-11-11 16:34:41 -08003081 x += i;
Michael Jurka0280c3b2010-09-17 15:00:07 -07003082 continue inner;
3083 }
3084 }
3085 }
3086 if (cellXY != null) {
3087 cellXY[0] = x;
3088 cellXY[1] = y;
3089 }
Michael Jurka28750fb2010-09-24 17:43:49 -07003090 foundCell = true;
3091 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07003092 }
3093 }
3094 if (intersectX == -1 && intersectY == -1) {
3095 break;
3096 } else {
3097 // if we failed to find anything, try again but without any requirements of
3098 // intersecting
3099 intersectX = -1;
3100 intersectY = -1;
3101 continue;
3102 }
3103 }
3104
Michael Jurkac6ee42e2010-09-30 12:04:50 -07003105 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08003106 markCellsAsOccupiedForView(ignoreView, occupied);
Michael Jurka28750fb2010-09-24 17:43:49 -07003107 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07003108 }
3109
3110 /**
Winson Chungc07918d2011-07-01 15:35:26 -07003111 * A drag event has begun over this layout.
3112 * It may have begun over this layout (in which case onDragChild is called first),
3113 * or it may have begun on another layout.
3114 */
3115 void onDragEnter() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07003116 mDragEnforcer.onDragEnter();
Winson Chungc07918d2011-07-01 15:35:26 -07003117 mDragging = true;
3118 }
3119
3120 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07003121 * Called when drag has left this CellLayout or has been completed (successfully or not)
3122 */
3123 void onDragExit() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07003124 mDragEnforcer.onDragExit();
Joe Onorato4be866d2010-10-10 11:26:02 -07003125 // This can actually be called when we aren't in a drag, e.g. when adding a new
3126 // item to this layout via the customize drawer.
3127 // Guard against that case.
3128 if (mDragging) {
3129 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07003130 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07003131
3132 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08003133 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07003134 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
3135 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07003136 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08003137 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07003138 }
3139
3140 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07003141 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07003142 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07003143 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003144 *
3145 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003146 */
Adam Cohen716b51e2011-06-30 12:09:54 -07003147 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07003148 if (child != null) {
3149 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08003150 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07003151 child.requestLayout();
Romain Guyd94533d2009-08-17 10:01:15 -07003152 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003153 }
3154
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003155 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003156 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07003157 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003158 * @param cellX X coordinate of upper left corner expressed as a cell position
3159 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07003160 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003161 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07003162 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003163 */
Adam Cohend41fbf52012-02-16 23:53:59 -08003164 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003165 final int cellWidth = mCellWidth;
3166 final int cellHeight = mCellHeight;
3167 final int widthGap = mWidthGap;
3168 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07003169
Winson Chung4b825dcd2011-06-19 12:41:22 -07003170 final int hStartPadding = getPaddingLeft();
3171 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07003172
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003173 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
3174 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
3175
3176 int x = hStartPadding + cellX * (cellWidth + widthGap);
3177 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07003178
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07003179 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003180 }
Winson Chungaafa03c2010-06-11 17:34:16 -07003181
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003182 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07003183 * Computes the required horizontal and vertical cell spans to always
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003184 * fit the given rectangle.
Winson Chungaafa03c2010-06-11 17:34:16 -07003185 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003186 * @param width Width in pixels
3187 * @param height Height in pixels
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07003188 * @param result An array of length 2 in which to store the result (may be null).
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003189 */
Winson Chung66700732013-08-20 16:56:15 -07003190 public static int[] rectToCell(int width, int height, int[] result) {
Winson Chung5f8afe62013-08-12 16:19:28 -07003191 LauncherAppState app = LauncherAppState.getInstance();
3192 DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
Winson Chung66700732013-08-20 16:56:15 -07003193 Rect padding = grid.getWorkspacePadding(grid.isLandscape ?
3194 CellLayout.LANDSCAPE : CellLayout.PORTRAIT);
Winson Chung5f8afe62013-08-12 16:19:28 -07003195
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003196 // Always assume we're working with the smallest span to make sure we
3197 // reserve enough space in both orientations.
Winson Chung66700732013-08-20 16:56:15 -07003198 int parentWidth = grid.calculateCellWidth(grid.widthPx
3199 - padding.left - padding.right, (int) grid.numColumns);
3200 int parentHeight = grid.calculateCellHeight(grid.heightPx
3201 - padding.top - padding.bottom, (int) grid.numRows);
3202 int smallerSize = Math.min(parentWidth, parentHeight);
Joe Onorato79e56262009-09-21 15:23:04 -04003203
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003204 // Always round up to next largest cell
Winson Chung54c725c2011-08-03 12:03:40 -07003205 int spanX = (int) Math.ceil(width / (float) smallerSize);
3206 int spanY = (int) Math.ceil(height / (float) smallerSize);
Joe Onorato79e56262009-09-21 15:23:04 -04003207
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07003208 if (result == null) {
3209 return new int[] { spanX, spanY };
3210 }
3211 result[0] = spanX;
3212 result[1] = spanY;
3213 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003214 }
3215
Michael Jurkaf12c75c2011-01-25 22:41:40 -08003216 public int[] cellSpansToSize(int hSpans, int vSpans) {
3217 int[] size = new int[2];
3218 size[0] = hSpans * mCellWidth + (hSpans - 1) * mWidthGap;
3219 size[1] = vSpans * mCellHeight + (vSpans - 1) * mHeightGap;
3220 return size;
3221 }
3222
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003223 /**
Patrick Dubroy047379a2010-12-19 22:02:04 -08003224 * Calculate the grid spans needed to fit given item
3225 */
3226 public void calculateSpans(ItemInfo info) {
3227 final int minWidth;
3228 final int minHeight;
3229
3230 if (info instanceof LauncherAppWidgetInfo) {
3231 minWidth = ((LauncherAppWidgetInfo) info).minWidth;
3232 minHeight = ((LauncherAppWidgetInfo) info).minHeight;
3233 } else if (info instanceof PendingAddWidgetInfo) {
3234 minWidth = ((PendingAddWidgetInfo) info).minWidth;
3235 minHeight = ((PendingAddWidgetInfo) info).minHeight;
3236 } else {
3237 // It's not a widget, so it must be 1x1
3238 info.spanX = info.spanY = 1;
3239 return;
3240 }
3241 int[] spans = rectToCell(minWidth, minHeight, null);
3242 info.spanX = spans[0];
3243 info.spanY = spans[1];
3244 }
3245
3246 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003247 * Find the first vacant cell, if there is one.
3248 *
3249 * @param vacant Holds the x and y coordinate of the vacant cell
3250 * @param spanX Horizontal cell span.
3251 * @param spanY Vertical cell span.
Winson Chungaafa03c2010-06-11 17:34:16 -07003252 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003253 * @return True if a vacant cell was found
3254 */
3255 public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003256
Michael Jurka0280c3b2010-09-17 15:00:07 -07003257 return findVacantCell(vacant, spanX, spanY, mCountX, mCountY, mOccupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003258 }
3259
3260 static boolean findVacantCell(int[] vacant, int spanX, int spanY,
3261 int xCount, int yCount, boolean[][] occupied) {
3262
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08003263 for (int y = 0; (y + spanY) <= yCount; y++) {
3264 for (int x = 0; (x + spanX) <= xCount; x++) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003265 boolean available = !occupied[x][y];
Sunny Goyal71b5c0b2015-01-08 16:59:04 -08003266out: for (int i = x; i < x + spanX; i++) {
3267 for (int j = y; j < y + spanY; j++) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003268 available = available && !occupied[i][j];
3269 if (!available) break out;
3270 }
3271 }
3272
3273 if (available) {
3274 vacant[0] = x;
3275 vacant[1] = y;
3276 return true;
3277 }
3278 }
3279 }
3280
3281 return false;
3282 }
3283
Michael Jurka0280c3b2010-09-17 15:00:07 -07003284 private void clearOccupiedCells() {
3285 for (int x = 0; x < mCountX; x++) {
3286 for (int y = 0; y < mCountY; y++) {
3287 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003288 }
3289 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07003290 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003291
Adam Cohend41fbf52012-02-16 23:53:59 -08003292 public void onMove(View view, int newCellX, int newCellY, int newSpanX, int newSpanY) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07003293 markCellsAsUnoccupiedForView(view);
Adam Cohen482ed822012-03-02 14:15:13 -08003294 markCellsForView(newCellX, newCellY, newSpanX, newSpanY, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07003295 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003296
Adam Cohend4844c32011-02-18 19:25:06 -08003297 public void markCellsAsOccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08003298 markCellsAsOccupiedForView(view, mOccupied);
3299 }
3300 public void markCellsAsOccupiedForView(View view, boolean[][] occupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07003301 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07003302 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08003303 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07003304 }
3305
Adam Cohend4844c32011-02-18 19:25:06 -08003306 public void markCellsAsUnoccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08003307 markCellsAsUnoccupiedForView(view, mOccupied);
3308 }
3309 public void markCellsAsUnoccupiedForView(View view, boolean occupied[][]) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07003310 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07003311 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08003312 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07003313 }
3314
Adam Cohen482ed822012-03-02 14:15:13 -08003315 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
3316 boolean value) {
3317 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07003318 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
3319 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08003320 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003321 }
3322 }
3323 }
3324
Adam Cohen2801caf2011-05-13 20:57:39 -07003325 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07003326 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07003327 (Math.max((mCountX - 1), 0) * mWidthGap);
3328 }
3329
3330 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07003331 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07003332 (Math.max((mCountY - 1), 0) * mHeightGap);
3333 }
3334
Michael Jurka66d72172011-04-12 16:29:25 -07003335 public boolean isOccupied(int x, int y) {
3336 if (x < mCountX && y < mCountY) {
3337 return mOccupied[x][y];
3338 } else {
3339 throw new RuntimeException("Position exceeds the bound of this CellLayout");
3340 }
3341 }
3342
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003343 @Override
3344 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
3345 return new CellLayout.LayoutParams(getContext(), attrs);
3346 }
3347
3348 @Override
3349 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
3350 return p instanceof CellLayout.LayoutParams;
3351 }
3352
3353 @Override
3354 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
3355 return new CellLayout.LayoutParams(p);
3356 }
3357
Winson Chungaafa03c2010-06-11 17:34:16 -07003358 public static class CellLayoutAnimationController extends LayoutAnimationController {
3359 public CellLayoutAnimationController(Animation animation, float delay) {
3360 super(animation, delay);
3361 }
3362
3363 @Override
3364 protected long getDelayForView(View view) {
3365 return (int) (Math.random() * 150);
3366 }
3367 }
3368
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003369 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
3370 /**
3371 * Horizontal location of the item in the grid.
3372 */
3373 @ViewDebug.ExportedProperty
3374 public int cellX;
3375
3376 /**
3377 * Vertical location of the item in the grid.
3378 */
3379 @ViewDebug.ExportedProperty
3380 public int cellY;
3381
3382 /**
Adam Cohen482ed822012-03-02 14:15:13 -08003383 * Temporary horizontal location of the item in the grid during reorder
3384 */
3385 public int tmpCellX;
3386
3387 /**
3388 * Temporary vertical location of the item in the grid during reorder
3389 */
3390 public int tmpCellY;
3391
3392 /**
3393 * Indicates that the temporary coordinates should be used to layout the items
3394 */
3395 public boolean useTmpCoords;
3396
3397 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003398 * Number of cells spanned horizontally by the item.
3399 */
3400 @ViewDebug.ExportedProperty
3401 public int cellHSpan;
3402
3403 /**
3404 * Number of cells spanned vertically by the item.
3405 */
3406 @ViewDebug.ExportedProperty
3407 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07003408
Adam Cohen1b607ed2011-03-03 17:26:50 -08003409 /**
3410 * Indicates whether the item will set its x, y, width and height parameters freely,
3411 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
3412 */
Adam Cohend4844c32011-02-18 19:25:06 -08003413 public boolean isLockedToGrid = true;
3414
Adam Cohen482ed822012-03-02 14:15:13 -08003415 /**
Adam Cohenec40b2b2013-07-23 15:52:40 -07003416 * Indicates that this item should use the full extents of its parent.
3417 */
3418 public boolean isFullscreen = false;
3419
3420 /**
Adam Cohen482ed822012-03-02 14:15:13 -08003421 * Indicates whether this item can be reordered. Always true except in the case of the
3422 * the AllApps button.
3423 */
3424 public boolean canReorder = true;
3425
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003426 // X coordinate of the view in the layout.
3427 @ViewDebug.ExportedProperty
3428 int x;
3429 // Y coordinate of the view in the layout.
3430 @ViewDebug.ExportedProperty
3431 int y;
3432
Romain Guy84f296c2009-11-04 15:00:44 -08003433 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07003434
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003435 public LayoutParams(Context c, AttributeSet attrs) {
3436 super(c, attrs);
3437 cellHSpan = 1;
3438 cellVSpan = 1;
3439 }
3440
3441 public LayoutParams(ViewGroup.LayoutParams source) {
3442 super(source);
3443 cellHSpan = 1;
3444 cellVSpan = 1;
3445 }
Winson Chungaafa03c2010-06-11 17:34:16 -07003446
3447 public LayoutParams(LayoutParams source) {
3448 super(source);
3449 this.cellX = source.cellX;
3450 this.cellY = source.cellY;
3451 this.cellHSpan = source.cellHSpan;
3452 this.cellVSpan = source.cellVSpan;
3453 }
3454
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003455 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08003456 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003457 this.cellX = cellX;
3458 this.cellY = cellY;
3459 this.cellHSpan = cellHSpan;
3460 this.cellVSpan = cellVSpan;
3461 }
3462
Adam Cohen2374abf2013-04-16 14:56:57 -07003463 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap,
3464 boolean invertHorizontally, int colCount) {
Adam Cohend4844c32011-02-18 19:25:06 -08003465 if (isLockedToGrid) {
3466 final int myCellHSpan = cellHSpan;
3467 final int myCellVSpan = cellVSpan;
Adam Cohen2374abf2013-04-16 14:56:57 -07003468 int myCellX = useTmpCoords ? tmpCellX : cellX;
3469 int myCellY = useTmpCoords ? tmpCellY : cellY;
3470
3471 if (invertHorizontally) {
3472 myCellX = colCount - myCellX - cellHSpan;
3473 }
Adam Cohen1b607ed2011-03-03 17:26:50 -08003474
Adam Cohend4844c32011-02-18 19:25:06 -08003475 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
3476 leftMargin - rightMargin;
3477 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
3478 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08003479 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
3480 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08003481 }
3482 }
Winson Chungaafa03c2010-06-11 17:34:16 -07003483
Winson Chungaafa03c2010-06-11 17:34:16 -07003484 public String toString() {
3485 return "(" + this.cellX + ", " + this.cellY + ")";
3486 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07003487
3488 public void setWidth(int width) {
3489 this.width = width;
3490 }
3491
3492 public int getWidth() {
3493 return width;
3494 }
3495
3496 public void setHeight(int height) {
3497 this.height = height;
3498 }
3499
3500 public int getHeight() {
3501 return height;
3502 }
3503
3504 public void setX(int x) {
3505 this.x = x;
3506 }
3507
3508 public int getX() {
3509 return x;
3510 }
3511
3512 public void setY(int y) {
3513 this.y = y;
3514 }
3515
3516 public int getY() {
3517 return y;
3518 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003519 }
3520
Michael Jurka0280c3b2010-09-17 15:00:07 -07003521 // This class stores info for two purposes:
3522 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
3523 // its spanX, spanY, and the screen it is on
3524 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
3525 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
3526 // the CellLayout that was long clicked
Michael Jurkae5fb0f22011-04-11 13:27:46 -07003527 static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003528 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07003529 int cellX = -1;
3530 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003531 int spanX;
3532 int spanY;
Adam Cohendcd297f2013-06-18 13:13:40 -07003533 long screenId;
Winson Chung3d503fb2011-07-13 17:25:49 -07003534 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003535
Adam Cohene0aaa0d2014-05-12 12:44:22 -07003536 CellInfo(View v, ItemInfo info) {
3537 cell = v;
3538 cellX = info.cellX;
3539 cellY = info.cellY;
3540 spanX = info.spanX;
3541 spanY = info.spanY;
3542 screenId = info.screenId;
3543 container = info.container;
3544 }
3545
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003546 @Override
3547 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07003548 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
3549 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003550 }
3551 }
Michael Jurkad771c962011-08-09 15:00:48 -07003552
3553 public boolean lastDownOnOccupiedCell() {
3554 return mLastDownOnOccupiedCell;
3555 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003556}