blob: fb319fe0c6b513d80b07faf316170b80e7951660 [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
Winson Chung4b825dcd2011-06-19 12:41:22 -070060 private int mOriginalCellWidth;
61 private int mOriginalCellHeight;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080062 private int mCellWidth;
63 private int mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070064
Adam Cohend22015c2010-07-26 22:02:18 -070065 private int mCountX;
66 private int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080067
Adam Cohen234c4cd2011-07-17 21:03:04 -070068 private int mOriginalWidthGap;
69 private int mOriginalHeightGap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080070 private int mWidthGap;
71 private int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070072 private int mMaxGap;
Adam Cohenebea84d2011-11-09 17:20:41 -080073 private boolean mScrollingTransformsDirty = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074
75 private final Rect mRect = new Rect();
76 private final CellInfo mCellInfo = new CellInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -070077
Patrick Dubroyde7658b2010-09-27 11:15:43 -070078 // These are temporary variables to prevent having to allocate a new object just to
79 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Winson Chung0be025d2011-05-23 17:45:09 -070080 private final int[] mTmpXY = new int[2];
Patrick Dubroyde7658b2010-09-27 11:15:43 -070081 private final int[] mTmpPoint = new int[2];
82 private final PointF mTmpPointF = new PointF();
Adam Cohen69ce2e52011-07-03 19:25:21 -070083 int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070084
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -080086 boolean[][] mTmpOccupied;
Michael Jurkad771c962011-08-09 15:00:48 -070087 private boolean mLastDownOnOccupiedCell = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080088
Michael Jurkadee05892010-07-27 10:01:56 -070089 private OnTouchListener mInterceptTouchListener;
90
Adam Cohen69ce2e52011-07-03 19:25:21 -070091 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -070092 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -070093
Adam Cohenb5ba0972011-09-07 18:02:31 -070094 private int mForegroundAlpha = 0;
Michael Jurka5f1c5092010-09-03 14:15:02 -070095 private float mBackgroundAlpha;
Adam Cohen1b0aaac2010-10-28 11:11:18 -070096 private float mBackgroundAlphaMultiplier = 1.0f;
Adam Cohenf34bab52010-09-30 14:11:56 -070097
Michael Jurka33945b22010-12-21 18:19:38 -080098 private Drawable mNormalBackground;
Michael Jurka33945b22010-12-21 18:19:38 -080099 private Drawable mActiveGlowBackground;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700100 private Drawable mOverScrollForegroundDrawable;
101 private Drawable mOverScrollLeft;
102 private Drawable mOverScrollRight;
Michael Jurka18014792010-10-14 09:01:34 -0700103 private Rect mBackgroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700104 private Rect mForegroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700105 private int mForegroundPadding;
Patrick Dubroy1262e362010-10-06 15:49:50 -0700106
Michael Jurka33945b22010-12-21 18:19:38 -0800107 // If we're actively dragging something over this screen, mIsDragOverlapping is true
108 private boolean mIsDragOverlapping = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700109 private final Point mDragCenter = new Point();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700110
Winson Chung150fbab2010-09-29 17:14:26 -0700111 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700112 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohend41fbf52012-02-16 23:53:59 -0800113 private Rect[] mDragOutlines = new Rect[4];
Chet Haase472b2812010-10-14 07:02:04 -0700114 private float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700115 private InterruptibleInOutAnimator[] mDragOutlineAnims =
116 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700117
118 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700119 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700120 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700121
Patrick Dubroy96864c32011-03-10 17:17:23 -0800122 private BubbleTextView mPressedOrFocusedIcon;
123
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700124 private Drawable mCrosshairsDrawable = null;
Patrick Dubroy49250ad2010-10-08 15:33:52 -0700125 private InterruptibleInOutAnimator mCrosshairsAnimator = null;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700126 private float mCrosshairsVisibility = 0.0f;
127
Adam Cohen482ed822012-03-02 14:15:13 -0800128 private HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new
129 HashMap<CellLayout.LayoutParams, Animator>();
Adam Cohen19f37922012-03-21 11:59:11 -0700130 private HashMap<View, ReorderHintAnimation>
131 mShakeAnimators = new HashMap<View, ReorderHintAnimation>();
132
133 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700134
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700135 // When a drag operation is in progress, holds the nearest cell to the touch point
136 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800137
Joe Onorato4be866d2010-10-10 11:26:02 -0700138 private boolean mDragging = false;
139
Patrick Dubroyce34a972010-10-19 10:34:32 -0700140 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700141 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700142
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800143 private boolean mIsHotseat = false;
Winson Chungeecf02d2012-03-02 17:14:58 -0800144 private float mChildScale = 1f;
145 private float mHotseatChildScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800146
Adam Cohen482ed822012-03-02 14:15:13 -0800147 public static final int MODE_DRAG_OVER = 0;
148 public static final int MODE_ON_DROP = 1;
149 public static final int MODE_ON_DROP_EXTERNAL = 2;
150 public static final int MODE_ACCEPT_DROP = 3;
Adam Cohen19f37922012-03-21 11:59:11 -0700151 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800152 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
153
Adam Cohen19f37922012-03-21 11:59:11 -0700154 private static final float REORDER_HINT_MAGNITUDE = 0.27f;
155 private static final int REORDER_ANIMATION_DURATION = 150;
156 private float mReorderHintAnimationMagnitude;
157
Adam Cohen482ed822012-03-02 14:15:13 -0800158 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
159 private Rect mOccupiedRect = new Rect();
160 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700161 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700162 private static final int INVALID_DIRECTION = -100;
Adam Cohen482ed822012-03-02 14:15:13 -0800163
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164 public CellLayout(Context context) {
165 this(context, null);
166 }
167
168 public CellLayout(Context context, AttributeSet attrs) {
169 this(context, attrs, 0);
170 }
171
172 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
173 super(context, attrs, defStyle);
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);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700178
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800179 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
180
Winson Chung4b825dcd2011-06-19 12:41:22 -0700181 mOriginalCellWidth =
182 mCellWidth = a.getDimensionPixelSize(R.styleable.CellLayout_cellWidth, 10);
183 mOriginalCellHeight =
184 mCellHeight = a.getDimensionPixelSize(R.styleable.CellLayout_cellHeight, 10);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700185 mWidthGap = mOriginalWidthGap = a.getDimensionPixelSize(R.styleable.CellLayout_widthGap, 0);
186 mHeightGap = mOriginalHeightGap = a.getDimensionPixelSize(R.styleable.CellLayout_heightGap, 0);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700187 mMaxGap = a.getDimensionPixelSize(R.styleable.CellLayout_maxGap, 0);
Adam Cohend22015c2010-07-26 22:02:18 -0700188 mCountX = LauncherModel.getCellCountX();
189 mCountY = LauncherModel.getCellCountY();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700190 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800191 mTmpOccupied = new boolean[mCountX][mCountY];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800192
193 a.recycle();
194
195 setAlwaysDrawnWithCacheEnabled(false);
196
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700197 final Resources res = getResources();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700198
Winson Chung967289b2011-06-30 18:09:30 -0700199 mNormalBackground = res.getDrawable(R.drawable.homescreen_blue_normal_holo);
Winson Chungdea74b72011-09-13 18:06:43 -0700200 mActiveGlowBackground = res.getDrawable(R.drawable.homescreen_blue_strong_holo);
Michael Jurka33945b22010-12-21 18:19:38 -0800201
Adam Cohenb5ba0972011-09-07 18:02:31 -0700202 mOverScrollLeft = res.getDrawable(R.drawable.overscroll_glow_left);
203 mOverScrollRight = res.getDrawable(R.drawable.overscroll_glow_right);
204 mForegroundPadding =
205 res.getDimensionPixelSize(R.dimen.workspace_overscroll_drawable_padding);
Michael Jurka33945b22010-12-21 18:19:38 -0800206
Adam Cohen19f37922012-03-21 11:59:11 -0700207 mReorderHintAnimationMagnitude = (REORDER_HINT_MAGNITUDE *
208 res.getDimensionPixelSize(R.dimen.app_icon_size));
209
Winson Chungb26f3d62011-06-02 10:49:29 -0700210 mNormalBackground.setFilterBitmap(true);
Winson Chungb26f3d62011-06-02 10:49:29 -0700211 mActiveGlowBackground.setFilterBitmap(true);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700212
Winson Chungeecf02d2012-03-02 17:14:58 -0800213 int iconScale = res.getInteger(R.integer.app_icon_scale_percent);
214 if (iconScale >= 0) {
215 mChildScale = iconScale / 100f;
216 }
217 int hotseatIconScale = res.getInteger(R.integer.app_icon_hotseat_scale_percent);
218 if (hotseatIconScale >= 0) {
219 mHotseatChildScale = hotseatIconScale / 100f;
220 }
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800221
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700222 // Initialize the data structures used for the drag visualization.
Winson Chung150fbab2010-09-29 17:14:26 -0700223
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700224 mCrosshairsDrawable = res.getDrawable(R.drawable.gardening_crosshairs);
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 // Set up the animation for fading the crosshairs in and out
228 int animDuration = res.getInteger(R.integer.config_crosshairsFadeInTime);
Patrick Dubroy49250ad2010-10-08 15:33:52 -0700229 mCrosshairsAnimator = new InterruptibleInOutAnimator(animDuration, 0.0f, 1.0f);
Chet Haase472b2812010-10-14 07:02:04 -0700230 mCrosshairsAnimator.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700231 public void onAnimationUpdate(ValueAnimator animation) {
232 mCrosshairsVisibility = ((Float) animation.getAnimatedValue()).floatValue();
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700233 invalidate();
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700234 }
235 });
Patrick Dubroyce34a972010-10-19 10:34:32 -0700236 mCrosshairsAnimator.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700237
Winson Chungb8c69f32011-10-19 21:36:08 -0700238 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700239 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800240 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700241 }
242
243 // When dragging things around the home screens, we show a green outline of
244 // where the item will land. The outlines gradually fade out, leaving a trail
245 // behind the drag path.
246 // Set up all the animations that are used to implement this fading.
247 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700248 final float fromAlphaValue = 0;
249 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700250
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700251 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700252
253 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700254 final InterruptibleInOutAnimator anim =
255 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700256 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700257 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700258 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700259 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700260 final Bitmap outline = (Bitmap)anim.getTag();
261
262 // If an animation is started and then stopped very quickly, we can still
263 // get spurious updates we've cleared the tag. Guard against this.
264 if (outline == null) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700265 if (false) {
266 Object val = animation.getAnimatedValue();
267 Log.d(TAG, "anim " + thisIndex + " update: " + val +
268 ", isStopped " + anim.isStopped());
269 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700270 // Try to prevent it from continuing to run
271 animation.cancel();
272 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700273 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800274 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700275 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700276 }
277 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700278 // The animation holds a reference to the drag outline bitmap as long is it's
279 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700280 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700281 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700282 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700283 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700284 anim.setTag(null);
285 }
286 }
287 });
288 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700289 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700290
Michael Jurka18014792010-10-14 09:01:34 -0700291 mBackgroundRect = new Rect();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700292 mForegroundRect = new Rect();
Michael Jurkabea15192010-11-17 12:33:46 -0800293
Michael Jurkaa52570f2012-03-20 03:18:20 -0700294 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
295 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
296 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700297 }
298
Michael Jurkaf6440da2011-04-05 14:50:34 -0700299 static int widthInPortrait(Resources r, int numCells) {
300 // We use this method from Workspace to figure out how many rows/columns Launcher should
301 // have. We ignore the left/right padding on CellLayout because it turns out in our design
302 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700303 int cellWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700304 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
305 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700306
Winson Chung4b825dcd2011-06-19 12:41:22 -0700307 return minGap * (numCells - 1) + cellWidth * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700308 }
309
Michael Jurkaf6440da2011-04-05 14:50:34 -0700310 static int heightInLandscape(Resources r, int numCells) {
311 // We use this method from Workspace to figure out how many rows/columns Launcher should
312 // have. We ignore the left/right padding on CellLayout because it turns out in our design
313 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700314 int cellHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700315 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
316 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700317
Winson Chung4b825dcd2011-06-19 12:41:22 -0700318 return minGap * (numCells - 1) + cellHeight * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700319 }
320
Adam Cohen2801caf2011-05-13 20:57:39 -0700321 public void enableHardwareLayers() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700322 mShortcutsAndWidgets.enableHardwareLayers();
Adam Cohen2801caf2011-05-13 20:57:39 -0700323 }
324
325 public void setGridSize(int x, int y) {
326 mCountX = x;
327 mCountY = y;
328 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800329 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700330 mTempRectStack.clear();
Adam Cohen76fc0852011-06-17 13:26:23 -0700331 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700332 }
333
Patrick Dubroy96864c32011-03-10 17:17:23 -0800334 private void invalidateBubbleTextView(BubbleTextView icon) {
335 final int padding = icon.getPressedOrFocusedBackgroundPadding();
Winson Chung4b825dcd2011-06-19 12:41:22 -0700336 invalidate(icon.getLeft() + getPaddingLeft() - padding,
337 icon.getTop() + getPaddingTop() - padding,
338 icon.getRight() + getPaddingLeft() + padding,
339 icon.getBottom() + getPaddingTop() + padding);
Patrick Dubroy96864c32011-03-10 17:17:23 -0800340 }
341
Adam Cohenb5ba0972011-09-07 18:02:31 -0700342 void setOverScrollAmount(float r, boolean left) {
343 if (left && mOverScrollForegroundDrawable != mOverScrollLeft) {
344 mOverScrollForegroundDrawable = mOverScrollLeft;
345 } else if (!left && mOverScrollForegroundDrawable != mOverScrollRight) {
346 mOverScrollForegroundDrawable = mOverScrollRight;
347 }
348
349 mForegroundAlpha = (int) Math.round((r * 255));
350 mOverScrollForegroundDrawable.setAlpha(mForegroundAlpha);
351 invalidate();
352 }
353
Patrick Dubroy96864c32011-03-10 17:17:23 -0800354 void setPressedOrFocusedIcon(BubbleTextView icon) {
355 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
356 // requires an expanded clip rect (due to the glow's blur radius)
357 BubbleTextView oldIcon = mPressedOrFocusedIcon;
358 mPressedOrFocusedIcon = icon;
359 if (oldIcon != null) {
360 invalidateBubbleTextView(oldIcon);
361 }
362 if (mPressedOrFocusedIcon != null) {
363 invalidateBubbleTextView(mPressedOrFocusedIcon);
364 }
365 }
366
Michael Jurka33945b22010-12-21 18:19:38 -0800367 void setIsDragOverlapping(boolean isDragOverlapping) {
368 if (mIsDragOverlapping != isDragOverlapping) {
369 mIsDragOverlapping = isDragOverlapping;
370 invalidate();
371 }
372 }
373
374 boolean getIsDragOverlapping() {
375 return mIsDragOverlapping;
376 }
377
Adam Cohenebea84d2011-11-09 17:20:41 -0800378 protected void setOverscrollTransformsDirty(boolean dirty) {
379 mScrollingTransformsDirty = dirty;
380 }
381
382 protected void resetOverscrollTransforms() {
383 if (mScrollingTransformsDirty) {
384 setOverscrollTransformsDirty(false);
385 setTranslationX(0);
386 setRotationY(0);
387 // It doesn't matter if we pass true or false here, the important thing is that we
388 // pass 0, which results in the overscroll drawable not being drawn any more.
389 setOverScrollAmount(0, false);
390 setPivotX(getMeasuredWidth() / 2);
391 setPivotY(getMeasuredHeight() / 2);
392 }
393 }
394
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700395 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700396 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700397 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
398 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
399 // When we're small, we are either drawn normally or in the "accepts drops" state (during
400 // a drag). However, we also drag the mini hover background *over* one of those two
401 // backgrounds
Winson Chungb26f3d62011-06-02 10:49:29 -0700402 if (mBackgroundAlpha > 0.0f) {
Adam Cohenf34bab52010-09-30 14:11:56 -0700403 Drawable bg;
Michael Jurka33945b22010-12-21 18:19:38 -0800404
405 if (mIsDragOverlapping) {
406 // In the mini case, we draw the active_glow bg *over* the active background
Michael Jurkabdf78552011-10-31 14:34:25 -0700407 bg = mActiveGlowBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700408 } else {
Michael Jurkabdf78552011-10-31 14:34:25 -0700409 bg = mNormalBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700410 }
Michael Jurka33945b22010-12-21 18:19:38 -0800411
412 bg.setAlpha((int) (mBackgroundAlpha * mBackgroundAlphaMultiplier * 255));
413 bg.setBounds(mBackgroundRect);
414 bg.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700415 }
Romain Guya6abce82009-11-10 02:54:41 -0800416
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700417 if (mCrosshairsVisibility > 0.0f) {
418 final int countX = mCountX;
419 final int countY = mCountY;
420
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700421 final float MAX_ALPHA = 0.4f;
422 final int MAX_VISIBLE_DISTANCE = 600;
423 final float DISTANCE_MULTIPLIER = 0.002f;
424
425 final Drawable d = mCrosshairsDrawable;
426 final int width = d.getIntrinsicWidth();
427 final int height = d.getIntrinsicHeight();
428
Winson Chung4b825dcd2011-06-19 12:41:22 -0700429 int x = getPaddingLeft() - (mWidthGap / 2) - (width / 2);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700430 for (int col = 0; col <= countX; col++) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700431 int y = getPaddingTop() - (mHeightGap / 2) - (height / 2);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700432 for (int row = 0; row <= countY; row++) {
433 mTmpPointF.set(x - mDragCenter.x, y - mDragCenter.y);
434 float dist = mTmpPointF.length();
435 // Crosshairs further from the drag point are more faint
436 float alpha = Math.min(MAX_ALPHA,
437 DISTANCE_MULTIPLIER * (MAX_VISIBLE_DISTANCE - dist));
438 if (alpha > 0.0f) {
439 d.setBounds(x, y, x + width, y + height);
440 d.setAlpha((int) (alpha * 255 * mCrosshairsVisibility));
441 d.draw(canvas);
442 }
443 y += mCellHeight + mHeightGap;
444 }
445 x += mCellWidth + mWidthGap;
446 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700447 }
Winson Chung150fbab2010-09-29 17:14:26 -0700448
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700449 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700450 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700451 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700452 if (alpha > 0) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800453 final Rect r = mDragOutlines[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700454 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700455 paint.setAlpha((int)(alpha + .5f));
Adam Cohend41fbf52012-02-16 23:53:59 -0800456 canvas.drawBitmap(b, null, r, paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700457 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700458 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800459
460 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
461 // requires an expanded clip rect (due to the glow's blur radius)
462 if (mPressedOrFocusedIcon != null) {
463 final int padding = mPressedOrFocusedIcon.getPressedOrFocusedBackgroundPadding();
464 final Bitmap b = mPressedOrFocusedIcon.getPressedOrFocusedBackground();
465 if (b != null) {
466 canvas.drawBitmap(b,
Winson Chung4b825dcd2011-06-19 12:41:22 -0700467 mPressedOrFocusedIcon.getLeft() + getPaddingLeft() - padding,
468 mPressedOrFocusedIcon.getTop() + getPaddingTop() - padding,
Patrick Dubroy96864c32011-03-10 17:17:23 -0800469 null);
470 }
471 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700472
Adam Cohen482ed822012-03-02 14:15:13 -0800473 if (DEBUG_VISUALIZE_OCCUPIED) {
474 int[] pt = new int[2];
475 ColorDrawable cd = new ColorDrawable(Color.RED);
476 cd.setBounds(0, 0, 80, 80);
477 for (int i = 0; i < mCountX; i++) {
478 for (int j = 0; j < mCountY; j++) {
479 if (mOccupied[i][j]) {
480 cellToPoint(i, j, pt);
481 canvas.save();
482 canvas.translate(pt[0], pt[1]);
483 cd.draw(canvas);
484 canvas.restore();
485 }
486 }
487 }
488 }
489
Adam Cohen69ce2e52011-07-03 19:25:21 -0700490 // The folder outer / inner ring image(s)
491 for (int i = 0; i < mFolderOuterRings.size(); i++) {
492 FolderRingAnimator fra = mFolderOuterRings.get(i);
493
494 // Draw outer ring
495 Drawable d = FolderRingAnimator.sSharedOuterRingDrawable;
496 int width = (int) fra.getOuterRingSize();
497 int height = width;
498 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
499
500 int centerX = mTempLocation[0] + mCellWidth / 2;
501 int centerY = mTempLocation[1] + FolderRingAnimator.sPreviewSize / 2;
502
503 canvas.save();
504 canvas.translate(centerX - width / 2, centerY - height / 2);
505 d.setBounds(0, 0, width, height);
506 d.draw(canvas);
507 canvas.restore();
508
509 // Draw inner ring
510 d = FolderRingAnimator.sSharedInnerRingDrawable;
511 width = (int) fra.getInnerRingSize();
512 height = width;
513 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
514
515 centerX = mTempLocation[0] + mCellWidth / 2;
516 centerY = mTempLocation[1] + FolderRingAnimator.sPreviewSize / 2;
517 canvas.save();
518 canvas.translate(centerX - width / 2, centerY - width / 2);
519 d.setBounds(0, 0, width, height);
520 d.draw(canvas);
521 canvas.restore();
522 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700523
524 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
525 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
526 int width = d.getIntrinsicWidth();
527 int height = d.getIntrinsicHeight();
528
529 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
530 int centerX = mTempLocation[0] + mCellWidth / 2;
531 int centerY = mTempLocation[1] + FolderRingAnimator.sPreviewSize / 2;
532
533 canvas.save();
534 canvas.translate(centerX - width / 2, centerY - width / 2);
535 d.setBounds(0, 0, width, height);
536 d.draw(canvas);
537 canvas.restore();
538 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700539 }
540
Adam Cohenb5ba0972011-09-07 18:02:31 -0700541 @Override
542 protected void dispatchDraw(Canvas canvas) {
543 super.dispatchDraw(canvas);
544 if (mForegroundAlpha > 0) {
545 mOverScrollForegroundDrawable.setBounds(mForegroundRect);
546 Paint p = ((NinePatchDrawable) mOverScrollForegroundDrawable).getPaint();
547 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.ADD));
548 mOverScrollForegroundDrawable.draw(canvas);
549 p.setXfermode(null);
550 }
551 }
552
Adam Cohen69ce2e52011-07-03 19:25:21 -0700553 public void showFolderAccept(FolderRingAnimator fra) {
554 mFolderOuterRings.add(fra);
555 }
556
557 public void hideFolderAccept(FolderRingAnimator fra) {
558 if (mFolderOuterRings.contains(fra)) {
559 mFolderOuterRings.remove(fra);
560 }
561 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700562 }
563
Adam Cohenc51934b2011-07-26 21:07:43 -0700564 public void setFolderLeaveBehindCell(int x, int y) {
565 mFolderLeaveBehindCell[0] = x;
566 mFolderLeaveBehindCell[1] = y;
567 invalidate();
568 }
569
570 public void clearFolderLeaveBehind() {
571 mFolderLeaveBehindCell[0] = -1;
572 mFolderLeaveBehindCell[1] = -1;
573 invalidate();
574 }
575
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700576 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700577 public boolean shouldDelayChildPressedState() {
578 return false;
579 }
580
581 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700582 public void cancelLongPress() {
583 super.cancelLongPress();
584
585 // Cancel long press for all children
586 final int count = getChildCount();
587 for (int i = 0; i < count; i++) {
588 final View child = getChildAt(i);
589 child.cancelLongPress();
590 }
591 }
592
Michael Jurkadee05892010-07-27 10:01:56 -0700593 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
594 mInterceptTouchListener = listener;
595 }
596
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800597 int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700598 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 }
600
601 int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700602 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800603 }
604
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800605 public void setIsHotseat(boolean isHotseat) {
606 mIsHotseat = isHotseat;
607 }
608
Winson Chungeecf02d2012-03-02 17:14:58 -0800609 public float getChildrenScale() {
610 return mIsHotseat ? mHotseatChildScale : mChildScale;
611 }
612
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700613 public boolean addViewToCellLayout(
614 View child, int index, int childId, LayoutParams params, boolean markCells) {
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800615 return addViewToCellLayout(child, index, childId, params, markCells, false);
616 }
617
Winson Chungeecf02d2012-03-02 17:14:58 -0800618 private void scaleChild(BubbleTextView bubbleChild, float pivot, float scale) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800619 // If we haven't measured the child yet, do it now
620 // (this happens if we're being dropped from all-apps
621 if (bubbleChild.getLayoutParams() instanceof LayoutParams &&
622 (bubbleChild.getMeasuredWidth() | bubbleChild.getMeasuredHeight()) == 0) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700623 getShortcutsAndWidgets().measureChild(bubbleChild);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800624 }
Andrew Flynnbc239a12012-03-06 11:39:49 -0800625
Andrew Flynnbc239a12012-03-06 11:39:49 -0800626 bubbleChild.setScaleX(scale);
627 bubbleChild.setScaleY(scale);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800628 }
629
630 private void resetChild(BubbleTextView bubbleChild) {
631 bubbleChild.setScaleX(1f);
632 bubbleChild.setScaleY(1f);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800633
634 bubbleChild.setTextColor(getResources().getColor(R.color.workspace_icon_text_color));
635 }
636
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800637 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
638 boolean markCells, boolean allApps) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700639 final LayoutParams lp = params;
640
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800641 // Hotseat icons - scale down and remove text
642 // Don't scale the all apps button
643 // scale percent set to -1 means do not scale
644 // Only scale BubbleTextViews
645 if (child instanceof BubbleTextView) {
646 BubbleTextView bubbleChild = (BubbleTextView) child;
647
Andrew Flynnbc239a12012-03-06 11:39:49 -0800648 // Start the child with 100% scale and visible text
649 resetChild(bubbleChild);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800650
Winson Chungeecf02d2012-03-02 17:14:58 -0800651 if (mIsHotseat && !allApps && mHotseatChildScale >= 0) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800652 // Scale/make transparent for a hotseat
Winson Chungeecf02d2012-03-02 17:14:58 -0800653 scaleChild(bubbleChild, 0f, mHotseatChildScale);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800654
Andrew Flynnbc239a12012-03-06 11:39:49 -0800655 bubbleChild.setTextColor(getResources().getColor(android.R.color.transparent));
Winson Chungeecf02d2012-03-02 17:14:58 -0800656 } else if (mChildScale >= 0) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800657 // Else possibly still scale it if we need to for smaller icons
Winson Chungeecf02d2012-03-02 17:14:58 -0800658 scaleChild(bubbleChild, 0f, mChildScale);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800659 }
660 }
661
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800662 // Generate an id for each view, this assumes we have at most 256x256 cells
663 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700664 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700665 // If the horizontal or vertical span is set to -1, it is taken to
666 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700667 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
668 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800669
Winson Chungaafa03c2010-06-11 17:34:16 -0700670 child.setId(childId);
671
Michael Jurkaa52570f2012-03-20 03:18:20 -0700672 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700673
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700674 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700675
Winson Chungaafa03c2010-06-11 17:34:16 -0700676 return true;
677 }
678 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800679 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700680
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800681 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700682 public void removeAllViews() {
683 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700684 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700685 }
686
687 @Override
688 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700689 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700690 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700691 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700692 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700693 }
694
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700695 public void removeViewWithoutMarkingCells(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700696 mShortcutsAndWidgets.removeView(view);
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700697 }
698
Michael Jurka0280c3b2010-09-17 15:00:07 -0700699 @Override
700 public void removeView(View view) {
701 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700702 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700703 }
704
705 @Override
706 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700707 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
708 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700709 }
710
711 @Override
712 public void removeViewInLayout(View view) {
713 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700714 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700715 }
716
717 @Override
718 public void removeViews(int start, int count) {
719 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700720 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700721 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700722 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700723 }
724
725 @Override
726 public void removeViewsInLayout(int start, int count) {
727 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700728 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700729 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700730 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800731 }
732
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800733 @Override
734 protected void onAttachedToWindow() {
735 super.onAttachedToWindow();
736 mCellInfo.screen = ((ViewGroup) getParent()).indexOfChild(this);
737 }
738
Michael Jurkaaf442092010-06-10 17:01:57 -0700739 public void setTagToCellInfoForPoint(int touchX, int touchY) {
740 final CellInfo cellInfo = mCellInfo;
Winson Chungeecf02d2012-03-02 17:14:58 -0800741 Rect frame = mRect;
Michael Jurkaaf442092010-06-10 17:01:57 -0700742 final int x = touchX + mScrollX;
743 final int y = touchY + mScrollY;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700744 final int count = mShortcutsAndWidgets.getChildCount();
Michael Jurkaaf442092010-06-10 17:01:57 -0700745
746 boolean found = false;
747 for (int i = count - 1; i >= 0; i--) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700748 final View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohend4844c32011-02-18 19:25:06 -0800749 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurkaaf442092010-06-10 17:01:57 -0700750
Adam Cohen1b607ed2011-03-03 17:26:50 -0800751 if ((child.getVisibility() == VISIBLE || child.getAnimation() != null) &&
752 lp.isLockedToGrid) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700753 child.getHitRect(frame);
Winson Chung0be025d2011-05-23 17:45:09 -0700754
Winson Chungeecf02d2012-03-02 17:14:58 -0800755 float scale = child.getScaleX();
756 frame = new Rect(child.getLeft(), child.getTop(), child.getRight(),
757 child.getBottom());
Winson Chung0be025d2011-05-23 17:45:09 -0700758 // The child hit rect is relative to the CellLayoutChildren parent, so we need to
759 // offset that by this CellLayout's padding to test an (x,y) point that is relative
760 // to this view.
Winson Chung4b825dcd2011-06-19 12:41:22 -0700761 frame.offset(mPaddingLeft, mPaddingTop);
Winson Chungeecf02d2012-03-02 17:14:58 -0800762 frame.inset((int) (frame.width() * (1f - scale) / 2),
763 (int) (frame.height() * (1f - scale) / 2));
Winson Chung0be025d2011-05-23 17:45:09 -0700764
Michael Jurkaaf442092010-06-10 17:01:57 -0700765 if (frame.contains(x, y)) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700766 cellInfo.cell = child;
767 cellInfo.cellX = lp.cellX;
768 cellInfo.cellY = lp.cellY;
769 cellInfo.spanX = lp.cellHSpan;
770 cellInfo.spanY = lp.cellVSpan;
Michael Jurkaaf442092010-06-10 17:01:57 -0700771 found = true;
Michael Jurkaaf442092010-06-10 17:01:57 -0700772 break;
773 }
774 }
775 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700776
Michael Jurkad771c962011-08-09 15:00:48 -0700777 mLastDownOnOccupiedCell = found;
778
Michael Jurkaaf442092010-06-10 17:01:57 -0700779 if (!found) {
Winson Chung0be025d2011-05-23 17:45:09 -0700780 final int cellXY[] = mTmpXY;
Michael Jurkaaf442092010-06-10 17:01:57 -0700781 pointToCellExact(x, y, cellXY);
782
Michael Jurkaaf442092010-06-10 17:01:57 -0700783 cellInfo.cell = null;
784 cellInfo.cellX = cellXY[0];
785 cellInfo.cellY = cellXY[1];
786 cellInfo.spanX = 1;
787 cellInfo.spanY = 1;
Michael Jurkaaf442092010-06-10 17:01:57 -0700788 }
789 setTag(cellInfo);
790 }
791
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800792 @Override
793 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohenc1997fd2011-08-15 18:26:39 -0700794 // First we clear the tag to ensure that on every touch down we start with a fresh slate,
795 // even in the case where we return early. Not clearing here was causing bugs whereby on
796 // long-press we'd end up picking up an item from a previous drag operation.
797 final int action = ev.getAction();
798
799 if (action == MotionEvent.ACTION_DOWN) {
800 clearTagCellInfo();
801 }
802
Michael Jurkadee05892010-07-27 10:01:56 -0700803 if (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev)) {
804 return true;
805 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800806
807 if (action == MotionEvent.ACTION_DOWN) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700808 setTagToCellInfoForPoint((int) ev.getX(), (int) ev.getY());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800809 }
Winson Chungeecf02d2012-03-02 17:14:58 -0800810
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800811 return false;
812 }
813
Adam Cohenc1997fd2011-08-15 18:26:39 -0700814 private void clearTagCellInfo() {
815 final CellInfo cellInfo = mCellInfo;
816 cellInfo.cell = null;
817 cellInfo.cellX = -1;
818 cellInfo.cellY = -1;
819 cellInfo.spanX = 0;
820 cellInfo.spanY = 0;
821 setTag(cellInfo);
822 }
823
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800824 public CellInfo getTag() {
Michael Jurka0280c3b2010-09-17 15:00:07 -0700825 return (CellInfo) super.getTag();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800826 }
827
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700828 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700829 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800830 * @param x X coordinate of the point
831 * @param y Y coordinate of the point
832 * @param result Array of 2 ints to hold the x and y coordinate of the cell
833 */
834 void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700835 final int hStartPadding = getPaddingLeft();
836 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800837
838 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
839 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
840
Adam Cohend22015c2010-07-26 22:02:18 -0700841 final int xAxis = mCountX;
842 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800843
844 if (result[0] < 0) result[0] = 0;
845 if (result[0] >= xAxis) result[0] = xAxis - 1;
846 if (result[1] < 0) result[1] = 0;
847 if (result[1] >= yAxis) result[1] = yAxis - 1;
848 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700849
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800850 /**
851 * Given a point, return the cell that most closely encloses that point
852 * @param x X coordinate of the point
853 * @param y Y coordinate of the point
854 * @param result Array of 2 ints to hold the x and y coordinate of the cell
855 */
856 void pointToCellRounded(int x, int y, int[] result) {
857 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
858 }
859
860 /**
861 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700862 *
863 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800864 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700865 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800866 * @param result Array of 2 ints to hold the x and y coordinate of the point
867 */
868 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700869 final int hStartPadding = getPaddingLeft();
870 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800871
872 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
873 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
874 }
875
Adam Cohene3e27a82011-04-15 12:07:39 -0700876 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800877 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700878 *
879 * @param cellX X coordinate of the cell
880 * @param cellY Y coordinate of the cell
881 *
882 * @param result Array of 2 ints to hold the x and y coordinate of the point
883 */
884 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700885 regionToCenterPoint(cellX, cellY, 1, 1, result);
886 }
887
888 /**
889 * Given a cell coordinate and span return the point that represents the center of the regio
890 *
891 * @param cellX X coordinate of the cell
892 * @param cellY Y coordinate of the cell
893 *
894 * @param result Array of 2 ints to hold the x and y coordinate of the point
895 */
896 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700897 final int hStartPadding = getPaddingLeft();
898 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700899 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
900 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
901 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
902 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700903 }
904
Adam Cohen19f37922012-03-21 11:59:11 -0700905 /**
906 * Given a cell coordinate and span fills out a corresponding pixel rect
907 *
908 * @param cellX X coordinate of the cell
909 * @param cellY Y coordinate of the cell
910 * @param result Rect in which to write the result
911 */
912 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
913 final int hStartPadding = getPaddingLeft();
914 final int vStartPadding = getPaddingTop();
915 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
916 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
917 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
918 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
919 }
920
Adam Cohen482ed822012-03-02 14:15:13 -0800921 public float getDistanceFromCell(float x, float y, int[] cell) {
922 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
923 float distance = (float) Math.sqrt( Math.pow(x - mTmpPoint[0], 2) +
924 Math.pow(y - mTmpPoint[1], 2));
925 return distance;
926 }
927
Romain Guy84f296c2009-11-04 15:00:44 -0800928 int getCellWidth() {
929 return mCellWidth;
930 }
931
932 int getCellHeight() {
933 return mCellHeight;
934 }
935
Adam Cohend4844c32011-02-18 19:25:06 -0800936 int getWidthGap() {
937 return mWidthGap;
938 }
939
940 int getHeightGap() {
941 return mHeightGap;
942 }
943
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700944 Rect getContentRect(Rect r) {
945 if (r == null) {
946 r = new Rect();
947 }
948 int left = getPaddingLeft();
949 int top = getPaddingTop();
Winson Chung4b825dcd2011-06-19 12:41:22 -0700950 int right = left + getWidth() - mPaddingLeft - mPaddingRight;
951 int bottom = top + getHeight() - mPaddingTop - mPaddingBottom;
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700952 r.set(left, top, right, bottom);
953 return r;
954 }
955
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800956 @Override
957 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
958 // TODO: currently ignoring padding
Winson Chungaafa03c2010-06-11 17:34:16 -0700959
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800960 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700961 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
962
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800963 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
964 int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700965
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800966 if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
967 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
968 }
969
Adam Cohend22015c2010-07-26 22:02:18 -0700970 int numWidthGaps = mCountX - 1;
971 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800972
Adam Cohen234c4cd2011-07-17 21:03:04 -0700973 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700974 int hSpace = widthSpecSize - mPaddingLeft - mPaddingRight;
975 int vSpace = heightSpecSize - mPaddingTop - mPaddingBottom;
976 int hFreeSpace = hSpace - (mCountX * mOriginalCellWidth);
977 int vFreeSpace = vSpace - (mCountY * mOriginalCellHeight);
978 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
979 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700980 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700981 } else {
982 mWidthGap = mOriginalWidthGap;
983 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700984 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700985
Michael Jurka8c920dd2011-01-20 14:16:56 -0800986 // Initial values correspond to widthSpecMode == MeasureSpec.EXACTLY
987 int newWidth = widthSpecSize;
988 int newHeight = heightSpecSize;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700989 if (widthSpecMode == MeasureSpec.AT_MOST) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700990 newWidth = mPaddingLeft + mPaddingRight + (mCountX * mCellWidth) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700991 ((mCountX - 1) * mWidthGap);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700992 newHeight = mPaddingTop + mPaddingBottom + (mCountY * mCellHeight) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700993 ((mCountY - 1) * mHeightGap);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700994 setMeasuredDimension(newWidth, newHeight);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700995 }
Michael Jurka8c920dd2011-01-20 14:16:56 -0800996
997 int count = getChildCount();
998 for (int i = 0; i < count; i++) {
999 View child = getChildAt(i);
Winson Chung4b825dcd2011-06-19 12:41:22 -07001000 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth - mPaddingLeft -
1001 mPaddingRight, MeasureSpec.EXACTLY);
1002 int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight - mPaddingTop -
1003 mPaddingBottom, MeasureSpec.EXACTLY);
Michael Jurka8c920dd2011-01-20 14:16:56 -08001004 child.measure(childWidthMeasureSpec, childheightMeasureSpec);
1005 }
1006 setMeasuredDimension(newWidth, newHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001007 }
1008
1009 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -07001010 protected void onLayout(boolean changed, int l, int t, int r, int b) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001011 int count = getChildCount();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001012 for (int i = 0; i < count; i++) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08001013 View child = getChildAt(i);
Winson Chung4b825dcd2011-06-19 12:41:22 -07001014 child.layout(mPaddingLeft, mPaddingTop,
1015 r - l - mPaddingRight, b - t - mPaddingBottom);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001016 }
1017 }
1018
1019 @Override
Michael Jurkadee05892010-07-27 10:01:56 -07001020 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1021 super.onSizeChanged(w, h, oldw, oldh);
Michael Jurka18014792010-10-14 09:01:34 -07001022 mBackgroundRect.set(0, 0, w, h);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001023 mForegroundRect.set(mForegroundPadding, mForegroundPadding,
1024 w - 2 * mForegroundPadding, h - 2 * mForegroundPadding);
Michael Jurkadee05892010-07-27 10:01:56 -07001025 }
1026
1027 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001028 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001029 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001030 }
1031
1032 @Override
1033 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001034 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001035 }
1036
Michael Jurka5f1c5092010-09-03 14:15:02 -07001037 public float getBackgroundAlpha() {
1038 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -07001039 }
1040
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001041 public void setBackgroundAlphaMultiplier(float multiplier) {
1042 mBackgroundAlphaMultiplier = multiplier;
1043 }
1044
Adam Cohenddb82192010-11-10 16:32:54 -08001045 public float getBackgroundAlphaMultiplier() {
1046 return mBackgroundAlphaMultiplier;
1047 }
1048
Michael Jurka5f1c5092010-09-03 14:15:02 -07001049 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -08001050 if (mBackgroundAlpha != alpha) {
1051 mBackgroundAlpha = alpha;
1052 invalidate();
1053 }
Michael Jurkadee05892010-07-27 10:01:56 -07001054 }
1055
Michael Jurkaa52570f2012-03-20 03:18:20 -07001056 public void setShortcutAndWidgetAlpha(float alpha) {
Michael Jurka0142d492010-08-25 17:46:15 -07001057 final int childCount = getChildCount();
1058 for (int i = 0; i < childCount; i++) {
Michael Jurkadee05892010-07-27 10:01:56 -07001059 getChildAt(i).setAlpha(alpha);
1060 }
1061 }
1062
Michael Jurkaa52570f2012-03-20 03:18:20 -07001063 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
1064 if (getChildCount() > 0) {
1065 return (ShortcutAndWidgetContainer) getChildAt(0);
1066 }
1067 return null;
1068 }
1069
Patrick Dubroy440c3602010-07-13 17:50:32 -07001070 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001071 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001072 }
1073
Adam Cohen76fc0852011-06-17 13:26:23 -07001074 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001075 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001076 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -08001077 boolean[][] occupied = mOccupied;
1078 if (!permanent) {
1079 occupied = mTmpOccupied;
1080 }
1081
Adam Cohen19f37922012-03-21 11:59:11 -07001082 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001083 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
1084 final ItemInfo info = (ItemInfo) child.getTag();
1085
1086 // We cancel any existing animations
1087 if (mReorderAnimators.containsKey(lp)) {
1088 mReorderAnimators.get(lp).cancel();
1089 mReorderAnimators.remove(lp);
1090 }
1091
Adam Cohen482ed822012-03-02 14:15:13 -08001092 final int oldX = lp.x;
1093 final int oldY = lp.y;
1094 if (adjustOccupied) {
1095 occupied[lp.cellX][lp.cellY] = false;
1096 occupied[cellX][cellY] = true;
1097 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001098 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001099 if (permanent) {
1100 lp.cellX = info.cellX = cellX;
1101 lp.cellY = info.cellY = cellY;
1102 } else {
1103 lp.tmpCellX = cellX;
1104 lp.tmpCellY = cellY;
1105 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001106 clc.setupLp(lp);
1107 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001108 final int newX = lp.x;
1109 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001110
Adam Cohen76fc0852011-06-17 13:26:23 -07001111 lp.x = oldX;
1112 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001113
Adam Cohen482ed822012-03-02 14:15:13 -08001114 // Exit early if we're not actually moving the view
1115 if (oldX == newX && oldY == newY) {
1116 lp.isLockedToGrid = true;
1117 return true;
1118 }
1119
1120 ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
1121 va.setDuration(duration);
1122 mReorderAnimators.put(lp, va);
1123
1124 va.addUpdateListener(new AnimatorUpdateListener() {
1125 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001126 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001127 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001128 lp.x = (int) ((1 - r) * oldX + r * newX);
1129 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001130 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001131 }
1132 });
Adam Cohen482ed822012-03-02 14:15:13 -08001133 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001134 boolean cancelled = false;
1135 public void onAnimationEnd(Animator animation) {
1136 // If the animation was cancelled, it means that another animation
1137 // has interrupted this one, and we don't want to lock the item into
1138 // place just yet.
1139 if (!cancelled) {
1140 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001141 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001142 }
1143 if (mReorderAnimators.containsKey(lp)) {
1144 mReorderAnimators.remove(lp);
1145 }
1146 }
1147 public void onAnimationCancel(Animator animation) {
1148 cancelled = true;
1149 }
1150 });
Adam Cohen482ed822012-03-02 14:15:13 -08001151 va.setStartDelay(delay);
1152 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001153 return true;
1154 }
1155 return false;
1156 }
1157
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001158 /**
1159 * Estimate where the top left cell of the dragged item will land if it is dropped.
1160 *
1161 * @param originX The X value of the top left corner of the item
1162 * @param originY The Y value of the top left corner of the item
1163 * @param spanX The number of horizontal cells that the item spans
1164 * @param spanY The number of vertical cells that the item spans
1165 * @param result The estimated drop cell X and Y.
1166 */
1167 void estimateDropCell(int originX, int originY, int spanX, int spanY, int[] result) {
Adam Cohend22015c2010-07-26 22:02:18 -07001168 final int countX = mCountX;
1169 final int countY = mCountY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001170
Michael Jurkaa63c4522010-08-19 13:52:27 -07001171 // pointToCellRounded takes the top left of a cell but will pad that with
1172 // cellWidth/2 and cellHeight/2 when finding the matching cell
1173 pointToCellRounded(originX, originY, result);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001174
1175 // If the item isn't fully on this screen, snap to the edges
1176 int rightOverhang = result[0] + spanX - countX;
1177 if (rightOverhang > 0) {
1178 result[0] -= rightOverhang; // Snap to right
1179 }
1180 result[0] = Math.max(0, result[0]); // Snap to left
1181 int bottomOverhang = result[1] + spanY - countY;
1182 if (bottomOverhang > 0) {
1183 result[1] -= bottomOverhang; // Snap to bottom
1184 }
1185 result[1] = Math.max(0, result[1]); // Snap to top
1186 }
1187
Adam Cohen482ed822012-03-02 14:15:13 -08001188 void visualizeDropLocation(View v, Bitmap dragOutline, int originX, int originY, int cellX,
1189 int cellY, int spanX, int spanY, boolean resize, Point dragOffset, Rect dragRegion) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001190 final int oldDragCellX = mDragCell[0];
1191 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001192
Winson Chungb8c69f32011-10-19 21:36:08 -07001193 if (v != null && dragOffset == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07001194 mDragCenter.set(originX + (v.getWidth() / 2), originY + (v.getHeight() / 2));
1195 } else {
1196 mDragCenter.set(originX, originY);
1197 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001198
Adam Cohen2801caf2011-05-13 20:57:39 -07001199 if (dragOutline == null && v == null) {
1200 if (mCrosshairsDrawable != null) {
1201 invalidate();
1202 }
1203 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 }
Patrick Dubroy49250ad2010-10-08 15:33:52 -07001257
1258 // If we are drawing crosshairs, the entire CellLayout needs to be invalidated
1259 if (mCrosshairsDrawable != null) {
1260 invalidate();
1261 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001262 }
1263
Adam Cohene0310962011-04-18 16:15:31 -07001264 public void clearDragOutlines() {
1265 final int oldIndex = mDragOutlineCurrent;
1266 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001267 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001268 }
1269
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001270 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001271 * Find a vacant area that will fit the given bounds nearest the requested
1272 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001273 *
Romain Guy51afc022009-05-04 18:03:43 -07001274 * @param pixelX The X location at which you want to search for a vacant area.
1275 * @param pixelY The Y location at which you want to search for a vacant area.
Jeff Sharkey70864282009-04-07 21:08:40 -07001276 * @param spanX Horizontal span of the object.
1277 * @param spanY Vertical span of the object.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001278 * @param result Array in which to place the result, or null (in which case a new array will
1279 * be allocated)
Jeff Sharkey70864282009-04-07 21:08:40 -07001280 * @return The X, Y cell of a vacant area that can contain this object,
1281 * nearest the requested location.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001282 */
Adam Cohend41fbf52012-02-16 23:53:59 -08001283 int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY,
1284 int[] result) {
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001285 return findNearestVacantArea(pixelX, pixelY, spanX, spanY, null, result);
Michael Jurka6a1435d2010-09-27 17:35:12 -07001286 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001287
Michael Jurka6a1435d2010-09-27 17:35:12 -07001288 /**
1289 * Find a vacant area that will fit the given bounds nearest the requested
1290 * cell location. Uses Euclidean distance to score multiple vacant areas.
1291 *
1292 * @param pixelX The X location at which you want to search for a vacant area.
1293 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001294 * @param minSpanX The minimum horizontal span required
1295 * @param minSpanY The minimum vertical span required
1296 * @param spanX Horizontal span of the object.
1297 * @param spanY Vertical span of the object.
1298 * @param result Array in which to place the result, or null (in which case a new array will
1299 * be allocated)
1300 * @return The X, Y cell of a vacant area that can contain this object,
1301 * nearest the requested location.
1302 */
1303 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1304 int spanY, int[] result, int[] resultSpan) {
1305 return findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null,
1306 result, resultSpan);
1307 }
1308
1309 /**
1310 * Find a vacant area that will fit the given bounds nearest the requested
1311 * cell location. Uses Euclidean distance to score multiple vacant areas.
1312 *
1313 * @param pixelX The X location at which you want to search for a vacant area.
1314 * @param pixelY The Y location at which you want to search for a vacant area.
Michael Jurka6a1435d2010-09-27 17:35:12 -07001315 * @param spanX Horizontal span of the object.
1316 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07001317 * @param ignoreOccupied If true, the result can be an occupied cell
1318 * @param result Array in which to place the result, or null (in which case a new array will
1319 * be allocated)
Michael Jurka6a1435d2010-09-27 17:35:12 -07001320 * @return The X, Y cell of a vacant area that can contain this object,
1321 * nearest the requested location.
1322 */
Adam Cohendf035382011-04-11 17:22:04 -07001323 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, View ignoreView,
1324 boolean ignoreOccupied, int[] result) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001325 return findNearestArea(pixelX, pixelY, spanX, spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001326 spanX, spanY, ignoreView, ignoreOccupied, result, null, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08001327 }
1328
1329 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1330 private void lazyInitTempRectStack() {
1331 if (mTempRectStack.isEmpty()) {
1332 for (int i = 0; i < mCountX * mCountY; i++) {
1333 mTempRectStack.push(new Rect());
1334 }
1335 }
1336 }
Adam Cohen482ed822012-03-02 14:15:13 -08001337
Adam Cohend41fbf52012-02-16 23:53:59 -08001338 private void recycleTempRects(Stack<Rect> used) {
1339 while (!used.isEmpty()) {
1340 mTempRectStack.push(used.pop());
1341 }
1342 }
1343
1344 /**
1345 * Find a vacant area that will fit the given bounds nearest the requested
1346 * cell location. Uses Euclidean distance to score multiple vacant areas.
1347 *
1348 * @param pixelX The X location at which you want to search for a vacant area.
1349 * @param pixelY The Y location at which you want to search for a vacant area.
1350 * @param minSpanX The minimum horizontal span required
1351 * @param minSpanY The minimum vertical span required
1352 * @param spanX Horizontal span of the object.
1353 * @param spanY Vertical span of the object.
1354 * @param ignoreOccupied If true, the result can be an occupied cell
1355 * @param result Array in which to place the result, or null (in which case a new array will
1356 * be allocated)
1357 * @return The X, Y cell of a vacant area that can contain this object,
1358 * nearest the requested location.
1359 */
1360 int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001361 View ignoreView, boolean ignoreOccupied, int[] result, int[] resultSpan,
1362 boolean[][] occupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001363 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001364 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08001365 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001366
Adam Cohene3e27a82011-04-15 12:07:39 -07001367 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1368 // to the center of the item, but we are searching based on the top-left cell, so
1369 // we translate the point over to correspond to the top-left.
1370 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1371 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1372
Jeff Sharkey70864282009-04-07 21:08:40 -07001373 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001374 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001375 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001376 final Rect bestRect = new Rect(-1, -1, -1, -1);
1377 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001378
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001379 final int countX = mCountX;
1380 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001381
Adam Cohend41fbf52012-02-16 23:53:59 -08001382 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1383 spanX < minSpanX || spanY < minSpanY) {
1384 return bestXY;
1385 }
1386
1387 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001388 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001389 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1390 int ySize = -1;
1391 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001392 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001393 // First, let's see if this thing fits anywhere
1394 for (int i = 0; i < minSpanX; i++) {
1395 for (int j = 0; j < minSpanY; j++) {
Adam Cohendf035382011-04-11 17:22:04 -07001396 if (occupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001397 continue inner;
1398 }
Michael Jurkac28de512010-08-13 11:27:44 -07001399 }
1400 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001401 xSize = minSpanX;
1402 ySize = minSpanY;
1403
1404 // We know that the item will fit at _some_ acceptable size, now let's see
1405 // how big we can make it. We'll alternate between incrementing x and y spans
1406 // until we hit a limit.
1407 boolean incX = true;
1408 boolean hitMaxX = xSize >= spanX;
1409 boolean hitMaxY = ySize >= spanY;
1410 while (!(hitMaxX && hitMaxY)) {
1411 if (incX && !hitMaxX) {
1412 for (int j = 0; j < ySize; j++) {
1413 if (x + xSize > countX -1 || occupied[x + xSize][y + j]) {
1414 // We can't move out horizontally
1415 hitMaxX = true;
1416 }
1417 }
1418 if (!hitMaxX) {
1419 xSize++;
1420 }
1421 } else if (!hitMaxY) {
1422 for (int i = 0; i < xSize; i++) {
1423 if (y + ySize > countY - 1 || occupied[x + i][y + ySize]) {
1424 // We can't move out vertically
1425 hitMaxY = true;
1426 }
1427 }
1428 if (!hitMaxY) {
1429 ySize++;
1430 }
1431 }
1432 hitMaxX |= xSize >= spanX;
1433 hitMaxY |= ySize >= spanY;
1434 incX = !incX;
1435 }
1436 incX = true;
1437 hitMaxX = xSize >= spanX;
1438 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001439 }
Winson Chung0be025d2011-05-23 17:45:09 -07001440 final int[] cellXY = mTmpXY;
Adam Cohene3e27a82011-04-15 12:07:39 -07001441 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001442
Adam Cohend41fbf52012-02-16 23:53:59 -08001443 // We verify that the current rect is not a sub-rect of any of our previous
1444 // candidates. In this case, the current rect is disqualified in favour of the
1445 // containing rect.
1446 Rect currentRect = mTempRectStack.pop();
1447 currentRect.set(x, y, x + xSize, y + ySize);
1448 boolean contained = false;
1449 for (Rect r : validRegions) {
1450 if (r.contains(currentRect)) {
1451 contained = true;
1452 break;
1453 }
1454 }
1455 validRegions.push(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001456 double distance = Math.sqrt(Math.pow(cellXY[0] - pixelX, 2)
1457 + Math.pow(cellXY[1] - pixelY, 2));
Adam Cohen482ed822012-03-02 14:15:13 -08001458
Adam Cohend41fbf52012-02-16 23:53:59 -08001459 if ((distance <= bestDistance && !contained) ||
1460 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001461 bestDistance = distance;
1462 bestXY[0] = x;
1463 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001464 if (resultSpan != null) {
1465 resultSpan[0] = xSize;
1466 resultSpan[1] = ySize;
1467 }
1468 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001469 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001470 }
1471 }
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001472 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08001473 markCellsAsOccupiedForView(ignoreView, occupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001474
Adam Cohenc0dcf592011-06-01 15:30:43 -07001475 // Return -1, -1 if no suitable location found
1476 if (bestDistance == Double.MAX_VALUE) {
1477 bestXY[0] = -1;
1478 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001479 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001480 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001481 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001482 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001483
Adam Cohen482ed822012-03-02 14:15:13 -08001484 /**
1485 * Find a vacant area that will fit the given bounds nearest the requested
1486 * cell location, and will also weigh in a suggested direction vector of the
1487 * desired location. This method computers distance based on unit grid distances,
1488 * not pixel distances.
1489 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001490 * @param cellX The X cell nearest to which you want to search for a vacant area.
1491 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001492 * @param spanX Horizontal span of the object.
1493 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001494 * @param direction The favored direction in which the views should move from x, y
1495 * @param exactDirectionOnly If this parameter is true, then only solutions where the direction
1496 * matches exactly. Otherwise we find the best matching direction.
1497 * @param occoupied The array which represents which cells in the CellLayout are occupied
1498 * @param blockOccupied The array which represents which cells in the specified block (cellX,
1499 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001500 * @param result Array in which to place the result, or null (in which case a new array will
1501 * be allocated)
1502 * @return The X, Y cell of a vacant area that can contain this object,
1503 * nearest the requested location.
1504 */
1505 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001506 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001507 // Keep track of best-scoring drop area
1508 final int[] bestXY = result != null ? result : new int[2];
1509 float bestDistance = Float.MAX_VALUE;
1510 int bestDirectionScore = Integer.MIN_VALUE;
1511
1512 final int countX = mCountX;
1513 final int countY = mCountY;
1514
1515 for (int y = 0; y < countY - (spanY - 1); y++) {
1516 inner:
1517 for (int x = 0; x < countX - (spanX - 1); x++) {
1518 // First, let's see if this thing fits anywhere
1519 for (int i = 0; i < spanX; i++) {
1520 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001521 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001522 continue inner;
1523 }
1524 }
1525 }
1526
1527 float distance = (float)
1528 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1529 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001530 computeDirectionVector(x - cellX, y - cellY, curDirection);
1531 // The direction score is just the dot product of the two candidate direction
1532 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001533 int curDirectionScore = direction[0] * curDirection[0] +
1534 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001535 boolean exactDirectionOnly = false;
1536 boolean directionMatches = direction[0] == curDirection[0] &&
1537 direction[0] == curDirection[0];
1538 if ((directionMatches || !exactDirectionOnly) &&
1539 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001540 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1541 bestDistance = distance;
1542 bestDirectionScore = curDirectionScore;
1543 bestXY[0] = x;
1544 bestXY[1] = y;
1545 }
1546 }
1547 }
1548
1549 // Return -1, -1 if no suitable location found
1550 if (bestDistance == Float.MAX_VALUE) {
1551 bestXY[0] = -1;
1552 bestXY[1] = -1;
1553 }
1554 return bestXY;
1555 }
1556
Adam Cohen47a876d2012-03-19 13:21:41 -07001557 private int[] findNearestAreaInDirection(int cellX, int cellY, int spanX, int spanY,
1558 int[] direction,boolean[][] occupied,
1559 boolean blockOccupied[][], int[] result) {
1560 // Keep track of best-scoring drop area
1561 final int[] bestXY = result != null ? result : new int[2];
1562 bestXY[0] = -1;
1563 bestXY[1] = -1;
1564 float bestDistance = Float.MAX_VALUE;
1565
1566 // We use this to march in a single direction
1567 if (direction[0] != 0 && direction[1] != 0) {
1568 return bestXY;
1569 }
1570
1571 // This will only incrememnet one of x or y based on the assertion above
1572 int x = cellX + direction[0];
1573 int y = cellY + direction[1];
1574 while (x >= 0 && x + spanX <= mCountX && y >= 0 && y + spanY <= mCountY) {
1575
1576 boolean fail = false;
1577 for (int i = 0; i < spanX; i++) {
1578 for (int j = 0; j < spanY; j++) {
1579 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1580 fail = true;
1581 }
1582 }
1583 }
1584 if (!fail) {
1585 float distance = (float)
1586 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1587 if (Float.compare(distance, bestDistance) < 0) {
1588 bestDistance = distance;
1589 bestXY[0] = x;
1590 bestXY[1] = y;
1591 }
1592 }
1593 x += direction[0];
1594 y += direction[1];
1595 }
1596 return bestXY;
1597 }
1598
Adam Cohen482ed822012-03-02 14:15:13 -08001599 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001600 int[] direction, ItemConfiguration currentState) {
1601 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001602 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001603 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001604 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1605
Adam Cohen8baab352012-03-20 17:39:21 -07001606 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001607
1608 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001609 c.x = mTempLocation[0];
1610 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001611 success = true;
1612
1613 }
Adam Cohen8baab352012-03-20 17:39:21 -07001614 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001615 return success;
1616 }
1617
Adam Cohen47a876d2012-03-19 13:21:41 -07001618 // This method looks in the specified direction to see if there is an additional view
1619 // immediately adjecent in that direction
1620 private boolean addViewInDirection(ArrayList<View> views, Rect boundingRect, int[] direction,
Adam Cohen19f37922012-03-21 11:59:11 -07001621 boolean[][] occupied, View dragView, ItemConfiguration currentState) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001622 boolean found = false;
1623
Michael Jurkaa52570f2012-03-20 03:18:20 -07001624 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen47a876d2012-03-19 13:21:41 -07001625 Rect r0 = new Rect(boundingRect);
1626 Rect r1 = new Rect();
1627
1628 int deltaX = 0;
1629 int deltaY = 0;
1630 if (direction[1] < 0) {
1631 r0.set(r0.left, r0.top - 1, r0.right, r0.bottom);
1632 deltaY = -1;
1633 } else if (direction[1] > 0) {
1634 r0.set(r0.left, r0.top, r0.right, r0.bottom + 1);
1635 deltaY = 1;
1636 } else if (direction[0] < 0) {
1637 r0.set(r0.left - 1, r0.top, r0.right, r0.bottom);
1638 deltaX = -1;
1639 } else if (direction[0] > 0) {
1640 r0.set(r0.left, r0.top, r0.right + 1, r0.bottom);
1641 deltaX = 1;
1642 }
1643
1644 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001645 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen19f37922012-03-21 11:59:11 -07001646 if (views.contains(child) || child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001647 CellAndSpan c = currentState.map.get(child);
Adam Cohen47a876d2012-03-19 13:21:41 -07001648
Adam Cohen8baab352012-03-20 17:39:21 -07001649 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1650 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001651 if (Rect.intersects(r0, r1)) {
1652 if (!lp.canReorder) {
1653 return false;
1654 }
1655 boolean pushed = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001656 for (int x = c.x; x < c.x + c.spanX; x++) {
1657 for (int y = c.y; y < c.y + c.spanY; y++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001658 boolean inBounds = x - deltaX >= 0 && x -deltaX < mCountX
1659 && y - deltaY >= 0 && y - deltaY < mCountY;
1660 if (inBounds && occupied[x - deltaX][y - deltaY]) {
1661 pushed = true;
1662 }
1663 }
1664 }
1665 if (pushed) {
1666 views.add(child);
Adam Cohen8baab352012-03-20 17:39:21 -07001667 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001668 found = true;
1669 }
1670 }
1671 }
1672 return found;
1673 }
1674
Adam Cohen482ed822012-03-02 14:15:13 -08001675 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohen19f37922012-03-21 11:59:11 -07001676 int[] direction, boolean push, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001677 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001678
Adam Cohen8baab352012-03-20 17:39:21 -07001679 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001680 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001681 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001682 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001683 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001684 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001685 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001686 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001687 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001688 }
1689 }
Adam Cohen8baab352012-03-20 17:39:21 -07001690
1691 @SuppressWarnings("unchecked")
1692 ArrayList<View> dup = (ArrayList<View>) views.clone();
1693 // We try and expand the group of views in the direction vector passed, based on
1694 // whether they are physically adjacent, ie. based on "push mechanics".
Adam Cohen19f37922012-03-21 11:59:11 -07001695 while (push && addViewInDirection(dup, boundingRect, direction, mTmpOccupied, dragView,
Adam Cohen8baab352012-03-20 17:39:21 -07001696 currentState)) {
1697 }
1698
1699 // Mark the occupied state as false for the group of views we want to move.
1700 for (View v: dup) {
1701 CellAndSpan c = currentState.map.get(v);
1702 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1703 }
1704
Adam Cohen47a876d2012-03-19 13:21:41 -07001705 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1706 int top = boundingRect.top;
1707 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001708 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
1709 // for tetris-style interlocking.
1710 for (View v: dup) {
1711 CellAndSpan c = currentState.map.get(v);
1712 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001713 }
1714
Adam Cohen482ed822012-03-02 14:15:13 -08001715 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1716
Adam Cohen8baab352012-03-20 17:39:21 -07001717 if (push) {
1718 findNearestAreaInDirection(boundingRect.left, boundingRect.top, boundingRect.width(),
1719 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1720 } else {
1721 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1722 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1723 }
Adam Cohen482ed822012-03-02 14:15:13 -08001724
Adam Cohen8baab352012-03-20 17:39:21 -07001725 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001726 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001727 int deltaX = mTempLocation[0] - boundingRect.left;
1728 int deltaY = mTempLocation[1] - boundingRect.top;
1729 for (View v: dup) {
1730 CellAndSpan c = currentState.map.get(v);
1731 c.x += deltaX;
1732 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001733 }
1734 success = true;
1735 }
Adam Cohen8baab352012-03-20 17:39:21 -07001736
1737 // In either case, we set the occupied array as marked for the location of the views
1738 for (View v: dup) {
1739 CellAndSpan c = currentState.map.get(v);
1740 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001741 }
1742 return success;
1743 }
1744
1745 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1746 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1747 }
1748
1749 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001750 View ignoreView, ItemConfiguration solution) {
Adam Cohen482ed822012-03-02 14:15:13 -08001751
Adam Cohen8baab352012-03-20 17:39:21 -07001752 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001753 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001754
Adam Cohen8baab352012-03-20 17:39:21 -07001755 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001756 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001757 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001758 if (c != null) {
1759 c.x = cellX;
1760 c.y = cellY;
1761 }
Adam Cohen482ed822012-03-02 14:15:13 -08001762 }
Adam Cohen482ed822012-03-02 14:15:13 -08001763 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1764 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001765 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001766 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001767 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001768 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001769 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001770 if (Rect.intersects(r0, r1)) {
1771 if (!lp.canReorder) {
1772 return false;
1773 }
1774 mIntersectingViews.add(child);
1775 }
1776 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001777
Adam Cohen8baab352012-03-20 17:39:21 -07001778 // We try to move the intersecting views as a block using the push mechanic
Adam Cohen19f37922012-03-21 11:59:11 -07001779 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, true, ignoreView,
1780 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001781 return true;
1782 }
1783 // Try the opposite direction
1784 direction[0] *= -1;
1785 direction[1] *= -1;
Adam Cohen19f37922012-03-21 11:59:11 -07001786 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, true, ignoreView,
1787 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001788 return true;
1789 }
1790 // Switch the direction back
1791 direction[0] *= -1;
1792 direction[1] *= -1;
1793
Adam Cohen8baab352012-03-20 17:39:21 -07001794 // Next we try moving the views as a block , but without requiring the push mechanic
Adam Cohen19f37922012-03-21 11:59:11 -07001795 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, false, ignoreView,
1796 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001797 return true;
1798 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001799
Adam Cohen482ed822012-03-02 14:15:13 -08001800 // Ok, they couldn't move as a block, let's move them individually
1801 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001802 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001803 return false;
1804 }
1805 }
1806 return true;
1807 }
1808
1809 /*
1810 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1811 * the provided point and the provided cell
1812 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001813 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001814 double angle = Math.atan(((float) deltaY) / deltaX);
1815
1816 result[0] = 0;
1817 result[1] = 0;
1818 if (Math.abs(Math.cos(angle)) > 0.5f) {
1819 result[0] = (int) Math.signum(deltaX);
1820 }
1821 if (Math.abs(Math.sin(angle)) > 0.5f) {
1822 result[1] = (int) Math.signum(deltaY);
1823 }
1824 }
1825
Adam Cohen8baab352012-03-20 17:39:21 -07001826 private void copyOccupiedArray(boolean[][] occupied) {
1827 for (int i = 0; i < mCountX; i++) {
1828 for (int j = 0; j < mCountY; j++) {
1829 occupied[i][j] = mOccupied[i][j];
1830 }
1831 }
1832 }
1833
Adam Cohen482ed822012-03-02 14:15:13 -08001834 ItemConfiguration simpleSwap(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1835 int spanY, int[] direction, View dragView, boolean decX, ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001836 // Copy the current state into the solution. This solution will be manipulated as necessary.
1837 copyCurrentStateToSolution(solution, false);
1838 // Copy the current occupied array into the temporary occupied array. This array will be
1839 // manipulated as necessary to find a solution.
1840 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001841
1842 // We find the nearest cell into which we would place the dragged item, assuming there's
1843 // nothing in its way.
1844 int result[] = new int[2];
1845 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1846
1847 boolean success = false;
1848 // First we try the exact nearest position of the item being dragged,
1849 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001850 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1851 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001852
1853 if (!success) {
1854 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1855 // x, then 1 in y etc.
1856 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
1857 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY, direction,
1858 dragView, false, solution);
1859 } else if (spanY > minSpanY) {
1860 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1, direction,
1861 dragView, true, solution);
1862 }
1863 solution.isSolution = false;
1864 } else {
1865 solution.isSolution = true;
1866 solution.dragViewX = result[0];
1867 solution.dragViewY = result[1];
1868 solution.dragViewSpanX = spanX;
1869 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001870 }
1871 return solution;
1872 }
1873
1874 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001875 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001876 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001877 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001878 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001879 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08001880 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07001881 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001882 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001883 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001884 }
Adam Cohen8baab352012-03-20 17:39:21 -07001885 solution.map.put(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08001886 }
1887 }
1888
1889 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
1890 for (int i = 0; i < mCountX; i++) {
1891 for (int j = 0; j < mCountY; j++) {
1892 mTmpOccupied[i][j] = false;
1893 }
1894 }
1895
Michael Jurkaa52570f2012-03-20 03:18:20 -07001896 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001897 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001898 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001899 if (child == dragView) continue;
1900 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001901 CellAndSpan c = solution.map.get(child);
1902 if (c != null) {
1903 lp.tmpCellX = c.x;
1904 lp.tmpCellY = c.y;
1905 lp.cellHSpan = c.spanX;
1906 lp.cellVSpan = c.spanY;
1907 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001908 }
1909 }
1910 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1911 solution.dragViewSpanY, mTmpOccupied, true);
1912 }
1913
1914 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1915 commitDragView) {
1916
1917 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1918 for (int i = 0; i < mCountX; i++) {
1919 for (int j = 0; j < mCountY; j++) {
1920 occupied[i][j] = false;
1921 }
1922 }
1923
Michael Jurkaa52570f2012-03-20 03:18:20 -07001924 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001925 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001926 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001927 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001928 CellAndSpan c = solution.map.get(child);
1929 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07001930 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
1931 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07001932 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001933 }
1934 }
1935 if (commitDragView) {
1936 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1937 solution.dragViewSpanY, occupied, true);
1938 }
1939 }
1940
Adam Cohen19f37922012-03-21 11:59:11 -07001941 // This method starts or changes the reorder hint animations
1942 private void beginOrAdjustHintAnimations(ItemConfiguration solution, View dragView, int delay) {
1943 int childCount = mShortcutsAndWidgets.getChildCount();
1944 int timeForPriorAnimationToComplete = getMaxCompletionTime();
1945 for (int i = 0; i < childCount; i++) {
1946 View child = mShortcutsAndWidgets.getChildAt(i);
1947 if (child == dragView) continue;
1948 CellAndSpan c = solution.map.get(child);
1949 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1950 if (c != null) {
1951 ReorderHintAnimation rha = new ReorderHintAnimation(child, lp.cellX, lp.cellY,
1952 c.x, c.y, c.spanX, c.spanY);
1953 rha.animate(timeForPriorAnimationToComplete);
1954 }
1955 }
1956 }
1957
1958 // Class which represents the reorder hint animations. These animations show that an item is
1959 // in a temporary state, and hint at where the item will return to.
1960 class ReorderHintAnimation {
1961 View child;
1962 float deltaX;
1963 float deltaY;
1964 private static final int DURATION = 140;
1965 private int repeatCount;
1966 private boolean cancelOnCycleComplete = false;
1967 ValueAnimator va;
1968
1969 public ReorderHintAnimation(View child, int cellX0, int cellY0, int cellX1, int cellY1,
1970 int spanX, int spanY) {
1971 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
1972 final int x0 = mTmpPoint[0];
1973 final int y0 = mTmpPoint[1];
1974 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
1975 final int x1 = mTmpPoint[0];
1976 final int y1 = mTmpPoint[1];
1977 final int dX = x1 - x0;
1978 final int dY = y1 - y0;
1979 deltaX = 0;
1980 deltaY = 0;
1981 if (dX == dY && dX == 0) {
1982 } else {
1983 if (dY == 0) {
1984 deltaX = mReorderHintAnimationMagnitude;
1985 } else if (dX == 0) {
1986 deltaY = mReorderHintAnimationMagnitude;
1987 } else {
1988 double angle = Math.atan( (float) (dY) / dX);
1989 deltaX = (int) (Math.cos(angle) * mReorderHintAnimationMagnitude);
1990 deltaY = (int) (Math.sin(angle) * mReorderHintAnimationMagnitude);
1991 }
1992 }
1993 this.child = child;
1994 }
1995
1996 void animate(int delay) {
1997 if (mShakeAnimators.containsKey(child)) {
1998 ReorderHintAnimation oldAnimation = mShakeAnimators.get(child);
1999 oldAnimation.completeAnimation();
2000 mShakeAnimators.remove(child);
2001 }
2002 if (deltaX == 0 && deltaY == 0) {
2003 return;
2004 }
2005 va = ValueAnimator.ofFloat(0f, 1f);
2006 va.setRepeatMode(ValueAnimator.REVERSE);
2007 va.setRepeatCount(ValueAnimator.INFINITE);
2008 va.setDuration(DURATION);
2009 va.addUpdateListener(new AnimatorUpdateListener() {
2010 @Override
2011 public void onAnimationUpdate(ValueAnimator animation) {
2012 float r = ((Float) animation.getAnimatedValue()).floatValue();
2013 float x = r * deltaX;
2014 float y = r * deltaY;
2015 child.setTranslationX(x);
2016 child.setTranslationY(y);
2017 }
2018 });
2019 va.addListener(new AnimatorListenerAdapter() {
2020 public void onAnimationRepeat(Animator animation) {
2021 repeatCount++;
2022 // We make sure to end only after a full period
2023 if (cancelOnCycleComplete && repeatCount % 2 == 0) {
2024 va.cancel();
2025 }
2026 }
2027 });
2028 va.setStartDelay(Math.max(REORDER_ANIMATION_DURATION, delay));
2029 mShakeAnimators.put(child, this);
2030 va.start();
2031 }
2032
2033
2034 private void completeAnimation() {
2035 cancelOnCycleComplete = true;
2036 }
2037
2038 // Returns the time required to complete the current oscillating animation
2039 private int completionTime() {
2040 if (repeatCount % 2 == 0) {
2041 return (int) (va.getDuration() - va.getCurrentPlayTime() + DURATION);
2042 } else {
2043 return (int) (va.getDuration() - va.getCurrentPlayTime());
2044 }
2045 }
2046 }
2047
2048 private void completeAndClearReorderHintAnimations() {
2049 for (ReorderHintAnimation a: mShakeAnimators.values()) {
2050 a.completeAnimation();
2051 }
2052 mShakeAnimators.clear();
2053 }
2054
2055 private int getMaxCompletionTime() {
2056 int maxTime = 0;
2057 for (ReorderHintAnimation a: mShakeAnimators.values()) {
2058 maxTime = Math.max(maxTime, a.completionTime());
2059 }
2060 return maxTime;
2061 }
2062
Adam Cohen482ed822012-03-02 14:15:13 -08002063 private void commitTempPlacement() {
2064 for (int i = 0; i < mCountX; i++) {
2065 for (int j = 0; j < mCountY; j++) {
2066 mOccupied[i][j] = mTmpOccupied[i][j];
2067 }
2068 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002069 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002070 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002071 View child = mShortcutsAndWidgets.getChildAt(i);
2072 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2073 ItemInfo info = (ItemInfo) child.getTag();
2074 info.cellX = lp.cellX = lp.tmpCellX;
2075 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohen482ed822012-03-02 14:15:13 -08002076 }
Adam Cohenea889a22012-03-27 16:45:39 -07002077 Workspace workspace = (Workspace) getParent();
2078 workspace.updateItemLocationsInDatabase(this);
Adam Cohen482ed822012-03-02 14:15:13 -08002079 }
2080
2081 public void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002082 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002083 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002084 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002085 lp.useTmpCoords = useTempCoords;
2086 }
2087 }
2088
Adam Cohen482ed822012-03-02 14:15:13 -08002089 ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
2090 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2091 int[] result = new int[2];
2092 int[] resultSpan = new int[2];
2093 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null, result,
2094 resultSpan);
2095 if (result[0] >= 0 && result[1] >= 0) {
2096 copyCurrentStateToSolution(solution, false);
2097 solution.dragViewX = result[0];
2098 solution.dragViewY = result[1];
2099 solution.dragViewSpanX = resultSpan[0];
2100 solution.dragViewSpanY = resultSpan[1];
2101 solution.isSolution = true;
2102 } else {
2103 solution.isSolution = false;
2104 }
2105 return solution;
2106 }
2107
2108 public void prepareChildForDrag(View child) {
2109 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002110 }
2111
Adam Cohen19f37922012-03-21 11:59:11 -07002112 /* This seems like it should be obvious and straight-forward, but when the direction vector
2113 needs to match with the notion of the dragView pushing other views, we have to employ
2114 a slightly more subtle notion of the direction vector. The question is what two points is
2115 the vector between? The center of the dragView and its desired destination? Not quite, as
2116 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2117 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2118 or right, which helps make pushing feel right.
2119 */
2120 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2121 int spanY, View dragView, int[] resultDirection) {
2122 int[] targetDestination = new int[2];
2123
2124 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2125 Rect dragRect = new Rect();
2126 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2127 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2128
2129 Rect dropRegionRect = new Rect();
2130 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2131 dragView, dropRegionRect, mIntersectingViews);
2132
2133 int dropRegionSpanX = dropRegionRect.width();
2134 int dropRegionSpanY = dropRegionRect.height();
2135
2136 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2137 dropRegionRect.height(), dropRegionRect);
2138
2139 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2140 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2141
2142 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2143 deltaX = 0;
2144 }
2145 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2146 deltaY = 0;
2147 }
2148
2149 if (deltaX == 0 && deltaY == 0) {
2150 // No idea what to do, give a random direction.
2151 resultDirection[0] = 1;
2152 resultDirection[1] = 0;
2153 } else {
2154 computeDirectionVector(deltaX, deltaY, resultDirection);
2155 }
2156 }
2157
2158 // For a given cell and span, fetch the set of views intersecting the region.
2159 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2160 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2161 if (boundingRect != null) {
2162 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2163 }
2164 intersectingViews.clear();
2165 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2166 Rect r1 = new Rect();
2167 final int count = mShortcutsAndWidgets.getChildCount();
2168 for (int i = 0; i < count; i++) {
2169 View child = mShortcutsAndWidgets.getChildAt(i);
2170 if (child == dragView) continue;
2171 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2172 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2173 if (Rect.intersects(r0, r1)) {
2174 mIntersectingViews.add(child);
2175 if (boundingRect != null) {
2176 boundingRect.union(r1);
2177 }
2178 }
2179 }
2180 }
2181
2182 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2183 View dragView, int[] result) {
2184 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2185 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2186 mIntersectingViews);
2187 return !mIntersectingViews.isEmpty();
2188 }
2189
2190 void revertTempState() {
2191 if (!isItemPlacementDirty() || DESTRUCTIVE_REORDER) return;
2192 final int count = mShortcutsAndWidgets.getChildCount();
2193 for (int i = 0; i < count; i++) {
2194 View child = mShortcutsAndWidgets.getChildAt(i);
2195 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2196 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2197 lp.tmpCellX = lp.cellX;
2198 lp.tmpCellY = lp.cellY;
2199 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2200 0, false, false);
2201 }
2202 }
2203 completeAndClearReorderHintAnimations();
2204 setItemPlacementDirty(false);
2205 }
2206
Adam Cohen482ed822012-03-02 14:15:13 -08002207 int[] createArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2208 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002209 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002210 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002211
2212 if (resultSpan == null) {
2213 resultSpan = new int[2];
2214 }
2215
Adam Cohen19f37922012-03-21 11:59:11 -07002216 // When we are checking drop validity or actually dropping, we don't recompute the
2217 // direction vector, since we want the solution to match the preview, and it's possible
2218 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002219 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2220 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002221 mDirectionVector[0] = mPreviousReorderDirection[0];
2222 mDirectionVector[1] = mPreviousReorderDirection[1];
2223 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002224 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2225 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2226 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002227 }
Adam Cohenb209e632012-03-27 17:09:36 -07002228
Adam Cohen19f37922012-03-21 11:59:11 -07002229 } else {
2230 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2231 mPreviousReorderDirection[0] = mDirectionVector[0];
2232 mPreviousReorderDirection[1] = mDirectionVector[1];
2233 }
2234
Adam Cohen482ed822012-03-02 14:15:13 -08002235 ItemConfiguration swapSolution = simpleSwap(pixelX, pixelY, minSpanX, minSpanY,
2236 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2237
2238 // We attempt the approach which doesn't shuffle views at all
2239 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2240 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2241
2242 ItemConfiguration finalSolution = null;
2243 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2244 finalSolution = swapSolution;
2245 } else if (noShuffleSolution.isSolution) {
2246 finalSolution = noShuffleSolution;
2247 }
2248
2249 boolean foundSolution = true;
2250 if (!DESTRUCTIVE_REORDER) {
2251 setUseTempCoords(true);
2252 }
2253
2254 if (finalSolution != null) {
2255 result[0] = finalSolution.dragViewX;
2256 result[1] = finalSolution.dragViewY;
2257 resultSpan[0] = finalSolution.dragViewSpanX;
2258 resultSpan[1] = finalSolution.dragViewSpanY;
2259
2260 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2261 // committing anything or animating anything as we just want to determine if a solution
2262 // exists
2263 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2264 if (!DESTRUCTIVE_REORDER) {
2265 copySolutionToTempState(finalSolution, dragView);
2266 }
2267 setItemPlacementDirty(true);
2268 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2269
Adam Cohen19f37922012-03-21 11:59:11 -07002270 if (!DESTRUCTIVE_REORDER &&
2271 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002272 commitTempPlacement();
Adam Cohen19f37922012-03-21 11:59:11 -07002273 completeAndClearReorderHintAnimations();
2274 setItemPlacementDirty(false);
2275 } else {
2276 beginOrAdjustHintAnimations(finalSolution, dragView,
2277 REORDER_ANIMATION_DURATION);
Adam Cohen482ed822012-03-02 14:15:13 -08002278 }
2279 }
2280 } else {
2281 foundSolution = false;
2282 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2283 }
2284
2285 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2286 setUseTempCoords(false);
2287 }
Adam Cohen482ed822012-03-02 14:15:13 -08002288
Michael Jurkaa52570f2012-03-20 03:18:20 -07002289 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002290 return result;
2291 }
2292
Adam Cohen19f37922012-03-21 11:59:11 -07002293 void setItemPlacementDirty(boolean dirty) {
2294 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002295 }
Adam Cohen19f37922012-03-21 11:59:11 -07002296 boolean isItemPlacementDirty() {
2297 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002298 }
2299
2300 private class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002301 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohen482ed822012-03-02 14:15:13 -08002302 boolean isSolution = false;
2303 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2304
2305 int area() {
2306 return dragViewSpanX * dragViewSpanY;
2307 }
Adam Cohen8baab352012-03-20 17:39:21 -07002308 }
2309
2310 private class CellAndSpan {
2311 int x, y;
2312 int spanX, spanY;
2313
2314 public CellAndSpan(int x, int y, int spanX, int spanY) {
2315 this.x = x;
2316 this.y = y;
2317 this.spanX = spanX;
2318 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002319 }
2320 }
2321
Adam Cohendf035382011-04-11 17:22:04 -07002322 /**
2323 * Find a vacant area that will fit the given bounds nearest the requested
2324 * cell location. Uses Euclidean distance to score multiple vacant areas.
2325 *
2326 * @param pixelX The X location at which you want to search for a vacant area.
2327 * @param pixelY The Y location at which you want to search for a vacant area.
2328 * @param spanX Horizontal span of the object.
2329 * @param spanY Vertical span of the object.
2330 * @param ignoreView Considers space occupied by this view as unoccupied
2331 * @param result Previously returned value to possibly recycle.
2332 * @return The X, Y cell of a vacant area that can contain this object,
2333 * nearest the requested location.
2334 */
2335 int[] findNearestVacantArea(
2336 int pixelX, int pixelY, int spanX, int spanY, View ignoreView, int[] result) {
2337 return findNearestArea(pixelX, pixelY, spanX, spanY, ignoreView, true, result);
2338 }
2339
2340 /**
Adam Cohend41fbf52012-02-16 23:53:59 -08002341 * Find a vacant area that will fit the given bounds nearest the requested
2342 * cell location. Uses Euclidean distance to score multiple vacant areas.
2343 *
2344 * @param pixelX The X location at which you want to search for a vacant area.
2345 * @param pixelY The Y location at which you want to search for a vacant area.
2346 * @param minSpanX The minimum horizontal span required
2347 * @param minSpanY The minimum vertical span required
2348 * @param spanX Horizontal span of the object.
2349 * @param spanY Vertical span of the object.
2350 * @param ignoreView Considers space occupied by this view as unoccupied
2351 * @param result Previously returned value to possibly recycle.
2352 * @return The X, Y cell of a vacant area that can contain this object,
2353 * nearest the requested location.
2354 */
2355 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
2356 int spanX, int spanY, View ignoreView, int[] result, int[] resultSpan) {
Adam Cohen482ed822012-03-02 14:15:13 -08002357 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, true,
2358 result, resultSpan, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08002359 }
2360
2361 /**
Adam Cohendf035382011-04-11 17:22:04 -07002362 * Find a starting cell position that will fit the given bounds nearest the requested
2363 * cell location. Uses Euclidean distance to score multiple vacant areas.
2364 *
2365 * @param pixelX The X location at which you want to search for a vacant area.
2366 * @param pixelY The Y location at which you want to search for a vacant area.
2367 * @param spanX Horizontal span of the object.
2368 * @param spanY Vertical span of the object.
2369 * @param ignoreView Considers space occupied by this view as unoccupied
2370 * @param result Previously returned value to possibly recycle.
2371 * @return The X, Y cell of a vacant area that can contain this object,
2372 * nearest the requested location.
2373 */
2374 int[] findNearestArea(
2375 int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2376 return findNearestArea(pixelX, pixelY, spanX, spanY, null, false, result);
2377 }
2378
Michael Jurka0280c3b2010-09-17 15:00:07 -07002379 boolean existsEmptyCell() {
2380 return findCellForSpan(null, 1, 1);
2381 }
2382
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002383 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002384 * Finds the upper-left coordinate of the first rectangle in the grid that can
2385 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2386 * then this method will only return coordinates for rectangles that contain the cell
2387 * (intersectX, intersectY)
2388 *
2389 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2390 * can be found.
2391 * @param spanX The horizontal span of the cell we want to find.
2392 * @param spanY The vertical span of the cell we want to find.
2393 *
2394 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002395 */
Michael Jurka0280c3b2010-09-17 15:00:07 -07002396 boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08002397 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002398 }
2399
2400 /**
2401 * Like above, but ignores any cells occupied by the item "ignoreView"
2402 *
2403 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2404 * can be found.
2405 * @param spanX The horizontal span of the cell we want to find.
2406 * @param spanY The vertical span of the cell we want to find.
2407 * @param ignoreView The home screen item we should treat as not occupying any space
2408 * @return
2409 */
2410 boolean findCellForSpanIgnoring(int[] cellXY, int spanX, int spanY, View ignoreView) {
Adam Cohen482ed822012-03-02 14:15:13 -08002411 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1,
2412 ignoreView, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002413 }
2414
2415 /**
2416 * Like above, but if intersectX and intersectY are not -1, then this method will try to
2417 * return coordinates for rectangles that contain the cell [intersectX, intersectY]
2418 *
2419 * @param spanX The horizontal span of the cell we want to find.
2420 * @param spanY The vertical span of the cell we want to find.
2421 * @param ignoreView The home screen item we should treat as not occupying any space
2422 * @param intersectX The X coordinate of the cell that we should try to overlap
2423 * @param intersectX The Y coordinate of the cell that we should try to overlap
2424 *
2425 * @return True if a vacant cell of the specified dimension was found, false otherwise.
2426 */
2427 boolean findCellForSpanThatIntersects(int[] cellXY, int spanX, int spanY,
2428 int intersectX, int intersectY) {
2429 return findCellForSpanThatIntersectsIgnoring(
Adam Cohen482ed822012-03-02 14:15:13 -08002430 cellXY, spanX, spanY, intersectX, intersectY, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002431 }
2432
2433 /**
2434 * The superset of the above two methods
2435 */
2436 boolean findCellForSpanThatIntersectsIgnoring(int[] cellXY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002437 int intersectX, int intersectY, View ignoreView, boolean occupied[][]) {
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002438 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08002439 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002440
Michael Jurka28750fb2010-09-24 17:43:49 -07002441 boolean foundCell = false;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002442 while (true) {
2443 int startX = 0;
2444 if (intersectX >= 0) {
2445 startX = Math.max(startX, intersectX - (spanX - 1));
2446 }
2447 int endX = mCountX - (spanX - 1);
2448 if (intersectX >= 0) {
2449 endX = Math.min(endX, intersectX + (spanX - 1) + (spanX == 1 ? 1 : 0));
2450 }
2451 int startY = 0;
2452 if (intersectY >= 0) {
2453 startY = Math.max(startY, intersectY - (spanY - 1));
2454 }
2455 int endY = mCountY - (spanY - 1);
2456 if (intersectY >= 0) {
2457 endY = Math.min(endY, intersectY + (spanY - 1) + (spanY == 1 ? 1 : 0));
2458 }
2459
Winson Chungbbc60d82010-11-11 16:34:41 -08002460 for (int y = startY; y < endY && !foundCell; y++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002461 inner:
Winson Chungbbc60d82010-11-11 16:34:41 -08002462 for (int x = startX; x < endX; x++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002463 for (int i = 0; i < spanX; i++) {
2464 for (int j = 0; j < spanY; j++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002465 if (occupied[x + i][y + j]) {
Winson Chungbbc60d82010-11-11 16:34:41 -08002466 // small optimization: we can skip to after the column we just found
Michael Jurka0280c3b2010-09-17 15:00:07 -07002467 // an occupied cell
Winson Chungbbc60d82010-11-11 16:34:41 -08002468 x += i;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002469 continue inner;
2470 }
2471 }
2472 }
2473 if (cellXY != null) {
2474 cellXY[0] = x;
2475 cellXY[1] = y;
2476 }
Michael Jurka28750fb2010-09-24 17:43:49 -07002477 foundCell = true;
2478 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002479 }
2480 }
2481 if (intersectX == -1 && intersectY == -1) {
2482 break;
2483 } else {
2484 // if we failed to find anything, try again but without any requirements of
2485 // intersecting
2486 intersectX = -1;
2487 intersectY = -1;
2488 continue;
2489 }
2490 }
2491
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002492 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08002493 markCellsAsOccupiedForView(ignoreView, occupied);
Michael Jurka28750fb2010-09-24 17:43:49 -07002494 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002495 }
2496
2497 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002498 * A drag event has begun over this layout.
2499 * It may have begun over this layout (in which case onDragChild is called first),
2500 * or it may have begun on another layout.
2501 */
2502 void onDragEnter() {
2503 if (!mDragging) {
2504 // Fade in the drag indicators
2505 if (mCrosshairsAnimator != null) {
2506 mCrosshairsAnimator.animateIn();
2507 }
2508 }
2509 mDragging = true;
2510 }
2511
2512 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002513 * Called when drag has left this CellLayout or has been completed (successfully or not)
2514 */
2515 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002516 // This can actually be called when we aren't in a drag, e.g. when adding a new
2517 // item to this layout via the customize drawer.
2518 // Guard against that case.
2519 if (mDragging) {
2520 mDragging = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002521
Joe Onorato4be866d2010-10-10 11:26:02 -07002522 // Fade out the drag indicators
2523 if (mCrosshairsAnimator != null) {
2524 mCrosshairsAnimator.animateOut();
2525 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002526 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002527
2528 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002529 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002530 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2531 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002532 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002533 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002534 }
2535
2536 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002537 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002538 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002539 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002540 *
2541 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002542 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002543 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002544 if (child != null) {
2545 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002546 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002547 child.requestLayout();
Romain Guyd94533d2009-08-17 10:01:15 -07002548 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002549 }
2550
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002551 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002552 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002553 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002554 * @param cellX X coordinate of upper left corner expressed as a cell position
2555 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002556 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002557 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002558 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002559 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002560 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002561 final int cellWidth = mCellWidth;
2562 final int cellHeight = mCellHeight;
2563 final int widthGap = mWidthGap;
2564 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002565
Winson Chung4b825dcd2011-06-19 12:41:22 -07002566 final int hStartPadding = getPaddingLeft();
2567 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002568
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002569 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2570 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2571
2572 int x = hStartPadding + cellX * (cellWidth + widthGap);
2573 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002574
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002575 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002576 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002577
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002578 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002579 * Computes the required horizontal and vertical cell spans to always
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002580 * fit the given rectangle.
Winson Chungaafa03c2010-06-11 17:34:16 -07002581 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002582 * @param width Width in pixels
2583 * @param height Height in pixels
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002584 * @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 -08002585 */
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002586 public int[] rectToCell(int width, int height, int[] result) {
Michael Jurka9987a5c2010-10-08 16:58:12 -07002587 return rectToCell(getResources(), width, height, result);
2588 }
2589
2590 public static int[] rectToCell(Resources resources, int width, int height, int[] result) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002591 // Always assume we're working with the smallest span to make sure we
2592 // reserve enough space in both orientations.
Joe Onorato79e56262009-09-21 15:23:04 -04002593 int actualWidth = resources.getDimensionPixelSize(R.dimen.workspace_cell_width);
2594 int actualHeight = resources.getDimensionPixelSize(R.dimen.workspace_cell_height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002595 int smallerSize = Math.min(actualWidth, actualHeight);
Joe Onorato79e56262009-09-21 15:23:04 -04002596
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002597 // Always round up to next largest cell
Winson Chung54c725c2011-08-03 12:03:40 -07002598 int spanX = (int) Math.ceil(width / (float) smallerSize);
2599 int spanY = (int) Math.ceil(height / (float) smallerSize);
Joe Onorato79e56262009-09-21 15:23:04 -04002600
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002601 if (result == null) {
2602 return new int[] { spanX, spanY };
2603 }
2604 result[0] = spanX;
2605 result[1] = spanY;
2606 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002607 }
2608
Michael Jurkaf12c75c2011-01-25 22:41:40 -08002609 public int[] cellSpansToSize(int hSpans, int vSpans) {
2610 int[] size = new int[2];
2611 size[0] = hSpans * mCellWidth + (hSpans - 1) * mWidthGap;
2612 size[1] = vSpans * mCellHeight + (vSpans - 1) * mHeightGap;
2613 return size;
2614 }
2615
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002616 /**
Patrick Dubroy047379a2010-12-19 22:02:04 -08002617 * Calculate the grid spans needed to fit given item
2618 */
2619 public void calculateSpans(ItemInfo info) {
2620 final int minWidth;
2621 final int minHeight;
2622
2623 if (info instanceof LauncherAppWidgetInfo) {
2624 minWidth = ((LauncherAppWidgetInfo) info).minWidth;
2625 minHeight = ((LauncherAppWidgetInfo) info).minHeight;
2626 } else if (info instanceof PendingAddWidgetInfo) {
2627 minWidth = ((PendingAddWidgetInfo) info).minWidth;
2628 minHeight = ((PendingAddWidgetInfo) info).minHeight;
2629 } else {
2630 // It's not a widget, so it must be 1x1
2631 info.spanX = info.spanY = 1;
2632 return;
2633 }
2634 int[] spans = rectToCell(minWidth, minHeight, null);
2635 info.spanX = spans[0];
2636 info.spanY = spans[1];
2637 }
2638
2639 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002640 * Find the first vacant cell, if there is one.
2641 *
2642 * @param vacant Holds the x and y coordinate of the vacant cell
2643 * @param spanX Horizontal cell span.
2644 * @param spanY Vertical cell span.
Winson Chungaafa03c2010-06-11 17:34:16 -07002645 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002646 * @return True if a vacant cell was found
2647 */
2648 public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002649
Michael Jurka0280c3b2010-09-17 15:00:07 -07002650 return findVacantCell(vacant, spanX, spanY, mCountX, mCountY, mOccupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002651 }
2652
2653 static boolean findVacantCell(int[] vacant, int spanX, int spanY,
2654 int xCount, int yCount, boolean[][] occupied) {
2655
Adam Cohen2801caf2011-05-13 20:57:39 -07002656 for (int y = 0; y < yCount; y++) {
2657 for (int x = 0; x < xCount; x++) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002658 boolean available = !occupied[x][y];
2659out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
2660 for (int j = y; j < y + spanY - 1 && y < yCount; j++) {
2661 available = available && !occupied[i][j];
2662 if (!available) break out;
2663 }
2664 }
2665
2666 if (available) {
2667 vacant[0] = x;
2668 vacant[1] = y;
2669 return true;
2670 }
2671 }
2672 }
2673
2674 return false;
2675 }
2676
Michael Jurka0280c3b2010-09-17 15:00:07 -07002677 private void clearOccupiedCells() {
2678 for (int x = 0; x < mCountX; x++) {
2679 for (int y = 0; y < mCountY; y++) {
2680 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002681 }
2682 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002683 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002684
Adam Cohen1b607ed2011-03-03 17:26:50 -08002685 /**
2686 * Given a view, determines how much that view can be expanded in all directions, in terms of
2687 * whether or not there are other items occupying adjacent cells. Used by the
2688 * AppWidgetResizeFrame to determine how the widget can be resized.
2689 */
Adam Cohend4844c32011-02-18 19:25:06 -08002690 public void getExpandabilityArrayForView(View view, int[] expandability) {
Adam Cohen1b607ed2011-03-03 17:26:50 -08002691 final LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohend4844c32011-02-18 19:25:06 -08002692 boolean flag;
2693
Adam Cohen1b607ed2011-03-03 17:26:50 -08002694 expandability[AppWidgetResizeFrame.LEFT] = 0;
Adam Cohend4844c32011-02-18 19:25:06 -08002695 for (int x = lp.cellX - 1; x >= 0; x--) {
2696 flag = false;
2697 for (int y = lp.cellY; y < lp.cellY + lp.cellVSpan; y++) {
2698 if (mOccupied[x][y]) flag = true;
2699 }
2700 if (flag) break;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002701 expandability[AppWidgetResizeFrame.LEFT]++;
Adam Cohend4844c32011-02-18 19:25:06 -08002702 }
2703
Adam Cohen1b607ed2011-03-03 17:26:50 -08002704 expandability[AppWidgetResizeFrame.TOP] = 0;
Adam Cohend4844c32011-02-18 19:25:06 -08002705 for (int y = lp.cellY - 1; y >= 0; y--) {
2706 flag = false;
2707 for (int x = lp.cellX; x < lp.cellX + lp.cellHSpan; x++) {
2708 if (mOccupied[x][y]) flag = true;
2709 }
2710 if (flag) break;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002711 expandability[AppWidgetResizeFrame.TOP]++;
2712 }
Adam Cohend4844c32011-02-18 19:25:06 -08002713
Adam Cohen1b607ed2011-03-03 17:26:50 -08002714 expandability[AppWidgetResizeFrame.RIGHT] = 0;
Adam Cohend4844c32011-02-18 19:25:06 -08002715 for (int x = lp.cellX + lp.cellHSpan; x < mCountX; x++) {
2716 flag = false;
2717 for (int y = lp.cellY; y < lp.cellY + lp.cellVSpan; y++) {
2718 if (mOccupied[x][y]) flag = true;
2719 }
2720 if (flag) break;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002721 expandability[AppWidgetResizeFrame.RIGHT]++;
2722 }
Adam Cohend4844c32011-02-18 19:25:06 -08002723
Adam Cohen1b607ed2011-03-03 17:26:50 -08002724 expandability[AppWidgetResizeFrame.BOTTOM] = 0;
Adam Cohend4844c32011-02-18 19:25:06 -08002725 for (int y = lp.cellY + lp.cellVSpan; y < mCountY; y++) {
2726 flag = false;
2727 for (int x = lp.cellX; x < lp.cellX + lp.cellHSpan; x++) {
2728 if (mOccupied[x][y]) flag = true;
2729 }
2730 if (flag) break;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002731 expandability[AppWidgetResizeFrame.BOTTOM]++;
2732 }
Adam Cohend4844c32011-02-18 19:25:06 -08002733 }
2734
Adam Cohend41fbf52012-02-16 23:53:59 -08002735 public void onMove(View view, int newCellX, int newCellY, int newSpanX, int newSpanY) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002736 markCellsAsUnoccupiedForView(view);
Adam Cohen482ed822012-03-02 14:15:13 -08002737 markCellsForView(newCellX, newCellY, newSpanX, newSpanY, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002738 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002739
Adam Cohend4844c32011-02-18 19:25:06 -08002740 public void markCellsAsOccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002741 markCellsAsOccupiedForView(view, mOccupied);
2742 }
2743 public void markCellsAsOccupiedForView(View view, boolean[][] occupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002744 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002745 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002746 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002747 }
2748
Adam Cohend4844c32011-02-18 19:25:06 -08002749 public void markCellsAsUnoccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002750 markCellsAsUnoccupiedForView(view, mOccupied);
2751 }
2752 public void markCellsAsUnoccupiedForView(View view, boolean occupied[][]) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002753 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002754 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002755 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002756 }
2757
Adam Cohen482ed822012-03-02 14:15:13 -08002758 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2759 boolean value) {
2760 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002761 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2762 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002763 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002764 }
2765 }
2766 }
2767
Adam Cohen2801caf2011-05-13 20:57:39 -07002768 public int getDesiredWidth() {
Winson Chung4b825dcd2011-06-19 12:41:22 -07002769 return mPaddingLeft + mPaddingRight + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002770 (Math.max((mCountX - 1), 0) * mWidthGap);
2771 }
2772
2773 public int getDesiredHeight() {
Winson Chung4b825dcd2011-06-19 12:41:22 -07002774 return mPaddingTop + mPaddingBottom + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002775 (Math.max((mCountY - 1), 0) * mHeightGap);
2776 }
2777
Michael Jurka66d72172011-04-12 16:29:25 -07002778 public boolean isOccupied(int x, int y) {
2779 if (x < mCountX && y < mCountY) {
2780 return mOccupied[x][y];
2781 } else {
2782 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2783 }
2784 }
2785
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002786 @Override
2787 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2788 return new CellLayout.LayoutParams(getContext(), attrs);
2789 }
2790
2791 @Override
2792 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2793 return p instanceof CellLayout.LayoutParams;
2794 }
2795
2796 @Override
2797 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2798 return new CellLayout.LayoutParams(p);
2799 }
2800
Winson Chungaafa03c2010-06-11 17:34:16 -07002801 public static class CellLayoutAnimationController extends LayoutAnimationController {
2802 public CellLayoutAnimationController(Animation animation, float delay) {
2803 super(animation, delay);
2804 }
2805
2806 @Override
2807 protected long getDelayForView(View view) {
2808 return (int) (Math.random() * 150);
2809 }
2810 }
2811
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002812 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2813 /**
2814 * Horizontal location of the item in the grid.
2815 */
2816 @ViewDebug.ExportedProperty
2817 public int cellX;
2818
2819 /**
2820 * Vertical location of the item in the grid.
2821 */
2822 @ViewDebug.ExportedProperty
2823 public int cellY;
2824
2825 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002826 * Temporary horizontal location of the item in the grid during reorder
2827 */
2828 public int tmpCellX;
2829
2830 /**
2831 * Temporary vertical location of the item in the grid during reorder
2832 */
2833 public int tmpCellY;
2834
2835 /**
2836 * Indicates that the temporary coordinates should be used to layout the items
2837 */
2838 public boolean useTmpCoords;
2839
2840 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002841 * Number of cells spanned horizontally by the item.
2842 */
2843 @ViewDebug.ExportedProperty
2844 public int cellHSpan;
2845
2846 /**
2847 * Number of cells spanned vertically by the item.
2848 */
2849 @ViewDebug.ExportedProperty
2850 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002851
Adam Cohen1b607ed2011-03-03 17:26:50 -08002852 /**
2853 * Indicates whether the item will set its x, y, width and height parameters freely,
2854 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2855 */
Adam Cohend4844c32011-02-18 19:25:06 -08002856 public boolean isLockedToGrid = true;
2857
Adam Cohen482ed822012-03-02 14:15:13 -08002858 /**
2859 * Indicates whether this item can be reordered. Always true except in the case of the
2860 * the AllApps button.
2861 */
2862 public boolean canReorder = true;
2863
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002864 // X coordinate of the view in the layout.
2865 @ViewDebug.ExportedProperty
2866 int x;
2867 // Y coordinate of the view in the layout.
2868 @ViewDebug.ExportedProperty
2869 int y;
2870
Romain Guy84f296c2009-11-04 15:00:44 -08002871 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002872
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002873 public LayoutParams(Context c, AttributeSet attrs) {
2874 super(c, attrs);
2875 cellHSpan = 1;
2876 cellVSpan = 1;
2877 }
2878
2879 public LayoutParams(ViewGroup.LayoutParams source) {
2880 super(source);
2881 cellHSpan = 1;
2882 cellVSpan = 1;
2883 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002884
2885 public LayoutParams(LayoutParams source) {
2886 super(source);
2887 this.cellX = source.cellX;
2888 this.cellY = source.cellY;
2889 this.cellHSpan = source.cellHSpan;
2890 this.cellVSpan = source.cellVSpan;
2891 }
2892
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002893 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002894 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002895 this.cellX = cellX;
2896 this.cellY = cellY;
2897 this.cellHSpan = cellHSpan;
2898 this.cellVSpan = cellVSpan;
2899 }
2900
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002901 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap) {
Adam Cohend4844c32011-02-18 19:25:06 -08002902 if (isLockedToGrid) {
2903 final int myCellHSpan = cellHSpan;
2904 final int myCellVSpan = cellVSpan;
Adam Cohen482ed822012-03-02 14:15:13 -08002905 final int myCellX = useTmpCoords ? tmpCellX : cellX;
2906 final int myCellY = useTmpCoords ? tmpCellY : cellY;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002907
Adam Cohend4844c32011-02-18 19:25:06 -08002908 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2909 leftMargin - rightMargin;
2910 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2911 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002912 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2913 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002914 }
2915 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002916
Winson Chungaafa03c2010-06-11 17:34:16 -07002917 public String toString() {
2918 return "(" + this.cellX + ", " + this.cellY + ")";
2919 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002920
2921 public void setWidth(int width) {
2922 this.width = width;
2923 }
2924
2925 public int getWidth() {
2926 return width;
2927 }
2928
2929 public void setHeight(int height) {
2930 this.height = height;
2931 }
2932
2933 public int getHeight() {
2934 return height;
2935 }
2936
2937 public void setX(int x) {
2938 this.x = x;
2939 }
2940
2941 public int getX() {
2942 return x;
2943 }
2944
2945 public void setY(int y) {
2946 this.y = y;
2947 }
2948
2949 public int getY() {
2950 return y;
2951 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002952 }
2953
Michael Jurka0280c3b2010-09-17 15:00:07 -07002954 // This class stores info for two purposes:
2955 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2956 // its spanX, spanY, and the screen it is on
2957 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2958 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2959 // the CellLayout that was long clicked
Michael Jurkae5fb0f22011-04-11 13:27:46 -07002960 static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002961 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002962 int cellX = -1;
2963 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002964 int spanX;
2965 int spanY;
2966 int screen;
Winson Chung3d503fb2011-07-13 17:25:49 -07002967 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002968
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002969 @Override
2970 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002971 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2972 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002973 }
2974 }
Michael Jurkad771c962011-08-09 15:00:48 -07002975
2976 public boolean lastDownOnOccupiedCell() {
2977 return mLastDownOnOccupiedCell;
2978 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002979}