blob: 6f4759d1ed0d9222473801b95fad3958cdc00b3f [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;
20import android.animation.AnimatorListenerAdapter;
Chet Haase00397b12010-10-07 11:13:10 -070021import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070022import android.animation.ValueAnimator;
23import android.animation.ValueAnimator.AnimatorUpdateListener;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080024import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040025import android.content.res.Resources;
Winson Chungaafa03c2010-06-11 17:34:16 -070026import android.content.res.TypedArray;
Joe Onorato4be866d2010-10-10 11:26:02 -070027import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070028import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080029import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070030import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070031import android.graphics.Point;
32import android.graphics.PointF;
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;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070040import android.util.Log;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.view.MotionEvent;
42import android.view.View;
43import android.view.ViewDebug;
44import android.view.ViewGroup;
Winson Chungaafa03c2010-06-11 17:34:16 -070045import android.view.animation.Animation;
Winson Chung150fbab2010-09-29 17:14:26 -070046import android.view.animation.DecelerateInterpolator;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.view.animation.LayoutAnimationController;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080048
Adam Cohen66396872011-04-15 17:50:36 -070049import com.android.launcher.R;
Adam Cohen69ce2e52011-07-03 19:25:21 -070050import com.android.launcher2.FolderIcon.FolderRingAnimator;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070051
Adam Cohen69ce2e52011-07-03 19:25:21 -070052import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070053import java.util.Arrays;
Adam Cohenbfbfd262011-06-13 16:55:12 -070054import java.util.HashMap;
Adam Cohend41fbf52012-02-16 23:53:59 -080055import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070056
Michael Jurkabdb5c532011-02-01 15:05:06 -080057public class CellLayout extends ViewGroup {
Winson Chungaafa03c2010-06-11 17:34:16 -070058 static final String TAG = "CellLayout";
59
Adam Cohen2acce882012-03-28 19:03:19 -070060 private Launcher mLauncher;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061 private int mCellWidth;
62 private int mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070063
Adam Cohend22015c2010-07-26 22:02:18 -070064 private int mCountX;
65 private int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066
Adam Cohen234c4cd2011-07-17 21:03:04 -070067 private int mOriginalWidthGap;
68 private int mOriginalHeightGap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069 private int mWidthGap;
70 private int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070071 private int mMaxGap;
Adam Cohenebea84d2011-11-09 17:20:41 -080072 private boolean mScrollingTransformsDirty = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
74 private final Rect mRect = new Rect();
75 private final CellInfo mCellInfo = new CellInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -070076
Patrick Dubroyde7658b2010-09-27 11:15:43 -070077 // These are temporary variables to prevent having to allocate a new object just to
78 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Winson Chung0be025d2011-05-23 17:45:09 -070079 private final int[] mTmpXY = new int[2];
Patrick Dubroyde7658b2010-09-27 11:15:43 -070080 private final int[] mTmpPoint = new int[2];
81 private final PointF mTmpPointF = new PointF();
Adam Cohen69ce2e52011-07-03 19:25:21 -070082 int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070083
The Android Open Source Project31dd5032009-03-03 19:32:27 -080084 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -080085 boolean[][] mTmpOccupied;
Michael Jurkad771c962011-08-09 15:00:48 -070086 private boolean mLastDownOnOccupiedCell = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087
Michael Jurkadee05892010-07-27 10:01:56 -070088 private OnTouchListener mInterceptTouchListener;
89
Adam Cohen69ce2e52011-07-03 19:25:21 -070090 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -070091 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -070092
Adam Cohenb5ba0972011-09-07 18:02:31 -070093 private int mForegroundAlpha = 0;
Michael Jurka5f1c5092010-09-03 14:15:02 -070094 private float mBackgroundAlpha;
Adam Cohen1b0aaac2010-10-28 11:11:18 -070095 private float mBackgroundAlphaMultiplier = 1.0f;
Adam Cohenf34bab52010-09-30 14:11:56 -070096
Michael Jurka33945b22010-12-21 18:19:38 -080097 private Drawable mNormalBackground;
Michael Jurka33945b22010-12-21 18:19:38 -080098 private Drawable mActiveGlowBackground;
Adam Cohenb5ba0972011-09-07 18:02:31 -070099 private Drawable mOverScrollForegroundDrawable;
100 private Drawable mOverScrollLeft;
101 private Drawable mOverScrollRight;
Michael Jurka18014792010-10-14 09:01:34 -0700102 private Rect mBackgroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700103 private Rect mForegroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700104 private int mForegroundPadding;
Patrick Dubroy1262e362010-10-06 15:49:50 -0700105
Michael Jurka33945b22010-12-21 18:19:38 -0800106 // If we're actively dragging something over this screen, mIsDragOverlapping is true
107 private boolean mIsDragOverlapping = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700108 private final Point mDragCenter = new Point();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700109
Winson Chung150fbab2010-09-29 17:14:26 -0700110 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700111 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohend41fbf52012-02-16 23:53:59 -0800112 private Rect[] mDragOutlines = new Rect[4];
Chet Haase472b2812010-10-14 07:02:04 -0700113 private float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700114 private InterruptibleInOutAnimator[] mDragOutlineAnims =
115 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700116
117 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700118 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700119 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700120
Patrick Dubroy96864c32011-03-10 17:17:23 -0800121 private BubbleTextView mPressedOrFocusedIcon;
122
Adam Cohen482ed822012-03-02 14:15:13 -0800123 private HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new
124 HashMap<CellLayout.LayoutParams, Animator>();
Adam Cohen19f37922012-03-21 11:59:11 -0700125 private HashMap<View, ReorderHintAnimation>
126 mShakeAnimators = new HashMap<View, ReorderHintAnimation>();
127
128 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700129
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700130 // When a drag operation is in progress, holds the nearest cell to the touch point
131 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800132
Joe Onorato4be866d2010-10-10 11:26:02 -0700133 private boolean mDragging = false;
134
Patrick Dubroyce34a972010-10-19 10:34:32 -0700135 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700136 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700137
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800138 private boolean mIsHotseat = false;
Winson Chungeecf02d2012-03-02 17:14:58 -0800139 private float mChildScale = 1f;
140 private float mHotseatChildScale = 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 Cohen19f37922012-03-21 11:59:11 -0700152 private static final float REORDER_HINT_MAGNITUDE = 0.27f;
153 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
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800163 public CellLayout(Context context) {
164 this(context, null);
165 }
166
167 public CellLayout(Context context, AttributeSet attrs) {
168 this(context, attrs, 0);
169 }
170
171 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
172 super(context, attrs, defStyle);
Michael Jurka8b805b12012-04-18 14:23:14 -0700173 mDragEnforcer = new DropTarget.DragEnforcer(context);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700174
175 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
176 // the user where a dragged item will land when dropped.
177 setWillNotDraw(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700178 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700179
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
181
Adam Cohenf4bd5792012-04-27 11:35:29 -0700182 mCellWidth = a.getDimensionPixelSize(R.styleable.CellLayout_cellWidth, 10);
183 mCellHeight = a.getDimensionPixelSize(R.styleable.CellLayout_cellHeight, 10);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700184 mWidthGap = mOriginalWidthGap = a.getDimensionPixelSize(R.styleable.CellLayout_widthGap, 0);
185 mHeightGap = mOriginalHeightGap = a.getDimensionPixelSize(R.styleable.CellLayout_heightGap, 0);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700186 mMaxGap = a.getDimensionPixelSize(R.styleable.CellLayout_maxGap, 0);
Adam Cohend22015c2010-07-26 22:02:18 -0700187 mCountX = LauncherModel.getCellCountX();
188 mCountY = LauncherModel.getCellCountY();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700189 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800190 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700191 mPreviousReorderDirection[0] = INVALID_DIRECTION;
192 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800193
194 a.recycle();
195
196 setAlwaysDrawnWithCacheEnabled(false);
197
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700198 final Resources res = getResources();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700199
Winson Chung967289b2011-06-30 18:09:30 -0700200 mNormalBackground = res.getDrawable(R.drawable.homescreen_blue_normal_holo);
Winson Chungdea74b72011-09-13 18:06:43 -0700201 mActiveGlowBackground = res.getDrawable(R.drawable.homescreen_blue_strong_holo);
Michael Jurka33945b22010-12-21 18:19:38 -0800202
Adam Cohenb5ba0972011-09-07 18:02:31 -0700203 mOverScrollLeft = res.getDrawable(R.drawable.overscroll_glow_left);
204 mOverScrollRight = res.getDrawable(R.drawable.overscroll_glow_right);
205 mForegroundPadding =
206 res.getDimensionPixelSize(R.dimen.workspace_overscroll_drawable_padding);
Michael Jurka33945b22010-12-21 18:19:38 -0800207
Adam Cohen19f37922012-03-21 11:59:11 -0700208 mReorderHintAnimationMagnitude = (REORDER_HINT_MAGNITUDE *
209 res.getDimensionPixelSize(R.dimen.app_icon_size));
210
Winson Chungb26f3d62011-06-02 10:49:29 -0700211 mNormalBackground.setFilterBitmap(true);
Winson Chungb26f3d62011-06-02 10:49:29 -0700212 mActiveGlowBackground.setFilterBitmap(true);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700213
Winson Chungeecf02d2012-03-02 17:14:58 -0800214 int iconScale = res.getInteger(R.integer.app_icon_scale_percent);
215 if (iconScale >= 0) {
216 mChildScale = iconScale / 100f;
217 }
218 int hotseatIconScale = res.getInteger(R.integer.app_icon_hotseat_scale_percent);
219 if (hotseatIconScale >= 0) {
220 mHotseatChildScale = hotseatIconScale / 100f;
221 }
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800222
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700223 // Initialize the data structures used for the drag visualization.
Winson Chung150fbab2010-09-29 17:14:26 -0700224
Patrick Dubroyce34a972010-10-19 10:34:32 -0700225 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700226
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700227
Winson Chungb8c69f32011-10-19 21:36:08 -0700228 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700229 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800230 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700231 }
232
233 // When dragging things around the home screens, we show a green outline of
234 // where the item will land. The outlines gradually fade out, leaving a trail
235 // behind the drag path.
236 // Set up all the animations that are used to implement this fading.
237 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700238 final float fromAlphaValue = 0;
239 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700240
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700241 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700242
243 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700244 final InterruptibleInOutAnimator anim =
245 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700246 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700247 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700248 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700249 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700250 final Bitmap outline = (Bitmap)anim.getTag();
251
252 // If an animation is started and then stopped very quickly, we can still
253 // get spurious updates we've cleared the tag. Guard against this.
254 if (outline == null) {
Michael Jurka3a9fced2012-04-13 14:44:29 -0700255 @SuppressWarnings("all") // suppress dead code warning
256 final boolean debug = false;
257 if (debug) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700258 Object val = animation.getAnimatedValue();
259 Log.d(TAG, "anim " + thisIndex + " update: " + val +
260 ", isStopped " + anim.isStopped());
261 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700262 // Try to prevent it from continuing to run
263 animation.cancel();
264 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700265 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800266 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700267 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700268 }
269 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700270 // The animation holds a reference to the drag outline bitmap as long is it's
271 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700272 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700273 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700274 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700275 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700276 anim.setTag(null);
277 }
278 }
279 });
280 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700281 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700282
Michael Jurka18014792010-10-14 09:01:34 -0700283 mBackgroundRect = new Rect();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700284 mForegroundRect = new Rect();
Michael Jurkabea15192010-11-17 12:33:46 -0800285
Michael Jurkaa52570f2012-03-20 03:18:20 -0700286 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
287 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
288 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700289 }
290
Michael Jurkaf6440da2011-04-05 14:50:34 -0700291 static int widthInPortrait(Resources r, int numCells) {
292 // We use this method from Workspace to figure out how many rows/columns Launcher should
293 // have. We ignore the left/right padding on CellLayout because it turns out in our design
294 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700295 int cellWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700296 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
297 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700298
Winson Chung4b825dcd2011-06-19 12:41:22 -0700299 return minGap * (numCells - 1) + cellWidth * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700300 }
301
Michael Jurkaf6440da2011-04-05 14:50:34 -0700302 static int heightInLandscape(Resources r, int numCells) {
303 // We use this method from Workspace to figure out how many rows/columns Launcher should
304 // have. We ignore the left/right padding on CellLayout because it turns out in our design
305 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700306 int cellHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700307 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
308 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700309
Winson Chung4b825dcd2011-06-19 12:41:22 -0700310 return minGap * (numCells - 1) + cellHeight * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700311 }
312
Adam Cohen2801caf2011-05-13 20:57:39 -0700313 public void enableHardwareLayers() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700314 mShortcutsAndWidgets.enableHardwareLayers();
Adam Cohen2801caf2011-05-13 20:57:39 -0700315 }
316
317 public void setGridSize(int x, int y) {
318 mCountX = x;
319 mCountY = y;
320 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800321 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700322 mTempRectStack.clear();
Adam Cohen76fc0852011-06-17 13:26:23 -0700323 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700324 }
325
Patrick Dubroy96864c32011-03-10 17:17:23 -0800326 private void invalidateBubbleTextView(BubbleTextView icon) {
327 final int padding = icon.getPressedOrFocusedBackgroundPadding();
Winson Chung4b825dcd2011-06-19 12:41:22 -0700328 invalidate(icon.getLeft() + getPaddingLeft() - padding,
329 icon.getTop() + getPaddingTop() - padding,
330 icon.getRight() + getPaddingLeft() + padding,
331 icon.getBottom() + getPaddingTop() + padding);
Patrick Dubroy96864c32011-03-10 17:17:23 -0800332 }
333
Adam Cohenb5ba0972011-09-07 18:02:31 -0700334 void setOverScrollAmount(float r, boolean left) {
335 if (left && mOverScrollForegroundDrawable != mOverScrollLeft) {
336 mOverScrollForegroundDrawable = mOverScrollLeft;
337 } else if (!left && mOverScrollForegroundDrawable != mOverScrollRight) {
338 mOverScrollForegroundDrawable = mOverScrollRight;
339 }
340
341 mForegroundAlpha = (int) Math.round((r * 255));
342 mOverScrollForegroundDrawable.setAlpha(mForegroundAlpha);
343 invalidate();
344 }
345
Patrick Dubroy96864c32011-03-10 17:17:23 -0800346 void setPressedOrFocusedIcon(BubbleTextView icon) {
347 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
348 // requires an expanded clip rect (due to the glow's blur radius)
349 BubbleTextView oldIcon = mPressedOrFocusedIcon;
350 mPressedOrFocusedIcon = icon;
351 if (oldIcon != null) {
352 invalidateBubbleTextView(oldIcon);
353 }
354 if (mPressedOrFocusedIcon != null) {
355 invalidateBubbleTextView(mPressedOrFocusedIcon);
356 }
357 }
358
Michael Jurka33945b22010-12-21 18:19:38 -0800359 void setIsDragOverlapping(boolean isDragOverlapping) {
360 if (mIsDragOverlapping != isDragOverlapping) {
361 mIsDragOverlapping = isDragOverlapping;
362 invalidate();
363 }
364 }
365
366 boolean getIsDragOverlapping() {
367 return mIsDragOverlapping;
368 }
369
Adam Cohenebea84d2011-11-09 17:20:41 -0800370 protected void setOverscrollTransformsDirty(boolean dirty) {
371 mScrollingTransformsDirty = dirty;
372 }
373
374 protected void resetOverscrollTransforms() {
375 if (mScrollingTransformsDirty) {
376 setOverscrollTransformsDirty(false);
377 setTranslationX(0);
378 setRotationY(0);
379 // It doesn't matter if we pass true or false here, the important thing is that we
380 // pass 0, which results in the overscroll drawable not being drawn any more.
381 setOverScrollAmount(0, false);
382 setPivotX(getMeasuredWidth() / 2);
383 setPivotY(getMeasuredHeight() / 2);
384 }
385 }
386
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700387 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700388 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700389 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
390 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
391 // When we're small, we are either drawn normally or in the "accepts drops" state (during
392 // a drag). However, we also drag the mini hover background *over* one of those two
393 // backgrounds
Winson Chungb26f3d62011-06-02 10:49:29 -0700394 if (mBackgroundAlpha > 0.0f) {
Adam Cohenf34bab52010-09-30 14:11:56 -0700395 Drawable bg;
Michael Jurka33945b22010-12-21 18:19:38 -0800396
397 if (mIsDragOverlapping) {
398 // In the mini case, we draw the active_glow bg *over* the active background
Michael Jurkabdf78552011-10-31 14:34:25 -0700399 bg = mActiveGlowBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700400 } else {
Michael Jurkabdf78552011-10-31 14:34:25 -0700401 bg = mNormalBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700402 }
Michael Jurka33945b22010-12-21 18:19:38 -0800403
404 bg.setAlpha((int) (mBackgroundAlpha * mBackgroundAlphaMultiplier * 255));
405 bg.setBounds(mBackgroundRect);
406 bg.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700407 }
Romain Guya6abce82009-11-10 02:54:41 -0800408
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700409 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700410 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700411 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700412 if (alpha > 0) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800413 final Rect r = mDragOutlines[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700414 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700415 paint.setAlpha((int)(alpha + .5f));
Adam Cohend41fbf52012-02-16 23:53:59 -0800416 canvas.drawBitmap(b, null, r, paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700417 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700418 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800419
420 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
421 // requires an expanded clip rect (due to the glow's blur radius)
422 if (mPressedOrFocusedIcon != null) {
423 final int padding = mPressedOrFocusedIcon.getPressedOrFocusedBackgroundPadding();
424 final Bitmap b = mPressedOrFocusedIcon.getPressedOrFocusedBackground();
425 if (b != null) {
426 canvas.drawBitmap(b,
Winson Chung4b825dcd2011-06-19 12:41:22 -0700427 mPressedOrFocusedIcon.getLeft() + getPaddingLeft() - padding,
428 mPressedOrFocusedIcon.getTop() + getPaddingTop() - padding,
Patrick Dubroy96864c32011-03-10 17:17:23 -0800429 null);
430 }
431 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700432
Adam Cohen482ed822012-03-02 14:15:13 -0800433 if (DEBUG_VISUALIZE_OCCUPIED) {
434 int[] pt = new int[2];
435 ColorDrawable cd = new ColorDrawable(Color.RED);
436 cd.setBounds(0, 0, 80, 80);
437 for (int i = 0; i < mCountX; i++) {
438 for (int j = 0; j < mCountY; j++) {
439 if (mOccupied[i][j]) {
440 cellToPoint(i, j, pt);
441 canvas.save();
442 canvas.translate(pt[0], pt[1]);
443 cd.draw(canvas);
444 canvas.restore();
445 }
446 }
447 }
448 }
449
Andrew Flynn850d2e72012-04-26 16:51:20 -0700450 int previewOffset = FolderRingAnimator.sPreviewSize;
451
Adam Cohen69ce2e52011-07-03 19:25:21 -0700452 // The folder outer / inner ring image(s)
453 for (int i = 0; i < mFolderOuterRings.size(); i++) {
454 FolderRingAnimator fra = mFolderOuterRings.get(i);
455
456 // Draw outer ring
457 Drawable d = FolderRingAnimator.sSharedOuterRingDrawable;
458 int width = (int) fra.getOuterRingSize();
459 int height = width;
460 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
461
462 int centerX = mTempLocation[0] + mCellWidth / 2;
Andrew Flynn850d2e72012-04-26 16:51:20 -0700463 int centerY = mTempLocation[1] + previewOffset / 2;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700464
465 canvas.save();
466 canvas.translate(centerX - width / 2, centerY - height / 2);
467 d.setBounds(0, 0, width, height);
468 d.draw(canvas);
469 canvas.restore();
470
471 // Draw inner ring
472 d = FolderRingAnimator.sSharedInnerRingDrawable;
473 width = (int) fra.getInnerRingSize();
474 height = width;
475 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
476
477 centerX = mTempLocation[0] + mCellWidth / 2;
Andrew Flynn850d2e72012-04-26 16:51:20 -0700478 centerY = mTempLocation[1] + previewOffset / 2;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700479 canvas.save();
480 canvas.translate(centerX - width / 2, centerY - width / 2);
481 d.setBounds(0, 0, width, height);
482 d.draw(canvas);
483 canvas.restore();
484 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700485
486 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
487 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
488 int width = d.getIntrinsicWidth();
489 int height = d.getIntrinsicHeight();
490
491 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
492 int centerX = mTempLocation[0] + mCellWidth / 2;
Andrew Flynn850d2e72012-04-26 16:51:20 -0700493 int centerY = mTempLocation[1] + previewOffset / 2;
Adam Cohenc51934b2011-07-26 21:07:43 -0700494
495 canvas.save();
496 canvas.translate(centerX - width / 2, centerY - width / 2);
497 d.setBounds(0, 0, width, height);
498 d.draw(canvas);
499 canvas.restore();
500 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700501 }
502
Adam Cohenb5ba0972011-09-07 18:02:31 -0700503 @Override
504 protected void dispatchDraw(Canvas canvas) {
505 super.dispatchDraw(canvas);
506 if (mForegroundAlpha > 0) {
507 mOverScrollForegroundDrawable.setBounds(mForegroundRect);
508 Paint p = ((NinePatchDrawable) mOverScrollForegroundDrawable).getPaint();
509 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.ADD));
510 mOverScrollForegroundDrawable.draw(canvas);
511 p.setXfermode(null);
512 }
513 }
514
Adam Cohen69ce2e52011-07-03 19:25:21 -0700515 public void showFolderAccept(FolderRingAnimator fra) {
516 mFolderOuterRings.add(fra);
517 }
518
519 public void hideFolderAccept(FolderRingAnimator fra) {
520 if (mFolderOuterRings.contains(fra)) {
521 mFolderOuterRings.remove(fra);
522 }
523 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700524 }
525
Adam Cohenc51934b2011-07-26 21:07:43 -0700526 public void setFolderLeaveBehindCell(int x, int y) {
527 mFolderLeaveBehindCell[0] = x;
528 mFolderLeaveBehindCell[1] = y;
529 invalidate();
530 }
531
532 public void clearFolderLeaveBehind() {
533 mFolderLeaveBehindCell[0] = -1;
534 mFolderLeaveBehindCell[1] = -1;
535 invalidate();
536 }
537
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700538 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700539 public boolean shouldDelayChildPressedState() {
540 return false;
541 }
542
543 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700544 public void cancelLongPress() {
545 super.cancelLongPress();
546
547 // Cancel long press for all children
548 final int count = getChildCount();
549 for (int i = 0; i < count; i++) {
550 final View child = getChildAt(i);
551 child.cancelLongPress();
552 }
553 }
554
Michael Jurkadee05892010-07-27 10:01:56 -0700555 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
556 mInterceptTouchListener = listener;
557 }
558
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800559 int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700560 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800561 }
562
563 int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700564 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800565 }
566
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800567 public void setIsHotseat(boolean isHotseat) {
568 mIsHotseat = isHotseat;
569 }
570
Winson Chungeecf02d2012-03-02 17:14:58 -0800571 public float getChildrenScale() {
572 return mIsHotseat ? mHotseatChildScale : mChildScale;
573 }
574
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800575
Andrew Flynn850d2e72012-04-26 16:51:20 -0700576 private void scaleChild(BubbleTextView bubbleChild, float scale) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800577 // If we haven't measured the child yet, do it now
578 // (this happens if we're being dropped from all-apps
579 if (bubbleChild.getLayoutParams() instanceof LayoutParams &&
580 (bubbleChild.getMeasuredWidth() | bubbleChild.getMeasuredHeight()) == 0) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700581 getShortcutsAndWidgets().measureChild(bubbleChild);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800582 }
Andrew Flynnbc239a12012-03-06 11:39:49 -0800583
Andrew Flynnbc239a12012-03-06 11:39:49 -0800584 bubbleChild.setScaleX(scale);
585 bubbleChild.setScaleY(scale);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800586 }
587
588 private void resetChild(BubbleTextView bubbleChild) {
589 bubbleChild.setScaleX(1f);
590 bubbleChild.setScaleY(1f);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800591
592 bubbleChild.setTextColor(getResources().getColor(R.color.workspace_icon_text_color));
593 }
594
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800595 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Andrew Flynn850d2e72012-04-26 16:51:20 -0700596 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700597 final LayoutParams lp = params;
598
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800599 // Hotseat icons - scale down and remove text
600 // Don't scale the all apps button
601 // scale percent set to -1 means do not scale
602 // Only scale BubbleTextViews
603 if (child instanceof BubbleTextView) {
604 BubbleTextView bubbleChild = (BubbleTextView) child;
605
Andrew Flynnbc239a12012-03-06 11:39:49 -0800606 // Start the child with 100% scale and visible text
607 resetChild(bubbleChild);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800608
Andrew Flynn850d2e72012-04-26 16:51:20 -0700609 if (mIsHotseat && mHotseatChildScale >= 0) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800610 // Scale/make transparent for a hotseat
Andrew Flynn850d2e72012-04-26 16:51:20 -0700611 scaleChild(bubbleChild, mHotseatChildScale);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800612
Andrew Flynnbc239a12012-03-06 11:39:49 -0800613 bubbleChild.setTextColor(getResources().getColor(android.R.color.transparent));
Winson Chungeecf02d2012-03-02 17:14:58 -0800614 } else if (mChildScale >= 0) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800615 // Else possibly still scale it if we need to for smaller icons
Andrew Flynn850d2e72012-04-26 16:51:20 -0700616 scaleChild(bubbleChild, mChildScale);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800617 }
618 }
619
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800620 // Generate an id for each view, this assumes we have at most 256x256 cells
621 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700622 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700623 // If the horizontal or vertical span is set to -1, it is taken to
624 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700625 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
626 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627
Winson Chungaafa03c2010-06-11 17:34:16 -0700628 child.setId(childId);
629
Michael Jurkaa52570f2012-03-20 03:18:20 -0700630 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700631
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700632 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700633
Winson Chungaafa03c2010-06-11 17:34:16 -0700634 return true;
635 }
636 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800637 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700638
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800639 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700640 public void removeAllViews() {
641 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700642 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700643 }
644
645 @Override
646 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700647 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700648 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700649 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700650 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700651 }
652
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700653 public void removeViewWithoutMarkingCells(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700654 mShortcutsAndWidgets.removeView(view);
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700655 }
656
Michael Jurka0280c3b2010-09-17 15:00:07 -0700657 @Override
658 public void removeView(View view) {
659 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700660 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700661 }
662
663 @Override
664 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700665 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
666 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700667 }
668
669 @Override
670 public void removeViewInLayout(View view) {
671 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700672 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700673 }
674
675 @Override
676 public void removeViews(int start, int count) {
677 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700678 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700679 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700680 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700681 }
682
683 @Override
684 public void removeViewsInLayout(int start, int count) {
685 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700686 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700687 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700688 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800689 }
690
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800691 @Override
692 protected void onAttachedToWindow() {
693 super.onAttachedToWindow();
694 mCellInfo.screen = ((ViewGroup) getParent()).indexOfChild(this);
695 }
696
Michael Jurkaaf442092010-06-10 17:01:57 -0700697 public void setTagToCellInfoForPoint(int touchX, int touchY) {
698 final CellInfo cellInfo = mCellInfo;
Winson Chungeecf02d2012-03-02 17:14:58 -0800699 Rect frame = mRect;
Michael Jurka8b805b12012-04-18 14:23:14 -0700700 final int x = touchX + getScrollX();
701 final int y = touchY + getScrollY();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700702 final int count = mShortcutsAndWidgets.getChildCount();
Michael Jurkaaf442092010-06-10 17:01:57 -0700703
704 boolean found = false;
705 for (int i = count - 1; i >= 0; i--) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700706 final View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohend4844c32011-02-18 19:25:06 -0800707 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurkaaf442092010-06-10 17:01:57 -0700708
Adam Cohen1b607ed2011-03-03 17:26:50 -0800709 if ((child.getVisibility() == VISIBLE || child.getAnimation() != null) &&
710 lp.isLockedToGrid) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700711 child.getHitRect(frame);
Winson Chung0be025d2011-05-23 17:45:09 -0700712
Winson Chungeecf02d2012-03-02 17:14:58 -0800713 float scale = child.getScaleX();
714 frame = new Rect(child.getLeft(), child.getTop(), child.getRight(),
715 child.getBottom());
Winson Chung0be025d2011-05-23 17:45:09 -0700716 // The child hit rect is relative to the CellLayoutChildren parent, so we need to
717 // offset that by this CellLayout's padding to test an (x,y) point that is relative
718 // to this view.
Michael Jurka8b805b12012-04-18 14:23:14 -0700719 frame.offset(getPaddingLeft(), getPaddingTop());
Winson Chungeecf02d2012-03-02 17:14:58 -0800720 frame.inset((int) (frame.width() * (1f - scale) / 2),
721 (int) (frame.height() * (1f - scale) / 2));
Winson Chung0be025d2011-05-23 17:45:09 -0700722
Michael Jurkaaf442092010-06-10 17:01:57 -0700723 if (frame.contains(x, y)) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700724 cellInfo.cell = child;
725 cellInfo.cellX = lp.cellX;
726 cellInfo.cellY = lp.cellY;
727 cellInfo.spanX = lp.cellHSpan;
728 cellInfo.spanY = lp.cellVSpan;
Michael Jurkaaf442092010-06-10 17:01:57 -0700729 found = true;
Michael Jurkaaf442092010-06-10 17:01:57 -0700730 break;
731 }
732 }
733 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700734
Michael Jurkad771c962011-08-09 15:00:48 -0700735 mLastDownOnOccupiedCell = found;
736
Michael Jurkaaf442092010-06-10 17:01:57 -0700737 if (!found) {
Winson Chung0be025d2011-05-23 17:45:09 -0700738 final int cellXY[] = mTmpXY;
Michael Jurkaaf442092010-06-10 17:01:57 -0700739 pointToCellExact(x, y, cellXY);
740
Michael Jurkaaf442092010-06-10 17:01:57 -0700741 cellInfo.cell = null;
742 cellInfo.cellX = cellXY[0];
743 cellInfo.cellY = cellXY[1];
744 cellInfo.spanX = 1;
745 cellInfo.spanY = 1;
Michael Jurkaaf442092010-06-10 17:01:57 -0700746 }
747 setTag(cellInfo);
748 }
749
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800750 @Override
751 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohenc1997fd2011-08-15 18:26:39 -0700752 // First we clear the tag to ensure that on every touch down we start with a fresh slate,
753 // even in the case where we return early. Not clearing here was causing bugs whereby on
754 // long-press we'd end up picking up an item from a previous drag operation.
755 final int action = ev.getAction();
756
757 if (action == MotionEvent.ACTION_DOWN) {
758 clearTagCellInfo();
759 }
760
Michael Jurkadee05892010-07-27 10:01:56 -0700761 if (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev)) {
762 return true;
763 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800764
765 if (action == MotionEvent.ACTION_DOWN) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700766 setTagToCellInfoForPoint((int) ev.getX(), (int) ev.getY());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800767 }
Winson Chungeecf02d2012-03-02 17:14:58 -0800768
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800769 return false;
770 }
771
Adam Cohenc1997fd2011-08-15 18:26:39 -0700772 private void clearTagCellInfo() {
773 final CellInfo cellInfo = mCellInfo;
774 cellInfo.cell = null;
775 cellInfo.cellX = -1;
776 cellInfo.cellY = -1;
777 cellInfo.spanX = 0;
778 cellInfo.spanY = 0;
779 setTag(cellInfo);
780 }
781
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800782 public CellInfo getTag() {
Michael Jurka0280c3b2010-09-17 15:00:07 -0700783 return (CellInfo) super.getTag();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800784 }
785
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700786 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700787 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800788 * @param x X coordinate of the point
789 * @param y Y coordinate of the point
790 * @param result Array of 2 ints to hold the x and y coordinate of the cell
791 */
792 void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700793 final int hStartPadding = getPaddingLeft();
794 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800795
796 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
797 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
798
Adam Cohend22015c2010-07-26 22:02:18 -0700799 final int xAxis = mCountX;
800 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800801
802 if (result[0] < 0) result[0] = 0;
803 if (result[0] >= xAxis) result[0] = xAxis - 1;
804 if (result[1] < 0) result[1] = 0;
805 if (result[1] >= yAxis) result[1] = yAxis - 1;
806 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700807
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800808 /**
809 * Given a point, return the cell that most closely encloses that point
810 * @param x X coordinate of the point
811 * @param y Y coordinate of the point
812 * @param result Array of 2 ints to hold the x and y coordinate of the cell
813 */
814 void pointToCellRounded(int x, int y, int[] result) {
815 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
816 }
817
818 /**
819 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700820 *
821 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800822 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700823 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800824 * @param result Array of 2 ints to hold the x and y coordinate of the point
825 */
826 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700827 final int hStartPadding = getPaddingLeft();
828 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800829
830 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
831 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
832 }
833
Adam Cohene3e27a82011-04-15 12:07:39 -0700834 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800835 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700836 *
837 * @param cellX X coordinate of the cell
838 * @param cellY Y coordinate of the cell
839 *
840 * @param result Array of 2 ints to hold the x and y coordinate of the point
841 */
842 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700843 regionToCenterPoint(cellX, cellY, 1, 1, result);
844 }
845
846 /**
847 * Given a cell coordinate and span return the point that represents the center of the regio
848 *
849 * @param cellX X coordinate of the cell
850 * @param cellY Y coordinate of the cell
851 *
852 * @param result Array of 2 ints to hold the x and y coordinate of the point
853 */
854 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700855 final int hStartPadding = getPaddingLeft();
856 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700857 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
858 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
859 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
860 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700861 }
862
Adam Cohen19f37922012-03-21 11:59:11 -0700863 /**
864 * Given a cell coordinate and span fills out a corresponding pixel rect
865 *
866 * @param cellX X coordinate of the cell
867 * @param cellY Y coordinate of the cell
868 * @param result Rect in which to write the result
869 */
870 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
871 final int hStartPadding = getPaddingLeft();
872 final int vStartPadding = getPaddingTop();
873 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
874 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
875 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
876 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
877 }
878
Adam Cohen482ed822012-03-02 14:15:13 -0800879 public float getDistanceFromCell(float x, float y, int[] cell) {
880 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
881 float distance = (float) Math.sqrt( Math.pow(x - mTmpPoint[0], 2) +
882 Math.pow(y - mTmpPoint[1], 2));
883 return distance;
884 }
885
Romain Guy84f296c2009-11-04 15:00:44 -0800886 int getCellWidth() {
887 return mCellWidth;
888 }
889
890 int getCellHeight() {
891 return mCellHeight;
892 }
893
Adam Cohend4844c32011-02-18 19:25:06 -0800894 int getWidthGap() {
895 return mWidthGap;
896 }
897
898 int getHeightGap() {
899 return mHeightGap;
900 }
901
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700902 Rect getContentRect(Rect r) {
903 if (r == null) {
904 r = new Rect();
905 }
906 int left = getPaddingLeft();
907 int top = getPaddingTop();
Michael Jurka8b805b12012-04-18 14:23:14 -0700908 int right = left + getWidth() - getPaddingLeft() - getPaddingRight();
909 int bottom = top + getHeight() - getPaddingTop() - getPaddingBottom();
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700910 r.set(left, top, right, bottom);
911 return r;
912 }
913
Adam Cohena897f392012-04-27 18:12:05 -0700914 static void getMetrics(Rect metrics, Resources res, int measureWidth, int measureHeight,
915 int countX, int countY, int orientation) {
916 int numWidthGaps = countX - 1;
917 int numHeightGaps = countY - 1;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700918
919 int widthGap;
920 int heightGap;
921 int cellWidth;
922 int cellHeight;
923 int paddingLeft;
924 int paddingRight;
925 int paddingTop;
926 int paddingBottom;
927
Adam Cohena897f392012-04-27 18:12:05 -0700928 int maxGap = res.getDimensionPixelSize(R.dimen.workspace_max_gap);
Adam Cohenf4bd5792012-04-27 11:35:29 -0700929 if (orientation == LANDSCAPE) {
930 cellWidth = res.getDimensionPixelSize(R.dimen.workspace_cell_width_land);
931 cellHeight = res.getDimensionPixelSize(R.dimen.workspace_cell_height_land);
932 widthGap = res.getDimensionPixelSize(R.dimen.workspace_width_gap_land);
933 heightGap = res.getDimensionPixelSize(R.dimen.workspace_height_gap_land);
934 paddingLeft = res.getDimensionPixelSize(R.dimen.cell_layout_left_padding_land);
935 paddingRight = res.getDimensionPixelSize(R.dimen.cell_layout_right_padding_land);
936 paddingTop = res.getDimensionPixelSize(R.dimen.cell_layout_top_padding_land);
937 paddingBottom = res.getDimensionPixelSize(R.dimen.cell_layout_bottom_padding_land);
938 } else {
939 // PORTRAIT
940 cellWidth = res.getDimensionPixelSize(R.dimen.workspace_cell_width_port);
941 cellHeight = res.getDimensionPixelSize(R.dimen.workspace_cell_height_port);
942 widthGap = res.getDimensionPixelSize(R.dimen.workspace_width_gap_port);
943 heightGap = res.getDimensionPixelSize(R.dimen.workspace_height_gap_port);
944 paddingLeft = res.getDimensionPixelSize(R.dimen.cell_layout_left_padding_port);
945 paddingRight = res.getDimensionPixelSize(R.dimen.cell_layout_right_padding_port);
946 paddingTop = res.getDimensionPixelSize(R.dimen.cell_layout_top_padding_port);
947 paddingBottom = res.getDimensionPixelSize(R.dimen.cell_layout_bottom_padding_port);
948 }
949
950 if (widthGap < 0 || heightGap < 0) {
951 int hSpace = measureWidth - paddingLeft - paddingRight;
952 int vSpace = measureHeight - paddingTop - paddingBottom;
Adam Cohena897f392012-04-27 18:12:05 -0700953 int hFreeSpace = hSpace - (countX * cellWidth);
954 int vFreeSpace = vSpace - (countY * cellHeight);
955 widthGap = Math.min(maxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
956 heightGap = Math.min(maxGap, numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Adam Cohenf4bd5792012-04-27 11:35:29 -0700957 }
958 metrics.set(cellWidth, cellHeight, widthGap, heightGap);
959 }
960
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800961 @Override
962 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800963 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700964 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
965
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800966 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
967 int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700968
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800969 if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
970 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
971 }
972
Adam Cohend22015c2010-07-26 22:02:18 -0700973 int numWidthGaps = mCountX - 1;
974 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800975
Adam Cohen234c4cd2011-07-17 21:03:04 -0700976 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Michael Jurkadd13e3d2012-05-01 12:38:17 -0700977 int hSpace = widthSpecSize - getPaddingLeft() - getPaddingRight();
978 int vSpace = heightSpecSize - getPaddingTop() - getPaddingBottom();
Adam Cohenf4bd5792012-04-27 11:35:29 -0700979 int hFreeSpace = hSpace - (mCountX * mCellWidth);
980 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700981 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
982 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700983 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700984 } else {
985 mWidthGap = mOriginalWidthGap;
986 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700987 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700988
Michael Jurka8c920dd2011-01-20 14:16:56 -0800989 // Initial values correspond to widthSpecMode == MeasureSpec.EXACTLY
990 int newWidth = widthSpecSize;
991 int newHeight = heightSpecSize;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700992 if (widthSpecMode == MeasureSpec.AT_MOST) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700993 newWidth = getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700994 ((mCountX - 1) * mWidthGap);
Michael Jurka8b805b12012-04-18 14:23:14 -0700995 newHeight = getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700996 ((mCountY - 1) * mHeightGap);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700997 setMeasuredDimension(newWidth, newHeight);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700998 }
Michael Jurka8c920dd2011-01-20 14:16:56 -0800999
1000 int count = getChildCount();
1001 for (int i = 0; i < count; i++) {
1002 View child = getChildAt(i);
Michael Jurka8b805b12012-04-18 14:23:14 -07001003 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth - getPaddingLeft() -
1004 getPaddingRight(), MeasureSpec.EXACTLY);
1005 int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight - getPaddingTop() -
1006 getPaddingBottom(), MeasureSpec.EXACTLY);
Michael Jurka8c920dd2011-01-20 14:16:56 -08001007 child.measure(childWidthMeasureSpec, childheightMeasureSpec);
1008 }
1009 setMeasuredDimension(newWidth, newHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001010 }
1011
1012 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -07001013 protected void onLayout(boolean changed, int l, int t, int r, int b) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001014 int count = getChildCount();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001015 for (int i = 0; i < count; i++) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08001016 View child = getChildAt(i);
Michael Jurka8b805b12012-04-18 14:23:14 -07001017 child.layout(getPaddingLeft(), getPaddingTop(),
1018 r - l - getPaddingRight(), b - t - getPaddingBottom());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001019 }
1020 }
1021
1022 @Override
Michael Jurkadee05892010-07-27 10:01:56 -07001023 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1024 super.onSizeChanged(w, h, oldw, oldh);
Michael Jurka18014792010-10-14 09:01:34 -07001025 mBackgroundRect.set(0, 0, w, h);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001026 mForegroundRect.set(mForegroundPadding, mForegroundPadding,
1027 w - 2 * mForegroundPadding, h - 2 * mForegroundPadding);
Michael Jurkadee05892010-07-27 10:01:56 -07001028 }
1029
1030 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001031 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001032 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001033 }
1034
1035 @Override
1036 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001037 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001038 }
1039
Michael Jurka5f1c5092010-09-03 14:15:02 -07001040 public float getBackgroundAlpha() {
1041 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -07001042 }
1043
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001044 public void setBackgroundAlphaMultiplier(float multiplier) {
1045 mBackgroundAlphaMultiplier = multiplier;
1046 }
1047
Adam Cohenddb82192010-11-10 16:32:54 -08001048 public float getBackgroundAlphaMultiplier() {
1049 return mBackgroundAlphaMultiplier;
1050 }
1051
Michael Jurka5f1c5092010-09-03 14:15:02 -07001052 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -08001053 if (mBackgroundAlpha != alpha) {
1054 mBackgroundAlpha = alpha;
1055 invalidate();
1056 }
Michael Jurkadee05892010-07-27 10:01:56 -07001057 }
1058
Michael Jurkaa52570f2012-03-20 03:18:20 -07001059 public void setShortcutAndWidgetAlpha(float alpha) {
Michael Jurka0142d492010-08-25 17:46:15 -07001060 final int childCount = getChildCount();
1061 for (int i = 0; i < childCount; i++) {
Michael Jurkadee05892010-07-27 10:01:56 -07001062 getChildAt(i).setAlpha(alpha);
1063 }
1064 }
1065
Michael Jurkaa52570f2012-03-20 03:18:20 -07001066 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
1067 if (getChildCount() > 0) {
1068 return (ShortcutAndWidgetContainer) getChildAt(0);
1069 }
1070 return null;
1071 }
1072
Patrick Dubroy440c3602010-07-13 17:50:32 -07001073 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001074 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001075 }
1076
Adam Cohen76fc0852011-06-17 13:26:23 -07001077 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001078 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001079 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -08001080 boolean[][] occupied = mOccupied;
1081 if (!permanent) {
1082 occupied = mTmpOccupied;
1083 }
1084
Adam Cohen19f37922012-03-21 11:59:11 -07001085 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001086 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
1087 final ItemInfo info = (ItemInfo) child.getTag();
1088
1089 // We cancel any existing animations
1090 if (mReorderAnimators.containsKey(lp)) {
1091 mReorderAnimators.get(lp).cancel();
1092 mReorderAnimators.remove(lp);
1093 }
1094
Adam Cohen482ed822012-03-02 14:15:13 -08001095 final int oldX = lp.x;
1096 final int oldY = lp.y;
1097 if (adjustOccupied) {
1098 occupied[lp.cellX][lp.cellY] = false;
1099 occupied[cellX][cellY] = true;
1100 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001101 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001102 if (permanent) {
1103 lp.cellX = info.cellX = cellX;
1104 lp.cellY = info.cellY = cellY;
1105 } else {
1106 lp.tmpCellX = cellX;
1107 lp.tmpCellY = cellY;
1108 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001109 clc.setupLp(lp);
1110 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001111 final int newX = lp.x;
1112 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001113
Adam Cohen76fc0852011-06-17 13:26:23 -07001114 lp.x = oldX;
1115 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001116
Adam Cohen482ed822012-03-02 14:15:13 -08001117 // Exit early if we're not actually moving the view
1118 if (oldX == newX && oldY == newY) {
1119 lp.isLockedToGrid = true;
1120 return true;
1121 }
1122
1123 ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
1124 va.setDuration(duration);
1125 mReorderAnimators.put(lp, va);
1126
1127 va.addUpdateListener(new AnimatorUpdateListener() {
1128 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001129 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001130 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001131 lp.x = (int) ((1 - r) * oldX + r * newX);
1132 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001133 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001134 }
1135 });
Adam Cohen482ed822012-03-02 14:15:13 -08001136 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001137 boolean cancelled = false;
1138 public void onAnimationEnd(Animator animation) {
1139 // If the animation was cancelled, it means that another animation
1140 // has interrupted this one, and we don't want to lock the item into
1141 // place just yet.
1142 if (!cancelled) {
1143 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001144 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001145 }
1146 if (mReorderAnimators.containsKey(lp)) {
1147 mReorderAnimators.remove(lp);
1148 }
1149 }
1150 public void onAnimationCancel(Animator animation) {
1151 cancelled = true;
1152 }
1153 });
Adam Cohen482ed822012-03-02 14:15:13 -08001154 va.setStartDelay(delay);
1155 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001156 return true;
1157 }
1158 return false;
1159 }
1160
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001161 /**
1162 * Estimate where the top left cell of the dragged item will land if it is dropped.
1163 *
1164 * @param originX The X value of the top left corner of the item
1165 * @param originY The Y value of the top left corner of the item
1166 * @param spanX The number of horizontal cells that the item spans
1167 * @param spanY The number of vertical cells that the item spans
1168 * @param result The estimated drop cell X and Y.
1169 */
1170 void estimateDropCell(int originX, int originY, int spanX, int spanY, int[] result) {
Adam Cohend22015c2010-07-26 22:02:18 -07001171 final int countX = mCountX;
1172 final int countY = mCountY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001173
Michael Jurkaa63c4522010-08-19 13:52:27 -07001174 // pointToCellRounded takes the top left of a cell but will pad that with
1175 // cellWidth/2 and cellHeight/2 when finding the matching cell
1176 pointToCellRounded(originX, originY, result);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001177
1178 // If the item isn't fully on this screen, snap to the edges
1179 int rightOverhang = result[0] + spanX - countX;
1180 if (rightOverhang > 0) {
1181 result[0] -= rightOverhang; // Snap to right
1182 }
1183 result[0] = Math.max(0, result[0]); // Snap to left
1184 int bottomOverhang = result[1] + spanY - countY;
1185 if (bottomOverhang > 0) {
1186 result[1] -= bottomOverhang; // Snap to bottom
1187 }
1188 result[1] = Math.max(0, result[1]); // Snap to top
1189 }
1190
Adam Cohen482ed822012-03-02 14:15:13 -08001191 void visualizeDropLocation(View v, Bitmap dragOutline, int originX, int originY, int cellX,
1192 int cellY, int spanX, int spanY, boolean resize, Point dragOffset, Rect dragRegion) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001193 final int oldDragCellX = mDragCell[0];
1194 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001195
Winson Chungb8c69f32011-10-19 21:36:08 -07001196 if (v != null && dragOffset == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07001197 mDragCenter.set(originX + (v.getWidth() / 2), originY + (v.getHeight() / 2));
1198 } else {
1199 mDragCenter.set(originX, originY);
1200 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001201
Adam Cohen2801caf2011-05-13 20:57:39 -07001202 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001203 return;
1204 }
1205
Adam Cohen482ed822012-03-02 14:15:13 -08001206 if (cellX != oldDragCellX || cellY != oldDragCellY) {
1207 mDragCell[0] = cellX;
1208 mDragCell[1] = cellY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001209 // Find the top left corner of the rect the object will occupy
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001210 final int[] topLeft = mTmpPoint;
Adam Cohen482ed822012-03-02 14:15:13 -08001211 cellToPoint(cellX, cellY, topLeft);
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001212
Joe Onorato4be866d2010-10-10 11:26:02 -07001213 int left = topLeft[0];
1214 int top = topLeft[1];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001215
Winson Chungb8c69f32011-10-19 21:36:08 -07001216 if (v != null && dragOffset == null) {
Adam Cohen99e8b402011-03-25 19:23:43 -07001217 // When drawing the drag outline, it did not account for margin offsets
1218 // added by the view's parent.
1219 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1220 left += lp.leftMargin;
1221 top += lp.topMargin;
Winson Chung150fbab2010-09-29 17:14:26 -07001222
Adam Cohen99e8b402011-03-25 19:23:43 -07001223 // Offsets due to the size difference between the View and the dragOutline.
1224 // There is a size difference to account for the outer blur, which may lie
1225 // outside the bounds of the view.
Winson Chunga9abd0e2010-10-27 17:18:37 -07001226 top += (v.getHeight() - dragOutline.getHeight()) / 2;
Adam Cohenae915ce2011-08-25 13:47:22 -07001227 // We center about the x axis
1228 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1229 - dragOutline.getWidth()) / 2;
Adam Cohen66396872011-04-15 17:50:36 -07001230 } else {
Winson Chungb8c69f32011-10-19 21:36:08 -07001231 if (dragOffset != null && dragRegion != null) {
1232 // Center the drag region *horizontally* in the cell and apply a drag
1233 // outline offset
1234 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1235 - dragRegion.width()) / 2;
1236 top += dragOffset.y;
1237 } else {
1238 // Center the drag outline in the cell
1239 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1240 - dragOutline.getWidth()) / 2;
1241 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1242 - dragOutline.getHeight()) / 2;
1243 }
Winson Chunga9abd0e2010-10-27 17:18:37 -07001244 }
Joe Onorato4be866d2010-10-10 11:26:02 -07001245 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001246 mDragOutlineAnims[oldIndex].animateOut();
1247 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001248 Rect r = mDragOutlines[mDragOutlineCurrent];
1249 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
1250 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001251 cellToRect(cellX, cellY, spanX, spanY, r);
Adam Cohend41fbf52012-02-16 23:53:59 -08001252 }
Winson Chung150fbab2010-09-29 17:14:26 -07001253
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001254 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1255 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001256 }
1257 }
1258
Adam Cohene0310962011-04-18 16:15:31 -07001259 public void clearDragOutlines() {
1260 final int oldIndex = mDragOutlineCurrent;
1261 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001262 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001263 }
1264
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001265 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001266 * Find a vacant area that will fit the given bounds nearest the requested
1267 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001268 *
Romain Guy51afc022009-05-04 18:03:43 -07001269 * @param pixelX The X location at which you want to search for a vacant area.
1270 * @param pixelY The Y location at which you want to search for a vacant area.
Jeff Sharkey70864282009-04-07 21:08:40 -07001271 * @param spanX Horizontal span of the object.
1272 * @param spanY Vertical span of the object.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001273 * @param result Array in which to place the result, or null (in which case a new array will
1274 * be allocated)
Jeff Sharkey70864282009-04-07 21:08:40 -07001275 * @return The X, Y cell of a vacant area that can contain this object,
1276 * nearest the requested location.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001277 */
Adam Cohend41fbf52012-02-16 23:53:59 -08001278 int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY,
1279 int[] result) {
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001280 return findNearestVacantArea(pixelX, pixelY, spanX, spanY, null, result);
Michael Jurka6a1435d2010-09-27 17:35:12 -07001281 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001282
Michael Jurka6a1435d2010-09-27 17:35:12 -07001283 /**
1284 * Find a vacant area that will fit the given bounds nearest the requested
1285 * cell location. Uses Euclidean distance to score multiple vacant areas.
1286 *
1287 * @param pixelX The X location at which you want to search for a vacant area.
1288 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001289 * @param minSpanX The minimum horizontal span required
1290 * @param minSpanY The minimum vertical span required
1291 * @param spanX Horizontal span of the object.
1292 * @param spanY Vertical span of the object.
1293 * @param result Array in which to place the result, or null (in which case a new array will
1294 * be allocated)
1295 * @return The X, Y cell of a vacant area that can contain this object,
1296 * nearest the requested location.
1297 */
1298 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1299 int spanY, int[] result, int[] resultSpan) {
1300 return findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null,
1301 result, resultSpan);
1302 }
1303
1304 /**
1305 * Find a vacant area that will fit the given bounds nearest the requested
1306 * cell location. Uses Euclidean distance to score multiple vacant areas.
1307 *
1308 * @param pixelX The X location at which you want to search for a vacant area.
1309 * @param pixelY The Y location at which you want to search for a vacant area.
Michael Jurka6a1435d2010-09-27 17:35:12 -07001310 * @param spanX Horizontal span of the object.
1311 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07001312 * @param ignoreOccupied If true, the result can be an occupied cell
1313 * @param result Array in which to place the result, or null (in which case a new array will
1314 * be allocated)
Michael Jurka6a1435d2010-09-27 17:35:12 -07001315 * @return The X, Y cell of a vacant area that can contain this object,
1316 * nearest the requested location.
1317 */
Adam Cohendf035382011-04-11 17:22:04 -07001318 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, View ignoreView,
1319 boolean ignoreOccupied, int[] result) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001320 return findNearestArea(pixelX, pixelY, spanX, spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001321 spanX, spanY, ignoreView, ignoreOccupied, result, null, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08001322 }
1323
1324 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1325 private void lazyInitTempRectStack() {
1326 if (mTempRectStack.isEmpty()) {
1327 for (int i = 0; i < mCountX * mCountY; i++) {
1328 mTempRectStack.push(new Rect());
1329 }
1330 }
1331 }
Adam Cohen482ed822012-03-02 14:15:13 -08001332
Adam Cohend41fbf52012-02-16 23:53:59 -08001333 private void recycleTempRects(Stack<Rect> used) {
1334 while (!used.isEmpty()) {
1335 mTempRectStack.push(used.pop());
1336 }
1337 }
1338
1339 /**
1340 * Find a vacant area that will fit the given bounds nearest the requested
1341 * cell location. Uses Euclidean distance to score multiple vacant areas.
1342 *
1343 * @param pixelX The X location at which you want to search for a vacant area.
1344 * @param pixelY The Y location at which you want to search for a vacant area.
1345 * @param minSpanX The minimum horizontal span required
1346 * @param minSpanY The minimum vertical span required
1347 * @param spanX Horizontal span of the object.
1348 * @param spanY Vertical span of the object.
1349 * @param ignoreOccupied If true, the result can be an occupied cell
1350 * @param result Array in which to place the result, or null (in which case a new array will
1351 * be allocated)
1352 * @return The X, Y cell of a vacant area that can contain this object,
1353 * nearest the requested location.
1354 */
1355 int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001356 View ignoreView, boolean ignoreOccupied, int[] result, int[] resultSpan,
1357 boolean[][] occupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001358 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001359 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08001360 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001361
Adam Cohene3e27a82011-04-15 12:07:39 -07001362 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1363 // to the center of the item, but we are searching based on the top-left cell, so
1364 // we translate the point over to correspond to the top-left.
1365 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1366 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1367
Jeff Sharkey70864282009-04-07 21:08:40 -07001368 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001369 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001370 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001371 final Rect bestRect = new Rect(-1, -1, -1, -1);
1372 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001373
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001374 final int countX = mCountX;
1375 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001376
Adam Cohend41fbf52012-02-16 23:53:59 -08001377 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1378 spanX < minSpanX || spanY < minSpanY) {
1379 return bestXY;
1380 }
1381
1382 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001383 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001384 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1385 int ySize = -1;
1386 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001387 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001388 // First, let's see if this thing fits anywhere
1389 for (int i = 0; i < minSpanX; i++) {
1390 for (int j = 0; j < minSpanY; j++) {
Adam Cohendf035382011-04-11 17:22:04 -07001391 if (occupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001392 continue inner;
1393 }
Michael Jurkac28de512010-08-13 11:27:44 -07001394 }
1395 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001396 xSize = minSpanX;
1397 ySize = minSpanY;
1398
1399 // We know that the item will fit at _some_ acceptable size, now let's see
1400 // how big we can make it. We'll alternate between incrementing x and y spans
1401 // until we hit a limit.
1402 boolean incX = true;
1403 boolean hitMaxX = xSize >= spanX;
1404 boolean hitMaxY = ySize >= spanY;
1405 while (!(hitMaxX && hitMaxY)) {
1406 if (incX && !hitMaxX) {
1407 for (int j = 0; j < ySize; j++) {
1408 if (x + xSize > countX -1 || occupied[x + xSize][y + j]) {
1409 // We can't move out horizontally
1410 hitMaxX = true;
1411 }
1412 }
1413 if (!hitMaxX) {
1414 xSize++;
1415 }
1416 } else if (!hitMaxY) {
1417 for (int i = 0; i < xSize; i++) {
1418 if (y + ySize > countY - 1 || occupied[x + i][y + ySize]) {
1419 // We can't move out vertically
1420 hitMaxY = true;
1421 }
1422 }
1423 if (!hitMaxY) {
1424 ySize++;
1425 }
1426 }
1427 hitMaxX |= xSize >= spanX;
1428 hitMaxY |= ySize >= spanY;
1429 incX = !incX;
1430 }
1431 incX = true;
1432 hitMaxX = xSize >= spanX;
1433 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001434 }
Winson Chung0be025d2011-05-23 17:45:09 -07001435 final int[] cellXY = mTmpXY;
Adam Cohene3e27a82011-04-15 12:07:39 -07001436 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001437
Adam Cohend41fbf52012-02-16 23:53:59 -08001438 // We verify that the current rect is not a sub-rect of any of our previous
1439 // candidates. In this case, the current rect is disqualified in favour of the
1440 // containing rect.
1441 Rect currentRect = mTempRectStack.pop();
1442 currentRect.set(x, y, x + xSize, y + ySize);
1443 boolean contained = false;
1444 for (Rect r : validRegions) {
1445 if (r.contains(currentRect)) {
1446 contained = true;
1447 break;
1448 }
1449 }
1450 validRegions.push(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001451 double distance = Math.sqrt(Math.pow(cellXY[0] - pixelX, 2)
1452 + Math.pow(cellXY[1] - pixelY, 2));
Adam Cohen482ed822012-03-02 14:15:13 -08001453
Adam Cohend41fbf52012-02-16 23:53:59 -08001454 if ((distance <= bestDistance && !contained) ||
1455 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001456 bestDistance = distance;
1457 bestXY[0] = x;
1458 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001459 if (resultSpan != null) {
1460 resultSpan[0] = xSize;
1461 resultSpan[1] = ySize;
1462 }
1463 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001464 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001465 }
1466 }
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001467 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08001468 markCellsAsOccupiedForView(ignoreView, occupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001469
Adam Cohenc0dcf592011-06-01 15:30:43 -07001470 // Return -1, -1 if no suitable location found
1471 if (bestDistance == Double.MAX_VALUE) {
1472 bestXY[0] = -1;
1473 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001474 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001475 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001476 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001477 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001478
Adam Cohen482ed822012-03-02 14:15:13 -08001479 /**
1480 * Find a vacant area that will fit the given bounds nearest the requested
1481 * cell location, and will also weigh in a suggested direction vector of the
1482 * desired location. This method computers distance based on unit grid distances,
1483 * not pixel distances.
1484 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001485 * @param cellX The X cell nearest to which you want to search for a vacant area.
1486 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001487 * @param spanX Horizontal span of the object.
1488 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001489 * @param direction The favored direction in which the views should move from x, y
1490 * @param exactDirectionOnly If this parameter is true, then only solutions where the direction
1491 * matches exactly. Otherwise we find the best matching direction.
1492 * @param occoupied The array which represents which cells in the CellLayout are occupied
1493 * @param blockOccupied The array which represents which cells in the specified block (cellX,
1494 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001495 * @param result Array in which to place the result, or null (in which case a new array will
1496 * be allocated)
1497 * @return The X, Y cell of a vacant area that can contain this object,
1498 * nearest the requested location.
1499 */
1500 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001501 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001502 // Keep track of best-scoring drop area
1503 final int[] bestXY = result != null ? result : new int[2];
1504 float bestDistance = Float.MAX_VALUE;
1505 int bestDirectionScore = Integer.MIN_VALUE;
1506
1507 final int countX = mCountX;
1508 final int countY = mCountY;
1509
1510 for (int y = 0; y < countY - (spanY - 1); y++) {
1511 inner:
1512 for (int x = 0; x < countX - (spanX - 1); x++) {
1513 // First, let's see if this thing fits anywhere
1514 for (int i = 0; i < spanX; i++) {
1515 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001516 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001517 continue inner;
1518 }
1519 }
1520 }
1521
1522 float distance = (float)
1523 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1524 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001525 computeDirectionVector(x - cellX, y - cellY, curDirection);
1526 // The direction score is just the dot product of the two candidate direction
1527 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001528 int curDirectionScore = direction[0] * curDirection[0] +
1529 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001530 boolean exactDirectionOnly = false;
1531 boolean directionMatches = direction[0] == curDirection[0] &&
1532 direction[0] == curDirection[0];
1533 if ((directionMatches || !exactDirectionOnly) &&
1534 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001535 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1536 bestDistance = distance;
1537 bestDirectionScore = curDirectionScore;
1538 bestXY[0] = x;
1539 bestXY[1] = y;
1540 }
1541 }
1542 }
1543
1544 // Return -1, -1 if no suitable location found
1545 if (bestDistance == Float.MAX_VALUE) {
1546 bestXY[0] = -1;
1547 bestXY[1] = -1;
1548 }
1549 return bestXY;
1550 }
1551
Adam Cohen47a876d2012-03-19 13:21:41 -07001552 private int[] findNearestAreaInDirection(int cellX, int cellY, int spanX, int spanY,
1553 int[] direction,boolean[][] occupied,
1554 boolean blockOccupied[][], int[] result) {
1555 // Keep track of best-scoring drop area
1556 final int[] bestXY = result != null ? result : new int[2];
1557 bestXY[0] = -1;
1558 bestXY[1] = -1;
1559 float bestDistance = Float.MAX_VALUE;
1560
1561 // We use this to march in a single direction
Adam Cohen5b53f292012-03-29 14:30:35 -07001562 if ((direction[0] != 0 && direction[1] != 0) ||
1563 (direction[0] == 0 && direction[1] == 0)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001564 return bestXY;
1565 }
1566
1567 // This will only incrememnet one of x or y based on the assertion above
1568 int x = cellX + direction[0];
1569 int y = cellY + direction[1];
1570 while (x >= 0 && x + spanX <= mCountX && y >= 0 && y + spanY <= mCountY) {
1571
1572 boolean fail = false;
1573 for (int i = 0; i < spanX; i++) {
1574 for (int j = 0; j < spanY; j++) {
1575 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1576 fail = true;
1577 }
1578 }
1579 }
1580 if (!fail) {
1581 float distance = (float)
1582 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1583 if (Float.compare(distance, bestDistance) < 0) {
1584 bestDistance = distance;
1585 bestXY[0] = x;
1586 bestXY[1] = y;
1587 }
1588 }
1589 x += direction[0];
1590 y += direction[1];
1591 }
1592 return bestXY;
1593 }
1594
Adam Cohen482ed822012-03-02 14:15:13 -08001595 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001596 int[] direction, ItemConfiguration currentState) {
1597 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001598 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001599 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001600 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1601
Adam Cohen8baab352012-03-20 17:39:21 -07001602 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001603
1604 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001605 c.x = mTempLocation[0];
1606 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001607 success = true;
1608
1609 }
Adam Cohen8baab352012-03-20 17:39:21 -07001610 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001611 return success;
1612 }
1613
Adam Cohen47a876d2012-03-19 13:21:41 -07001614 // This method looks in the specified direction to see if there is an additional view
1615 // immediately adjecent in that direction
1616 private boolean addViewInDirection(ArrayList<View> views, Rect boundingRect, int[] direction,
Adam Cohen19f37922012-03-21 11:59:11 -07001617 boolean[][] occupied, View dragView, ItemConfiguration currentState) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001618 boolean found = false;
1619
Michael Jurkaa52570f2012-03-20 03:18:20 -07001620 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen47a876d2012-03-19 13:21:41 -07001621 Rect r0 = new Rect(boundingRect);
1622 Rect r1 = new Rect();
1623
1624 int deltaX = 0;
1625 int deltaY = 0;
1626 if (direction[1] < 0) {
1627 r0.set(r0.left, r0.top - 1, r0.right, r0.bottom);
1628 deltaY = -1;
1629 } else if (direction[1] > 0) {
1630 r0.set(r0.left, r0.top, r0.right, r0.bottom + 1);
1631 deltaY = 1;
1632 } else if (direction[0] < 0) {
1633 r0.set(r0.left - 1, r0.top, r0.right, r0.bottom);
1634 deltaX = -1;
1635 } else if (direction[0] > 0) {
1636 r0.set(r0.left, r0.top, r0.right + 1, r0.bottom);
1637 deltaX = 1;
1638 }
1639
1640 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001641 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen19f37922012-03-21 11:59:11 -07001642 if (views.contains(child) || child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001643 CellAndSpan c = currentState.map.get(child);
Adam Cohen47a876d2012-03-19 13:21:41 -07001644
Adam Cohen8baab352012-03-20 17:39:21 -07001645 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1646 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001647 if (Rect.intersects(r0, r1)) {
1648 if (!lp.canReorder) {
1649 return false;
1650 }
1651 boolean pushed = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001652 for (int x = c.x; x < c.x + c.spanX; x++) {
1653 for (int y = c.y; y < c.y + c.spanY; y++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001654 boolean inBounds = x - deltaX >= 0 && x -deltaX < mCountX
1655 && y - deltaY >= 0 && y - deltaY < mCountY;
1656 if (inBounds && occupied[x - deltaX][y - deltaY]) {
1657 pushed = true;
1658 }
1659 }
1660 }
1661 if (pushed) {
1662 views.add(child);
Adam Cohen8baab352012-03-20 17:39:21 -07001663 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001664 found = true;
1665 }
1666 }
1667 }
1668 return found;
1669 }
1670
Adam Cohen482ed822012-03-02 14:15:13 -08001671 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohen19f37922012-03-21 11:59:11 -07001672 int[] direction, boolean push, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001673 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001674
Adam Cohen8baab352012-03-20 17:39:21 -07001675 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001676 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001677 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001678 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001679 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001680 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001681 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001682 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001683 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001684 }
1685 }
Adam Cohen8baab352012-03-20 17:39:21 -07001686
1687 @SuppressWarnings("unchecked")
1688 ArrayList<View> dup = (ArrayList<View>) views.clone();
1689 // We try and expand the group of views in the direction vector passed, based on
1690 // whether they are physically adjacent, ie. based on "push mechanics".
Adam Cohen19f37922012-03-21 11:59:11 -07001691 while (push && addViewInDirection(dup, boundingRect, direction, mTmpOccupied, dragView,
Adam Cohen8baab352012-03-20 17:39:21 -07001692 currentState)) {
1693 }
1694
1695 // Mark the occupied state as false for the group of views we want to move.
1696 for (View v: dup) {
1697 CellAndSpan c = currentState.map.get(v);
1698 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1699 }
1700
Adam Cohen47a876d2012-03-19 13:21:41 -07001701 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1702 int top = boundingRect.top;
1703 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001704 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
1705 // for tetris-style interlocking.
1706 for (View v: dup) {
1707 CellAndSpan c = currentState.map.get(v);
1708 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001709 }
1710
Adam Cohen482ed822012-03-02 14:15:13 -08001711 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1712
Adam Cohen8baab352012-03-20 17:39:21 -07001713 if (push) {
1714 findNearestAreaInDirection(boundingRect.left, boundingRect.top, boundingRect.width(),
1715 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1716 } else {
1717 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1718 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1719 }
Adam Cohen482ed822012-03-02 14:15:13 -08001720
Adam Cohen8baab352012-03-20 17:39:21 -07001721 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001722 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001723 int deltaX = mTempLocation[0] - boundingRect.left;
1724 int deltaY = mTempLocation[1] - boundingRect.top;
1725 for (View v: dup) {
1726 CellAndSpan c = currentState.map.get(v);
1727 c.x += deltaX;
1728 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001729 }
1730 success = true;
1731 }
Adam Cohen8baab352012-03-20 17:39:21 -07001732
1733 // In either case, we set the occupied array as marked for the location of the views
1734 for (View v: dup) {
1735 CellAndSpan c = currentState.map.get(v);
1736 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001737 }
1738 return success;
1739 }
1740
1741 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1742 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1743 }
1744
1745 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001746 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001747 // Return early if get invalid cell positions
1748 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001749
Adam Cohen8baab352012-03-20 17:39:21 -07001750 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001751 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001752
Adam Cohen8baab352012-03-20 17:39:21 -07001753 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001754 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001755 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001756 if (c != null) {
1757 c.x = cellX;
1758 c.y = cellY;
1759 }
Adam Cohen482ed822012-03-02 14:15:13 -08001760 }
Adam Cohen482ed822012-03-02 14:15:13 -08001761 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1762 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001763 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001764 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001765 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001766 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001767 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001768 if (Rect.intersects(r0, r1)) {
1769 if (!lp.canReorder) {
1770 return false;
1771 }
1772 mIntersectingViews.add(child);
1773 }
1774 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001775
Adam Cohen8baab352012-03-20 17:39:21 -07001776 // We try to move the intersecting views as a block using the push mechanic
Adam Cohen19f37922012-03-21 11:59:11 -07001777 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, true, ignoreView,
1778 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001779 return true;
1780 }
1781 // Try the opposite direction
1782 direction[0] *= -1;
1783 direction[1] *= -1;
Adam Cohen19f37922012-03-21 11:59:11 -07001784 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, true, ignoreView,
1785 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001786 return true;
1787 }
1788 // Switch the direction back
1789 direction[0] *= -1;
1790 direction[1] *= -1;
1791
Adam Cohen8baab352012-03-20 17:39:21 -07001792 // Next we try moving the views as a block , but without requiring the push mechanic
Adam Cohen19f37922012-03-21 11:59:11 -07001793 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, false, ignoreView,
1794 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001795 return true;
1796 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001797
Adam Cohen482ed822012-03-02 14:15:13 -08001798 // Ok, they couldn't move as a block, let's move them individually
1799 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001800 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001801 return false;
1802 }
1803 }
1804 return true;
1805 }
1806
1807 /*
1808 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1809 * the provided point and the provided cell
1810 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001811 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001812 double angle = Math.atan(((float) deltaY) / deltaX);
1813
1814 result[0] = 0;
1815 result[1] = 0;
1816 if (Math.abs(Math.cos(angle)) > 0.5f) {
1817 result[0] = (int) Math.signum(deltaX);
1818 }
1819 if (Math.abs(Math.sin(angle)) > 0.5f) {
1820 result[1] = (int) Math.signum(deltaY);
1821 }
1822 }
1823
Adam Cohen8baab352012-03-20 17:39:21 -07001824 private void copyOccupiedArray(boolean[][] occupied) {
1825 for (int i = 0; i < mCountX; i++) {
1826 for (int j = 0; j < mCountY; j++) {
1827 occupied[i][j] = mOccupied[i][j];
1828 }
1829 }
1830 }
1831
Adam Cohen482ed822012-03-02 14:15:13 -08001832 ItemConfiguration simpleSwap(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1833 int spanY, int[] direction, View dragView, boolean decX, ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001834 // Copy the current state into the solution. This solution will be manipulated as necessary.
1835 copyCurrentStateToSolution(solution, false);
1836 // Copy the current occupied array into the temporary occupied array. This array will be
1837 // manipulated as necessary to find a solution.
1838 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001839
1840 // We find the nearest cell into which we would place the dragged item, assuming there's
1841 // nothing in its way.
1842 int result[] = new int[2];
1843 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1844
1845 boolean success = false;
1846 // First we try the exact nearest position of the item being dragged,
1847 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001848 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1849 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001850
1851 if (!success) {
1852 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1853 // x, then 1 in y etc.
1854 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
1855 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY, direction,
1856 dragView, false, solution);
1857 } else if (spanY > minSpanY) {
1858 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1, direction,
1859 dragView, true, solution);
1860 }
1861 solution.isSolution = false;
1862 } else {
1863 solution.isSolution = true;
1864 solution.dragViewX = result[0];
1865 solution.dragViewY = result[1];
1866 solution.dragViewSpanX = spanX;
1867 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001868 }
1869 return solution;
1870 }
1871
1872 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001873 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001874 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001875 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001876 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001877 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08001878 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07001879 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001880 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001881 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001882 }
Adam Cohen8baab352012-03-20 17:39:21 -07001883 solution.map.put(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08001884 }
1885 }
1886
1887 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
1888 for (int i = 0; i < mCountX; i++) {
1889 for (int j = 0; j < mCountY; j++) {
1890 mTmpOccupied[i][j] = false;
1891 }
1892 }
1893
Michael Jurkaa52570f2012-03-20 03:18:20 -07001894 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001895 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001896 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001897 if (child == dragView) continue;
1898 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001899 CellAndSpan c = solution.map.get(child);
1900 if (c != null) {
1901 lp.tmpCellX = c.x;
1902 lp.tmpCellY = c.y;
1903 lp.cellHSpan = c.spanX;
1904 lp.cellVSpan = c.spanY;
1905 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001906 }
1907 }
1908 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1909 solution.dragViewSpanY, mTmpOccupied, true);
1910 }
1911
1912 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1913 commitDragView) {
1914
1915 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1916 for (int i = 0; i < mCountX; i++) {
1917 for (int j = 0; j < mCountY; j++) {
1918 occupied[i][j] = false;
1919 }
1920 }
1921
Michael Jurkaa52570f2012-03-20 03:18:20 -07001922 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001923 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001924 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001925 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001926 CellAndSpan c = solution.map.get(child);
1927 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07001928 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
1929 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07001930 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001931 }
1932 }
1933 if (commitDragView) {
1934 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1935 solution.dragViewSpanY, occupied, true);
1936 }
1937 }
1938
Adam Cohen19f37922012-03-21 11:59:11 -07001939 // This method starts or changes the reorder hint animations
1940 private void beginOrAdjustHintAnimations(ItemConfiguration solution, View dragView, int delay) {
1941 int childCount = mShortcutsAndWidgets.getChildCount();
1942 int timeForPriorAnimationToComplete = getMaxCompletionTime();
1943 for (int i = 0; i < childCount; i++) {
1944 View child = mShortcutsAndWidgets.getChildAt(i);
1945 if (child == dragView) continue;
1946 CellAndSpan c = solution.map.get(child);
1947 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1948 if (c != null) {
1949 ReorderHintAnimation rha = new ReorderHintAnimation(child, lp.cellX, lp.cellY,
1950 c.x, c.y, c.spanX, c.spanY);
1951 rha.animate(timeForPriorAnimationToComplete);
1952 }
1953 }
1954 }
1955
1956 // Class which represents the reorder hint animations. These animations show that an item is
1957 // in a temporary state, and hint at where the item will return to.
1958 class ReorderHintAnimation {
1959 View child;
1960 float deltaX;
1961 float deltaY;
1962 private static final int DURATION = 140;
1963 private int repeatCount;
1964 private boolean cancelOnCycleComplete = false;
1965 ValueAnimator va;
1966
1967 public ReorderHintAnimation(View child, int cellX0, int cellY0, int cellX1, int cellY1,
1968 int spanX, int spanY) {
1969 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
1970 final int x0 = mTmpPoint[0];
1971 final int y0 = mTmpPoint[1];
1972 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
1973 final int x1 = mTmpPoint[0];
1974 final int y1 = mTmpPoint[1];
1975 final int dX = x1 - x0;
1976 final int dY = y1 - y0;
1977 deltaX = 0;
1978 deltaY = 0;
1979 if (dX == dY && dX == 0) {
1980 } else {
1981 if (dY == 0) {
1982 deltaX = mReorderHintAnimationMagnitude;
1983 } else if (dX == 0) {
1984 deltaY = mReorderHintAnimationMagnitude;
1985 } else {
1986 double angle = Math.atan( (float) (dY) / dX);
1987 deltaX = (int) (Math.cos(angle) * mReorderHintAnimationMagnitude);
1988 deltaY = (int) (Math.sin(angle) * mReorderHintAnimationMagnitude);
1989 }
1990 }
1991 this.child = child;
1992 }
1993
1994 void animate(int delay) {
1995 if (mShakeAnimators.containsKey(child)) {
1996 ReorderHintAnimation oldAnimation = mShakeAnimators.get(child);
1997 oldAnimation.completeAnimation();
1998 mShakeAnimators.remove(child);
1999 }
2000 if (deltaX == 0 && deltaY == 0) {
2001 return;
2002 }
2003 va = ValueAnimator.ofFloat(0f, 1f);
2004 va.setRepeatMode(ValueAnimator.REVERSE);
2005 va.setRepeatCount(ValueAnimator.INFINITE);
2006 va.setDuration(DURATION);
2007 va.addUpdateListener(new AnimatorUpdateListener() {
2008 @Override
2009 public void onAnimationUpdate(ValueAnimator animation) {
2010 float r = ((Float) animation.getAnimatedValue()).floatValue();
2011 float x = r * deltaX;
2012 float y = r * deltaY;
2013 child.setTranslationX(x);
2014 child.setTranslationY(y);
2015 }
2016 });
2017 va.addListener(new AnimatorListenerAdapter() {
2018 public void onAnimationRepeat(Animator animation) {
2019 repeatCount++;
2020 // We make sure to end only after a full period
2021 if (cancelOnCycleComplete && repeatCount % 2 == 0) {
2022 va.cancel();
2023 }
2024 }
2025 });
2026 va.setStartDelay(Math.max(REORDER_ANIMATION_DURATION, delay));
2027 mShakeAnimators.put(child, this);
2028 va.start();
2029 }
2030
2031
2032 private void completeAnimation() {
2033 cancelOnCycleComplete = true;
2034 }
2035
2036 // Returns the time required to complete the current oscillating animation
2037 private int completionTime() {
2038 if (repeatCount % 2 == 0) {
2039 return (int) (va.getDuration() - va.getCurrentPlayTime() + DURATION);
2040 } else {
2041 return (int) (va.getDuration() - va.getCurrentPlayTime());
2042 }
2043 }
2044 }
2045
2046 private void completeAndClearReorderHintAnimations() {
2047 for (ReorderHintAnimation a: mShakeAnimators.values()) {
2048 a.completeAnimation();
2049 }
2050 mShakeAnimators.clear();
2051 }
2052
2053 private int getMaxCompletionTime() {
2054 int maxTime = 0;
2055 for (ReorderHintAnimation a: mShakeAnimators.values()) {
2056 maxTime = Math.max(maxTime, a.completionTime());
2057 }
2058 return maxTime;
2059 }
2060
Adam Cohen482ed822012-03-02 14:15:13 -08002061 private void commitTempPlacement() {
2062 for (int i = 0; i < mCountX; i++) {
2063 for (int j = 0; j < mCountY; j++) {
2064 mOccupied[i][j] = mTmpOccupied[i][j];
2065 }
2066 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002067 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002068 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002069 View child = mShortcutsAndWidgets.getChildAt(i);
2070 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2071 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002072 // We do a null check here because the item info can be null in the case of the
2073 // AllApps button in the hotseat.
2074 if (info != null) {
2075 info.cellX = lp.cellX = lp.tmpCellX;
2076 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002077 info.spanX = lp.cellHSpan;
2078 info.spanY = lp.cellVSpan;
Adam Cohen2acce882012-03-28 19:03:19 -07002079 }
Adam Cohen482ed822012-03-02 14:15:13 -08002080 }
Adam Cohen2acce882012-03-28 19:03:19 -07002081 mLauncher.getWorkspace().updateItemLocationsInDatabase(this);
Adam Cohen482ed822012-03-02 14:15:13 -08002082 }
2083
2084 public void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002085 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002086 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002087 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002088 lp.useTmpCoords = useTempCoords;
2089 }
2090 }
2091
Adam Cohen482ed822012-03-02 14:15:13 -08002092 ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
2093 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2094 int[] result = new int[2];
2095 int[] resultSpan = new int[2];
2096 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null, result,
2097 resultSpan);
2098 if (result[0] >= 0 && result[1] >= 0) {
2099 copyCurrentStateToSolution(solution, false);
2100 solution.dragViewX = result[0];
2101 solution.dragViewY = result[1];
2102 solution.dragViewSpanX = resultSpan[0];
2103 solution.dragViewSpanY = resultSpan[1];
2104 solution.isSolution = true;
2105 } else {
2106 solution.isSolution = false;
2107 }
2108 return solution;
2109 }
2110
2111 public void prepareChildForDrag(View child) {
2112 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002113 }
2114
Adam Cohen19f37922012-03-21 11:59:11 -07002115 /* This seems like it should be obvious and straight-forward, but when the direction vector
2116 needs to match with the notion of the dragView pushing other views, we have to employ
2117 a slightly more subtle notion of the direction vector. The question is what two points is
2118 the vector between? The center of the dragView and its desired destination? Not quite, as
2119 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2120 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2121 or right, which helps make pushing feel right.
2122 */
2123 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2124 int spanY, View dragView, int[] resultDirection) {
2125 int[] targetDestination = new int[2];
2126
2127 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2128 Rect dragRect = new Rect();
2129 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2130 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2131
2132 Rect dropRegionRect = new Rect();
2133 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2134 dragView, dropRegionRect, mIntersectingViews);
2135
2136 int dropRegionSpanX = dropRegionRect.width();
2137 int dropRegionSpanY = dropRegionRect.height();
2138
2139 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2140 dropRegionRect.height(), dropRegionRect);
2141
2142 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2143 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2144
2145 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2146 deltaX = 0;
2147 }
2148 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2149 deltaY = 0;
2150 }
2151
2152 if (deltaX == 0 && deltaY == 0) {
2153 // No idea what to do, give a random direction.
2154 resultDirection[0] = 1;
2155 resultDirection[1] = 0;
2156 } else {
2157 computeDirectionVector(deltaX, deltaY, resultDirection);
2158 }
2159 }
2160
2161 // For a given cell and span, fetch the set of views intersecting the region.
2162 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2163 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2164 if (boundingRect != null) {
2165 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2166 }
2167 intersectingViews.clear();
2168 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2169 Rect r1 = new Rect();
2170 final int count = mShortcutsAndWidgets.getChildCount();
2171 for (int i = 0; i < count; i++) {
2172 View child = mShortcutsAndWidgets.getChildAt(i);
2173 if (child == dragView) continue;
2174 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2175 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2176 if (Rect.intersects(r0, r1)) {
2177 mIntersectingViews.add(child);
2178 if (boundingRect != null) {
2179 boundingRect.union(r1);
2180 }
2181 }
2182 }
2183 }
2184
2185 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2186 View dragView, int[] result) {
2187 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2188 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2189 mIntersectingViews);
2190 return !mIntersectingViews.isEmpty();
2191 }
2192
2193 void revertTempState() {
2194 if (!isItemPlacementDirty() || DESTRUCTIVE_REORDER) return;
2195 final int count = mShortcutsAndWidgets.getChildCount();
2196 for (int i = 0; i < count; i++) {
2197 View child = mShortcutsAndWidgets.getChildAt(i);
2198 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2199 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2200 lp.tmpCellX = lp.cellX;
2201 lp.tmpCellY = lp.cellY;
2202 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2203 0, false, false);
2204 }
2205 }
2206 completeAndClearReorderHintAnimations();
2207 setItemPlacementDirty(false);
2208 }
2209
Adam Cohenbebf0422012-04-11 18:06:28 -07002210 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2211 View dragView, int[] direction, boolean commit) {
2212 int[] pixelXY = new int[2];
2213 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2214
2215 // First we determine if things have moved enough to cause a different layout
2216 ItemConfiguration swapSolution = simpleSwap(pixelXY[0], pixelXY[1], spanX, spanY,
2217 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2218
2219 setUseTempCoords(true);
2220 if (swapSolution != null && swapSolution.isSolution) {
2221 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2222 // committing anything or animating anything as we just want to determine if a solution
2223 // exists
2224 copySolutionToTempState(swapSolution, dragView);
2225 setItemPlacementDirty(true);
2226 animateItemsToSolution(swapSolution, dragView, commit);
2227
2228 if (commit) {
2229 commitTempPlacement();
2230 completeAndClearReorderHintAnimations();
2231 setItemPlacementDirty(false);
2232 } else {
2233 beginOrAdjustHintAnimations(swapSolution, dragView,
2234 REORDER_ANIMATION_DURATION);
2235 }
2236 mShortcutsAndWidgets.requestLayout();
2237 }
2238 return swapSolution.isSolution;
2239 }
2240
Adam Cohen482ed822012-03-02 14:15:13 -08002241 int[] createArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2242 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002243 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002244 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002245
2246 if (resultSpan == null) {
2247 resultSpan = new int[2];
2248 }
2249
Adam Cohen19f37922012-03-21 11:59:11 -07002250 // When we are checking drop validity or actually dropping, we don't recompute the
2251 // direction vector, since we want the solution to match the preview, and it's possible
2252 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002253 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2254 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002255 mDirectionVector[0] = mPreviousReorderDirection[0];
2256 mDirectionVector[1] = mPreviousReorderDirection[1];
2257 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002258 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2259 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2260 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002261 }
2262 } else {
2263 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2264 mPreviousReorderDirection[0] = mDirectionVector[0];
2265 mPreviousReorderDirection[1] = mDirectionVector[1];
2266 }
2267
Adam Cohen482ed822012-03-02 14:15:13 -08002268 ItemConfiguration swapSolution = simpleSwap(pixelX, pixelY, minSpanX, minSpanY,
2269 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2270
2271 // We attempt the approach which doesn't shuffle views at all
2272 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2273 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2274
2275 ItemConfiguration finalSolution = null;
2276 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2277 finalSolution = swapSolution;
2278 } else if (noShuffleSolution.isSolution) {
2279 finalSolution = noShuffleSolution;
2280 }
2281
2282 boolean foundSolution = true;
2283 if (!DESTRUCTIVE_REORDER) {
2284 setUseTempCoords(true);
2285 }
2286
2287 if (finalSolution != null) {
2288 result[0] = finalSolution.dragViewX;
2289 result[1] = finalSolution.dragViewY;
2290 resultSpan[0] = finalSolution.dragViewSpanX;
2291 resultSpan[1] = finalSolution.dragViewSpanY;
2292
2293 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2294 // committing anything or animating anything as we just want to determine if a solution
2295 // exists
2296 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2297 if (!DESTRUCTIVE_REORDER) {
2298 copySolutionToTempState(finalSolution, dragView);
2299 }
2300 setItemPlacementDirty(true);
2301 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2302
Adam Cohen19f37922012-03-21 11:59:11 -07002303 if (!DESTRUCTIVE_REORDER &&
2304 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002305 commitTempPlacement();
Adam Cohen19f37922012-03-21 11:59:11 -07002306 completeAndClearReorderHintAnimations();
2307 setItemPlacementDirty(false);
2308 } else {
2309 beginOrAdjustHintAnimations(finalSolution, dragView,
2310 REORDER_ANIMATION_DURATION);
Adam Cohen482ed822012-03-02 14:15:13 -08002311 }
2312 }
2313 } else {
2314 foundSolution = false;
2315 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2316 }
2317
2318 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2319 setUseTempCoords(false);
2320 }
Adam Cohen482ed822012-03-02 14:15:13 -08002321
Michael Jurkaa52570f2012-03-20 03:18:20 -07002322 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002323 return result;
2324 }
2325
Adam Cohen19f37922012-03-21 11:59:11 -07002326 void setItemPlacementDirty(boolean dirty) {
2327 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002328 }
Adam Cohen19f37922012-03-21 11:59:11 -07002329 boolean isItemPlacementDirty() {
2330 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002331 }
2332
2333 private class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002334 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohen482ed822012-03-02 14:15:13 -08002335 boolean isSolution = false;
2336 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2337
2338 int area() {
2339 return dragViewSpanX * dragViewSpanY;
2340 }
Adam Cohen8baab352012-03-20 17:39:21 -07002341 }
2342
2343 private class CellAndSpan {
2344 int x, y;
2345 int spanX, spanY;
2346
2347 public CellAndSpan(int x, int y, int spanX, int spanY) {
2348 this.x = x;
2349 this.y = y;
2350 this.spanX = spanX;
2351 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002352 }
2353 }
2354
Adam Cohendf035382011-04-11 17:22:04 -07002355 /**
2356 * Find a vacant area that will fit the given bounds nearest the requested
2357 * cell location. Uses Euclidean distance to score multiple vacant areas.
2358 *
2359 * @param pixelX The X location at which you want to search for a vacant area.
2360 * @param pixelY The Y location at which you want to search for a vacant area.
2361 * @param spanX Horizontal span of the object.
2362 * @param spanY Vertical span of the object.
2363 * @param ignoreView Considers space occupied by this view as unoccupied
2364 * @param result Previously returned value to possibly recycle.
2365 * @return The X, Y cell of a vacant area that can contain this object,
2366 * nearest the requested location.
2367 */
2368 int[] findNearestVacantArea(
2369 int pixelX, int pixelY, int spanX, int spanY, View ignoreView, int[] result) {
2370 return findNearestArea(pixelX, pixelY, spanX, spanY, ignoreView, true, result);
2371 }
2372
2373 /**
Adam Cohend41fbf52012-02-16 23:53:59 -08002374 * Find a vacant area that will fit the given bounds nearest the requested
2375 * cell location. Uses Euclidean distance to score multiple vacant areas.
2376 *
2377 * @param pixelX The X location at which you want to search for a vacant area.
2378 * @param pixelY The Y location at which you want to search for a vacant area.
2379 * @param minSpanX The minimum horizontal span required
2380 * @param minSpanY The minimum vertical span required
2381 * @param spanX Horizontal span of the object.
2382 * @param spanY Vertical span of the object.
2383 * @param ignoreView Considers space occupied by this view as unoccupied
2384 * @param result Previously returned value to possibly recycle.
2385 * @return The X, Y cell of a vacant area that can contain this object,
2386 * nearest the requested location.
2387 */
2388 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
2389 int spanX, int spanY, View ignoreView, int[] result, int[] resultSpan) {
Adam Cohen482ed822012-03-02 14:15:13 -08002390 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, true,
2391 result, resultSpan, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08002392 }
2393
2394 /**
Adam Cohendf035382011-04-11 17:22:04 -07002395 * Find a starting cell position that will fit the given bounds nearest the requested
2396 * cell location. Uses Euclidean distance to score multiple vacant areas.
2397 *
2398 * @param pixelX The X location at which you want to search for a vacant area.
2399 * @param pixelY The Y location at which you want to search for a vacant area.
2400 * @param spanX Horizontal span of the object.
2401 * @param spanY Vertical span of the object.
2402 * @param ignoreView Considers space occupied by this view as unoccupied
2403 * @param result Previously returned value to possibly recycle.
2404 * @return The X, Y cell of a vacant area that can contain this object,
2405 * nearest the requested location.
2406 */
2407 int[] findNearestArea(
2408 int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2409 return findNearestArea(pixelX, pixelY, spanX, spanY, null, false, result);
2410 }
2411
Michael Jurka0280c3b2010-09-17 15:00:07 -07002412 boolean existsEmptyCell() {
2413 return findCellForSpan(null, 1, 1);
2414 }
2415
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002416 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002417 * Finds the upper-left coordinate of the first rectangle in the grid that can
2418 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2419 * then this method will only return coordinates for rectangles that contain the cell
2420 * (intersectX, intersectY)
2421 *
2422 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2423 * can be found.
2424 * @param spanX The horizontal span of the cell we want to find.
2425 * @param spanY The vertical span of the cell we want to find.
2426 *
2427 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002428 */
Michael Jurka0280c3b2010-09-17 15:00:07 -07002429 boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08002430 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002431 }
2432
2433 /**
2434 * Like above, but ignores any cells occupied by the item "ignoreView"
2435 *
2436 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2437 * can be found.
2438 * @param spanX The horizontal span of the cell we want to find.
2439 * @param spanY The vertical span of the cell we want to find.
2440 * @param ignoreView The home screen item we should treat as not occupying any space
2441 * @return
2442 */
2443 boolean findCellForSpanIgnoring(int[] cellXY, int spanX, int spanY, View ignoreView) {
Adam Cohen482ed822012-03-02 14:15:13 -08002444 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1,
2445 ignoreView, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002446 }
2447
2448 /**
2449 * Like above, but if intersectX and intersectY are not -1, then this method will try to
2450 * return coordinates for rectangles that contain the cell [intersectX, intersectY]
2451 *
2452 * @param spanX The horizontal span of the cell we want to find.
2453 * @param spanY The vertical span of the cell we want to find.
2454 * @param ignoreView The home screen item we should treat as not occupying any space
2455 * @param intersectX The X coordinate of the cell that we should try to overlap
2456 * @param intersectX The Y coordinate of the cell that we should try to overlap
2457 *
2458 * @return True if a vacant cell of the specified dimension was found, false otherwise.
2459 */
2460 boolean findCellForSpanThatIntersects(int[] cellXY, int spanX, int spanY,
2461 int intersectX, int intersectY) {
2462 return findCellForSpanThatIntersectsIgnoring(
Adam Cohen482ed822012-03-02 14:15:13 -08002463 cellXY, spanX, spanY, intersectX, intersectY, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002464 }
2465
2466 /**
2467 * The superset of the above two methods
2468 */
2469 boolean findCellForSpanThatIntersectsIgnoring(int[] cellXY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002470 int intersectX, int intersectY, View ignoreView, boolean occupied[][]) {
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002471 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08002472 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002473
Michael Jurka28750fb2010-09-24 17:43:49 -07002474 boolean foundCell = false;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002475 while (true) {
2476 int startX = 0;
2477 if (intersectX >= 0) {
2478 startX = Math.max(startX, intersectX - (spanX - 1));
2479 }
2480 int endX = mCountX - (spanX - 1);
2481 if (intersectX >= 0) {
2482 endX = Math.min(endX, intersectX + (spanX - 1) + (spanX == 1 ? 1 : 0));
2483 }
2484 int startY = 0;
2485 if (intersectY >= 0) {
2486 startY = Math.max(startY, intersectY - (spanY - 1));
2487 }
2488 int endY = mCountY - (spanY - 1);
2489 if (intersectY >= 0) {
2490 endY = Math.min(endY, intersectY + (spanY - 1) + (spanY == 1 ? 1 : 0));
2491 }
2492
Winson Chungbbc60d82010-11-11 16:34:41 -08002493 for (int y = startY; y < endY && !foundCell; y++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002494 inner:
Winson Chungbbc60d82010-11-11 16:34:41 -08002495 for (int x = startX; x < endX; x++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002496 for (int i = 0; i < spanX; i++) {
2497 for (int j = 0; j < spanY; j++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002498 if (occupied[x + i][y + j]) {
Winson Chungbbc60d82010-11-11 16:34:41 -08002499 // small optimization: we can skip to after the column we just found
Michael Jurka0280c3b2010-09-17 15:00:07 -07002500 // an occupied cell
Winson Chungbbc60d82010-11-11 16:34:41 -08002501 x += i;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002502 continue inner;
2503 }
2504 }
2505 }
2506 if (cellXY != null) {
2507 cellXY[0] = x;
2508 cellXY[1] = y;
2509 }
Michael Jurka28750fb2010-09-24 17:43:49 -07002510 foundCell = true;
2511 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002512 }
2513 }
2514 if (intersectX == -1 && intersectY == -1) {
2515 break;
2516 } else {
2517 // if we failed to find anything, try again but without any requirements of
2518 // intersecting
2519 intersectX = -1;
2520 intersectY = -1;
2521 continue;
2522 }
2523 }
2524
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002525 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08002526 markCellsAsOccupiedForView(ignoreView, occupied);
Michael Jurka28750fb2010-09-24 17:43:49 -07002527 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002528 }
2529
2530 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002531 * A drag event has begun over this layout.
2532 * It may have begun over this layout (in which case onDragChild is called first),
2533 * or it may have begun on another layout.
2534 */
2535 void onDragEnter() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002536 mDragEnforcer.onDragEnter();
Winson Chungc07918d2011-07-01 15:35:26 -07002537 mDragging = true;
2538 }
2539
2540 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002541 * Called when drag has left this CellLayout or has been completed (successfully or not)
2542 */
2543 void onDragExit() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002544 mDragEnforcer.onDragExit();
Joe Onorato4be866d2010-10-10 11:26:02 -07002545 // This can actually be called when we aren't in a drag, e.g. when adding a new
2546 // item to this layout via the customize drawer.
2547 // Guard against that case.
2548 if (mDragging) {
2549 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002550 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002551
2552 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002553 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002554 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2555 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002556 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002557 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002558 }
2559
2560 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002561 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002562 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002563 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002564 *
2565 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002566 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002567 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002568 if (child != null) {
2569 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002570 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002571 child.requestLayout();
Romain Guyd94533d2009-08-17 10:01:15 -07002572 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002573 }
2574
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002575 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002576 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002577 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002578 * @param cellX X coordinate of upper left corner expressed as a cell position
2579 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002580 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002581 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002582 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002583 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002584 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002585 final int cellWidth = mCellWidth;
2586 final int cellHeight = mCellHeight;
2587 final int widthGap = mWidthGap;
2588 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002589
Winson Chung4b825dcd2011-06-19 12:41:22 -07002590 final int hStartPadding = getPaddingLeft();
2591 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002592
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002593 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2594 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2595
2596 int x = hStartPadding + cellX * (cellWidth + widthGap);
2597 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002598
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002599 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002600 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002601
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002602 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002603 * Computes the required horizontal and vertical cell spans to always
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002604 * fit the given rectangle.
Winson Chungaafa03c2010-06-11 17:34:16 -07002605 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002606 * @param width Width in pixels
2607 * @param height Height in pixels
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002608 * @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 -08002609 */
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002610 public int[] rectToCell(int width, int height, int[] result) {
Michael Jurka9987a5c2010-10-08 16:58:12 -07002611 return rectToCell(getResources(), width, height, result);
2612 }
2613
2614 public static int[] rectToCell(Resources resources, int width, int height, int[] result) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002615 // Always assume we're working with the smallest span to make sure we
2616 // reserve enough space in both orientations.
Joe Onorato79e56262009-09-21 15:23:04 -04002617 int actualWidth = resources.getDimensionPixelSize(R.dimen.workspace_cell_width);
2618 int actualHeight = resources.getDimensionPixelSize(R.dimen.workspace_cell_height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002619 int smallerSize = Math.min(actualWidth, actualHeight);
Joe Onorato79e56262009-09-21 15:23:04 -04002620
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002621 // Always round up to next largest cell
Winson Chung54c725c2011-08-03 12:03:40 -07002622 int spanX = (int) Math.ceil(width / (float) smallerSize);
2623 int spanY = (int) Math.ceil(height / (float) smallerSize);
Joe Onorato79e56262009-09-21 15:23:04 -04002624
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002625 if (result == null) {
2626 return new int[] { spanX, spanY };
2627 }
2628 result[0] = spanX;
2629 result[1] = spanY;
2630 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002631 }
2632
Michael Jurkaf12c75c2011-01-25 22:41:40 -08002633 public int[] cellSpansToSize(int hSpans, int vSpans) {
2634 int[] size = new int[2];
2635 size[0] = hSpans * mCellWidth + (hSpans - 1) * mWidthGap;
2636 size[1] = vSpans * mCellHeight + (vSpans - 1) * mHeightGap;
2637 return size;
2638 }
2639
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002640 /**
Patrick Dubroy047379a2010-12-19 22:02:04 -08002641 * Calculate the grid spans needed to fit given item
2642 */
2643 public void calculateSpans(ItemInfo info) {
2644 final int minWidth;
2645 final int minHeight;
2646
2647 if (info instanceof LauncherAppWidgetInfo) {
2648 minWidth = ((LauncherAppWidgetInfo) info).minWidth;
2649 minHeight = ((LauncherAppWidgetInfo) info).minHeight;
2650 } else if (info instanceof PendingAddWidgetInfo) {
2651 minWidth = ((PendingAddWidgetInfo) info).minWidth;
2652 minHeight = ((PendingAddWidgetInfo) info).minHeight;
2653 } else {
2654 // It's not a widget, so it must be 1x1
2655 info.spanX = info.spanY = 1;
2656 return;
2657 }
2658 int[] spans = rectToCell(minWidth, minHeight, null);
2659 info.spanX = spans[0];
2660 info.spanY = spans[1];
2661 }
2662
2663 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002664 * Find the first vacant cell, if there is one.
2665 *
2666 * @param vacant Holds the x and y coordinate of the vacant cell
2667 * @param spanX Horizontal cell span.
2668 * @param spanY Vertical cell span.
Winson Chungaafa03c2010-06-11 17:34:16 -07002669 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002670 * @return True if a vacant cell was found
2671 */
2672 public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002673
Michael Jurka0280c3b2010-09-17 15:00:07 -07002674 return findVacantCell(vacant, spanX, spanY, mCountX, mCountY, mOccupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002675 }
2676
2677 static boolean findVacantCell(int[] vacant, int spanX, int spanY,
2678 int xCount, int yCount, boolean[][] occupied) {
2679
Adam Cohen2801caf2011-05-13 20:57:39 -07002680 for (int y = 0; y < yCount; y++) {
2681 for (int x = 0; x < xCount; x++) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002682 boolean available = !occupied[x][y];
2683out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
2684 for (int j = y; j < y + spanY - 1 && y < yCount; j++) {
2685 available = available && !occupied[i][j];
2686 if (!available) break out;
2687 }
2688 }
2689
2690 if (available) {
2691 vacant[0] = x;
2692 vacant[1] = y;
2693 return true;
2694 }
2695 }
2696 }
2697
2698 return false;
2699 }
2700
Michael Jurka0280c3b2010-09-17 15:00:07 -07002701 private void clearOccupiedCells() {
2702 for (int x = 0; x < mCountX; x++) {
2703 for (int y = 0; y < mCountY; y++) {
2704 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002705 }
2706 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002707 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002708
Adam Cohend41fbf52012-02-16 23:53:59 -08002709 public void onMove(View view, int newCellX, int newCellY, int newSpanX, int newSpanY) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002710 markCellsAsUnoccupiedForView(view);
Adam Cohen482ed822012-03-02 14:15:13 -08002711 markCellsForView(newCellX, newCellY, newSpanX, newSpanY, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002712 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002713
Adam Cohend4844c32011-02-18 19:25:06 -08002714 public void markCellsAsOccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002715 markCellsAsOccupiedForView(view, mOccupied);
2716 }
2717 public void markCellsAsOccupiedForView(View view, boolean[][] occupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002718 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002719 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002720 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002721 }
2722
Adam Cohend4844c32011-02-18 19:25:06 -08002723 public void markCellsAsUnoccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002724 markCellsAsUnoccupiedForView(view, mOccupied);
2725 }
2726 public void markCellsAsUnoccupiedForView(View view, boolean occupied[][]) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002727 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002728 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002729 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002730 }
2731
Adam Cohen482ed822012-03-02 14:15:13 -08002732 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2733 boolean value) {
2734 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002735 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2736 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002737 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002738 }
2739 }
2740 }
2741
Adam Cohen2801caf2011-05-13 20:57:39 -07002742 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002743 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002744 (Math.max((mCountX - 1), 0) * mWidthGap);
2745 }
2746
2747 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002748 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002749 (Math.max((mCountY - 1), 0) * mHeightGap);
2750 }
2751
Michael Jurka66d72172011-04-12 16:29:25 -07002752 public boolean isOccupied(int x, int y) {
2753 if (x < mCountX && y < mCountY) {
2754 return mOccupied[x][y];
2755 } else {
2756 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2757 }
2758 }
2759
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002760 @Override
2761 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2762 return new CellLayout.LayoutParams(getContext(), attrs);
2763 }
2764
2765 @Override
2766 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2767 return p instanceof CellLayout.LayoutParams;
2768 }
2769
2770 @Override
2771 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2772 return new CellLayout.LayoutParams(p);
2773 }
2774
Winson Chungaafa03c2010-06-11 17:34:16 -07002775 public static class CellLayoutAnimationController extends LayoutAnimationController {
2776 public CellLayoutAnimationController(Animation animation, float delay) {
2777 super(animation, delay);
2778 }
2779
2780 @Override
2781 protected long getDelayForView(View view) {
2782 return (int) (Math.random() * 150);
2783 }
2784 }
2785
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002786 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2787 /**
2788 * Horizontal location of the item in the grid.
2789 */
2790 @ViewDebug.ExportedProperty
2791 public int cellX;
2792
2793 /**
2794 * Vertical location of the item in the grid.
2795 */
2796 @ViewDebug.ExportedProperty
2797 public int cellY;
2798
2799 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002800 * Temporary horizontal location of the item in the grid during reorder
2801 */
2802 public int tmpCellX;
2803
2804 /**
2805 * Temporary vertical location of the item in the grid during reorder
2806 */
2807 public int tmpCellY;
2808
2809 /**
2810 * Indicates that the temporary coordinates should be used to layout the items
2811 */
2812 public boolean useTmpCoords;
2813
2814 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002815 * Number of cells spanned horizontally by the item.
2816 */
2817 @ViewDebug.ExportedProperty
2818 public int cellHSpan;
2819
2820 /**
2821 * Number of cells spanned vertically by the item.
2822 */
2823 @ViewDebug.ExportedProperty
2824 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002825
Adam Cohen1b607ed2011-03-03 17:26:50 -08002826 /**
2827 * Indicates whether the item will set its x, y, width and height parameters freely,
2828 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2829 */
Adam Cohend4844c32011-02-18 19:25:06 -08002830 public boolean isLockedToGrid = true;
2831
Adam Cohen482ed822012-03-02 14:15:13 -08002832 /**
2833 * Indicates whether this item can be reordered. Always true except in the case of the
2834 * the AllApps button.
2835 */
2836 public boolean canReorder = true;
2837
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002838 // X coordinate of the view in the layout.
2839 @ViewDebug.ExportedProperty
2840 int x;
2841 // Y coordinate of the view in the layout.
2842 @ViewDebug.ExportedProperty
2843 int y;
2844
Romain Guy84f296c2009-11-04 15:00:44 -08002845 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002846
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002847 public LayoutParams(Context c, AttributeSet attrs) {
2848 super(c, attrs);
2849 cellHSpan = 1;
2850 cellVSpan = 1;
2851 }
2852
2853 public LayoutParams(ViewGroup.LayoutParams source) {
2854 super(source);
2855 cellHSpan = 1;
2856 cellVSpan = 1;
2857 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002858
2859 public LayoutParams(LayoutParams source) {
2860 super(source);
2861 this.cellX = source.cellX;
2862 this.cellY = source.cellY;
2863 this.cellHSpan = source.cellHSpan;
2864 this.cellVSpan = source.cellVSpan;
2865 }
2866
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002867 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002868 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002869 this.cellX = cellX;
2870 this.cellY = cellY;
2871 this.cellHSpan = cellHSpan;
2872 this.cellVSpan = cellVSpan;
2873 }
2874
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002875 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap) {
Adam Cohend4844c32011-02-18 19:25:06 -08002876 if (isLockedToGrid) {
2877 final int myCellHSpan = cellHSpan;
2878 final int myCellVSpan = cellVSpan;
Adam Cohen482ed822012-03-02 14:15:13 -08002879 final int myCellX = useTmpCoords ? tmpCellX : cellX;
2880 final int myCellY = useTmpCoords ? tmpCellY : cellY;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002881
Adam Cohend4844c32011-02-18 19:25:06 -08002882 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2883 leftMargin - rightMargin;
2884 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2885 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002886 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2887 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002888 }
2889 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002890
Winson Chungaafa03c2010-06-11 17:34:16 -07002891 public String toString() {
2892 return "(" + this.cellX + ", " + this.cellY + ")";
2893 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002894
2895 public void setWidth(int width) {
2896 this.width = width;
2897 }
2898
2899 public int getWidth() {
2900 return width;
2901 }
2902
2903 public void setHeight(int height) {
2904 this.height = height;
2905 }
2906
2907 public int getHeight() {
2908 return height;
2909 }
2910
2911 public void setX(int x) {
2912 this.x = x;
2913 }
2914
2915 public int getX() {
2916 return x;
2917 }
2918
2919 public void setY(int y) {
2920 this.y = y;
2921 }
2922
2923 public int getY() {
2924 return y;
2925 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002926 }
2927
Michael Jurka0280c3b2010-09-17 15:00:07 -07002928 // This class stores info for two purposes:
2929 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2930 // its spanX, spanY, and the screen it is on
2931 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2932 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2933 // the CellLayout that was long clicked
Michael Jurkae5fb0f22011-04-11 13:27:46 -07002934 static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002935 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002936 int cellX = -1;
2937 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002938 int spanX;
2939 int spanY;
2940 int screen;
Winson Chung3d503fb2011-07-13 17:25:49 -07002941 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002942
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002943 @Override
2944 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002945 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2946 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002947 }
2948 }
Michael Jurkad771c962011-08-09 15:00:48 -07002949
2950 public boolean lastDownOnOccupiedCell() {
2951 return mLastDownOnOccupiedCell;
2952 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002953}