blob: 4f4ef4e2512500cd2e5c3593e9f0b35cc4a34ac1 [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
Joe Onoratoa5902522009-07-30 13:37:37 -070017package com.android.launcher2;
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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040026import android.content.res.Resources;
Winson Chungaafa03c2010-06-11 17:34:16 -070027import android.content.res.TypedArray;
Joe Onorato4be866d2010-10-10 11:26:02 -070028import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070029import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080030import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070031import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070032import android.graphics.Point;
Adam Cohenb5ba0972011-09-07 18:02:31 -070033import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080036import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070037import android.graphics.drawable.Drawable;
Adam Cohenb5ba0972011-09-07 18:02:31 -070038import android.graphics.drawable.NinePatchDrawable;
Adam Cohen1462de32012-07-24 22:34:36 -070039import android.os.Parcelable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070041import android.util.Log;
Adam Cohen1462de32012-07-24 22:34:36 -070042import android.util.SparseArray;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.view.MotionEvent;
44import android.view.View;
45import android.view.ViewDebug;
46import android.view.ViewGroup;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.view.animation.Animation;
Winson Chung150fbab2010-09-29 17:14:26 -070048import android.view.animation.DecelerateInterpolator;
Winson Chungaafa03c2010-06-11 17:34:16 -070049import android.view.animation.LayoutAnimationController;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080050
Adam Cohen66396872011-04-15 17:50:36 -070051import com.android.launcher.R;
Adam Cohen69ce2e52011-07-03 19:25:21 -070052import com.android.launcher2.FolderIcon.FolderRingAnimator;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070053
Adam Cohen69ce2e52011-07-03 19:25:21 -070054import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070055import java.util.Arrays;
Adam Cohenbfbfd262011-06-13 16:55:12 -070056import java.util.HashMap;
Adam Cohend41fbf52012-02-16 23:53:59 -080057import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070058
Michael Jurkabdb5c532011-02-01 15:05:06 -080059public class CellLayout extends ViewGroup {
Winson Chungaafa03c2010-06-11 17:34:16 -070060 static final String TAG = "CellLayout";
61
Adam Cohen2acce882012-03-28 19:03:19 -070062 private Launcher mLauncher;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080063 private int mCellWidth;
64 private int mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070065
Adam Cohend22015c2010-07-26 22:02:18 -070066 private int mCountX;
67 private int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068
Adam Cohen234c4cd2011-07-17 21:03:04 -070069 private int mOriginalWidthGap;
70 private int mOriginalHeightGap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071 private int mWidthGap;
72 private int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070073 private int mMaxGap;
Adam Cohenebea84d2011-11-09 17:20:41 -080074 private boolean mScrollingTransformsDirty = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
76 private final Rect mRect = new Rect();
77 private final CellInfo mCellInfo = new CellInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -070078
Patrick Dubroyde7658b2010-09-27 11:15:43 -070079 // These are temporary variables to prevent having to allocate a new object just to
80 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Winson Chung0be025d2011-05-23 17:45:09 -070081 private final int[] mTmpXY = new int[2];
Patrick Dubroyde7658b2010-09-27 11:15:43 -070082 private final int[] mTmpPoint = new int[2];
Adam Cohen69ce2e52011-07-03 19:25:21 -070083 int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070084
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -080086 boolean[][] mTmpOccupied;
Michael Jurkad771c962011-08-09 15:00:48 -070087 private boolean mLastDownOnOccupiedCell = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
Michael Jurkadee05892010-07-27 10:01:56 -070089 private OnTouchListener mInterceptTouchListener;
90
Adam Cohen69ce2e52011-07-03 19:25:21 -070091 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -070092 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -070093
Adam Cohenb5ba0972011-09-07 18:02:31 -070094 private int mForegroundAlpha = 0;
Michael Jurka5f1c5092010-09-03 14:15:02 -070095 private float mBackgroundAlpha;
Adam Cohen1b0aaac2010-10-28 11:11:18 -070096 private float mBackgroundAlphaMultiplier = 1.0f;
Adam Cohenf34bab52010-09-30 14:11:56 -070097
Michael Jurka33945b22010-12-21 18:19:38 -080098 private Drawable mNormalBackground;
Michael Jurka33945b22010-12-21 18:19:38 -080099 private Drawable mActiveGlowBackground;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700100 private Drawable mOverScrollForegroundDrawable;
101 private Drawable mOverScrollLeft;
102 private Drawable mOverScrollRight;
Michael Jurka18014792010-10-14 09:01:34 -0700103 private Rect mBackgroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700104 private Rect mForegroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700105 private int mForegroundPadding;
Patrick Dubroy1262e362010-10-06 15:49:50 -0700106
Michael Jurka33945b22010-12-21 18:19:38 -0800107 // If we're actively dragging something over this screen, mIsDragOverlapping is true
108 private boolean mIsDragOverlapping = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700109 private final Point mDragCenter = new Point();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700110
Winson Chung150fbab2010-09-29 17:14:26 -0700111 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700112 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohend41fbf52012-02-16 23:53:59 -0800113 private Rect[] mDragOutlines = new Rect[4];
Chet Haase472b2812010-10-14 07:02:04 -0700114 private float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700115 private InterruptibleInOutAnimator[] mDragOutlineAnims =
116 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700117
118 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700119 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700120 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700121
Patrick Dubroy96864c32011-03-10 17:17:23 -0800122 private BubbleTextView mPressedOrFocusedIcon;
123
Adam Cohen482ed822012-03-02 14:15:13 -0800124 private HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new
125 HashMap<CellLayout.LayoutParams, Animator>();
Adam Cohen19f37922012-03-21 11:59:11 -0700126 private HashMap<View, ReorderHintAnimation>
127 mShakeAnimators = new HashMap<View, ReorderHintAnimation>();
128
129 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700130
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700131 // When a drag operation is in progress, holds the nearest cell to the touch point
132 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800133
Joe Onorato4be866d2010-10-10 11:26:02 -0700134 private boolean mDragging = false;
135
Patrick Dubroyce34a972010-10-19 10:34:32 -0700136 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700137 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700138
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800139 private boolean mIsHotseat = false;
Adam Cohen307fe232012-08-16 17:55:58 -0700140 private float mHotseatScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800141
Adam Cohen482ed822012-03-02 14:15:13 -0800142 public static final int MODE_DRAG_OVER = 0;
143 public static final int MODE_ON_DROP = 1;
144 public static final int MODE_ON_DROP_EXTERNAL = 2;
145 public static final int MODE_ACCEPT_DROP = 3;
Adam Cohen19f37922012-03-21 11:59:11 -0700146 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800147 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
148
Adam Cohena897f392012-04-27 18:12:05 -0700149 static final int LANDSCAPE = 0;
150 static final int PORTRAIT = 1;
151
Adam Cohen7bdfc972012-05-22 16:50:35 -0700152 private static final float REORDER_HINT_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700153 private static final int REORDER_ANIMATION_DURATION = 150;
154 private float mReorderHintAnimationMagnitude;
155
Adam Cohen482ed822012-03-02 14:15:13 -0800156 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
157 private Rect mOccupiedRect = new Rect();
158 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700159 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700160 private static final int INVALID_DIRECTION = -100;
Adam Cohenc6cc61d2012-04-04 12:47:08 -0700161 private DropTarget.DragEnforcer mDragEnforcer;
Adam Cohen482ed822012-03-02 14:15:13 -0800162
Romain Guy8a0bff52012-05-06 13:14:33 -0700163 private final static PorterDuffXfermode sAddBlendMode =
164 new PorterDuffXfermode(PorterDuff.Mode.ADD);
Michael Jurkaca993832012-06-29 15:17:04 -0700165 private final static Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700166
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800167 public CellLayout(Context context) {
168 this(context, null);
169 }
170
171 public CellLayout(Context context, AttributeSet attrs) {
172 this(context, attrs, 0);
173 }
174
175 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
176 super(context, attrs, defStyle);
Michael Jurka8b805b12012-04-18 14:23:14 -0700177 mDragEnforcer = new DropTarget.DragEnforcer(context);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700178
179 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
180 // the user where a dragged item will land when dropped.
181 setWillNotDraw(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700182 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700183
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
185
Adam Cohenf4bd5792012-04-27 11:35:29 -0700186 mCellWidth = a.getDimensionPixelSize(R.styleable.CellLayout_cellWidth, 10);
187 mCellHeight = a.getDimensionPixelSize(R.styleable.CellLayout_cellHeight, 10);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700188 mWidthGap = mOriginalWidthGap = a.getDimensionPixelSize(R.styleable.CellLayout_widthGap, 0);
189 mHeightGap = mOriginalHeightGap = a.getDimensionPixelSize(R.styleable.CellLayout_heightGap, 0);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700190 mMaxGap = a.getDimensionPixelSize(R.styleable.CellLayout_maxGap, 0);
Adam Cohend22015c2010-07-26 22:02:18 -0700191 mCountX = LauncherModel.getCellCountX();
192 mCountY = LauncherModel.getCellCountY();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700193 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800194 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700195 mPreviousReorderDirection[0] = INVALID_DIRECTION;
196 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800197
198 a.recycle();
199
200 setAlwaysDrawnWithCacheEnabled(false);
201
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700202 final Resources res = getResources();
Adam Cohen307fe232012-08-16 17:55:58 -0700203 mHotseatScale = (res.getInteger(R.integer.hotseat_item_scale_percentage) / 100f);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700204
Winson Chung967289b2011-06-30 18:09:30 -0700205 mNormalBackground = res.getDrawable(R.drawable.homescreen_blue_normal_holo);
Winson Chungdea74b72011-09-13 18:06:43 -0700206 mActiveGlowBackground = res.getDrawable(R.drawable.homescreen_blue_strong_holo);
Michael Jurka33945b22010-12-21 18:19:38 -0800207
Adam Cohenb5ba0972011-09-07 18:02:31 -0700208 mOverScrollLeft = res.getDrawable(R.drawable.overscroll_glow_left);
209 mOverScrollRight = res.getDrawable(R.drawable.overscroll_glow_right);
210 mForegroundPadding =
211 res.getDimensionPixelSize(R.dimen.workspace_overscroll_drawable_padding);
Michael Jurka33945b22010-12-21 18:19:38 -0800212
Adam Cohen19f37922012-03-21 11:59:11 -0700213 mReorderHintAnimationMagnitude = (REORDER_HINT_MAGNITUDE *
214 res.getDimensionPixelSize(R.dimen.app_icon_size));
215
Winson Chungb26f3d62011-06-02 10:49:29 -0700216 mNormalBackground.setFilterBitmap(true);
Winson Chungb26f3d62011-06-02 10:49:29 -0700217 mActiveGlowBackground.setFilterBitmap(true);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700218
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700219 // Initialize the data structures used for the drag visualization.
Winson Chung150fbab2010-09-29 17:14:26 -0700220
Patrick Dubroyce34a972010-10-19 10:34:32 -0700221 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700222
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700223
Winson Chungb8c69f32011-10-19 21:36:08 -0700224 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700225 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800226 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700227 }
228
229 // When dragging things around the home screens, we show a green outline of
230 // where the item will land. The outlines gradually fade out, leaving a trail
231 // behind the drag path.
232 // Set up all the animations that are used to implement this fading.
233 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700234 final float fromAlphaValue = 0;
235 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700236
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700237 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700238
239 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700240 final InterruptibleInOutAnimator anim =
241 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700242 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700243 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700244 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700245 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700246 final Bitmap outline = (Bitmap)anim.getTag();
247
248 // If an animation is started and then stopped very quickly, we can still
249 // get spurious updates we've cleared the tag. Guard against this.
250 if (outline == null) {
Michael Jurka3a9fced2012-04-13 14:44:29 -0700251 @SuppressWarnings("all") // suppress dead code warning
252 final boolean debug = false;
253 if (debug) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700254 Object val = animation.getAnimatedValue();
255 Log.d(TAG, "anim " + thisIndex + " update: " + val +
256 ", isStopped " + anim.isStopped());
257 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700258 // Try to prevent it from continuing to run
259 animation.cancel();
260 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700261 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800262 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700263 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700264 }
265 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700266 // The animation holds a reference to the drag outline bitmap as long is it's
267 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700268 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700269 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700270 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700271 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700272 anim.setTag(null);
273 }
274 }
275 });
276 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700277 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700278
Michael Jurka18014792010-10-14 09:01:34 -0700279 mBackgroundRect = new Rect();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700280 mForegroundRect = new Rect();
Michael Jurkabea15192010-11-17 12:33:46 -0800281
Michael Jurkaa52570f2012-03-20 03:18:20 -0700282 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
283 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
284 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700285 }
286
Michael Jurkaf6440da2011-04-05 14:50:34 -0700287 static int widthInPortrait(Resources r, int numCells) {
288 // We use this method from Workspace to figure out how many rows/columns Launcher should
289 // have. We ignore the left/right padding on CellLayout because it turns out in our design
290 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700291 int cellWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700292 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
293 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700294
Winson Chung4b825dcd2011-06-19 12:41:22 -0700295 return minGap * (numCells - 1) + cellWidth * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700296 }
297
Michael Jurkaf6440da2011-04-05 14:50:34 -0700298 static int heightInLandscape(Resources r, int numCells) {
299 // We use this method from Workspace to figure out how many rows/columns Launcher should
300 // have. We ignore the left/right padding on CellLayout because it turns out in our design
301 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700302 int cellHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700303 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
304 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700305
Winson Chung4b825dcd2011-06-19 12:41:22 -0700306 return minGap * (numCells - 1) + cellHeight * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700307 }
308
Adam Cohen2801caf2011-05-13 20:57:39 -0700309 public void enableHardwareLayers() {
Michael Jurkaca993832012-06-29 15:17:04 -0700310 mShortcutsAndWidgets.setLayerType(LAYER_TYPE_HARDWARE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700311 }
312
313 public void disableHardwareLayers() {
Michael Jurkaca993832012-06-29 15:17:04 -0700314 mShortcutsAndWidgets.setLayerType(LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700315 }
316
317 public void buildHardwareLayer() {
318 mShortcutsAndWidgets.buildLayer();
Adam Cohen2801caf2011-05-13 20:57:39 -0700319 }
320
Adam Cohen307fe232012-08-16 17:55:58 -0700321 public float getChildrenScale() {
322 return mIsHotseat ? mHotseatScale : 1.0f;
323 }
324
Adam Cohen2801caf2011-05-13 20:57:39 -0700325 public void setGridSize(int x, int y) {
326 mCountX = x;
327 mCountY = y;
328 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800329 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700330 mTempRectStack.clear();
Adam Cohen76fc0852011-06-17 13:26:23 -0700331 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700332 }
333
Patrick Dubroy96864c32011-03-10 17:17:23 -0800334 private void invalidateBubbleTextView(BubbleTextView icon) {
335 final int padding = icon.getPressedOrFocusedBackgroundPadding();
Winson Chung4b825dcd2011-06-19 12:41:22 -0700336 invalidate(icon.getLeft() + getPaddingLeft() - padding,
337 icon.getTop() + getPaddingTop() - padding,
338 icon.getRight() + getPaddingLeft() + padding,
339 icon.getBottom() + getPaddingTop() + padding);
Patrick Dubroy96864c32011-03-10 17:17:23 -0800340 }
341
Adam Cohenb5ba0972011-09-07 18:02:31 -0700342 void setOverScrollAmount(float r, boolean left) {
343 if (left && mOverScrollForegroundDrawable != mOverScrollLeft) {
344 mOverScrollForegroundDrawable = mOverScrollLeft;
345 } else if (!left && mOverScrollForegroundDrawable != mOverScrollRight) {
346 mOverScrollForegroundDrawable = mOverScrollRight;
347 }
348
349 mForegroundAlpha = (int) Math.round((r * 255));
350 mOverScrollForegroundDrawable.setAlpha(mForegroundAlpha);
351 invalidate();
352 }
353
Patrick Dubroy96864c32011-03-10 17:17:23 -0800354 void setPressedOrFocusedIcon(BubbleTextView icon) {
355 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
356 // requires an expanded clip rect (due to the glow's blur radius)
357 BubbleTextView oldIcon = mPressedOrFocusedIcon;
358 mPressedOrFocusedIcon = icon;
359 if (oldIcon != null) {
360 invalidateBubbleTextView(oldIcon);
361 }
362 if (mPressedOrFocusedIcon != null) {
363 invalidateBubbleTextView(mPressedOrFocusedIcon);
364 }
365 }
366
Michael Jurka33945b22010-12-21 18:19:38 -0800367 void setIsDragOverlapping(boolean isDragOverlapping) {
368 if (mIsDragOverlapping != isDragOverlapping) {
369 mIsDragOverlapping = isDragOverlapping;
370 invalidate();
371 }
372 }
373
374 boolean getIsDragOverlapping() {
375 return mIsDragOverlapping;
376 }
377
Adam Cohenebea84d2011-11-09 17:20:41 -0800378 protected void setOverscrollTransformsDirty(boolean dirty) {
379 mScrollingTransformsDirty = dirty;
380 }
381
382 protected void resetOverscrollTransforms() {
383 if (mScrollingTransformsDirty) {
384 setOverscrollTransformsDirty(false);
385 setTranslationX(0);
386 setRotationY(0);
387 // It doesn't matter if we pass true or false here, the important thing is that we
388 // pass 0, which results in the overscroll drawable not being drawn any more.
389 setOverScrollAmount(0, false);
390 setPivotX(getMeasuredWidth() / 2);
391 setPivotY(getMeasuredHeight() / 2);
392 }
393 }
394
Adam Cohen307fe232012-08-16 17:55:58 -0700395 public void scaleRect(Rect r, float scale) {
396 if (scale != 1.0f) {
397 r.left = (int) (r.left * scale + 0.5f);
398 r.top = (int) (r.top * scale + 0.5f);
399 r.right = (int) (r.right * scale + 0.5f);
400 r.bottom = (int) (r.bottom * scale + 0.5f);
401 }
402 }
403
404 Rect temp = new Rect();
405 void scaleRectAboutCenter(Rect in, Rect out, float scale) {
406 int cx = in.centerX();
407 int cy = in.centerY();
408 out.set(in);
409 out.offset(-cx, -cy);
410 scaleRect(out, scale);
411 out.offset(cx, cy);
412 }
413
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700414 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700415 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700416 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
417 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
418 // When we're small, we are either drawn normally or in the "accepts drops" state (during
419 // a drag). However, we also drag the mini hover background *over* one of those two
420 // backgrounds
Winson Chungb26f3d62011-06-02 10:49:29 -0700421 if (mBackgroundAlpha > 0.0f) {
Adam Cohenf34bab52010-09-30 14:11:56 -0700422 Drawable bg;
Michael Jurka33945b22010-12-21 18:19:38 -0800423
424 if (mIsDragOverlapping) {
425 // In the mini case, we draw the active_glow bg *over* the active background
Michael Jurkabdf78552011-10-31 14:34:25 -0700426 bg = mActiveGlowBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700427 } else {
Michael Jurkabdf78552011-10-31 14:34:25 -0700428 bg = mNormalBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700429 }
Michael Jurka33945b22010-12-21 18:19:38 -0800430
431 bg.setAlpha((int) (mBackgroundAlpha * mBackgroundAlphaMultiplier * 255));
432 bg.setBounds(mBackgroundRect);
433 bg.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700434 }
Romain Guya6abce82009-11-10 02:54:41 -0800435
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700436 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700437 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700438 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700439 if (alpha > 0) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800440 final Rect r = mDragOutlines[i];
Adam Cohen307fe232012-08-16 17:55:58 -0700441 scaleRectAboutCenter(r, temp, getChildrenScale());
Joe Onorato4be866d2010-10-10 11:26:02 -0700442 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700443 paint.setAlpha((int)(alpha + .5f));
Adam Cohen307fe232012-08-16 17:55:58 -0700444 canvas.drawBitmap(b, null, temp, paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700445 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700446 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800447
448 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
449 // requires an expanded clip rect (due to the glow's blur radius)
450 if (mPressedOrFocusedIcon != null) {
451 final int padding = mPressedOrFocusedIcon.getPressedOrFocusedBackgroundPadding();
452 final Bitmap b = mPressedOrFocusedIcon.getPressedOrFocusedBackground();
453 if (b != null) {
454 canvas.drawBitmap(b,
Winson Chung4b825dcd2011-06-19 12:41:22 -0700455 mPressedOrFocusedIcon.getLeft() + getPaddingLeft() - padding,
456 mPressedOrFocusedIcon.getTop() + getPaddingTop() - padding,
Patrick Dubroy96864c32011-03-10 17:17:23 -0800457 null);
458 }
459 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700460
Adam Cohen482ed822012-03-02 14:15:13 -0800461 if (DEBUG_VISUALIZE_OCCUPIED) {
462 int[] pt = new int[2];
463 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700464 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800465 for (int i = 0; i < mCountX; i++) {
466 for (int j = 0; j < mCountY; j++) {
467 if (mOccupied[i][j]) {
468 cellToPoint(i, j, pt);
469 canvas.save();
470 canvas.translate(pt[0], pt[1]);
471 cd.draw(canvas);
472 canvas.restore();
473 }
474 }
475 }
476 }
477
Andrew Flynn850d2e72012-04-26 16:51:20 -0700478 int previewOffset = FolderRingAnimator.sPreviewSize;
479
Adam Cohen69ce2e52011-07-03 19:25:21 -0700480 // The folder outer / inner ring image(s)
481 for (int i = 0; i < mFolderOuterRings.size(); i++) {
482 FolderRingAnimator fra = mFolderOuterRings.get(i);
483
484 // Draw outer ring
485 Drawable d = FolderRingAnimator.sSharedOuterRingDrawable;
486 int width = (int) fra.getOuterRingSize();
487 int height = width;
488 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
489
490 int centerX = mTempLocation[0] + mCellWidth / 2;
Andrew Flynn850d2e72012-04-26 16:51:20 -0700491 int centerY = mTempLocation[1] + previewOffset / 2;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700492
493 canvas.save();
494 canvas.translate(centerX - width / 2, centerY - height / 2);
495 d.setBounds(0, 0, width, height);
496 d.draw(canvas);
497 canvas.restore();
498
499 // Draw inner ring
500 d = FolderRingAnimator.sSharedInnerRingDrawable;
501 width = (int) fra.getInnerRingSize();
502 height = width;
503 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
504
505 centerX = mTempLocation[0] + mCellWidth / 2;
Andrew Flynn850d2e72012-04-26 16:51:20 -0700506 centerY = mTempLocation[1] + previewOffset / 2;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700507 canvas.save();
508 canvas.translate(centerX - width / 2, centerY - width / 2);
509 d.setBounds(0, 0, width, height);
510 d.draw(canvas);
511 canvas.restore();
512 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700513
514 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
515 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
516 int width = d.getIntrinsicWidth();
517 int height = d.getIntrinsicHeight();
518
519 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
520 int centerX = mTempLocation[0] + mCellWidth / 2;
Andrew Flynn850d2e72012-04-26 16:51:20 -0700521 int centerY = mTempLocation[1] + previewOffset / 2;
Adam Cohenc51934b2011-07-26 21:07:43 -0700522
523 canvas.save();
524 canvas.translate(centerX - width / 2, centerY - width / 2);
525 d.setBounds(0, 0, width, height);
526 d.draw(canvas);
527 canvas.restore();
528 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700529 }
530
Adam Cohenb5ba0972011-09-07 18:02:31 -0700531 @Override
532 protected void dispatchDraw(Canvas canvas) {
533 super.dispatchDraw(canvas);
534 if (mForegroundAlpha > 0) {
535 mOverScrollForegroundDrawable.setBounds(mForegroundRect);
536 Paint p = ((NinePatchDrawable) mOverScrollForegroundDrawable).getPaint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700537 p.setXfermode(sAddBlendMode);
Adam Cohenb5ba0972011-09-07 18:02:31 -0700538 mOverScrollForegroundDrawable.draw(canvas);
539 p.setXfermode(null);
540 }
541 }
542
Adam Cohen69ce2e52011-07-03 19:25:21 -0700543 public void showFolderAccept(FolderRingAnimator fra) {
544 mFolderOuterRings.add(fra);
545 }
546
547 public void hideFolderAccept(FolderRingAnimator fra) {
548 if (mFolderOuterRings.contains(fra)) {
549 mFolderOuterRings.remove(fra);
550 }
551 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700552 }
553
Adam Cohenc51934b2011-07-26 21:07:43 -0700554 public void setFolderLeaveBehindCell(int x, int y) {
555 mFolderLeaveBehindCell[0] = x;
556 mFolderLeaveBehindCell[1] = y;
557 invalidate();
558 }
559
560 public void clearFolderLeaveBehind() {
561 mFolderLeaveBehindCell[0] = -1;
562 mFolderLeaveBehindCell[1] = -1;
563 invalidate();
564 }
565
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700566 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700567 public boolean shouldDelayChildPressedState() {
568 return false;
569 }
570
Adam Cohen1462de32012-07-24 22:34:36 -0700571 public void restoreInstanceState(SparseArray<Parcelable> states) {
572 dispatchRestoreInstanceState(states);
573 }
574
Michael Jurkae6235dd2011-10-04 15:02:05 -0700575 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700576 public void cancelLongPress() {
577 super.cancelLongPress();
578
579 // Cancel long press for all children
580 final int count = getChildCount();
581 for (int i = 0; i < count; i++) {
582 final View child = getChildAt(i);
583 child.cancelLongPress();
584 }
585 }
586
Michael Jurkadee05892010-07-27 10:01:56 -0700587 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
588 mInterceptTouchListener = listener;
589 }
590
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800591 int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700592 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800593 }
594
595 int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700596 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800597 }
598
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800599 public void setIsHotseat(boolean isHotseat) {
600 mIsHotseat = isHotseat;
601 }
602
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800603 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Andrew Flynn850d2e72012-04-26 16:51:20 -0700604 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700605 final LayoutParams lp = params;
606
Andrew Flynnde38e422012-05-08 11:22:15 -0700607 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800608 if (child instanceof BubbleTextView) {
609 BubbleTextView bubbleChild = (BubbleTextView) child;
610
Andrew Flynnde38e422012-05-08 11:22:15 -0700611 Resources res = getResources();
612 if (mIsHotseat) {
613 bubbleChild.setTextColor(res.getColor(android.R.color.transparent));
614 } else {
615 bubbleChild.setTextColor(res.getColor(R.color.workspace_icon_text_color));
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800616 }
617 }
618
Adam Cohen307fe232012-08-16 17:55:58 -0700619 child.setScaleX(getChildrenScale());
620 child.setScaleY(getChildrenScale());
621
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800622 // Generate an id for each view, this assumes we have at most 256x256 cells
623 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700624 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700625 // If the horizontal or vertical span is set to -1, it is taken to
626 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700627 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
628 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629
Winson Chungaafa03c2010-06-11 17:34:16 -0700630 child.setId(childId);
631
Michael Jurkaa52570f2012-03-20 03:18:20 -0700632 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700633
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700634 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700635
Winson Chungaafa03c2010-06-11 17:34:16 -0700636 return true;
637 }
638 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800639 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700640
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800641 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700642 public void removeAllViews() {
643 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700644 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700645 }
646
647 @Override
648 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700649 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700650 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700651 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700652 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700653 }
654
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700655 public void removeViewWithoutMarkingCells(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700656 mShortcutsAndWidgets.removeView(view);
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700657 }
658
Michael Jurka0280c3b2010-09-17 15:00:07 -0700659 @Override
660 public void removeView(View view) {
661 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700662 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700663 }
664
665 @Override
666 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700667 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
668 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700669 }
670
671 @Override
672 public void removeViewInLayout(View view) {
673 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700674 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700675 }
676
677 @Override
678 public void removeViews(int start, int count) {
679 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700680 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700681 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700682 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700683 }
684
685 @Override
686 public void removeViewsInLayout(int start, int count) {
687 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700688 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700689 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700690 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800691 }
692
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800693 @Override
694 protected void onAttachedToWindow() {
695 super.onAttachedToWindow();
696 mCellInfo.screen = ((ViewGroup) getParent()).indexOfChild(this);
697 }
698
Michael Jurkaaf442092010-06-10 17:01:57 -0700699 public void setTagToCellInfoForPoint(int touchX, int touchY) {
700 final CellInfo cellInfo = mCellInfo;
Winson Chungeecf02d2012-03-02 17:14:58 -0800701 Rect frame = mRect;
Michael Jurka8b805b12012-04-18 14:23:14 -0700702 final int x = touchX + getScrollX();
703 final int y = touchY + getScrollY();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700704 final int count = mShortcutsAndWidgets.getChildCount();
Michael Jurkaaf442092010-06-10 17:01:57 -0700705
706 boolean found = false;
707 for (int i = count - 1; i >= 0; i--) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700708 final View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohend4844c32011-02-18 19:25:06 -0800709 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurkaaf442092010-06-10 17:01:57 -0700710
Adam Cohen1b607ed2011-03-03 17:26:50 -0800711 if ((child.getVisibility() == VISIBLE || child.getAnimation() != null) &&
712 lp.isLockedToGrid) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700713 child.getHitRect(frame);
Winson Chung0be025d2011-05-23 17:45:09 -0700714
Winson Chungeecf02d2012-03-02 17:14:58 -0800715 float scale = child.getScaleX();
716 frame = new Rect(child.getLeft(), child.getTop(), child.getRight(),
717 child.getBottom());
Winson Chung0be025d2011-05-23 17:45:09 -0700718 // The child hit rect is relative to the CellLayoutChildren parent, so we need to
719 // offset that by this CellLayout's padding to test an (x,y) point that is relative
720 // to this view.
Michael Jurka8b805b12012-04-18 14:23:14 -0700721 frame.offset(getPaddingLeft(), getPaddingTop());
Winson Chungeecf02d2012-03-02 17:14:58 -0800722 frame.inset((int) (frame.width() * (1f - scale) / 2),
723 (int) (frame.height() * (1f - scale) / 2));
Winson Chung0be025d2011-05-23 17:45:09 -0700724
Michael Jurkaaf442092010-06-10 17:01:57 -0700725 if (frame.contains(x, y)) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700726 cellInfo.cell = child;
727 cellInfo.cellX = lp.cellX;
728 cellInfo.cellY = lp.cellY;
729 cellInfo.spanX = lp.cellHSpan;
730 cellInfo.spanY = lp.cellVSpan;
Michael Jurkaaf442092010-06-10 17:01:57 -0700731 found = true;
Michael Jurkaaf442092010-06-10 17:01:57 -0700732 break;
733 }
734 }
735 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700736
Michael Jurkad771c962011-08-09 15:00:48 -0700737 mLastDownOnOccupiedCell = found;
738
Michael Jurkaaf442092010-06-10 17:01:57 -0700739 if (!found) {
Winson Chung0be025d2011-05-23 17:45:09 -0700740 final int cellXY[] = mTmpXY;
Michael Jurkaaf442092010-06-10 17:01:57 -0700741 pointToCellExact(x, y, cellXY);
742
Michael Jurkaaf442092010-06-10 17:01:57 -0700743 cellInfo.cell = null;
744 cellInfo.cellX = cellXY[0];
745 cellInfo.cellY = cellXY[1];
746 cellInfo.spanX = 1;
747 cellInfo.spanY = 1;
Michael Jurkaaf442092010-06-10 17:01:57 -0700748 }
749 setTag(cellInfo);
750 }
751
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800752 @Override
753 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohenc1997fd2011-08-15 18:26:39 -0700754 // First we clear the tag to ensure that on every touch down we start with a fresh slate,
755 // even in the case where we return early. Not clearing here was causing bugs whereby on
756 // long-press we'd end up picking up an item from a previous drag operation.
757 final int action = ev.getAction();
758
759 if (action == MotionEvent.ACTION_DOWN) {
760 clearTagCellInfo();
761 }
762
Michael Jurkadee05892010-07-27 10:01:56 -0700763 if (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev)) {
764 return true;
765 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800766
767 if (action == MotionEvent.ACTION_DOWN) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700768 setTagToCellInfoForPoint((int) ev.getX(), (int) ev.getY());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800769 }
Winson Chungeecf02d2012-03-02 17:14:58 -0800770
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800771 return false;
772 }
773
Adam Cohenc1997fd2011-08-15 18:26:39 -0700774 private void clearTagCellInfo() {
775 final CellInfo cellInfo = mCellInfo;
776 cellInfo.cell = null;
777 cellInfo.cellX = -1;
778 cellInfo.cellY = -1;
779 cellInfo.spanX = 0;
780 cellInfo.spanY = 0;
781 setTag(cellInfo);
782 }
783
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800784 public CellInfo getTag() {
Michael Jurka0280c3b2010-09-17 15:00:07 -0700785 return (CellInfo) super.getTag();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800786 }
787
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700788 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700789 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800790 * @param x X coordinate of the point
791 * @param y Y coordinate of the point
792 * @param result Array of 2 ints to hold the x and y coordinate of the cell
793 */
794 void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700795 final int hStartPadding = getPaddingLeft();
796 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800797
798 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
799 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
800
Adam Cohend22015c2010-07-26 22:02:18 -0700801 final int xAxis = mCountX;
802 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800803
804 if (result[0] < 0) result[0] = 0;
805 if (result[0] >= xAxis) result[0] = xAxis - 1;
806 if (result[1] < 0) result[1] = 0;
807 if (result[1] >= yAxis) result[1] = yAxis - 1;
808 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700809
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800810 /**
811 * Given a point, return the cell that most closely encloses that point
812 * @param x X coordinate of the point
813 * @param y Y coordinate of the point
814 * @param result Array of 2 ints to hold the x and y coordinate of the cell
815 */
816 void pointToCellRounded(int x, int y, int[] result) {
817 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
818 }
819
820 /**
821 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700822 *
823 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800824 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700825 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800826 * @param result Array of 2 ints to hold the x and y coordinate of the point
827 */
828 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700829 final int hStartPadding = getPaddingLeft();
830 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800831
832 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
833 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
834 }
835
Adam Cohene3e27a82011-04-15 12:07:39 -0700836 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800837 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700838 *
839 * @param cellX X coordinate of the cell
840 * @param cellY Y coordinate of the cell
841 *
842 * @param result Array of 2 ints to hold the x and y coordinate of the point
843 */
844 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700845 regionToCenterPoint(cellX, cellY, 1, 1, result);
846 }
847
848 /**
849 * Given a cell coordinate and span return the point that represents the center of the regio
850 *
851 * @param cellX X coordinate of the cell
852 * @param cellY Y coordinate of the cell
853 *
854 * @param result Array of 2 ints to hold the x and y coordinate of the point
855 */
856 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700857 final int hStartPadding = getPaddingLeft();
858 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700859 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
860 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
861 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
862 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700863 }
864
Adam Cohen19f37922012-03-21 11:59:11 -0700865 /**
866 * Given a cell coordinate and span fills out a corresponding pixel rect
867 *
868 * @param cellX X coordinate of the cell
869 * @param cellY Y coordinate of the cell
870 * @param result Rect in which to write the result
871 */
872 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
873 final int hStartPadding = getPaddingLeft();
874 final int vStartPadding = getPaddingTop();
875 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
876 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
877 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
878 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
879 }
880
Adam Cohen482ed822012-03-02 14:15:13 -0800881 public float getDistanceFromCell(float x, float y, int[] cell) {
882 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
883 float distance = (float) Math.sqrt( Math.pow(x - mTmpPoint[0], 2) +
884 Math.pow(y - mTmpPoint[1], 2));
885 return distance;
886 }
887
Romain Guy84f296c2009-11-04 15:00:44 -0800888 int getCellWidth() {
889 return mCellWidth;
890 }
891
892 int getCellHeight() {
893 return mCellHeight;
894 }
895
Adam Cohend4844c32011-02-18 19:25:06 -0800896 int getWidthGap() {
897 return mWidthGap;
898 }
899
900 int getHeightGap() {
901 return mHeightGap;
902 }
903
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700904 Rect getContentRect(Rect r) {
905 if (r == null) {
906 r = new Rect();
907 }
908 int left = getPaddingLeft();
909 int top = getPaddingTop();
Michael Jurka8b805b12012-04-18 14:23:14 -0700910 int right = left + getWidth() - getPaddingLeft() - getPaddingRight();
911 int bottom = top + getHeight() - getPaddingTop() - getPaddingBottom();
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700912 r.set(left, top, right, bottom);
913 return r;
914 }
915
Adam Cohena897f392012-04-27 18:12:05 -0700916 static void getMetrics(Rect metrics, Resources res, int measureWidth, int measureHeight,
917 int countX, int countY, int orientation) {
918 int numWidthGaps = countX - 1;
919 int numHeightGaps = countY - 1;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700920
921 int widthGap;
922 int heightGap;
923 int cellWidth;
924 int cellHeight;
925 int paddingLeft;
926 int paddingRight;
927 int paddingTop;
928 int paddingBottom;
929
Adam Cohena897f392012-04-27 18:12:05 -0700930 int maxGap = res.getDimensionPixelSize(R.dimen.workspace_max_gap);
Adam Cohenf4bd5792012-04-27 11:35:29 -0700931 if (orientation == LANDSCAPE) {
932 cellWidth = res.getDimensionPixelSize(R.dimen.workspace_cell_width_land);
933 cellHeight = res.getDimensionPixelSize(R.dimen.workspace_cell_height_land);
934 widthGap = res.getDimensionPixelSize(R.dimen.workspace_width_gap_land);
935 heightGap = res.getDimensionPixelSize(R.dimen.workspace_height_gap_land);
936 paddingLeft = res.getDimensionPixelSize(R.dimen.cell_layout_left_padding_land);
937 paddingRight = res.getDimensionPixelSize(R.dimen.cell_layout_right_padding_land);
938 paddingTop = res.getDimensionPixelSize(R.dimen.cell_layout_top_padding_land);
939 paddingBottom = res.getDimensionPixelSize(R.dimen.cell_layout_bottom_padding_land);
940 } else {
941 // PORTRAIT
942 cellWidth = res.getDimensionPixelSize(R.dimen.workspace_cell_width_port);
943 cellHeight = res.getDimensionPixelSize(R.dimen.workspace_cell_height_port);
944 widthGap = res.getDimensionPixelSize(R.dimen.workspace_width_gap_port);
945 heightGap = res.getDimensionPixelSize(R.dimen.workspace_height_gap_port);
946 paddingLeft = res.getDimensionPixelSize(R.dimen.cell_layout_left_padding_port);
947 paddingRight = res.getDimensionPixelSize(R.dimen.cell_layout_right_padding_port);
948 paddingTop = res.getDimensionPixelSize(R.dimen.cell_layout_top_padding_port);
949 paddingBottom = res.getDimensionPixelSize(R.dimen.cell_layout_bottom_padding_port);
950 }
951
952 if (widthGap < 0 || heightGap < 0) {
953 int hSpace = measureWidth - paddingLeft - paddingRight;
954 int vSpace = measureHeight - paddingTop - paddingBottom;
Adam Cohena897f392012-04-27 18:12:05 -0700955 int hFreeSpace = hSpace - (countX * cellWidth);
956 int vFreeSpace = vSpace - (countY * cellHeight);
957 widthGap = Math.min(maxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
958 heightGap = Math.min(maxGap, numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Adam Cohenf4bd5792012-04-27 11:35:29 -0700959 }
960 metrics.set(cellWidth, cellHeight, widthGap, heightGap);
961 }
962
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800963 @Override
964 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800965 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700966 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
967
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800968 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
969 int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700970
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800971 if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
972 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
973 }
974
Adam Cohend22015c2010-07-26 22:02:18 -0700975 int numWidthGaps = mCountX - 1;
976 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800977
Adam Cohen234c4cd2011-07-17 21:03:04 -0700978 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Michael Jurkadd13e3d2012-05-01 12:38:17 -0700979 int hSpace = widthSpecSize - getPaddingLeft() - getPaddingRight();
980 int vSpace = heightSpecSize - getPaddingTop() - getPaddingBottom();
Adam Cohenf4bd5792012-04-27 11:35:29 -0700981 int hFreeSpace = hSpace - (mCountX * mCellWidth);
982 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700983 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
984 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700985 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700986 } else {
987 mWidthGap = mOriginalWidthGap;
988 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700989 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700990
Michael Jurka8c920dd2011-01-20 14:16:56 -0800991 // Initial values correspond to widthSpecMode == MeasureSpec.EXACTLY
992 int newWidth = widthSpecSize;
993 int newHeight = heightSpecSize;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700994 if (widthSpecMode == MeasureSpec.AT_MOST) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700995 newWidth = getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700996 ((mCountX - 1) * mWidthGap);
Michael Jurka8b805b12012-04-18 14:23:14 -0700997 newHeight = getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700998 ((mCountY - 1) * mHeightGap);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700999 setMeasuredDimension(newWidth, newHeight);
Michael Jurka5f1c5092010-09-03 14:15:02 -07001000 }
Michael Jurka8c920dd2011-01-20 14:16:56 -08001001
1002 int count = getChildCount();
1003 for (int i = 0; i < count; i++) {
1004 View child = getChildAt(i);
Michael Jurka8b805b12012-04-18 14:23:14 -07001005 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth - getPaddingLeft() -
1006 getPaddingRight(), MeasureSpec.EXACTLY);
1007 int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight - getPaddingTop() -
1008 getPaddingBottom(), MeasureSpec.EXACTLY);
Michael Jurka8c920dd2011-01-20 14:16:56 -08001009 child.measure(childWidthMeasureSpec, childheightMeasureSpec);
1010 }
1011 setMeasuredDimension(newWidth, newHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001012 }
1013
1014 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -07001015 protected void onLayout(boolean changed, int l, int t, int r, int b) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001016 int count = getChildCount();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001017 for (int i = 0; i < count; i++) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08001018 View child = getChildAt(i);
Michael Jurka8b805b12012-04-18 14:23:14 -07001019 child.layout(getPaddingLeft(), getPaddingTop(),
1020 r - l - getPaddingRight(), b - t - getPaddingBottom());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001021 }
1022 }
1023
1024 @Override
Michael Jurkadee05892010-07-27 10:01:56 -07001025 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1026 super.onSizeChanged(w, h, oldw, oldh);
Michael Jurka18014792010-10-14 09:01:34 -07001027 mBackgroundRect.set(0, 0, w, h);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001028 mForegroundRect.set(mForegroundPadding, mForegroundPadding,
1029 w - 2 * mForegroundPadding, h - 2 * mForegroundPadding);
Michael Jurkadee05892010-07-27 10:01:56 -07001030 }
1031
1032 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001033 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001034 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001035 }
1036
1037 @Override
1038 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001039 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001040 }
1041
Michael Jurka5f1c5092010-09-03 14:15:02 -07001042 public float getBackgroundAlpha() {
1043 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -07001044 }
1045
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001046 public void setBackgroundAlphaMultiplier(float multiplier) {
Michael Jurkaa3d30ad2012-05-08 13:43:43 -07001047 if (mBackgroundAlphaMultiplier != multiplier) {
1048 mBackgroundAlphaMultiplier = multiplier;
1049 invalidate();
1050 }
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001051 }
1052
Adam Cohenddb82192010-11-10 16:32:54 -08001053 public float getBackgroundAlphaMultiplier() {
1054 return mBackgroundAlphaMultiplier;
1055 }
1056
Michael Jurka5f1c5092010-09-03 14:15:02 -07001057 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -08001058 if (mBackgroundAlpha != alpha) {
1059 mBackgroundAlpha = alpha;
1060 invalidate();
1061 }
Michael Jurkadee05892010-07-27 10:01:56 -07001062 }
1063
Michael Jurkaa52570f2012-03-20 03:18:20 -07001064 public void setShortcutAndWidgetAlpha(float alpha) {
Michael Jurka0142d492010-08-25 17:46:15 -07001065 final int childCount = getChildCount();
1066 for (int i = 0; i < childCount; i++) {
Michael Jurkadee05892010-07-27 10:01:56 -07001067 getChildAt(i).setAlpha(alpha);
1068 }
1069 }
1070
Michael Jurkaa52570f2012-03-20 03:18:20 -07001071 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
1072 if (getChildCount() > 0) {
1073 return (ShortcutAndWidgetContainer) getChildAt(0);
1074 }
1075 return null;
1076 }
1077
Patrick Dubroy440c3602010-07-13 17:50:32 -07001078 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001079 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001080 }
1081
Adam Cohen76fc0852011-06-17 13:26:23 -07001082 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001083 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001084 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -08001085 boolean[][] occupied = mOccupied;
1086 if (!permanent) {
1087 occupied = mTmpOccupied;
1088 }
1089
Adam Cohen19f37922012-03-21 11:59:11 -07001090 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001091 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
1092 final ItemInfo info = (ItemInfo) child.getTag();
1093
1094 // We cancel any existing animations
1095 if (mReorderAnimators.containsKey(lp)) {
1096 mReorderAnimators.get(lp).cancel();
1097 mReorderAnimators.remove(lp);
1098 }
1099
Adam Cohen482ed822012-03-02 14:15:13 -08001100 final int oldX = lp.x;
1101 final int oldY = lp.y;
1102 if (adjustOccupied) {
1103 occupied[lp.cellX][lp.cellY] = false;
1104 occupied[cellX][cellY] = true;
1105 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001106 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001107 if (permanent) {
1108 lp.cellX = info.cellX = cellX;
1109 lp.cellY = info.cellY = cellY;
1110 } else {
1111 lp.tmpCellX = cellX;
1112 lp.tmpCellY = cellY;
1113 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001114 clc.setupLp(lp);
1115 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001116 final int newX = lp.x;
1117 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001118
Adam Cohen76fc0852011-06-17 13:26:23 -07001119 lp.x = oldX;
1120 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001121
Adam Cohen482ed822012-03-02 14:15:13 -08001122 // Exit early if we're not actually moving the view
1123 if (oldX == newX && oldY == newY) {
1124 lp.isLockedToGrid = true;
1125 return true;
1126 }
1127
Michael Jurka2ecf9952012-06-18 12:52:28 -07001128 ValueAnimator va = LauncherAnimUtils.ofFloat(0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001129 va.setDuration(duration);
1130 mReorderAnimators.put(lp, va);
1131
1132 va.addUpdateListener(new AnimatorUpdateListener() {
1133 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001134 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001135 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001136 lp.x = (int) ((1 - r) * oldX + r * newX);
1137 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001138 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001139 }
1140 });
Adam Cohen482ed822012-03-02 14:15:13 -08001141 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001142 boolean cancelled = false;
1143 public void onAnimationEnd(Animator animation) {
1144 // If the animation was cancelled, it means that another animation
1145 // has interrupted this one, and we don't want to lock the item into
1146 // place just yet.
1147 if (!cancelled) {
1148 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001149 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001150 }
1151 if (mReorderAnimators.containsKey(lp)) {
1152 mReorderAnimators.remove(lp);
1153 }
1154 }
1155 public void onAnimationCancel(Animator animation) {
1156 cancelled = true;
1157 }
1158 });
Adam Cohen482ed822012-03-02 14:15:13 -08001159 va.setStartDelay(delay);
1160 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001161 return true;
1162 }
1163 return false;
1164 }
1165
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001166 /**
1167 * Estimate where the top left cell of the dragged item will land if it is dropped.
1168 *
1169 * @param originX The X value of the top left corner of the item
1170 * @param originY The Y value of the top left corner of the item
1171 * @param spanX The number of horizontal cells that the item spans
1172 * @param spanY The number of vertical cells that the item spans
1173 * @param result The estimated drop cell X and Y.
1174 */
1175 void estimateDropCell(int originX, int originY, int spanX, int spanY, int[] result) {
Adam Cohend22015c2010-07-26 22:02:18 -07001176 final int countX = mCountX;
1177 final int countY = mCountY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001178
Michael Jurkaa63c4522010-08-19 13:52:27 -07001179 // pointToCellRounded takes the top left of a cell but will pad that with
1180 // cellWidth/2 and cellHeight/2 when finding the matching cell
1181 pointToCellRounded(originX, originY, result);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001182
1183 // If the item isn't fully on this screen, snap to the edges
1184 int rightOverhang = result[0] + spanX - countX;
1185 if (rightOverhang > 0) {
1186 result[0] -= rightOverhang; // Snap to right
1187 }
1188 result[0] = Math.max(0, result[0]); // Snap to left
1189 int bottomOverhang = result[1] + spanY - countY;
1190 if (bottomOverhang > 0) {
1191 result[1] -= bottomOverhang; // Snap to bottom
1192 }
1193 result[1] = Math.max(0, result[1]); // Snap to top
1194 }
1195
Adam Cohen482ed822012-03-02 14:15:13 -08001196 void visualizeDropLocation(View v, Bitmap dragOutline, int originX, int originY, int cellX,
1197 int cellY, int spanX, int spanY, boolean resize, Point dragOffset, Rect dragRegion) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001198 final int oldDragCellX = mDragCell[0];
1199 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001200
Winson Chungb8c69f32011-10-19 21:36:08 -07001201 if (v != null && dragOffset == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07001202 mDragCenter.set(originX + (v.getWidth() / 2), originY + (v.getHeight() / 2));
1203 } else {
1204 mDragCenter.set(originX, originY);
1205 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001206
Adam Cohen2801caf2011-05-13 20:57:39 -07001207 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001208 return;
1209 }
1210
Adam Cohen482ed822012-03-02 14:15:13 -08001211 if (cellX != oldDragCellX || cellY != oldDragCellY) {
1212 mDragCell[0] = cellX;
1213 mDragCell[1] = cellY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001214 // Find the top left corner of the rect the object will occupy
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001215 final int[] topLeft = mTmpPoint;
Adam Cohen482ed822012-03-02 14:15:13 -08001216 cellToPoint(cellX, cellY, topLeft);
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001217
Joe Onorato4be866d2010-10-10 11:26:02 -07001218 int left = topLeft[0];
1219 int top = topLeft[1];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001220
Winson Chungb8c69f32011-10-19 21:36:08 -07001221 if (v != null && dragOffset == null) {
Adam Cohen99e8b402011-03-25 19:23:43 -07001222 // When drawing the drag outline, it did not account for margin offsets
1223 // added by the view's parent.
1224 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1225 left += lp.leftMargin;
1226 top += lp.topMargin;
Winson Chung150fbab2010-09-29 17:14:26 -07001227
Adam Cohen99e8b402011-03-25 19:23:43 -07001228 // Offsets due to the size difference between the View and the dragOutline.
1229 // There is a size difference to account for the outer blur, which may lie
1230 // outside the bounds of the view.
Winson Chunga9abd0e2010-10-27 17:18:37 -07001231 top += (v.getHeight() - dragOutline.getHeight()) / 2;
Adam Cohenae915ce2011-08-25 13:47:22 -07001232 // We center about the x axis
1233 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1234 - dragOutline.getWidth()) / 2;
Adam Cohen66396872011-04-15 17:50:36 -07001235 } else {
Winson Chungb8c69f32011-10-19 21:36:08 -07001236 if (dragOffset != null && dragRegion != null) {
1237 // Center the drag region *horizontally* in the cell and apply a drag
1238 // outline offset
1239 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1240 - dragRegion.width()) / 2;
1241 top += dragOffset.y;
1242 } else {
1243 // Center the drag outline in the cell
1244 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1245 - dragOutline.getWidth()) / 2;
1246 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1247 - dragOutline.getHeight()) / 2;
1248 }
Winson Chunga9abd0e2010-10-27 17:18:37 -07001249 }
Joe Onorato4be866d2010-10-10 11:26:02 -07001250 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001251 mDragOutlineAnims[oldIndex].animateOut();
1252 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001253 Rect r = mDragOutlines[mDragOutlineCurrent];
1254 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
1255 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001256 cellToRect(cellX, cellY, spanX, spanY, r);
Adam Cohend41fbf52012-02-16 23:53:59 -08001257 }
Winson Chung150fbab2010-09-29 17:14:26 -07001258
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001259 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1260 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001261 }
1262 }
1263
Adam Cohene0310962011-04-18 16:15:31 -07001264 public void clearDragOutlines() {
1265 final int oldIndex = mDragOutlineCurrent;
1266 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001267 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001268 }
1269
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001270 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001271 * Find a vacant area that will fit the given bounds nearest the requested
1272 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001273 *
Romain Guy51afc022009-05-04 18:03:43 -07001274 * @param pixelX The X location at which you want to search for a vacant area.
1275 * @param pixelY The Y location at which you want to search for a vacant area.
Jeff Sharkey70864282009-04-07 21:08:40 -07001276 * @param spanX Horizontal span of the object.
1277 * @param spanY Vertical span of the object.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001278 * @param result Array in which to place the result, or null (in which case a new array will
1279 * be allocated)
Jeff Sharkey70864282009-04-07 21:08:40 -07001280 * @return The X, Y cell of a vacant area that can contain this object,
1281 * nearest the requested location.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001282 */
Adam Cohend41fbf52012-02-16 23:53:59 -08001283 int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY,
1284 int[] result) {
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001285 return findNearestVacantArea(pixelX, pixelY, spanX, spanY, null, result);
Michael Jurka6a1435d2010-09-27 17:35:12 -07001286 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001287
Michael Jurka6a1435d2010-09-27 17:35:12 -07001288 /**
1289 * Find a vacant area that will fit the given bounds nearest the requested
1290 * cell location. Uses Euclidean distance to score multiple vacant areas.
1291 *
1292 * @param pixelX The X location at which you want to search for a vacant area.
1293 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001294 * @param minSpanX The minimum horizontal span required
1295 * @param minSpanY The minimum vertical span required
1296 * @param spanX Horizontal span of the object.
1297 * @param spanY Vertical span of the object.
1298 * @param result Array in which to place the result, or null (in which case a new array will
1299 * be allocated)
1300 * @return The X, Y cell of a vacant area that can contain this object,
1301 * nearest the requested location.
1302 */
1303 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1304 int spanY, int[] result, int[] resultSpan) {
1305 return findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null,
1306 result, resultSpan);
1307 }
1308
1309 /**
1310 * Find a vacant area that will fit the given bounds nearest the requested
1311 * cell location. Uses Euclidean distance to score multiple vacant areas.
1312 *
1313 * @param pixelX The X location at which you want to search for a vacant area.
1314 * @param pixelY The Y location at which you want to search for a vacant area.
Michael Jurka6a1435d2010-09-27 17:35:12 -07001315 * @param spanX Horizontal span of the object.
1316 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07001317 * @param ignoreOccupied If true, the result can be an occupied cell
1318 * @param result Array in which to place the result, or null (in which case a new array will
1319 * be allocated)
Michael Jurka6a1435d2010-09-27 17:35:12 -07001320 * @return The X, Y cell of a vacant area that can contain this object,
1321 * nearest the requested location.
1322 */
Adam Cohendf035382011-04-11 17:22:04 -07001323 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, View ignoreView,
1324 boolean ignoreOccupied, int[] result) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001325 return findNearestArea(pixelX, pixelY, spanX, spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001326 spanX, spanY, ignoreView, ignoreOccupied, result, null, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08001327 }
1328
1329 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1330 private void lazyInitTempRectStack() {
1331 if (mTempRectStack.isEmpty()) {
1332 for (int i = 0; i < mCountX * mCountY; i++) {
1333 mTempRectStack.push(new Rect());
1334 }
1335 }
1336 }
Adam Cohen482ed822012-03-02 14:15:13 -08001337
Adam Cohend41fbf52012-02-16 23:53:59 -08001338 private void recycleTempRects(Stack<Rect> used) {
1339 while (!used.isEmpty()) {
1340 mTempRectStack.push(used.pop());
1341 }
1342 }
1343
1344 /**
1345 * Find a vacant area that will fit the given bounds nearest the requested
1346 * cell location. Uses Euclidean distance to score multiple vacant areas.
1347 *
1348 * @param pixelX The X location at which you want to search for a vacant area.
1349 * @param pixelY The Y location at which you want to search for a vacant area.
1350 * @param minSpanX The minimum horizontal span required
1351 * @param minSpanY The minimum vertical span required
1352 * @param spanX Horizontal span of the object.
1353 * @param spanY Vertical span of the object.
1354 * @param ignoreOccupied If true, the result can be an occupied cell
1355 * @param result Array in which to place the result, or null (in which case a new array will
1356 * be allocated)
1357 * @return The X, Y cell of a vacant area that can contain this object,
1358 * nearest the requested location.
1359 */
1360 int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001361 View ignoreView, boolean ignoreOccupied, int[] result, int[] resultSpan,
1362 boolean[][] occupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001363 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001364 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08001365 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001366
Adam Cohene3e27a82011-04-15 12:07:39 -07001367 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1368 // to the center of the item, but we are searching based on the top-left cell, so
1369 // we translate the point over to correspond to the top-left.
1370 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1371 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1372
Jeff Sharkey70864282009-04-07 21:08:40 -07001373 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001374 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001375 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001376 final Rect bestRect = new Rect(-1, -1, -1, -1);
1377 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001378
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001379 final int countX = mCountX;
1380 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001381
Adam Cohend41fbf52012-02-16 23:53:59 -08001382 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1383 spanX < minSpanX || spanY < minSpanY) {
1384 return bestXY;
1385 }
1386
1387 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001388 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001389 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1390 int ySize = -1;
1391 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001392 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001393 // First, let's see if this thing fits anywhere
1394 for (int i = 0; i < minSpanX; i++) {
1395 for (int j = 0; j < minSpanY; j++) {
Adam Cohendf035382011-04-11 17:22:04 -07001396 if (occupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001397 continue inner;
1398 }
Michael Jurkac28de512010-08-13 11:27:44 -07001399 }
1400 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001401 xSize = minSpanX;
1402 ySize = minSpanY;
1403
1404 // We know that the item will fit at _some_ acceptable size, now let's see
1405 // how big we can make it. We'll alternate between incrementing x and y spans
1406 // until we hit a limit.
1407 boolean incX = true;
1408 boolean hitMaxX = xSize >= spanX;
1409 boolean hitMaxY = ySize >= spanY;
1410 while (!(hitMaxX && hitMaxY)) {
1411 if (incX && !hitMaxX) {
1412 for (int j = 0; j < ySize; j++) {
1413 if (x + xSize > countX -1 || occupied[x + xSize][y + j]) {
1414 // We can't move out horizontally
1415 hitMaxX = true;
1416 }
1417 }
1418 if (!hitMaxX) {
1419 xSize++;
1420 }
1421 } else if (!hitMaxY) {
1422 for (int i = 0; i < xSize; i++) {
1423 if (y + ySize > countY - 1 || occupied[x + i][y + ySize]) {
1424 // We can't move out vertically
1425 hitMaxY = true;
1426 }
1427 }
1428 if (!hitMaxY) {
1429 ySize++;
1430 }
1431 }
1432 hitMaxX |= xSize >= spanX;
1433 hitMaxY |= ySize >= spanY;
1434 incX = !incX;
1435 }
1436 incX = true;
1437 hitMaxX = xSize >= spanX;
1438 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001439 }
Winson Chung0be025d2011-05-23 17:45:09 -07001440 final int[] cellXY = mTmpXY;
Adam Cohene3e27a82011-04-15 12:07:39 -07001441 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001442
Adam Cohend41fbf52012-02-16 23:53:59 -08001443 // We verify that the current rect is not a sub-rect of any of our previous
1444 // candidates. In this case, the current rect is disqualified in favour of the
1445 // containing rect.
1446 Rect currentRect = mTempRectStack.pop();
1447 currentRect.set(x, y, x + xSize, y + ySize);
1448 boolean contained = false;
1449 for (Rect r : validRegions) {
1450 if (r.contains(currentRect)) {
1451 contained = true;
1452 break;
1453 }
1454 }
1455 validRegions.push(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001456 double distance = Math.sqrt(Math.pow(cellXY[0] - pixelX, 2)
1457 + Math.pow(cellXY[1] - pixelY, 2));
Adam Cohen482ed822012-03-02 14:15:13 -08001458
Adam Cohend41fbf52012-02-16 23:53:59 -08001459 if ((distance <= bestDistance && !contained) ||
1460 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001461 bestDistance = distance;
1462 bestXY[0] = x;
1463 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001464 if (resultSpan != null) {
1465 resultSpan[0] = xSize;
1466 resultSpan[1] = ySize;
1467 }
1468 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001469 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001470 }
1471 }
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001472 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08001473 markCellsAsOccupiedForView(ignoreView, occupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001474
Adam Cohenc0dcf592011-06-01 15:30:43 -07001475 // Return -1, -1 if no suitable location found
1476 if (bestDistance == Double.MAX_VALUE) {
1477 bestXY[0] = -1;
1478 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001479 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001480 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001481 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001482 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001483
Adam Cohen482ed822012-03-02 14:15:13 -08001484 /**
1485 * Find a vacant area that will fit the given bounds nearest the requested
1486 * cell location, and will also weigh in a suggested direction vector of the
1487 * desired location. This method computers distance based on unit grid distances,
1488 * not pixel distances.
1489 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001490 * @param cellX The X cell nearest to which you want to search for a vacant area.
1491 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001492 * @param spanX Horizontal span of the object.
1493 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001494 * @param direction The favored direction in which the views should move from x, y
1495 * @param exactDirectionOnly If this parameter is true, then only solutions where the direction
1496 * matches exactly. Otherwise we find the best matching direction.
1497 * @param occoupied The array which represents which cells in the CellLayout are occupied
1498 * @param blockOccupied The array which represents which cells in the specified block (cellX,
1499 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001500 * @param result Array in which to place the result, or null (in which case a new array will
1501 * be allocated)
1502 * @return The X, Y cell of a vacant area that can contain this object,
1503 * nearest the requested location.
1504 */
1505 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001506 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001507 // Keep track of best-scoring drop area
1508 final int[] bestXY = result != null ? result : new int[2];
1509 float bestDistance = Float.MAX_VALUE;
1510 int bestDirectionScore = Integer.MIN_VALUE;
1511
1512 final int countX = mCountX;
1513 final int countY = mCountY;
1514
1515 for (int y = 0; y < countY - (spanY - 1); y++) {
1516 inner:
1517 for (int x = 0; x < countX - (spanX - 1); x++) {
1518 // First, let's see if this thing fits anywhere
1519 for (int i = 0; i < spanX; i++) {
1520 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001521 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001522 continue inner;
1523 }
1524 }
1525 }
1526
1527 float distance = (float)
1528 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1529 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001530 computeDirectionVector(x - cellX, y - cellY, curDirection);
1531 // The direction score is just the dot product of the two candidate direction
1532 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001533 int curDirectionScore = direction[0] * curDirection[0] +
1534 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001535 boolean exactDirectionOnly = false;
1536 boolean directionMatches = direction[0] == curDirection[0] &&
1537 direction[0] == curDirection[0];
1538 if ((directionMatches || !exactDirectionOnly) &&
1539 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001540 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1541 bestDistance = distance;
1542 bestDirectionScore = curDirectionScore;
1543 bestXY[0] = x;
1544 bestXY[1] = y;
1545 }
1546 }
1547 }
1548
1549 // Return -1, -1 if no suitable location found
1550 if (bestDistance == Float.MAX_VALUE) {
1551 bestXY[0] = -1;
1552 bestXY[1] = -1;
1553 }
1554 return bestXY;
1555 }
1556
Adam Cohen47a876d2012-03-19 13:21:41 -07001557 private int[] findNearestAreaInDirection(int cellX, int cellY, int spanX, int spanY,
1558 int[] direction,boolean[][] occupied,
1559 boolean blockOccupied[][], int[] result) {
1560 // Keep track of best-scoring drop area
1561 final int[] bestXY = result != null ? result : new int[2];
1562 bestXY[0] = -1;
1563 bestXY[1] = -1;
1564 float bestDistance = Float.MAX_VALUE;
1565
1566 // We use this to march in a single direction
Adam Cohen5b53f292012-03-29 14:30:35 -07001567 if ((direction[0] != 0 && direction[1] != 0) ||
1568 (direction[0] == 0 && direction[1] == 0)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001569 return bestXY;
1570 }
1571
1572 // This will only incrememnet one of x or y based on the assertion above
1573 int x = cellX + direction[0];
1574 int y = cellY + direction[1];
1575 while (x >= 0 && x + spanX <= mCountX && y >= 0 && y + spanY <= mCountY) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001576 boolean fail = false;
1577 for (int i = 0; i < spanX; i++) {
1578 for (int j = 0; j < spanY; j++) {
1579 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1580 fail = true;
1581 }
1582 }
1583 }
1584 if (!fail) {
1585 float distance = (float)
1586 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1587 if (Float.compare(distance, bestDistance) < 0) {
1588 bestDistance = distance;
1589 bestXY[0] = x;
1590 bestXY[1] = y;
1591 }
1592 }
1593 x += direction[0];
1594 y += direction[1];
1595 }
1596 return bestXY;
1597 }
1598
Adam Cohen482ed822012-03-02 14:15:13 -08001599 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001600 int[] direction, ItemConfiguration currentState) {
1601 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001602 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001603 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001604 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1605
Adam Cohen8baab352012-03-20 17:39:21 -07001606 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001607
1608 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001609 c.x = mTempLocation[0];
1610 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001611 success = true;
1612
1613 }
Adam Cohen8baab352012-03-20 17:39:21 -07001614 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001615 return success;
1616 }
1617
Adam Cohena56dc102012-07-13 13:41:42 -07001618 // This method looks in the specified direction to see if there are additional views adjacent
1619 // to the current set of views in the. If there is, then these views are added to the current
1620 // set of views. This is performed iteratively, giving a cascading push behaviour.
Adam Cohen47a876d2012-03-19 13:21:41 -07001621 private boolean addViewInDirection(ArrayList<View> views, Rect boundingRect, int[] direction,
Adam Cohen19f37922012-03-21 11:59:11 -07001622 boolean[][] occupied, View dragView, ItemConfiguration currentState) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001623 boolean found = false;
1624
Michael Jurkaa52570f2012-03-20 03:18:20 -07001625 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen47a876d2012-03-19 13:21:41 -07001626 Rect r0 = new Rect(boundingRect);
1627 Rect r1 = new Rect();
1628
Adam Cohena56dc102012-07-13 13:41:42 -07001629 // First, we consider the rect of the views that we are trying to translate
Adam Cohen47a876d2012-03-19 13:21:41 -07001630 int deltaX = 0;
1631 int deltaY = 0;
1632 if (direction[1] < 0) {
Adam Cohena56dc102012-07-13 13:41:42 -07001633 r0.set(r0.left, r0.top - 1, r0.right, r0.bottom - 1);
Adam Cohen47a876d2012-03-19 13:21:41 -07001634 deltaY = -1;
1635 } else if (direction[1] > 0) {
Adam Cohena56dc102012-07-13 13:41:42 -07001636 r0.set(r0.left, r0.top + 1, r0.right, r0.bottom + 1);
Adam Cohen47a876d2012-03-19 13:21:41 -07001637 deltaY = 1;
1638 } else if (direction[0] < 0) {
Adam Cohena56dc102012-07-13 13:41:42 -07001639 r0.set(r0.left - 1, r0.top, r0.right - 1, r0.bottom);
Adam Cohen47a876d2012-03-19 13:21:41 -07001640 deltaX = -1;
1641 } else if (direction[0] > 0) {
Adam Cohena56dc102012-07-13 13:41:42 -07001642 r0.set(r0.left + 1, r0.top, r0.right + 1, r0.bottom);
Adam Cohen47a876d2012-03-19 13:21:41 -07001643 deltaX = 1;
1644 }
1645
Adam Cohena56dc102012-07-13 13:41:42 -07001646 // Now we see which views, if any, are being overlapped by shifting the current group
1647 // of views in the desired direction.
Adam Cohen47a876d2012-03-19 13:21:41 -07001648 for (int i = 0; i < childCount; i++) {
Adam Cohena56dc102012-07-13 13:41:42 -07001649 // We don't need to worry about views already in our group, or the current drag view.
Michael Jurkaa52570f2012-03-20 03:18:20 -07001650 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen19f37922012-03-21 11:59:11 -07001651 if (views.contains(child) || child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001652 CellAndSpan c = currentState.map.get(child);
Adam Cohen47a876d2012-03-19 13:21:41 -07001653
Adam Cohen8baab352012-03-20 17:39:21 -07001654 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1655 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001656 if (Rect.intersects(r0, r1)) {
1657 if (!lp.canReorder) {
1658 return false;
1659 }
Adam Cohena56dc102012-07-13 13:41:42 -07001660 // First we verify that the view in question is at the border of the extents
1661 // of the block of items we are pushing
1662 if ((direction[0] < 0 && c.x == r0.left) ||
1663 (direction[0] > 0 && c.x == r0.right - 1) ||
1664 (direction[1] < 0 && c.y == r0.top) ||
1665 (direction[1] > 0 && c.y == r0.bottom - 1)) {
1666 boolean pushed = false;
1667 // Since the bounding rect is a course description of the region (there can
1668 // be holes at the edge of the block), we need to check to verify that a solid
1669 // piece is intersecting. This ensures that interlocking is possible.
1670 for (int x = c.x; x < c.x + c.spanX; x++) {
1671 for (int y = c.y; y < c.y + c.spanY; y++) {
1672 if (occupied[x - deltaX][y - deltaY]) {
1673 pushed = true;
1674 break;
1675 }
1676 if (pushed) break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001677 }
1678 }
Adam Cohena56dc102012-07-13 13:41:42 -07001679 if (pushed) {
1680 views.add(child);
1681 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1682 found = true;
1683 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001684 }
1685 }
1686 }
1687 return found;
1688 }
1689
Adam Cohen482ed822012-03-02 14:15:13 -08001690 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohen19f37922012-03-21 11:59:11 -07001691 int[] direction, boolean push, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001692 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001693
Adam Cohen8baab352012-03-20 17:39:21 -07001694 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001695 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001696 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001697 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001698 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001699 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001700 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001701 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001702 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001703 }
1704 }
Adam Cohen8baab352012-03-20 17:39:21 -07001705
1706 @SuppressWarnings("unchecked")
1707 ArrayList<View> dup = (ArrayList<View>) views.clone();
1708 // We try and expand the group of views in the direction vector passed, based on
1709 // whether they are physically adjacent, ie. based on "push mechanics".
Adam Cohen19f37922012-03-21 11:59:11 -07001710 while (push && addViewInDirection(dup, boundingRect, direction, mTmpOccupied, dragView,
Adam Cohen8baab352012-03-20 17:39:21 -07001711 currentState)) {
1712 }
1713
1714 // Mark the occupied state as false for the group of views we want to move.
1715 for (View v: dup) {
1716 CellAndSpan c = currentState.map.get(v);
1717 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1718 }
1719
Adam Cohen47a876d2012-03-19 13:21:41 -07001720 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1721 int top = boundingRect.top;
1722 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001723 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001724 // for interlocking.
Adam Cohen8baab352012-03-20 17:39:21 -07001725 for (View v: dup) {
1726 CellAndSpan c = currentState.map.get(v);
1727 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001728 }
1729
Adam Cohen482ed822012-03-02 14:15:13 -08001730 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1731
Adam Cohen8baab352012-03-20 17:39:21 -07001732 if (push) {
1733 findNearestAreaInDirection(boundingRect.left, boundingRect.top, boundingRect.width(),
1734 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1735 } else {
1736 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1737 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1738 }
Adam Cohen482ed822012-03-02 14:15:13 -08001739
Adam Cohen8baab352012-03-20 17:39:21 -07001740 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001741 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001742 int deltaX = mTempLocation[0] - boundingRect.left;
1743 int deltaY = mTempLocation[1] - boundingRect.top;
1744 for (View v: dup) {
1745 CellAndSpan c = currentState.map.get(v);
1746 c.x += deltaX;
1747 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001748 }
1749 success = true;
1750 }
Adam Cohen8baab352012-03-20 17:39:21 -07001751
1752 // In either case, we set the occupied array as marked for the location of the views
1753 for (View v: dup) {
1754 CellAndSpan c = currentState.map.get(v);
1755 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001756 }
1757 return success;
1758 }
1759
1760 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1761 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1762 }
1763
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001764 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1765 // to push items in each of the cardinal directions, in an order based on the direction vector
1766 // passed.
1767 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1768 int[] direction, View ignoreView, ItemConfiguration solution) {
1769 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
1770 // If the direction vector has two non-zero components, we try pushing
1771 // separately in each of the components.
1772 int temp = direction[1];
1773 direction[1] = 0;
1774 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1775 ignoreView, solution)) {
1776 return true;
1777 }
1778 direction[1] = temp;
1779 temp = direction[0];
1780 direction[0] = 0;
1781 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1782 ignoreView, solution)) {
1783 return true;
1784 }
1785 // Revert the direction
1786 direction[0] = temp;
1787
1788 // Now we try pushing in each component of the opposite direction
1789 direction[0] *= -1;
1790 direction[1] *= -1;
1791 temp = direction[1];
1792 direction[1] = 0;
1793 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1794 ignoreView, solution)) {
1795 return true;
1796 }
1797
1798 direction[1] = temp;
1799 temp = direction[0];
1800 direction[0] = 0;
1801 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1802 ignoreView, solution)) {
1803 return true;
1804 }
1805 // revert the direction
1806 direction[0] = temp;
1807 direction[0] *= -1;
1808 direction[1] *= -1;
1809
1810 } else {
1811 // If the direction vector has a single non-zero component, we push first in the
1812 // direction of the vector
1813 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1814 ignoreView, solution)) {
1815 return true;
1816 }
1817
1818 // Then we try the opposite direction
1819 direction[0] *= -1;
1820 direction[1] *= -1;
1821 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1822 ignoreView, solution)) {
1823 return true;
1824 }
1825 // Switch the direction back
1826 direction[0] *= -1;
1827 direction[1] *= -1;
1828
1829 // If we have failed to find a push solution with the above, then we try
1830 // to find a solution by pushing along the perpendicular axis.
1831
1832 // Swap the components
1833 int temp = direction[1];
1834 direction[1] = direction[0];
1835 direction[0] = temp;
1836 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1837 ignoreView, solution)) {
1838 return true;
1839 }
1840
1841 // Then we try the opposite direction
1842 direction[0] *= -1;
1843 direction[1] *= -1;
1844 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1845 ignoreView, solution)) {
1846 return true;
1847 }
1848 // Switch the direction back
1849 direction[0] *= -1;
1850 direction[1] *= -1;
1851
1852 // Swap the components back
1853 temp = direction[1];
1854 direction[1] = direction[0];
1855 direction[0] = temp;
1856 }
1857 return false;
1858 }
1859
Adam Cohen482ed822012-03-02 14:15:13 -08001860 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001861 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001862 // Return early if get invalid cell positions
1863 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001864
Adam Cohen8baab352012-03-20 17:39:21 -07001865 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001866 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001867
Adam Cohen8baab352012-03-20 17:39:21 -07001868 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001869 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001870 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001871 if (c != null) {
1872 c.x = cellX;
1873 c.y = cellY;
1874 }
Adam Cohen482ed822012-03-02 14:15:13 -08001875 }
Adam Cohen482ed822012-03-02 14:15:13 -08001876 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1877 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001878 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001879 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001880 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001881 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001882 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001883 if (Rect.intersects(r0, r1)) {
1884 if (!lp.canReorder) {
1885 return false;
1886 }
1887 mIntersectingViews.add(child);
1888 }
1889 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001890
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001891 // First we try to find a solution which respects the push mechanic. That is,
1892 // we try to find a solution such that no displaced item travels through another item
1893 // without also displacing that item.
1894 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001895 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001896 return true;
1897 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001898
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001899 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohen19f37922012-03-21 11:59:11 -07001900 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, false, ignoreView,
1901 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001902 return true;
1903 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001904
Adam Cohen482ed822012-03-02 14:15:13 -08001905 // Ok, they couldn't move as a block, let's move them individually
1906 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001907 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001908 return false;
1909 }
1910 }
1911 return true;
1912 }
1913
1914 /*
1915 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1916 * the provided point and the provided cell
1917 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001918 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001919 double angle = Math.atan(((float) deltaY) / deltaX);
1920
1921 result[0] = 0;
1922 result[1] = 0;
1923 if (Math.abs(Math.cos(angle)) > 0.5f) {
1924 result[0] = (int) Math.signum(deltaX);
1925 }
1926 if (Math.abs(Math.sin(angle)) > 0.5f) {
1927 result[1] = (int) Math.signum(deltaY);
1928 }
1929 }
1930
Adam Cohen8baab352012-03-20 17:39:21 -07001931 private void copyOccupiedArray(boolean[][] occupied) {
1932 for (int i = 0; i < mCountX; i++) {
1933 for (int j = 0; j < mCountY; j++) {
1934 occupied[i][j] = mOccupied[i][j];
1935 }
1936 }
1937 }
1938
Adam Cohen482ed822012-03-02 14:15:13 -08001939 ItemConfiguration simpleSwap(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1940 int spanY, int[] direction, View dragView, boolean decX, ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001941 // Copy the current state into the solution. This solution will be manipulated as necessary.
1942 copyCurrentStateToSolution(solution, false);
1943 // Copy the current occupied array into the temporary occupied array. This array will be
1944 // manipulated as necessary to find a solution.
1945 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001946
1947 // We find the nearest cell into which we would place the dragged item, assuming there's
1948 // nothing in its way.
1949 int result[] = new int[2];
1950 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1951
1952 boolean success = false;
1953 // First we try the exact nearest position of the item being dragged,
1954 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001955 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1956 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001957
1958 if (!success) {
1959 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1960 // x, then 1 in y etc.
1961 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
1962 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY, direction,
1963 dragView, false, solution);
1964 } else if (spanY > minSpanY) {
1965 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1, direction,
1966 dragView, true, solution);
1967 }
1968 solution.isSolution = false;
1969 } else {
1970 solution.isSolution = true;
1971 solution.dragViewX = result[0];
1972 solution.dragViewY = result[1];
1973 solution.dragViewSpanX = spanX;
1974 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001975 }
1976 return solution;
1977 }
1978
1979 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001980 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001981 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001982 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001983 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001984 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08001985 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07001986 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001987 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001988 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001989 }
Adam Cohen8baab352012-03-20 17:39:21 -07001990 solution.map.put(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08001991 }
1992 }
1993
1994 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
1995 for (int i = 0; i < mCountX; i++) {
1996 for (int j = 0; j < mCountY; j++) {
1997 mTmpOccupied[i][j] = false;
1998 }
1999 }
2000
Michael Jurkaa52570f2012-03-20 03:18:20 -07002001 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002002 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002003 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002004 if (child == dragView) continue;
2005 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07002006 CellAndSpan c = solution.map.get(child);
2007 if (c != null) {
2008 lp.tmpCellX = c.x;
2009 lp.tmpCellY = c.y;
2010 lp.cellHSpan = c.spanX;
2011 lp.cellVSpan = c.spanY;
2012 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002013 }
2014 }
2015 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2016 solution.dragViewSpanY, mTmpOccupied, true);
2017 }
2018
2019 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
2020 commitDragView) {
2021
2022 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
2023 for (int i = 0; i < mCountX; i++) {
2024 for (int j = 0; j < mCountY; j++) {
2025 occupied[i][j] = false;
2026 }
2027 }
2028
Michael Jurkaa52570f2012-03-20 03:18:20 -07002029 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002030 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002031 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08002032 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07002033 CellAndSpan c = solution.map.get(child);
2034 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002035 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2036 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002037 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002038 }
2039 }
2040 if (commitDragView) {
2041 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2042 solution.dragViewSpanY, occupied, true);
2043 }
2044 }
2045
Adam Cohen19f37922012-03-21 11:59:11 -07002046 // This method starts or changes the reorder hint animations
2047 private void beginOrAdjustHintAnimations(ItemConfiguration solution, View dragView, int delay) {
2048 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002049 for (int i = 0; i < childCount; i++) {
2050 View child = mShortcutsAndWidgets.getChildAt(i);
2051 if (child == dragView) continue;
2052 CellAndSpan c = solution.map.get(child);
2053 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2054 if (c != null) {
2055 ReorderHintAnimation rha = new ReorderHintAnimation(child, lp.cellX, lp.cellY,
2056 c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002057 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002058 }
2059 }
2060 }
2061
2062 // Class which represents the reorder hint animations. These animations show that an item is
2063 // in a temporary state, and hint at where the item will return to.
2064 class ReorderHintAnimation {
2065 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002066 float finalDeltaX;
2067 float finalDeltaY;
2068 float initDeltaX;
2069 float initDeltaY;
2070 float finalScale;
2071 float initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002072 private static final int DURATION = 300;
Adam Cohene7587d22012-05-24 18:50:02 -07002073 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002074
2075 public ReorderHintAnimation(View child, int cellX0, int cellY0, int cellX1, int cellY1,
2076 int spanX, int spanY) {
2077 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2078 final int x0 = mTmpPoint[0];
2079 final int y0 = mTmpPoint[1];
2080 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2081 final int x1 = mTmpPoint[0];
2082 final int y1 = mTmpPoint[1];
2083 final int dX = x1 - x0;
2084 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002085 finalDeltaX = 0;
2086 finalDeltaY = 0;
Adam Cohen19f37922012-03-21 11:59:11 -07002087 if (dX == dY && dX == 0) {
2088 } else {
2089 if (dY == 0) {
Adam Cohend024f982012-05-23 18:26:45 -07002090 finalDeltaX = - Math.signum(dX) * mReorderHintAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002091 } else if (dX == 0) {
Adam Cohend024f982012-05-23 18:26:45 -07002092 finalDeltaY = - Math.signum(dY) * mReorderHintAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002093 } else {
2094 double angle = Math.atan( (float) (dY) / dX);
Adam Cohend024f982012-05-23 18:26:45 -07002095 finalDeltaX = (int) (- Math.signum(dX) *
Adam Cohenfe41ac62012-05-23 14:00:37 -07002096 Math.abs(Math.cos(angle) * mReorderHintAnimationMagnitude));
Adam Cohend024f982012-05-23 18:26:45 -07002097 finalDeltaY = (int) (- Math.signum(dY) *
Adam Cohenfe41ac62012-05-23 14:00:37 -07002098 Math.abs(Math.sin(angle) * mReorderHintAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002099 }
2100 }
Adam Cohend024f982012-05-23 18:26:45 -07002101 initDeltaX = child.getTranslationX();
2102 initDeltaY = child.getTranslationY();
Adam Cohen307fe232012-08-16 17:55:58 -07002103 finalScale = getChildrenScale() - 4.0f / child.getWidth();
Adam Cohend024f982012-05-23 18:26:45 -07002104 initScale = child.getScaleX();
Adam Cohen19f37922012-03-21 11:59:11 -07002105 this.child = child;
2106 }
2107
Adam Cohend024f982012-05-23 18:26:45 -07002108 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002109 if (mShakeAnimators.containsKey(child)) {
2110 ReorderHintAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002111 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002112 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002113 if (finalDeltaX == 0 && finalDeltaY == 0) {
2114 completeAnimationImmediately();
2115 return;
2116 }
Adam Cohen19f37922012-03-21 11:59:11 -07002117 }
Adam Cohend024f982012-05-23 18:26:45 -07002118 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002119 return;
2120 }
Michael Jurka2ecf9952012-06-18 12:52:28 -07002121 ValueAnimator va = LauncherAnimUtils.ofFloat(0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002122 a = va;
Adam Cohen19f37922012-03-21 11:59:11 -07002123 va.setRepeatMode(ValueAnimator.REVERSE);
2124 va.setRepeatCount(ValueAnimator.INFINITE);
Adam Cohen7bdfc972012-05-22 16:50:35 -07002125 va.setDuration(DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002126 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002127 va.addUpdateListener(new AnimatorUpdateListener() {
2128 @Override
2129 public void onAnimationUpdate(ValueAnimator animation) {
2130 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohend024f982012-05-23 18:26:45 -07002131 float x = r * finalDeltaX + (1 - r) * initDeltaX;
2132 float y = r * finalDeltaY + (1 - r) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002133 child.setTranslationX(x);
2134 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002135 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002136 child.setScaleX(s);
2137 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002138 }
2139 });
2140 va.addListener(new AnimatorListenerAdapter() {
2141 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002142 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002143 initDeltaX = 0;
2144 initDeltaY = 0;
Adam Cohen307fe232012-08-16 17:55:58 -07002145 initScale = getChildrenScale();
Adam Cohen19f37922012-03-21 11:59:11 -07002146 }
2147 });
Adam Cohen19f37922012-03-21 11:59:11 -07002148 mShakeAnimators.put(child, this);
2149 va.start();
2150 }
2151
Adam Cohend024f982012-05-23 18:26:45 -07002152 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002153 if (a != null) {
2154 a.cancel();
2155 }
Adam Cohen19f37922012-03-21 11:59:11 -07002156 }
Adam Cohene7587d22012-05-24 18:50:02 -07002157
Brandon Keely50e6e562012-05-08 16:28:49 -07002158 private void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002159 if (a != null) {
2160 a.cancel();
2161 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002162
Michael Jurka2ecf9952012-06-18 12:52:28 -07002163 AnimatorSet s = LauncherAnimUtils.createAnimatorSet();
Adam Cohene7587d22012-05-24 18:50:02 -07002164 a = s;
Brandon Keely50e6e562012-05-08 16:28:49 -07002165 s.playTogether(
Adam Cohen307fe232012-08-16 17:55:58 -07002166 LauncherAnimUtils.ofFloat(child, "scaleX", getChildrenScale()),
2167 LauncherAnimUtils.ofFloat(child, "scaleY", getChildrenScale()),
Michael Jurka2ecf9952012-06-18 12:52:28 -07002168 LauncherAnimUtils.ofFloat(child, "translationX", 0f),
2169 LauncherAnimUtils.ofFloat(child, "translationY", 0f)
Brandon Keely50e6e562012-05-08 16:28:49 -07002170 );
2171 s.setDuration(REORDER_ANIMATION_DURATION);
2172 s.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2173 s.start();
2174 }
Adam Cohen19f37922012-03-21 11:59:11 -07002175 }
2176
2177 private void completeAndClearReorderHintAnimations() {
2178 for (ReorderHintAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002179 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002180 }
2181 mShakeAnimators.clear();
2182 }
2183
Adam Cohen482ed822012-03-02 14:15:13 -08002184 private void commitTempPlacement() {
2185 for (int i = 0; i < mCountX; i++) {
2186 for (int j = 0; j < mCountY; j++) {
2187 mOccupied[i][j] = mTmpOccupied[i][j];
2188 }
2189 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002190 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002191 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002192 View child = mShortcutsAndWidgets.getChildAt(i);
2193 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2194 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002195 // We do a null check here because the item info can be null in the case of the
2196 // AllApps button in the hotseat.
2197 if (info != null) {
Adam Cohen487f7dd2012-06-28 18:12:10 -07002198 if (info.cellX != lp.tmpCellX || info.cellY != lp.tmpCellY ||
2199 info.spanX != lp.cellHSpan || info.spanY != lp.cellVSpan) {
2200 info.requiresDbUpdate = true;
2201 }
Adam Cohen2acce882012-03-28 19:03:19 -07002202 info.cellX = lp.cellX = lp.tmpCellX;
2203 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002204 info.spanX = lp.cellHSpan;
2205 info.spanY = lp.cellVSpan;
Adam Cohen2acce882012-03-28 19:03:19 -07002206 }
Adam Cohen482ed822012-03-02 14:15:13 -08002207 }
Adam Cohen2acce882012-03-28 19:03:19 -07002208 mLauncher.getWorkspace().updateItemLocationsInDatabase(this);
Adam Cohen482ed822012-03-02 14:15:13 -08002209 }
2210
2211 public void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002212 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002213 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002214 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002215 lp.useTmpCoords = useTempCoords;
2216 }
2217 }
2218
Adam Cohen482ed822012-03-02 14:15:13 -08002219 ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
2220 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2221 int[] result = new int[2];
2222 int[] resultSpan = new int[2];
2223 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null, result,
2224 resultSpan);
2225 if (result[0] >= 0 && result[1] >= 0) {
2226 copyCurrentStateToSolution(solution, false);
2227 solution.dragViewX = result[0];
2228 solution.dragViewY = result[1];
2229 solution.dragViewSpanX = resultSpan[0];
2230 solution.dragViewSpanY = resultSpan[1];
2231 solution.isSolution = true;
2232 } else {
2233 solution.isSolution = false;
2234 }
2235 return solution;
2236 }
2237
2238 public void prepareChildForDrag(View child) {
2239 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002240 }
2241
Adam Cohen19f37922012-03-21 11:59:11 -07002242 /* This seems like it should be obvious and straight-forward, but when the direction vector
2243 needs to match with the notion of the dragView pushing other views, we have to employ
2244 a slightly more subtle notion of the direction vector. The question is what two points is
2245 the vector between? The center of the dragView and its desired destination? Not quite, as
2246 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2247 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2248 or right, which helps make pushing feel right.
2249 */
2250 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2251 int spanY, View dragView, int[] resultDirection) {
2252 int[] targetDestination = new int[2];
2253
2254 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2255 Rect dragRect = new Rect();
2256 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2257 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2258
2259 Rect dropRegionRect = new Rect();
2260 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2261 dragView, dropRegionRect, mIntersectingViews);
2262
2263 int dropRegionSpanX = dropRegionRect.width();
2264 int dropRegionSpanY = dropRegionRect.height();
2265
2266 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2267 dropRegionRect.height(), dropRegionRect);
2268
2269 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2270 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2271
2272 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2273 deltaX = 0;
2274 }
2275 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2276 deltaY = 0;
2277 }
2278
2279 if (deltaX == 0 && deltaY == 0) {
2280 // No idea what to do, give a random direction.
2281 resultDirection[0] = 1;
2282 resultDirection[1] = 0;
2283 } else {
2284 computeDirectionVector(deltaX, deltaY, resultDirection);
2285 }
2286 }
2287
2288 // For a given cell and span, fetch the set of views intersecting the region.
2289 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2290 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2291 if (boundingRect != null) {
2292 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2293 }
2294 intersectingViews.clear();
2295 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2296 Rect r1 = new Rect();
2297 final int count = mShortcutsAndWidgets.getChildCount();
2298 for (int i = 0; i < count; i++) {
2299 View child = mShortcutsAndWidgets.getChildAt(i);
2300 if (child == dragView) continue;
2301 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2302 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2303 if (Rect.intersects(r0, r1)) {
2304 mIntersectingViews.add(child);
2305 if (boundingRect != null) {
2306 boundingRect.union(r1);
2307 }
2308 }
2309 }
2310 }
2311
2312 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2313 View dragView, int[] result) {
2314 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2315 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2316 mIntersectingViews);
2317 return !mIntersectingViews.isEmpty();
2318 }
2319
2320 void revertTempState() {
2321 if (!isItemPlacementDirty() || DESTRUCTIVE_REORDER) return;
2322 final int count = mShortcutsAndWidgets.getChildCount();
2323 for (int i = 0; i < count; i++) {
2324 View child = mShortcutsAndWidgets.getChildAt(i);
2325 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2326 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2327 lp.tmpCellX = lp.cellX;
2328 lp.tmpCellY = lp.cellY;
2329 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2330 0, false, false);
2331 }
2332 }
2333 completeAndClearReorderHintAnimations();
2334 setItemPlacementDirty(false);
2335 }
2336
Adam Cohenbebf0422012-04-11 18:06:28 -07002337 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2338 View dragView, int[] direction, boolean commit) {
2339 int[] pixelXY = new int[2];
2340 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2341
2342 // First we determine if things have moved enough to cause a different layout
2343 ItemConfiguration swapSolution = simpleSwap(pixelXY[0], pixelXY[1], spanX, spanY,
2344 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2345
2346 setUseTempCoords(true);
2347 if (swapSolution != null && swapSolution.isSolution) {
2348 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2349 // committing anything or animating anything as we just want to determine if a solution
2350 // exists
2351 copySolutionToTempState(swapSolution, dragView);
2352 setItemPlacementDirty(true);
2353 animateItemsToSolution(swapSolution, dragView, commit);
2354
2355 if (commit) {
2356 commitTempPlacement();
2357 completeAndClearReorderHintAnimations();
2358 setItemPlacementDirty(false);
2359 } else {
2360 beginOrAdjustHintAnimations(swapSolution, dragView,
2361 REORDER_ANIMATION_DURATION);
2362 }
2363 mShortcutsAndWidgets.requestLayout();
2364 }
2365 return swapSolution.isSolution;
2366 }
2367
Adam Cohen482ed822012-03-02 14:15:13 -08002368 int[] createArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2369 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002370 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002371 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002372
2373 if (resultSpan == null) {
2374 resultSpan = new int[2];
2375 }
2376
Adam Cohen19f37922012-03-21 11:59:11 -07002377 // When we are checking drop validity or actually dropping, we don't recompute the
2378 // direction vector, since we want the solution to match the preview, and it's possible
2379 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002380 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2381 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002382 mDirectionVector[0] = mPreviousReorderDirection[0];
2383 mDirectionVector[1] = mPreviousReorderDirection[1];
2384 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002385 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2386 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2387 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002388 }
2389 } else {
2390 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2391 mPreviousReorderDirection[0] = mDirectionVector[0];
2392 mPreviousReorderDirection[1] = mDirectionVector[1];
2393 }
2394
Adam Cohen482ed822012-03-02 14:15:13 -08002395 ItemConfiguration swapSolution = simpleSwap(pixelX, pixelY, minSpanX, minSpanY,
2396 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2397
2398 // We attempt the approach which doesn't shuffle views at all
2399 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2400 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2401
2402 ItemConfiguration finalSolution = null;
2403 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2404 finalSolution = swapSolution;
2405 } else if (noShuffleSolution.isSolution) {
2406 finalSolution = noShuffleSolution;
2407 }
2408
2409 boolean foundSolution = true;
2410 if (!DESTRUCTIVE_REORDER) {
2411 setUseTempCoords(true);
2412 }
2413
2414 if (finalSolution != null) {
2415 result[0] = finalSolution.dragViewX;
2416 result[1] = finalSolution.dragViewY;
2417 resultSpan[0] = finalSolution.dragViewSpanX;
2418 resultSpan[1] = finalSolution.dragViewSpanY;
2419
2420 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2421 // committing anything or animating anything as we just want to determine if a solution
2422 // exists
2423 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2424 if (!DESTRUCTIVE_REORDER) {
2425 copySolutionToTempState(finalSolution, dragView);
2426 }
2427 setItemPlacementDirty(true);
2428 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2429
Adam Cohen19f37922012-03-21 11:59:11 -07002430 if (!DESTRUCTIVE_REORDER &&
2431 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002432 commitTempPlacement();
Adam Cohen19f37922012-03-21 11:59:11 -07002433 completeAndClearReorderHintAnimations();
2434 setItemPlacementDirty(false);
2435 } else {
2436 beginOrAdjustHintAnimations(finalSolution, dragView,
2437 REORDER_ANIMATION_DURATION);
Adam Cohen482ed822012-03-02 14:15:13 -08002438 }
2439 }
2440 } else {
2441 foundSolution = false;
2442 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2443 }
2444
2445 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2446 setUseTempCoords(false);
2447 }
Adam Cohen482ed822012-03-02 14:15:13 -08002448
Michael Jurkaa52570f2012-03-20 03:18:20 -07002449 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002450 return result;
2451 }
2452
Adam Cohen19f37922012-03-21 11:59:11 -07002453 void setItemPlacementDirty(boolean dirty) {
2454 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002455 }
Adam Cohen19f37922012-03-21 11:59:11 -07002456 boolean isItemPlacementDirty() {
2457 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002458 }
2459
2460 private class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002461 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohen482ed822012-03-02 14:15:13 -08002462 boolean isSolution = false;
2463 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2464
2465 int area() {
2466 return dragViewSpanX * dragViewSpanY;
2467 }
Adam Cohen8baab352012-03-20 17:39:21 -07002468 }
2469
2470 private class CellAndSpan {
2471 int x, y;
2472 int spanX, spanY;
2473
2474 public CellAndSpan(int x, int y, int spanX, int spanY) {
2475 this.x = x;
2476 this.y = y;
2477 this.spanX = spanX;
2478 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002479 }
2480 }
2481
Adam Cohendf035382011-04-11 17:22:04 -07002482 /**
2483 * Find a vacant area that will fit the given bounds nearest the requested
2484 * cell location. Uses Euclidean distance to score multiple vacant areas.
2485 *
2486 * @param pixelX The X location at which you want to search for a vacant area.
2487 * @param pixelY The Y location at which you want to search for a vacant area.
2488 * @param spanX Horizontal span of the object.
2489 * @param spanY Vertical span of the object.
2490 * @param ignoreView Considers space occupied by this view as unoccupied
2491 * @param result Previously returned value to possibly recycle.
2492 * @return The X, Y cell of a vacant area that can contain this object,
2493 * nearest the requested location.
2494 */
2495 int[] findNearestVacantArea(
2496 int pixelX, int pixelY, int spanX, int spanY, View ignoreView, int[] result) {
2497 return findNearestArea(pixelX, pixelY, spanX, spanY, ignoreView, true, result);
2498 }
2499
2500 /**
Adam Cohend41fbf52012-02-16 23:53:59 -08002501 * Find a vacant area that will fit the given bounds nearest the requested
2502 * cell location. Uses Euclidean distance to score multiple vacant areas.
2503 *
2504 * @param pixelX The X location at which you want to search for a vacant area.
2505 * @param pixelY The Y location at which you want to search for a vacant area.
2506 * @param minSpanX The minimum horizontal span required
2507 * @param minSpanY The minimum vertical span required
2508 * @param spanX Horizontal span of the object.
2509 * @param spanY Vertical span of the object.
2510 * @param ignoreView Considers space occupied by this view as unoccupied
2511 * @param result Previously returned value to possibly recycle.
2512 * @return The X, Y cell of a vacant area that can contain this object,
2513 * nearest the requested location.
2514 */
2515 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
2516 int spanX, int spanY, View ignoreView, int[] result, int[] resultSpan) {
Adam Cohen482ed822012-03-02 14:15:13 -08002517 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, true,
2518 result, resultSpan, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08002519 }
2520
2521 /**
Adam Cohendf035382011-04-11 17:22:04 -07002522 * Find a starting cell position that will fit the given bounds nearest the requested
2523 * cell location. Uses Euclidean distance to score multiple vacant areas.
2524 *
2525 * @param pixelX The X location at which you want to search for a vacant area.
2526 * @param pixelY The Y location at which you want to search for a vacant area.
2527 * @param spanX Horizontal span of the object.
2528 * @param spanY Vertical span of the object.
2529 * @param ignoreView Considers space occupied by this view as unoccupied
2530 * @param result Previously returned value to possibly recycle.
2531 * @return The X, Y cell of a vacant area that can contain this object,
2532 * nearest the requested location.
2533 */
2534 int[] findNearestArea(
2535 int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2536 return findNearestArea(pixelX, pixelY, spanX, spanY, null, false, result);
2537 }
2538
Michael Jurka0280c3b2010-09-17 15:00:07 -07002539 boolean existsEmptyCell() {
2540 return findCellForSpan(null, 1, 1);
2541 }
2542
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002543 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002544 * Finds the upper-left coordinate of the first rectangle in the grid that can
2545 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2546 * then this method will only return coordinates for rectangles that contain the cell
2547 * (intersectX, intersectY)
2548 *
2549 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2550 * can be found.
2551 * @param spanX The horizontal span of the cell we want to find.
2552 * @param spanY The vertical span of the cell we want to find.
2553 *
2554 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002555 */
Michael Jurka0280c3b2010-09-17 15:00:07 -07002556 boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08002557 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002558 }
2559
2560 /**
2561 * Like above, but ignores any cells occupied by the item "ignoreView"
2562 *
2563 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2564 * can be found.
2565 * @param spanX The horizontal span of the cell we want to find.
2566 * @param spanY The vertical span of the cell we want to find.
2567 * @param ignoreView The home screen item we should treat as not occupying any space
2568 * @return
2569 */
2570 boolean findCellForSpanIgnoring(int[] cellXY, int spanX, int spanY, View ignoreView) {
Adam Cohen482ed822012-03-02 14:15:13 -08002571 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1,
2572 ignoreView, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002573 }
2574
2575 /**
2576 * Like above, but if intersectX and intersectY are not -1, then this method will try to
2577 * return coordinates for rectangles that contain the cell [intersectX, intersectY]
2578 *
2579 * @param spanX The horizontal span of the cell we want to find.
2580 * @param spanY The vertical span of the cell we want to find.
2581 * @param ignoreView The home screen item we should treat as not occupying any space
2582 * @param intersectX The X coordinate of the cell that we should try to overlap
2583 * @param intersectX The Y coordinate of the cell that we should try to overlap
2584 *
2585 * @return True if a vacant cell of the specified dimension was found, false otherwise.
2586 */
2587 boolean findCellForSpanThatIntersects(int[] cellXY, int spanX, int spanY,
2588 int intersectX, int intersectY) {
2589 return findCellForSpanThatIntersectsIgnoring(
Adam Cohen482ed822012-03-02 14:15:13 -08002590 cellXY, spanX, spanY, intersectX, intersectY, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002591 }
2592
2593 /**
2594 * The superset of the above two methods
2595 */
2596 boolean findCellForSpanThatIntersectsIgnoring(int[] cellXY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002597 int intersectX, int intersectY, View ignoreView, boolean occupied[][]) {
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002598 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08002599 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002600
Michael Jurka28750fb2010-09-24 17:43:49 -07002601 boolean foundCell = false;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002602 while (true) {
2603 int startX = 0;
2604 if (intersectX >= 0) {
2605 startX = Math.max(startX, intersectX - (spanX - 1));
2606 }
2607 int endX = mCountX - (spanX - 1);
2608 if (intersectX >= 0) {
2609 endX = Math.min(endX, intersectX + (spanX - 1) + (spanX == 1 ? 1 : 0));
2610 }
2611 int startY = 0;
2612 if (intersectY >= 0) {
2613 startY = Math.max(startY, intersectY - (spanY - 1));
2614 }
2615 int endY = mCountY - (spanY - 1);
2616 if (intersectY >= 0) {
2617 endY = Math.min(endY, intersectY + (spanY - 1) + (spanY == 1 ? 1 : 0));
2618 }
2619
Winson Chungbbc60d82010-11-11 16:34:41 -08002620 for (int y = startY; y < endY && !foundCell; y++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002621 inner:
Winson Chungbbc60d82010-11-11 16:34:41 -08002622 for (int x = startX; x < endX; x++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002623 for (int i = 0; i < spanX; i++) {
2624 for (int j = 0; j < spanY; j++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002625 if (occupied[x + i][y + j]) {
Winson Chungbbc60d82010-11-11 16:34:41 -08002626 // small optimization: we can skip to after the column we just found
Michael Jurka0280c3b2010-09-17 15:00:07 -07002627 // an occupied cell
Winson Chungbbc60d82010-11-11 16:34:41 -08002628 x += i;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002629 continue inner;
2630 }
2631 }
2632 }
2633 if (cellXY != null) {
2634 cellXY[0] = x;
2635 cellXY[1] = y;
2636 }
Michael Jurka28750fb2010-09-24 17:43:49 -07002637 foundCell = true;
2638 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002639 }
2640 }
2641 if (intersectX == -1 && intersectY == -1) {
2642 break;
2643 } else {
2644 // if we failed to find anything, try again but without any requirements of
2645 // intersecting
2646 intersectX = -1;
2647 intersectY = -1;
2648 continue;
2649 }
2650 }
2651
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002652 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08002653 markCellsAsOccupiedForView(ignoreView, occupied);
Michael Jurka28750fb2010-09-24 17:43:49 -07002654 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002655 }
2656
2657 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002658 * A drag event has begun over this layout.
2659 * It may have begun over this layout (in which case onDragChild is called first),
2660 * or it may have begun on another layout.
2661 */
2662 void onDragEnter() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002663 mDragEnforcer.onDragEnter();
Winson Chungc07918d2011-07-01 15:35:26 -07002664 mDragging = true;
2665 }
2666
2667 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002668 * Called when drag has left this CellLayout or has been completed (successfully or not)
2669 */
2670 void onDragExit() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002671 mDragEnforcer.onDragExit();
Joe Onorato4be866d2010-10-10 11:26:02 -07002672 // This can actually be called when we aren't in a drag, e.g. when adding a new
2673 // item to this layout via the customize drawer.
2674 // Guard against that case.
2675 if (mDragging) {
2676 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002677 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002678
2679 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002680 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002681 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2682 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002683 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002684 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002685 }
2686
2687 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002688 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002689 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002690 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002691 *
2692 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002693 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002694 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002695 if (child != null) {
2696 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002697 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002698 child.requestLayout();
Romain Guyd94533d2009-08-17 10:01:15 -07002699 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002700 }
2701
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002702 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002703 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002704 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002705 * @param cellX X coordinate of upper left corner expressed as a cell position
2706 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002707 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002708 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002709 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002710 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002711 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002712 final int cellWidth = mCellWidth;
2713 final int cellHeight = mCellHeight;
2714 final int widthGap = mWidthGap;
2715 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002716
Winson Chung4b825dcd2011-06-19 12:41:22 -07002717 final int hStartPadding = getPaddingLeft();
2718 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002719
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002720 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2721 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2722
2723 int x = hStartPadding + cellX * (cellWidth + widthGap);
2724 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002725
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002726 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002727 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002728
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002729 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002730 * Computes the required horizontal and vertical cell spans to always
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002731 * fit the given rectangle.
Winson Chungaafa03c2010-06-11 17:34:16 -07002732 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002733 * @param width Width in pixels
2734 * @param height Height in pixels
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002735 * @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 -08002736 */
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002737 public int[] rectToCell(int width, int height, int[] result) {
Michael Jurka9987a5c2010-10-08 16:58:12 -07002738 return rectToCell(getResources(), width, height, result);
2739 }
2740
2741 public static int[] rectToCell(Resources resources, int width, int height, int[] result) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002742 // Always assume we're working with the smallest span to make sure we
2743 // reserve enough space in both orientations.
Joe Onorato79e56262009-09-21 15:23:04 -04002744 int actualWidth = resources.getDimensionPixelSize(R.dimen.workspace_cell_width);
2745 int actualHeight = resources.getDimensionPixelSize(R.dimen.workspace_cell_height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002746 int smallerSize = Math.min(actualWidth, actualHeight);
Joe Onorato79e56262009-09-21 15:23:04 -04002747
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002748 // Always round up to next largest cell
Winson Chung54c725c2011-08-03 12:03:40 -07002749 int spanX = (int) Math.ceil(width / (float) smallerSize);
2750 int spanY = (int) Math.ceil(height / (float) smallerSize);
Joe Onorato79e56262009-09-21 15:23:04 -04002751
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002752 if (result == null) {
2753 return new int[] { spanX, spanY };
2754 }
2755 result[0] = spanX;
2756 result[1] = spanY;
2757 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002758 }
2759
Michael Jurkaf12c75c2011-01-25 22:41:40 -08002760 public int[] cellSpansToSize(int hSpans, int vSpans) {
2761 int[] size = new int[2];
2762 size[0] = hSpans * mCellWidth + (hSpans - 1) * mWidthGap;
2763 size[1] = vSpans * mCellHeight + (vSpans - 1) * mHeightGap;
2764 return size;
2765 }
2766
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002767 /**
Patrick Dubroy047379a2010-12-19 22:02:04 -08002768 * Calculate the grid spans needed to fit given item
2769 */
2770 public void calculateSpans(ItemInfo info) {
2771 final int minWidth;
2772 final int minHeight;
2773
2774 if (info instanceof LauncherAppWidgetInfo) {
2775 minWidth = ((LauncherAppWidgetInfo) info).minWidth;
2776 minHeight = ((LauncherAppWidgetInfo) info).minHeight;
2777 } else if (info instanceof PendingAddWidgetInfo) {
2778 minWidth = ((PendingAddWidgetInfo) info).minWidth;
2779 minHeight = ((PendingAddWidgetInfo) info).minHeight;
2780 } else {
2781 // It's not a widget, so it must be 1x1
2782 info.spanX = info.spanY = 1;
2783 return;
2784 }
2785 int[] spans = rectToCell(minWidth, minHeight, null);
2786 info.spanX = spans[0];
2787 info.spanY = spans[1];
2788 }
2789
2790 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002791 * Find the first vacant cell, if there is one.
2792 *
2793 * @param vacant Holds the x and y coordinate of the vacant cell
2794 * @param spanX Horizontal cell span.
2795 * @param spanY Vertical cell span.
Winson Chungaafa03c2010-06-11 17:34:16 -07002796 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002797 * @return True if a vacant cell was found
2798 */
2799 public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002800
Michael Jurka0280c3b2010-09-17 15:00:07 -07002801 return findVacantCell(vacant, spanX, spanY, mCountX, mCountY, mOccupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002802 }
2803
2804 static boolean findVacantCell(int[] vacant, int spanX, int spanY,
2805 int xCount, int yCount, boolean[][] occupied) {
2806
Adam Cohen2801caf2011-05-13 20:57:39 -07002807 for (int y = 0; y < yCount; y++) {
2808 for (int x = 0; x < xCount; x++) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002809 boolean available = !occupied[x][y];
2810out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
2811 for (int j = y; j < y + spanY - 1 && y < yCount; j++) {
2812 available = available && !occupied[i][j];
2813 if (!available) break out;
2814 }
2815 }
2816
2817 if (available) {
2818 vacant[0] = x;
2819 vacant[1] = y;
2820 return true;
2821 }
2822 }
2823 }
2824
2825 return false;
2826 }
2827
Michael Jurka0280c3b2010-09-17 15:00:07 -07002828 private void clearOccupiedCells() {
2829 for (int x = 0; x < mCountX; x++) {
2830 for (int y = 0; y < mCountY; y++) {
2831 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002832 }
2833 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002834 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002835
Adam Cohend41fbf52012-02-16 23:53:59 -08002836 public void onMove(View view, int newCellX, int newCellY, int newSpanX, int newSpanY) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002837 markCellsAsUnoccupiedForView(view);
Adam Cohen482ed822012-03-02 14:15:13 -08002838 markCellsForView(newCellX, newCellY, newSpanX, newSpanY, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002839 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002840
Adam Cohend4844c32011-02-18 19:25:06 -08002841 public void markCellsAsOccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002842 markCellsAsOccupiedForView(view, mOccupied);
2843 }
2844 public void markCellsAsOccupiedForView(View view, boolean[][] occupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002845 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002846 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002847 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002848 }
2849
Adam Cohend4844c32011-02-18 19:25:06 -08002850 public void markCellsAsUnoccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002851 markCellsAsUnoccupiedForView(view, mOccupied);
2852 }
2853 public void markCellsAsUnoccupiedForView(View view, boolean occupied[][]) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002854 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002855 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002856 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002857 }
2858
Adam Cohen482ed822012-03-02 14:15:13 -08002859 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2860 boolean value) {
2861 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002862 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2863 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002864 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002865 }
2866 }
2867 }
2868
Adam Cohen2801caf2011-05-13 20:57:39 -07002869 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002870 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002871 (Math.max((mCountX - 1), 0) * mWidthGap);
2872 }
2873
2874 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002875 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002876 (Math.max((mCountY - 1), 0) * mHeightGap);
2877 }
2878
Michael Jurka66d72172011-04-12 16:29:25 -07002879 public boolean isOccupied(int x, int y) {
2880 if (x < mCountX && y < mCountY) {
2881 return mOccupied[x][y];
2882 } else {
2883 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2884 }
2885 }
2886
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002887 @Override
2888 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2889 return new CellLayout.LayoutParams(getContext(), attrs);
2890 }
2891
2892 @Override
2893 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2894 return p instanceof CellLayout.LayoutParams;
2895 }
2896
2897 @Override
2898 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2899 return new CellLayout.LayoutParams(p);
2900 }
2901
Winson Chungaafa03c2010-06-11 17:34:16 -07002902 public static class CellLayoutAnimationController extends LayoutAnimationController {
2903 public CellLayoutAnimationController(Animation animation, float delay) {
2904 super(animation, delay);
2905 }
2906
2907 @Override
2908 protected long getDelayForView(View view) {
2909 return (int) (Math.random() * 150);
2910 }
2911 }
2912
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002913 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2914 /**
2915 * Horizontal location of the item in the grid.
2916 */
2917 @ViewDebug.ExportedProperty
2918 public int cellX;
2919
2920 /**
2921 * Vertical location of the item in the grid.
2922 */
2923 @ViewDebug.ExportedProperty
2924 public int cellY;
2925
2926 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002927 * Temporary horizontal location of the item in the grid during reorder
2928 */
2929 public int tmpCellX;
2930
2931 /**
2932 * Temporary vertical location of the item in the grid during reorder
2933 */
2934 public int tmpCellY;
2935
2936 /**
2937 * Indicates that the temporary coordinates should be used to layout the items
2938 */
2939 public boolean useTmpCoords;
2940
2941 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002942 * Number of cells spanned horizontally by the item.
2943 */
2944 @ViewDebug.ExportedProperty
2945 public int cellHSpan;
2946
2947 /**
2948 * Number of cells spanned vertically by the item.
2949 */
2950 @ViewDebug.ExportedProperty
2951 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002952
Adam Cohen1b607ed2011-03-03 17:26:50 -08002953 /**
2954 * Indicates whether the item will set its x, y, width and height parameters freely,
2955 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2956 */
Adam Cohend4844c32011-02-18 19:25:06 -08002957 public boolean isLockedToGrid = true;
2958
Adam Cohen482ed822012-03-02 14:15:13 -08002959 /**
2960 * Indicates whether this item can be reordered. Always true except in the case of the
2961 * the AllApps button.
2962 */
2963 public boolean canReorder = true;
2964
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002965 // X coordinate of the view in the layout.
2966 @ViewDebug.ExportedProperty
2967 int x;
2968 // Y coordinate of the view in the layout.
2969 @ViewDebug.ExportedProperty
2970 int y;
2971
Romain Guy84f296c2009-11-04 15:00:44 -08002972 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002973
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002974 public LayoutParams(Context c, AttributeSet attrs) {
2975 super(c, attrs);
2976 cellHSpan = 1;
2977 cellVSpan = 1;
2978 }
2979
2980 public LayoutParams(ViewGroup.LayoutParams source) {
2981 super(source);
2982 cellHSpan = 1;
2983 cellVSpan = 1;
2984 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002985
2986 public LayoutParams(LayoutParams source) {
2987 super(source);
2988 this.cellX = source.cellX;
2989 this.cellY = source.cellY;
2990 this.cellHSpan = source.cellHSpan;
2991 this.cellVSpan = source.cellVSpan;
2992 }
2993
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002994 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002995 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002996 this.cellX = cellX;
2997 this.cellY = cellY;
2998 this.cellHSpan = cellHSpan;
2999 this.cellVSpan = cellVSpan;
3000 }
3001
Adam Cohen7f4eabe2011-04-21 16:19:16 -07003002 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap) {
Adam Cohend4844c32011-02-18 19:25:06 -08003003 if (isLockedToGrid) {
3004 final int myCellHSpan = cellHSpan;
3005 final int myCellVSpan = cellVSpan;
Adam Cohen482ed822012-03-02 14:15:13 -08003006 final int myCellX = useTmpCoords ? tmpCellX : cellX;
3007 final int myCellY = useTmpCoords ? tmpCellY : cellY;
Adam Cohen1b607ed2011-03-03 17:26:50 -08003008
Adam Cohend4844c32011-02-18 19:25:06 -08003009 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
3010 leftMargin - rightMargin;
3011 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
3012 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08003013 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
3014 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08003015 }
3016 }
Winson Chungaafa03c2010-06-11 17:34:16 -07003017
Winson Chungaafa03c2010-06-11 17:34:16 -07003018 public String toString() {
3019 return "(" + this.cellX + ", " + this.cellY + ")";
3020 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07003021
3022 public void setWidth(int width) {
3023 this.width = width;
3024 }
3025
3026 public int getWidth() {
3027 return width;
3028 }
3029
3030 public void setHeight(int height) {
3031 this.height = height;
3032 }
3033
3034 public int getHeight() {
3035 return height;
3036 }
3037
3038 public void setX(int x) {
3039 this.x = x;
3040 }
3041
3042 public int getX() {
3043 return x;
3044 }
3045
3046 public void setY(int y) {
3047 this.y = y;
3048 }
3049
3050 public int getY() {
3051 return y;
3052 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003053 }
3054
Michael Jurka0280c3b2010-09-17 15:00:07 -07003055 // This class stores info for two purposes:
3056 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
3057 // its spanX, spanY, and the screen it is on
3058 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
3059 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
3060 // the CellLayout that was long clicked
Michael Jurkae5fb0f22011-04-11 13:27:46 -07003061 static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003062 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07003063 int cellX = -1;
3064 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003065 int spanX;
3066 int spanY;
3067 int screen;
Winson Chung3d503fb2011-07-13 17:25:49 -07003068 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003069
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003070 @Override
3071 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07003072 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
3073 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003074 }
3075 }
Michael Jurkad771c962011-08-09 15:00:48 -07003076
3077 public boolean lastDownOnOccupiedCell() {
3078 return mLastDownOnOccupiedCell;
3079 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003080}