blob: a19cceacf01af75aff7f9d80e34216c4b7553dc4 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Joe Onoratoa5902522009-07-30 13:37:37 -070017package com.android.launcher2;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Joe Onorato4be866d2010-10-10 11:26:02 -070019import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
Chet Haase00397b12010-10-07 11:13:10 -070021import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070022import android.animation.ValueAnimator;
23import android.animation.ValueAnimator.AnimatorUpdateListener;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080024import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040025import android.content.res.Resources;
Winson Chungaafa03c2010-06-11 17:34:16 -070026import android.content.res.TypedArray;
Joe Onorato4be866d2010-10-10 11:26:02 -070027import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070028import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080029import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070030import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070031import android.graphics.Point;
32import android.graphics.PointF;
Adam Cohenb5ba0972011-09-07 18:02:31 -070033import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080036import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070037import android.graphics.drawable.Drawable;
Adam Cohenb5ba0972011-09-07 18:02:31 -070038import android.graphics.drawable.NinePatchDrawable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070040import android.util.Log;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.view.MotionEvent;
42import android.view.View;
43import android.view.ViewDebug;
44import android.view.ViewGroup;
Winson Chungaafa03c2010-06-11 17:34:16 -070045import android.view.animation.Animation;
Winson Chung150fbab2010-09-29 17:14:26 -070046import android.view.animation.DecelerateInterpolator;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.view.animation.LayoutAnimationController;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080048
Adam Cohen66396872011-04-15 17:50:36 -070049import com.android.launcher.R;
Adam Cohen69ce2e52011-07-03 19:25:21 -070050import com.android.launcher2.FolderIcon.FolderRingAnimator;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070051
Adam Cohen69ce2e52011-07-03 19:25:21 -070052import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070053import java.util.Arrays;
Adam Cohenbfbfd262011-06-13 16:55:12 -070054import java.util.HashMap;
Adam Cohend41fbf52012-02-16 23:53:59 -080055import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070056
Michael Jurkabdb5c532011-02-01 15:05:06 -080057public class CellLayout extends ViewGroup {
Winson Chungaafa03c2010-06-11 17:34:16 -070058 static final String TAG = "CellLayout";
59
Adam Cohen2acce882012-03-28 19:03:19 -070060 private Launcher mLauncher;
Winson Chung4b825dcd2011-06-19 12:41:22 -070061 private int mOriginalCellWidth;
62 private int mOriginalCellHeight;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080063 private int mCellWidth;
64 private int mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070065
Adam Cohend22015c2010-07-26 22:02:18 -070066 private int mCountX;
67 private int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080068
Adam Cohen234c4cd2011-07-17 21:03:04 -070069 private int mOriginalWidthGap;
70 private int mOriginalHeightGap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071 private int mWidthGap;
72 private int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070073 private int mMaxGap;
Adam Cohenebea84d2011-11-09 17:20:41 -080074 private boolean mScrollingTransformsDirty = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
76 private final Rect mRect = new Rect();
77 private final CellInfo mCellInfo = new CellInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -070078
Patrick Dubroyde7658b2010-09-27 11:15:43 -070079 // These are temporary variables to prevent having to allocate a new object just to
80 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Winson Chung0be025d2011-05-23 17:45:09 -070081 private final int[] mTmpXY = new int[2];
Patrick Dubroyde7658b2010-09-27 11:15:43 -070082 private final int[] mTmpPoint = new int[2];
83 private final PointF mTmpPointF = new PointF();
Adam Cohen69ce2e52011-07-03 19:25:21 -070084 int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070085
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -080087 boolean[][] mTmpOccupied;
Michael Jurkad771c962011-08-09 15:00:48 -070088 private boolean mLastDownOnOccupiedCell = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089
Michael Jurkadee05892010-07-27 10:01:56 -070090 private OnTouchListener mInterceptTouchListener;
91
Adam Cohen69ce2e52011-07-03 19:25:21 -070092 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -070093 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -070094
Adam Cohenb5ba0972011-09-07 18:02:31 -070095 private int mForegroundAlpha = 0;
Michael Jurka5f1c5092010-09-03 14:15:02 -070096 private float mBackgroundAlpha;
Adam Cohen1b0aaac2010-10-28 11:11:18 -070097 private float mBackgroundAlphaMultiplier = 1.0f;
Adam Cohenf34bab52010-09-30 14:11:56 -070098
Michael Jurka33945b22010-12-21 18:19:38 -080099 private Drawable mNormalBackground;
Michael Jurka33945b22010-12-21 18:19:38 -0800100 private Drawable mActiveGlowBackground;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700101 private Drawable mOverScrollForegroundDrawable;
102 private Drawable mOverScrollLeft;
103 private Drawable mOverScrollRight;
Michael Jurka18014792010-10-14 09:01:34 -0700104 private Rect mBackgroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700105 private Rect mForegroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700106 private int mForegroundPadding;
Patrick Dubroy1262e362010-10-06 15:49:50 -0700107
Michael Jurka33945b22010-12-21 18:19:38 -0800108 // If we're actively dragging something over this screen, mIsDragOverlapping is true
109 private boolean mIsDragOverlapping = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700110 private final Point mDragCenter = new Point();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700111
Winson Chung150fbab2010-09-29 17:14:26 -0700112 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700113 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohend41fbf52012-02-16 23:53:59 -0800114 private Rect[] mDragOutlines = new Rect[4];
Chet Haase472b2812010-10-14 07:02:04 -0700115 private float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700116 private InterruptibleInOutAnimator[] mDragOutlineAnims =
117 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700118
119 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700120 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700121 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700122
Patrick Dubroy96864c32011-03-10 17:17:23 -0800123 private BubbleTextView mPressedOrFocusedIcon;
124
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700125 private Drawable mCrosshairsDrawable = null;
Patrick Dubroy49250ad2010-10-08 15:33:52 -0700126 private InterruptibleInOutAnimator mCrosshairsAnimator = null;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700127 private float mCrosshairsVisibility = 0.0f;
128
Adam Cohen482ed822012-03-02 14:15:13 -0800129 private HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new
130 HashMap<CellLayout.LayoutParams, Animator>();
Adam Cohen19f37922012-03-21 11:59:11 -0700131 private HashMap<View, ReorderHintAnimation>
132 mShakeAnimators = new HashMap<View, ReorderHintAnimation>();
133
134 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700135
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700136 // When a drag operation is in progress, holds the nearest cell to the touch point
137 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800138
Joe Onorato4be866d2010-10-10 11:26:02 -0700139 private boolean mDragging = false;
140
Patrick Dubroyce34a972010-10-19 10:34:32 -0700141 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700142 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700143
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800144 private boolean mIsHotseat = false;
Winson Chungeecf02d2012-03-02 17:14:58 -0800145 private float mChildScale = 1f;
146 private float mHotseatChildScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800147
Adam Cohen482ed822012-03-02 14:15:13 -0800148 public static final int MODE_DRAG_OVER = 0;
149 public static final int MODE_ON_DROP = 1;
150 public static final int MODE_ON_DROP_EXTERNAL = 2;
151 public static final int MODE_ACCEPT_DROP = 3;
Adam Cohen19f37922012-03-21 11:59:11 -0700152 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800153 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
154
Adam Cohen19f37922012-03-21 11:59:11 -0700155 private static final float REORDER_HINT_MAGNITUDE = 0.27f;
156 private static final int REORDER_ANIMATION_DURATION = 150;
157 private float mReorderHintAnimationMagnitude;
158
Adam Cohen482ed822012-03-02 14:15:13 -0800159 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
160 private Rect mOccupiedRect = new Rect();
161 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700162 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700163 private static final int INVALID_DIRECTION = -100;
Adam Cohenc6cc61d2012-04-04 12:47:08 -0700164 private DropTarget.DragEnforcer mDragEnforcer;
Adam Cohen482ed822012-03-02 14:15:13 -0800165
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800166 public CellLayout(Context context) {
167 this(context, null);
168 }
169
170 public CellLayout(Context context, AttributeSet attrs) {
171 this(context, attrs, 0);
172 }
173
174 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
175 super(context, attrs, defStyle);
Michael Jurka8b805b12012-04-18 14:23:14 -0700176 mDragEnforcer = new DropTarget.DragEnforcer(context);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700177
178 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
179 // the user where a dragged item will land when dropped.
180 setWillNotDraw(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700181 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700182
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800183 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
184
Winson Chung4b825dcd2011-06-19 12:41:22 -0700185 mOriginalCellWidth =
186 mCellWidth = a.getDimensionPixelSize(R.styleable.CellLayout_cellWidth, 10);
187 mOriginalCellHeight =
188 mCellHeight = a.getDimensionPixelSize(R.styleable.CellLayout_cellHeight, 10);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700189 mWidthGap = mOriginalWidthGap = a.getDimensionPixelSize(R.styleable.CellLayout_widthGap, 0);
190 mHeightGap = mOriginalHeightGap = a.getDimensionPixelSize(R.styleable.CellLayout_heightGap, 0);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700191 mMaxGap = a.getDimensionPixelSize(R.styleable.CellLayout_maxGap, 0);
Adam Cohend22015c2010-07-26 22:02:18 -0700192 mCountX = LauncherModel.getCellCountX();
193 mCountY = LauncherModel.getCellCountY();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700194 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800195 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700196 mPreviousReorderDirection[0] = INVALID_DIRECTION;
197 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800198
199 a.recycle();
200
201 setAlwaysDrawnWithCacheEnabled(false);
202
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700203 final Resources res = getResources();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700204
Winson Chung967289b2011-06-30 18:09:30 -0700205 mNormalBackground = res.getDrawable(R.drawable.homescreen_blue_normal_holo);
Winson Chungdea74b72011-09-13 18:06:43 -0700206 mActiveGlowBackground = res.getDrawable(R.drawable.homescreen_blue_strong_holo);
Michael Jurka33945b22010-12-21 18:19:38 -0800207
Adam Cohenb5ba0972011-09-07 18:02:31 -0700208 mOverScrollLeft = res.getDrawable(R.drawable.overscroll_glow_left);
209 mOverScrollRight = res.getDrawable(R.drawable.overscroll_glow_right);
210 mForegroundPadding =
211 res.getDimensionPixelSize(R.dimen.workspace_overscroll_drawable_padding);
Michael Jurka33945b22010-12-21 18:19:38 -0800212
Adam Cohen19f37922012-03-21 11:59:11 -0700213 mReorderHintAnimationMagnitude = (REORDER_HINT_MAGNITUDE *
214 res.getDimensionPixelSize(R.dimen.app_icon_size));
215
Winson Chungb26f3d62011-06-02 10:49:29 -0700216 mNormalBackground.setFilterBitmap(true);
Winson Chungb26f3d62011-06-02 10:49:29 -0700217 mActiveGlowBackground.setFilterBitmap(true);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700218
Winson Chungeecf02d2012-03-02 17:14:58 -0800219 int iconScale = res.getInteger(R.integer.app_icon_scale_percent);
220 if (iconScale >= 0) {
221 mChildScale = iconScale / 100f;
222 }
223 int hotseatIconScale = res.getInteger(R.integer.app_icon_hotseat_scale_percent);
224 if (hotseatIconScale >= 0) {
225 mHotseatChildScale = hotseatIconScale / 100f;
226 }
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800227
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700228 // Initialize the data structures used for the drag visualization.
Winson Chung150fbab2010-09-29 17:14:26 -0700229
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700230 mCrosshairsDrawable = res.getDrawable(R.drawable.gardening_crosshairs);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700231 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700232
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700233 // Set up the animation for fading the crosshairs in and out
234 int animDuration = res.getInteger(R.integer.config_crosshairsFadeInTime);
Patrick Dubroy49250ad2010-10-08 15:33:52 -0700235 mCrosshairsAnimator = new InterruptibleInOutAnimator(animDuration, 0.0f, 1.0f);
Chet Haase472b2812010-10-14 07:02:04 -0700236 mCrosshairsAnimator.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700237 public void onAnimationUpdate(ValueAnimator animation) {
238 mCrosshairsVisibility = ((Float) animation.getAnimatedValue()).floatValue();
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700239 invalidate();
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700240 }
241 });
Patrick Dubroyce34a972010-10-19 10:34:32 -0700242 mCrosshairsAnimator.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700243
Winson Chungb8c69f32011-10-19 21:36:08 -0700244 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700245 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800246 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700247 }
248
249 // When dragging things around the home screens, we show a green outline of
250 // where the item will land. The outlines gradually fade out, leaving a trail
251 // behind the drag path.
252 // Set up all the animations that are used to implement this fading.
253 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700254 final float fromAlphaValue = 0;
255 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700256
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700257 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700258
259 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700260 final InterruptibleInOutAnimator anim =
261 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700262 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700263 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700264 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700265 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700266 final Bitmap outline = (Bitmap)anim.getTag();
267
268 // If an animation is started and then stopped very quickly, we can still
269 // get spurious updates we've cleared the tag. Guard against this.
270 if (outline == null) {
Michael Jurka3a9fced2012-04-13 14:44:29 -0700271 @SuppressWarnings("all") // suppress dead code warning
272 final boolean debug = false;
273 if (debug) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700274 Object val = animation.getAnimatedValue();
275 Log.d(TAG, "anim " + thisIndex + " update: " + val +
276 ", isStopped " + anim.isStopped());
277 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700278 // Try to prevent it from continuing to run
279 animation.cancel();
280 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700281 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800282 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700283 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700284 }
285 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700286 // The animation holds a reference to the drag outline bitmap as long is it's
287 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700288 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700289 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700290 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700291 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700292 anim.setTag(null);
293 }
294 }
295 });
296 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700297 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700298
Michael Jurka18014792010-10-14 09:01:34 -0700299 mBackgroundRect = new Rect();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700300 mForegroundRect = new Rect();
Michael Jurkabea15192010-11-17 12:33:46 -0800301
Michael Jurkaa52570f2012-03-20 03:18:20 -0700302 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
303 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
304 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700305 }
306
Michael Jurkaf6440da2011-04-05 14:50:34 -0700307 static int widthInPortrait(Resources r, int numCells) {
308 // We use this method from Workspace to figure out how many rows/columns Launcher should
309 // have. We ignore the left/right padding on CellLayout because it turns out in our design
310 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700311 int cellWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700312 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
313 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700314
Winson Chung4b825dcd2011-06-19 12:41:22 -0700315 return minGap * (numCells - 1) + cellWidth * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700316 }
317
Michael Jurkaf6440da2011-04-05 14:50:34 -0700318 static int heightInLandscape(Resources r, int numCells) {
319 // We use this method from Workspace to figure out how many rows/columns Launcher should
320 // have. We ignore the left/right padding on CellLayout because it turns out in our design
321 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700322 int cellHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700323 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
324 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700325
Winson Chung4b825dcd2011-06-19 12:41:22 -0700326 return minGap * (numCells - 1) + cellHeight * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700327 }
328
Adam Cohen2801caf2011-05-13 20:57:39 -0700329 public void enableHardwareLayers() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700330 mShortcutsAndWidgets.enableHardwareLayers();
Adam Cohen2801caf2011-05-13 20:57:39 -0700331 }
332
333 public void setGridSize(int x, int y) {
334 mCountX = x;
335 mCountY = y;
336 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800337 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700338 mTempRectStack.clear();
Adam Cohen76fc0852011-06-17 13:26:23 -0700339 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700340 }
341
Patrick Dubroy96864c32011-03-10 17:17:23 -0800342 private void invalidateBubbleTextView(BubbleTextView icon) {
343 final int padding = icon.getPressedOrFocusedBackgroundPadding();
Winson Chung4b825dcd2011-06-19 12:41:22 -0700344 invalidate(icon.getLeft() + getPaddingLeft() - padding,
345 icon.getTop() + getPaddingTop() - padding,
346 icon.getRight() + getPaddingLeft() + padding,
347 icon.getBottom() + getPaddingTop() + padding);
Patrick Dubroy96864c32011-03-10 17:17:23 -0800348 }
349
Adam Cohenb5ba0972011-09-07 18:02:31 -0700350 void setOverScrollAmount(float r, boolean left) {
351 if (left && mOverScrollForegroundDrawable != mOverScrollLeft) {
352 mOverScrollForegroundDrawable = mOverScrollLeft;
353 } else if (!left && mOverScrollForegroundDrawable != mOverScrollRight) {
354 mOverScrollForegroundDrawable = mOverScrollRight;
355 }
356
357 mForegroundAlpha = (int) Math.round((r * 255));
358 mOverScrollForegroundDrawable.setAlpha(mForegroundAlpha);
359 invalidate();
360 }
361
Patrick Dubroy96864c32011-03-10 17:17:23 -0800362 void setPressedOrFocusedIcon(BubbleTextView icon) {
363 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
364 // requires an expanded clip rect (due to the glow's blur radius)
365 BubbleTextView oldIcon = mPressedOrFocusedIcon;
366 mPressedOrFocusedIcon = icon;
367 if (oldIcon != null) {
368 invalidateBubbleTextView(oldIcon);
369 }
370 if (mPressedOrFocusedIcon != null) {
371 invalidateBubbleTextView(mPressedOrFocusedIcon);
372 }
373 }
374
Michael Jurka33945b22010-12-21 18:19:38 -0800375 void setIsDragOverlapping(boolean isDragOverlapping) {
376 if (mIsDragOverlapping != isDragOverlapping) {
377 mIsDragOverlapping = isDragOverlapping;
378 invalidate();
379 }
380 }
381
382 boolean getIsDragOverlapping() {
383 return mIsDragOverlapping;
384 }
385
Adam Cohenebea84d2011-11-09 17:20:41 -0800386 protected void setOverscrollTransformsDirty(boolean dirty) {
387 mScrollingTransformsDirty = dirty;
388 }
389
390 protected void resetOverscrollTransforms() {
391 if (mScrollingTransformsDirty) {
392 setOverscrollTransformsDirty(false);
393 setTranslationX(0);
394 setRotationY(0);
395 // It doesn't matter if we pass true or false here, the important thing is that we
396 // pass 0, which results in the overscroll drawable not being drawn any more.
397 setOverScrollAmount(0, false);
398 setPivotX(getMeasuredWidth() / 2);
399 setPivotY(getMeasuredHeight() / 2);
400 }
401 }
402
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700403 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700404 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700405 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
406 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
407 // When we're small, we are either drawn normally or in the "accepts drops" state (during
408 // a drag). However, we also drag the mini hover background *over* one of those two
409 // backgrounds
Winson Chungb26f3d62011-06-02 10:49:29 -0700410 if (mBackgroundAlpha > 0.0f) {
Adam Cohenf34bab52010-09-30 14:11:56 -0700411 Drawable bg;
Michael Jurka33945b22010-12-21 18:19:38 -0800412
413 if (mIsDragOverlapping) {
414 // In the mini case, we draw the active_glow bg *over* the active background
Michael Jurkabdf78552011-10-31 14:34:25 -0700415 bg = mActiveGlowBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700416 } else {
Michael Jurkabdf78552011-10-31 14:34:25 -0700417 bg = mNormalBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700418 }
Michael Jurka33945b22010-12-21 18:19:38 -0800419
420 bg.setAlpha((int) (mBackgroundAlpha * mBackgroundAlphaMultiplier * 255));
421 bg.setBounds(mBackgroundRect);
422 bg.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700423 }
Romain Guya6abce82009-11-10 02:54:41 -0800424
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700425 if (mCrosshairsVisibility > 0.0f) {
426 final int countX = mCountX;
427 final int countY = mCountY;
428
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700429 final float MAX_ALPHA = 0.4f;
430 final int MAX_VISIBLE_DISTANCE = 600;
431 final float DISTANCE_MULTIPLIER = 0.002f;
432
433 final Drawable d = mCrosshairsDrawable;
434 final int width = d.getIntrinsicWidth();
435 final int height = d.getIntrinsicHeight();
436
Winson Chung4b825dcd2011-06-19 12:41:22 -0700437 int x = getPaddingLeft() - (mWidthGap / 2) - (width / 2);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700438 for (int col = 0; col <= countX; col++) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700439 int y = getPaddingTop() - (mHeightGap / 2) - (height / 2);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700440 for (int row = 0; row <= countY; row++) {
441 mTmpPointF.set(x - mDragCenter.x, y - mDragCenter.y);
442 float dist = mTmpPointF.length();
443 // Crosshairs further from the drag point are more faint
444 float alpha = Math.min(MAX_ALPHA,
445 DISTANCE_MULTIPLIER * (MAX_VISIBLE_DISTANCE - dist));
446 if (alpha > 0.0f) {
447 d.setBounds(x, y, x + width, y + height);
448 d.setAlpha((int) (alpha * 255 * mCrosshairsVisibility));
449 d.draw(canvas);
450 }
451 y += mCellHeight + mHeightGap;
452 }
453 x += mCellWidth + mWidthGap;
454 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700455 }
Winson Chung150fbab2010-09-29 17:14:26 -0700456
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700457 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700458 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700459 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700460 if (alpha > 0) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800461 final Rect r = mDragOutlines[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700462 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700463 paint.setAlpha((int)(alpha + .5f));
Adam Cohend41fbf52012-02-16 23:53:59 -0800464 canvas.drawBitmap(b, null, r, paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700465 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700466 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800467
468 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
469 // requires an expanded clip rect (due to the glow's blur radius)
470 if (mPressedOrFocusedIcon != null) {
471 final int padding = mPressedOrFocusedIcon.getPressedOrFocusedBackgroundPadding();
472 final Bitmap b = mPressedOrFocusedIcon.getPressedOrFocusedBackground();
473 if (b != null) {
474 canvas.drawBitmap(b,
Winson Chung4b825dcd2011-06-19 12:41:22 -0700475 mPressedOrFocusedIcon.getLeft() + getPaddingLeft() - padding,
476 mPressedOrFocusedIcon.getTop() + getPaddingTop() - padding,
Patrick Dubroy96864c32011-03-10 17:17:23 -0800477 null);
478 }
479 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700480
Adam Cohen482ed822012-03-02 14:15:13 -0800481 if (DEBUG_VISUALIZE_OCCUPIED) {
482 int[] pt = new int[2];
483 ColorDrawable cd = new ColorDrawable(Color.RED);
484 cd.setBounds(0, 0, 80, 80);
485 for (int i = 0; i < mCountX; i++) {
486 for (int j = 0; j < mCountY; j++) {
487 if (mOccupied[i][j]) {
488 cellToPoint(i, j, pt);
489 canvas.save();
490 canvas.translate(pt[0], pt[1]);
491 cd.draw(canvas);
492 canvas.restore();
493 }
494 }
495 }
496 }
497
Adam Cohen69ce2e52011-07-03 19:25:21 -0700498 // The folder outer / inner ring image(s)
499 for (int i = 0; i < mFolderOuterRings.size(); i++) {
500 FolderRingAnimator fra = mFolderOuterRings.get(i);
501
502 // Draw outer ring
503 Drawable d = FolderRingAnimator.sSharedOuterRingDrawable;
504 int width = (int) fra.getOuterRingSize();
505 int height = width;
506 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
507
508 int centerX = mTempLocation[0] + mCellWidth / 2;
509 int centerY = mTempLocation[1] + FolderRingAnimator.sPreviewSize / 2;
510
511 canvas.save();
512 canvas.translate(centerX - width / 2, centerY - height / 2);
513 d.setBounds(0, 0, width, height);
514 d.draw(canvas);
515 canvas.restore();
516
517 // Draw inner ring
518 d = FolderRingAnimator.sSharedInnerRingDrawable;
519 width = (int) fra.getInnerRingSize();
520 height = width;
521 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
522
523 centerX = mTempLocation[0] + mCellWidth / 2;
524 centerY = mTempLocation[1] + FolderRingAnimator.sPreviewSize / 2;
525 canvas.save();
526 canvas.translate(centerX - width / 2, centerY - width / 2);
527 d.setBounds(0, 0, width, height);
528 d.draw(canvas);
529 canvas.restore();
530 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700531
532 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
533 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
534 int width = d.getIntrinsicWidth();
535 int height = d.getIntrinsicHeight();
536
537 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
538 int centerX = mTempLocation[0] + mCellWidth / 2;
539 int centerY = mTempLocation[1] + FolderRingAnimator.sPreviewSize / 2;
540
541 canvas.save();
542 canvas.translate(centerX - width / 2, centerY - width / 2);
543 d.setBounds(0, 0, width, height);
544 d.draw(canvas);
545 canvas.restore();
546 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700547 }
548
Adam Cohenb5ba0972011-09-07 18:02:31 -0700549 @Override
550 protected void dispatchDraw(Canvas canvas) {
551 super.dispatchDraw(canvas);
552 if (mForegroundAlpha > 0) {
553 mOverScrollForegroundDrawable.setBounds(mForegroundRect);
554 Paint p = ((NinePatchDrawable) mOverScrollForegroundDrawable).getPaint();
555 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.ADD));
556 mOverScrollForegroundDrawable.draw(canvas);
557 p.setXfermode(null);
558 }
559 }
560
Adam Cohen69ce2e52011-07-03 19:25:21 -0700561 public void showFolderAccept(FolderRingAnimator fra) {
562 mFolderOuterRings.add(fra);
563 }
564
565 public void hideFolderAccept(FolderRingAnimator fra) {
566 if (mFolderOuterRings.contains(fra)) {
567 mFolderOuterRings.remove(fra);
568 }
569 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700570 }
571
Adam Cohenc51934b2011-07-26 21:07:43 -0700572 public void setFolderLeaveBehindCell(int x, int y) {
573 mFolderLeaveBehindCell[0] = x;
574 mFolderLeaveBehindCell[1] = y;
575 invalidate();
576 }
577
578 public void clearFolderLeaveBehind() {
579 mFolderLeaveBehindCell[0] = -1;
580 mFolderLeaveBehindCell[1] = -1;
581 invalidate();
582 }
583
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700584 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700585 public boolean shouldDelayChildPressedState() {
586 return false;
587 }
588
589 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700590 public void cancelLongPress() {
591 super.cancelLongPress();
592
593 // Cancel long press for all children
594 final int count = getChildCount();
595 for (int i = 0; i < count; i++) {
596 final View child = getChildAt(i);
597 child.cancelLongPress();
598 }
599 }
600
Michael Jurkadee05892010-07-27 10:01:56 -0700601 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
602 mInterceptTouchListener = listener;
603 }
604
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800605 int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700606 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800607 }
608
609 int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700610 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 }
612
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800613 public void setIsHotseat(boolean isHotseat) {
614 mIsHotseat = isHotseat;
615 }
616
Winson Chungeecf02d2012-03-02 17:14:58 -0800617 public float getChildrenScale() {
618 return mIsHotseat ? mHotseatChildScale : mChildScale;
619 }
620
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700621 public boolean addViewToCellLayout(
622 View child, int index, int childId, LayoutParams params, boolean markCells) {
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800623 return addViewToCellLayout(child, index, childId, params, markCells, false);
624 }
625
Winson Chungeecf02d2012-03-02 17:14:58 -0800626 private void scaleChild(BubbleTextView bubbleChild, float pivot, float scale) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800627 // If we haven't measured the child yet, do it now
628 // (this happens if we're being dropped from all-apps
629 if (bubbleChild.getLayoutParams() instanceof LayoutParams &&
630 (bubbleChild.getMeasuredWidth() | bubbleChild.getMeasuredHeight()) == 0) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700631 getShortcutsAndWidgets().measureChild(bubbleChild);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800632 }
Andrew Flynnbc239a12012-03-06 11:39:49 -0800633
Andrew Flynnbc239a12012-03-06 11:39:49 -0800634 bubbleChild.setScaleX(scale);
635 bubbleChild.setScaleY(scale);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800636 }
637
638 private void resetChild(BubbleTextView bubbleChild) {
639 bubbleChild.setScaleX(1f);
640 bubbleChild.setScaleY(1f);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800641
642 bubbleChild.setTextColor(getResources().getColor(R.color.workspace_icon_text_color));
643 }
644
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800645 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
646 boolean markCells, boolean allApps) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700647 final LayoutParams lp = params;
648
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800649 // Hotseat icons - scale down and remove text
650 // Don't scale the all apps button
651 // scale percent set to -1 means do not scale
652 // Only scale BubbleTextViews
653 if (child instanceof BubbleTextView) {
654 BubbleTextView bubbleChild = (BubbleTextView) child;
655
Andrew Flynnbc239a12012-03-06 11:39:49 -0800656 // Start the child with 100% scale and visible text
657 resetChild(bubbleChild);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800658
Winson Chungeecf02d2012-03-02 17:14:58 -0800659 if (mIsHotseat && !allApps && mHotseatChildScale >= 0) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800660 // Scale/make transparent for a hotseat
Winson Chungeecf02d2012-03-02 17:14:58 -0800661 scaleChild(bubbleChild, 0f, mHotseatChildScale);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800662
Andrew Flynnbc239a12012-03-06 11:39:49 -0800663 bubbleChild.setTextColor(getResources().getColor(android.R.color.transparent));
Winson Chungeecf02d2012-03-02 17:14:58 -0800664 } else if (mChildScale >= 0) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800665 // Else possibly still scale it if we need to for smaller icons
Winson Chungeecf02d2012-03-02 17:14:58 -0800666 scaleChild(bubbleChild, 0f, mChildScale);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800667 }
668 }
669
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800670 // Generate an id for each view, this assumes we have at most 256x256 cells
671 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700672 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700673 // If the horizontal or vertical span is set to -1, it is taken to
674 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700675 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
676 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800677
Winson Chungaafa03c2010-06-11 17:34:16 -0700678 child.setId(childId);
679
Michael Jurkaa52570f2012-03-20 03:18:20 -0700680 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700681
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700682 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700683
Winson Chungaafa03c2010-06-11 17:34:16 -0700684 return true;
685 }
686 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800687 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700688
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800689 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700690 public void removeAllViews() {
691 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700692 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700693 }
694
695 @Override
696 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700697 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700698 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700699 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700700 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700701 }
702
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700703 public void removeViewWithoutMarkingCells(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700704 mShortcutsAndWidgets.removeView(view);
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700705 }
706
Michael Jurka0280c3b2010-09-17 15:00:07 -0700707 @Override
708 public void removeView(View view) {
709 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700710 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700711 }
712
713 @Override
714 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700715 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
716 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700717 }
718
719 @Override
720 public void removeViewInLayout(View view) {
721 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700722 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700723 }
724
725 @Override
726 public void removeViews(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.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700731 }
732
733 @Override
734 public void removeViewsInLayout(int start, int count) {
735 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700736 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700737 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700738 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800739 }
740
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800741 @Override
742 protected void onAttachedToWindow() {
743 super.onAttachedToWindow();
744 mCellInfo.screen = ((ViewGroup) getParent()).indexOfChild(this);
745 }
746
Michael Jurkaaf442092010-06-10 17:01:57 -0700747 public void setTagToCellInfoForPoint(int touchX, int touchY) {
748 final CellInfo cellInfo = mCellInfo;
Winson Chungeecf02d2012-03-02 17:14:58 -0800749 Rect frame = mRect;
Michael Jurka8b805b12012-04-18 14:23:14 -0700750 final int x = touchX + getScrollX();
751 final int y = touchY + getScrollY();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700752 final int count = mShortcutsAndWidgets.getChildCount();
Michael Jurkaaf442092010-06-10 17:01:57 -0700753
754 boolean found = false;
755 for (int i = count - 1; i >= 0; i--) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700756 final View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohend4844c32011-02-18 19:25:06 -0800757 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurkaaf442092010-06-10 17:01:57 -0700758
Adam Cohen1b607ed2011-03-03 17:26:50 -0800759 if ((child.getVisibility() == VISIBLE || child.getAnimation() != null) &&
760 lp.isLockedToGrid) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700761 child.getHitRect(frame);
Winson Chung0be025d2011-05-23 17:45:09 -0700762
Winson Chungeecf02d2012-03-02 17:14:58 -0800763 float scale = child.getScaleX();
764 frame = new Rect(child.getLeft(), child.getTop(), child.getRight(),
765 child.getBottom());
Winson Chung0be025d2011-05-23 17:45:09 -0700766 // The child hit rect is relative to the CellLayoutChildren parent, so we need to
767 // offset that by this CellLayout's padding to test an (x,y) point that is relative
768 // to this view.
Michael Jurka8b805b12012-04-18 14:23:14 -0700769 frame.offset(getPaddingLeft(), getPaddingTop());
Winson Chungeecf02d2012-03-02 17:14:58 -0800770 frame.inset((int) (frame.width() * (1f - scale) / 2),
771 (int) (frame.height() * (1f - scale) / 2));
Winson Chung0be025d2011-05-23 17:45:09 -0700772
Michael Jurkaaf442092010-06-10 17:01:57 -0700773 if (frame.contains(x, y)) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700774 cellInfo.cell = child;
775 cellInfo.cellX = lp.cellX;
776 cellInfo.cellY = lp.cellY;
777 cellInfo.spanX = lp.cellHSpan;
778 cellInfo.spanY = lp.cellVSpan;
Michael Jurkaaf442092010-06-10 17:01:57 -0700779 found = true;
Michael Jurkaaf442092010-06-10 17:01:57 -0700780 break;
781 }
782 }
783 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700784
Michael Jurkad771c962011-08-09 15:00:48 -0700785 mLastDownOnOccupiedCell = found;
786
Michael Jurkaaf442092010-06-10 17:01:57 -0700787 if (!found) {
Winson Chung0be025d2011-05-23 17:45:09 -0700788 final int cellXY[] = mTmpXY;
Michael Jurkaaf442092010-06-10 17:01:57 -0700789 pointToCellExact(x, y, cellXY);
790
Michael Jurkaaf442092010-06-10 17:01:57 -0700791 cellInfo.cell = null;
792 cellInfo.cellX = cellXY[0];
793 cellInfo.cellY = cellXY[1];
794 cellInfo.spanX = 1;
795 cellInfo.spanY = 1;
Michael Jurkaaf442092010-06-10 17:01:57 -0700796 }
797 setTag(cellInfo);
798 }
799
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800800 @Override
801 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohenc1997fd2011-08-15 18:26:39 -0700802 // First we clear the tag to ensure that on every touch down we start with a fresh slate,
803 // even in the case where we return early. Not clearing here was causing bugs whereby on
804 // long-press we'd end up picking up an item from a previous drag operation.
805 final int action = ev.getAction();
806
807 if (action == MotionEvent.ACTION_DOWN) {
808 clearTagCellInfo();
809 }
810
Michael Jurkadee05892010-07-27 10:01:56 -0700811 if (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev)) {
812 return true;
813 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800814
815 if (action == MotionEvent.ACTION_DOWN) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700816 setTagToCellInfoForPoint((int) ev.getX(), (int) ev.getY());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800817 }
Winson Chungeecf02d2012-03-02 17:14:58 -0800818
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800819 return false;
820 }
821
Adam Cohenc1997fd2011-08-15 18:26:39 -0700822 private void clearTagCellInfo() {
823 final CellInfo cellInfo = mCellInfo;
824 cellInfo.cell = null;
825 cellInfo.cellX = -1;
826 cellInfo.cellY = -1;
827 cellInfo.spanX = 0;
828 cellInfo.spanY = 0;
829 setTag(cellInfo);
830 }
831
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800832 public CellInfo getTag() {
Michael Jurka0280c3b2010-09-17 15:00:07 -0700833 return (CellInfo) super.getTag();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800834 }
835
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700836 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700837 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800838 * @param x X coordinate of the point
839 * @param y Y coordinate of the point
840 * @param result Array of 2 ints to hold the x and y coordinate of the cell
841 */
842 void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700843 final int hStartPadding = getPaddingLeft();
844 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800845
846 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
847 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
848
Adam Cohend22015c2010-07-26 22:02:18 -0700849 final int xAxis = mCountX;
850 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800851
852 if (result[0] < 0) result[0] = 0;
853 if (result[0] >= xAxis) result[0] = xAxis - 1;
854 if (result[1] < 0) result[1] = 0;
855 if (result[1] >= yAxis) result[1] = yAxis - 1;
856 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700857
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800858 /**
859 * Given a point, return the cell that most closely encloses that point
860 * @param x X coordinate of the point
861 * @param y Y coordinate of the point
862 * @param result Array of 2 ints to hold the x and y coordinate of the cell
863 */
864 void pointToCellRounded(int x, int y, int[] result) {
865 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
866 }
867
868 /**
869 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700870 *
871 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800872 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700873 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800874 * @param result Array of 2 ints to hold the x and y coordinate of the point
875 */
876 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700877 final int hStartPadding = getPaddingLeft();
878 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800879
880 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
881 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
882 }
883
Adam Cohene3e27a82011-04-15 12:07:39 -0700884 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800885 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700886 *
887 * @param cellX X coordinate of the cell
888 * @param cellY Y coordinate of the cell
889 *
890 * @param result Array of 2 ints to hold the x and y coordinate of the point
891 */
892 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700893 regionToCenterPoint(cellX, cellY, 1, 1, result);
894 }
895
896 /**
897 * Given a cell coordinate and span return the point that represents the center of the regio
898 *
899 * @param cellX X coordinate of the cell
900 * @param cellY Y coordinate of the cell
901 *
902 * @param result Array of 2 ints to hold the x and y coordinate of the point
903 */
904 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700905 final int hStartPadding = getPaddingLeft();
906 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700907 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
908 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
909 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
910 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700911 }
912
Adam Cohen19f37922012-03-21 11:59:11 -0700913 /**
914 * Given a cell coordinate and span fills out a corresponding pixel rect
915 *
916 * @param cellX X coordinate of the cell
917 * @param cellY Y coordinate of the cell
918 * @param result Rect in which to write the result
919 */
920 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
921 final int hStartPadding = getPaddingLeft();
922 final int vStartPadding = getPaddingTop();
923 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
924 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
925 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
926 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
927 }
928
Adam Cohen482ed822012-03-02 14:15:13 -0800929 public float getDistanceFromCell(float x, float y, int[] cell) {
930 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
931 float distance = (float) Math.sqrt( Math.pow(x - mTmpPoint[0], 2) +
932 Math.pow(y - mTmpPoint[1], 2));
933 return distance;
934 }
935
Romain Guy84f296c2009-11-04 15:00:44 -0800936 int getCellWidth() {
937 return mCellWidth;
938 }
939
940 int getCellHeight() {
941 return mCellHeight;
942 }
943
Adam Cohend4844c32011-02-18 19:25:06 -0800944 int getWidthGap() {
945 return mWidthGap;
946 }
947
948 int getHeightGap() {
949 return mHeightGap;
950 }
951
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700952 Rect getContentRect(Rect r) {
953 if (r == null) {
954 r = new Rect();
955 }
956 int left = getPaddingLeft();
957 int top = getPaddingTop();
Michael Jurka8b805b12012-04-18 14:23:14 -0700958 int right = left + getWidth() - getPaddingLeft() - getPaddingRight();
959 int bottom = top + getHeight() - getPaddingTop() - getPaddingBottom();
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700960 r.set(left, top, right, bottom);
961 return r;
962 }
963
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800964 @Override
965 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
966 // TODO: currently ignoring padding
Winson Chungaafa03c2010-06-11 17:34:16 -0700967
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800968 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700969 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
970
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800971 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
972 int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700973
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800974 if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
975 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
976 }
977
Adam Cohend22015c2010-07-26 22:02:18 -0700978 int numWidthGaps = mCountX - 1;
979 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800980
Adam Cohen234c4cd2011-07-17 21:03:04 -0700981 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700982 int hSpace = widthSpecSize - getPaddingLeft() - getPaddingRight();
983 int vSpace = heightSpecSize - getPaddingTop() - getPaddingBottom();
Winson Chung4b825dcd2011-06-19 12:41:22 -0700984 int hFreeSpace = hSpace - (mCountX * mOriginalCellWidth);
985 int vFreeSpace = vSpace - (mCountY * mOriginalCellHeight);
986 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
987 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700988 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700989 } else {
990 mWidthGap = mOriginalWidthGap;
991 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700992 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700993
Michael Jurka8c920dd2011-01-20 14:16:56 -0800994 // Initial values correspond to widthSpecMode == MeasureSpec.EXACTLY
995 int newWidth = widthSpecSize;
996 int newHeight = heightSpecSize;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700997 if (widthSpecMode == MeasureSpec.AT_MOST) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700998 newWidth = getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700999 ((mCountX - 1) * mWidthGap);
Michael Jurka8b805b12012-04-18 14:23:14 -07001000 newHeight = getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Winson Chungece7f5b2010-10-22 14:54:12 -07001001 ((mCountY - 1) * mHeightGap);
Michael Jurka5f1c5092010-09-03 14:15:02 -07001002 setMeasuredDimension(newWidth, newHeight);
Michael Jurka5f1c5092010-09-03 14:15:02 -07001003 }
Michael Jurka8c920dd2011-01-20 14:16:56 -08001004
1005 int count = getChildCount();
1006 for (int i = 0; i < count; i++) {
1007 View child = getChildAt(i);
Michael Jurka8b805b12012-04-18 14:23:14 -07001008 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth - getPaddingLeft() -
1009 getPaddingRight(), MeasureSpec.EXACTLY);
1010 int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight - getPaddingTop() -
1011 getPaddingBottom(), MeasureSpec.EXACTLY);
Michael Jurka8c920dd2011-01-20 14:16:56 -08001012 child.measure(childWidthMeasureSpec, childheightMeasureSpec);
1013 }
1014 setMeasuredDimension(newWidth, newHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001015 }
1016
1017 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -07001018 protected void onLayout(boolean changed, int l, int t, int r, int b) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001019 int count = getChildCount();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001020 for (int i = 0; i < count; i++) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08001021 View child = getChildAt(i);
Michael Jurka8b805b12012-04-18 14:23:14 -07001022 child.layout(getPaddingLeft(), getPaddingTop(),
1023 r - l - getPaddingRight(), b - t - getPaddingBottom());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001024 }
1025 }
1026
1027 @Override
Michael Jurkadee05892010-07-27 10:01:56 -07001028 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1029 super.onSizeChanged(w, h, oldw, oldh);
Michael Jurka18014792010-10-14 09:01:34 -07001030 mBackgroundRect.set(0, 0, w, h);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001031 mForegroundRect.set(mForegroundPadding, mForegroundPadding,
1032 w - 2 * mForegroundPadding, h - 2 * mForegroundPadding);
Michael Jurkadee05892010-07-27 10:01:56 -07001033 }
1034
1035 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001036 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001037 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001038 }
1039
1040 @Override
1041 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001042 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001043 }
1044
Michael Jurka5f1c5092010-09-03 14:15:02 -07001045 public float getBackgroundAlpha() {
1046 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -07001047 }
1048
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001049 public void setBackgroundAlphaMultiplier(float multiplier) {
1050 mBackgroundAlphaMultiplier = multiplier;
1051 }
1052
Adam Cohenddb82192010-11-10 16:32:54 -08001053 public float getBackgroundAlphaMultiplier() {
1054 return mBackgroundAlphaMultiplier;
1055 }
1056
Michael Jurka5f1c5092010-09-03 14:15:02 -07001057 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -08001058 if (mBackgroundAlpha != alpha) {
1059 mBackgroundAlpha = alpha;
1060 invalidate();
1061 }
Michael Jurkadee05892010-07-27 10:01:56 -07001062 }
1063
Michael Jurkaa52570f2012-03-20 03:18:20 -07001064 public void setShortcutAndWidgetAlpha(float alpha) {
Michael Jurka0142d492010-08-25 17:46:15 -07001065 final int childCount = getChildCount();
1066 for (int i = 0; i < childCount; i++) {
Michael Jurkadee05892010-07-27 10:01:56 -07001067 getChildAt(i).setAlpha(alpha);
1068 }
1069 }
1070
Michael Jurkaa52570f2012-03-20 03:18:20 -07001071 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
1072 if (getChildCount() > 0) {
1073 return (ShortcutAndWidgetContainer) getChildAt(0);
1074 }
1075 return null;
1076 }
1077
Patrick Dubroy440c3602010-07-13 17:50:32 -07001078 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001079 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001080 }
1081
Adam Cohen76fc0852011-06-17 13:26:23 -07001082 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001083 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001084 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -08001085 boolean[][] occupied = mOccupied;
1086 if (!permanent) {
1087 occupied = mTmpOccupied;
1088 }
1089
Adam Cohen19f37922012-03-21 11:59:11 -07001090 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001091 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
1092 final ItemInfo info = (ItemInfo) child.getTag();
1093
1094 // We cancel any existing animations
1095 if (mReorderAnimators.containsKey(lp)) {
1096 mReorderAnimators.get(lp).cancel();
1097 mReorderAnimators.remove(lp);
1098 }
1099
Adam Cohen482ed822012-03-02 14:15:13 -08001100 final int oldX = lp.x;
1101 final int oldY = lp.y;
1102 if (adjustOccupied) {
1103 occupied[lp.cellX][lp.cellY] = false;
1104 occupied[cellX][cellY] = true;
1105 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001106 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001107 if (permanent) {
1108 lp.cellX = info.cellX = cellX;
1109 lp.cellY = info.cellY = cellY;
1110 } else {
1111 lp.tmpCellX = cellX;
1112 lp.tmpCellY = cellY;
1113 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001114 clc.setupLp(lp);
1115 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001116 final int newX = lp.x;
1117 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001118
Adam Cohen76fc0852011-06-17 13:26:23 -07001119 lp.x = oldX;
1120 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001121
Adam Cohen482ed822012-03-02 14:15:13 -08001122 // Exit early if we're not actually moving the view
1123 if (oldX == newX && oldY == newY) {
1124 lp.isLockedToGrid = true;
1125 return true;
1126 }
1127
1128 ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
1129 va.setDuration(duration);
1130 mReorderAnimators.put(lp, va);
1131
1132 va.addUpdateListener(new AnimatorUpdateListener() {
1133 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001134 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001135 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001136 lp.x = (int) ((1 - r) * oldX + r * newX);
1137 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001138 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001139 }
1140 });
Adam Cohen482ed822012-03-02 14:15:13 -08001141 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001142 boolean cancelled = false;
1143 public void onAnimationEnd(Animator animation) {
1144 // If the animation was cancelled, it means that another animation
1145 // has interrupted this one, and we don't want to lock the item into
1146 // place just yet.
1147 if (!cancelled) {
1148 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001149 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001150 }
1151 if (mReorderAnimators.containsKey(lp)) {
1152 mReorderAnimators.remove(lp);
1153 }
1154 }
1155 public void onAnimationCancel(Animator animation) {
1156 cancelled = true;
1157 }
1158 });
Adam Cohen482ed822012-03-02 14:15:13 -08001159 va.setStartDelay(delay);
1160 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001161 return true;
1162 }
1163 return false;
1164 }
1165
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001166 /**
1167 * Estimate where the top left cell of the dragged item will land if it is dropped.
1168 *
1169 * @param originX The X value of the top left corner of the item
1170 * @param originY The Y value of the top left corner of the item
1171 * @param spanX The number of horizontal cells that the item spans
1172 * @param spanY The number of vertical cells that the item spans
1173 * @param result The estimated drop cell X and Y.
1174 */
1175 void estimateDropCell(int originX, int originY, int spanX, int spanY, int[] result) {
Adam Cohend22015c2010-07-26 22:02:18 -07001176 final int countX = mCountX;
1177 final int countY = mCountY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001178
Michael Jurkaa63c4522010-08-19 13:52:27 -07001179 // pointToCellRounded takes the top left of a cell but will pad that with
1180 // cellWidth/2 and cellHeight/2 when finding the matching cell
1181 pointToCellRounded(originX, originY, result);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001182
1183 // If the item isn't fully on this screen, snap to the edges
1184 int rightOverhang = result[0] + spanX - countX;
1185 if (rightOverhang > 0) {
1186 result[0] -= rightOverhang; // Snap to right
1187 }
1188 result[0] = Math.max(0, result[0]); // Snap to left
1189 int bottomOverhang = result[1] + spanY - countY;
1190 if (bottomOverhang > 0) {
1191 result[1] -= bottomOverhang; // Snap to bottom
1192 }
1193 result[1] = Math.max(0, result[1]); // Snap to top
1194 }
1195
Adam Cohen482ed822012-03-02 14:15:13 -08001196 void visualizeDropLocation(View v, Bitmap dragOutline, int originX, int originY, int cellX,
1197 int cellY, int spanX, int spanY, boolean resize, Point dragOffset, Rect dragRegion) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001198 final int oldDragCellX = mDragCell[0];
1199 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001200
Winson Chungb8c69f32011-10-19 21:36:08 -07001201 if (v != null && dragOffset == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07001202 mDragCenter.set(originX + (v.getWidth() / 2), originY + (v.getHeight() / 2));
1203 } else {
1204 mDragCenter.set(originX, originY);
1205 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001206
Adam Cohen2801caf2011-05-13 20:57:39 -07001207 if (dragOutline == null && v == null) {
1208 if (mCrosshairsDrawable != null) {
1209 invalidate();
1210 }
1211 return;
1212 }
1213
Adam Cohen482ed822012-03-02 14:15:13 -08001214 if (cellX != oldDragCellX || cellY != oldDragCellY) {
1215 mDragCell[0] = cellX;
1216 mDragCell[1] = cellY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001217 // Find the top left corner of the rect the object will occupy
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001218 final int[] topLeft = mTmpPoint;
Adam Cohen482ed822012-03-02 14:15:13 -08001219 cellToPoint(cellX, cellY, topLeft);
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001220
Joe Onorato4be866d2010-10-10 11:26:02 -07001221 int left = topLeft[0];
1222 int top = topLeft[1];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001223
Winson Chungb8c69f32011-10-19 21:36:08 -07001224 if (v != null && dragOffset == null) {
Adam Cohen99e8b402011-03-25 19:23:43 -07001225 // When drawing the drag outline, it did not account for margin offsets
1226 // added by the view's parent.
1227 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1228 left += lp.leftMargin;
1229 top += lp.topMargin;
Winson Chung150fbab2010-09-29 17:14:26 -07001230
Adam Cohen99e8b402011-03-25 19:23:43 -07001231 // Offsets due to the size difference between the View and the dragOutline.
1232 // There is a size difference to account for the outer blur, which may lie
1233 // outside the bounds of the view.
Winson Chunga9abd0e2010-10-27 17:18:37 -07001234 top += (v.getHeight() - dragOutline.getHeight()) / 2;
Adam Cohenae915ce2011-08-25 13:47:22 -07001235 // We center about the x axis
1236 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1237 - dragOutline.getWidth()) / 2;
Adam Cohen66396872011-04-15 17:50:36 -07001238 } else {
Winson Chungb8c69f32011-10-19 21:36:08 -07001239 if (dragOffset != null && dragRegion != null) {
1240 // Center the drag region *horizontally* in the cell and apply a drag
1241 // outline offset
1242 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1243 - dragRegion.width()) / 2;
1244 top += dragOffset.y;
1245 } else {
1246 // Center the drag outline in the cell
1247 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1248 - dragOutline.getWidth()) / 2;
1249 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1250 - dragOutline.getHeight()) / 2;
1251 }
Winson Chunga9abd0e2010-10-27 17:18:37 -07001252 }
Joe Onorato4be866d2010-10-10 11:26:02 -07001253 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001254 mDragOutlineAnims[oldIndex].animateOut();
1255 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001256 Rect r = mDragOutlines[mDragOutlineCurrent];
1257 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
1258 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001259 cellToRect(cellX, cellY, spanX, spanY, r);
Adam Cohend41fbf52012-02-16 23:53:59 -08001260 }
Winson Chung150fbab2010-09-29 17:14:26 -07001261
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001262 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1263 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001264 }
Patrick Dubroy49250ad2010-10-08 15:33:52 -07001265
1266 // If we are drawing crosshairs, the entire CellLayout needs to be invalidated
1267 if (mCrosshairsDrawable != null) {
1268 invalidate();
1269 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001270 }
1271
Adam Cohene0310962011-04-18 16:15:31 -07001272 public void clearDragOutlines() {
1273 final int oldIndex = mDragOutlineCurrent;
1274 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001275 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001276 }
1277
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001278 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001279 * Find a vacant area that will fit the given bounds nearest the requested
1280 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001281 *
Romain Guy51afc022009-05-04 18:03:43 -07001282 * @param pixelX The X location at which you want to search for a vacant area.
1283 * @param pixelY The Y location at which you want to search for a vacant area.
Jeff Sharkey70864282009-04-07 21:08:40 -07001284 * @param spanX Horizontal span of the object.
1285 * @param spanY Vertical span of the object.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001286 * @param result Array in which to place the result, or null (in which case a new array will
1287 * be allocated)
Jeff Sharkey70864282009-04-07 21:08:40 -07001288 * @return The X, Y cell of a vacant area that can contain this object,
1289 * nearest the requested location.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001290 */
Adam Cohend41fbf52012-02-16 23:53:59 -08001291 int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY,
1292 int[] result) {
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001293 return findNearestVacantArea(pixelX, pixelY, spanX, spanY, null, result);
Michael Jurka6a1435d2010-09-27 17:35:12 -07001294 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001295
Michael Jurka6a1435d2010-09-27 17:35:12 -07001296 /**
1297 * Find a vacant area that will fit the given bounds nearest the requested
1298 * cell location. Uses Euclidean distance to score multiple vacant areas.
1299 *
1300 * @param pixelX The X location at which you want to search for a vacant area.
1301 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001302 * @param minSpanX The minimum horizontal span required
1303 * @param minSpanY The minimum vertical span required
1304 * @param spanX Horizontal span of the object.
1305 * @param spanY Vertical span of the object.
1306 * @param result Array in which to place the result, or null (in which case a new array will
1307 * be allocated)
1308 * @return The X, Y cell of a vacant area that can contain this object,
1309 * nearest the requested location.
1310 */
1311 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1312 int spanY, int[] result, int[] resultSpan) {
1313 return findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null,
1314 result, resultSpan);
1315 }
1316
1317 /**
1318 * Find a vacant area that will fit the given bounds nearest the requested
1319 * cell location. Uses Euclidean distance to score multiple vacant areas.
1320 *
1321 * @param pixelX The X location at which you want to search for a vacant area.
1322 * @param pixelY The Y location at which you want to search for a vacant area.
Michael Jurka6a1435d2010-09-27 17:35:12 -07001323 * @param spanX Horizontal span of the object.
1324 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07001325 * @param ignoreOccupied If true, the result can be an occupied cell
1326 * @param result Array in which to place the result, or null (in which case a new array will
1327 * be allocated)
Michael Jurka6a1435d2010-09-27 17:35:12 -07001328 * @return The X, Y cell of a vacant area that can contain this object,
1329 * nearest the requested location.
1330 */
Adam Cohendf035382011-04-11 17:22:04 -07001331 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, View ignoreView,
1332 boolean ignoreOccupied, int[] result) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001333 return findNearestArea(pixelX, pixelY, spanX, spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001334 spanX, spanY, ignoreView, ignoreOccupied, result, null, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08001335 }
1336
1337 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1338 private void lazyInitTempRectStack() {
1339 if (mTempRectStack.isEmpty()) {
1340 for (int i = 0; i < mCountX * mCountY; i++) {
1341 mTempRectStack.push(new Rect());
1342 }
1343 }
1344 }
Adam Cohen482ed822012-03-02 14:15:13 -08001345
Adam Cohend41fbf52012-02-16 23:53:59 -08001346 private void recycleTempRects(Stack<Rect> used) {
1347 while (!used.isEmpty()) {
1348 mTempRectStack.push(used.pop());
1349 }
1350 }
1351
1352 /**
1353 * Find a vacant area that will fit the given bounds nearest the requested
1354 * cell location. Uses Euclidean distance to score multiple vacant areas.
1355 *
1356 * @param pixelX The X location at which you want to search for a vacant area.
1357 * @param pixelY The Y location at which you want to search for a vacant area.
1358 * @param minSpanX The minimum horizontal span required
1359 * @param minSpanY The minimum vertical span required
1360 * @param spanX Horizontal span of the object.
1361 * @param spanY Vertical span of the object.
1362 * @param ignoreOccupied If true, the result can be an occupied cell
1363 * @param result Array in which to place the result, or null (in which case a new array will
1364 * be allocated)
1365 * @return The X, Y cell of a vacant area that can contain this object,
1366 * nearest the requested location.
1367 */
1368 int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001369 View ignoreView, boolean ignoreOccupied, int[] result, int[] resultSpan,
1370 boolean[][] occupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001371 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001372 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08001373 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001374
Adam Cohene3e27a82011-04-15 12:07:39 -07001375 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1376 // to the center of the item, but we are searching based on the top-left cell, so
1377 // we translate the point over to correspond to the top-left.
1378 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1379 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1380
Jeff Sharkey70864282009-04-07 21:08:40 -07001381 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001382 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001383 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001384 final Rect bestRect = new Rect(-1, -1, -1, -1);
1385 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001386
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001387 final int countX = mCountX;
1388 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001389
Adam Cohend41fbf52012-02-16 23:53:59 -08001390 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1391 spanX < minSpanX || spanY < minSpanY) {
1392 return bestXY;
1393 }
1394
1395 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001396 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001397 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1398 int ySize = -1;
1399 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001400 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001401 // First, let's see if this thing fits anywhere
1402 for (int i = 0; i < minSpanX; i++) {
1403 for (int j = 0; j < minSpanY; j++) {
Adam Cohendf035382011-04-11 17:22:04 -07001404 if (occupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001405 continue inner;
1406 }
Michael Jurkac28de512010-08-13 11:27:44 -07001407 }
1408 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001409 xSize = minSpanX;
1410 ySize = minSpanY;
1411
1412 // We know that the item will fit at _some_ acceptable size, now let's see
1413 // how big we can make it. We'll alternate between incrementing x and y spans
1414 // until we hit a limit.
1415 boolean incX = true;
1416 boolean hitMaxX = xSize >= spanX;
1417 boolean hitMaxY = ySize >= spanY;
1418 while (!(hitMaxX && hitMaxY)) {
1419 if (incX && !hitMaxX) {
1420 for (int j = 0; j < ySize; j++) {
1421 if (x + xSize > countX -1 || occupied[x + xSize][y + j]) {
1422 // We can't move out horizontally
1423 hitMaxX = true;
1424 }
1425 }
1426 if (!hitMaxX) {
1427 xSize++;
1428 }
1429 } else if (!hitMaxY) {
1430 for (int i = 0; i < xSize; i++) {
1431 if (y + ySize > countY - 1 || occupied[x + i][y + ySize]) {
1432 // We can't move out vertically
1433 hitMaxY = true;
1434 }
1435 }
1436 if (!hitMaxY) {
1437 ySize++;
1438 }
1439 }
1440 hitMaxX |= xSize >= spanX;
1441 hitMaxY |= ySize >= spanY;
1442 incX = !incX;
1443 }
1444 incX = true;
1445 hitMaxX = xSize >= spanX;
1446 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001447 }
Winson Chung0be025d2011-05-23 17:45:09 -07001448 final int[] cellXY = mTmpXY;
Adam Cohene3e27a82011-04-15 12:07:39 -07001449 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001450
Adam Cohend41fbf52012-02-16 23:53:59 -08001451 // We verify that the current rect is not a sub-rect of any of our previous
1452 // candidates. In this case, the current rect is disqualified in favour of the
1453 // containing rect.
1454 Rect currentRect = mTempRectStack.pop();
1455 currentRect.set(x, y, x + xSize, y + ySize);
1456 boolean contained = false;
1457 for (Rect r : validRegions) {
1458 if (r.contains(currentRect)) {
1459 contained = true;
1460 break;
1461 }
1462 }
1463 validRegions.push(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001464 double distance = Math.sqrt(Math.pow(cellXY[0] - pixelX, 2)
1465 + Math.pow(cellXY[1] - pixelY, 2));
Adam Cohen482ed822012-03-02 14:15:13 -08001466
Adam Cohend41fbf52012-02-16 23:53:59 -08001467 if ((distance <= bestDistance && !contained) ||
1468 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001469 bestDistance = distance;
1470 bestXY[0] = x;
1471 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001472 if (resultSpan != null) {
1473 resultSpan[0] = xSize;
1474 resultSpan[1] = ySize;
1475 }
1476 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001477 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001478 }
1479 }
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001480 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08001481 markCellsAsOccupiedForView(ignoreView, occupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001482
Adam Cohenc0dcf592011-06-01 15:30:43 -07001483 // Return -1, -1 if no suitable location found
1484 if (bestDistance == Double.MAX_VALUE) {
1485 bestXY[0] = -1;
1486 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001487 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001488 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001489 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001490 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001491
Adam Cohen482ed822012-03-02 14:15:13 -08001492 /**
1493 * Find a vacant area that will fit the given bounds nearest the requested
1494 * cell location, and will also weigh in a suggested direction vector of the
1495 * desired location. This method computers distance based on unit grid distances,
1496 * not pixel distances.
1497 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001498 * @param cellX The X cell nearest to which you want to search for a vacant area.
1499 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001500 * @param spanX Horizontal span of the object.
1501 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001502 * @param direction The favored direction in which the views should move from x, y
1503 * @param exactDirectionOnly If this parameter is true, then only solutions where the direction
1504 * matches exactly. Otherwise we find the best matching direction.
1505 * @param occoupied The array which represents which cells in the CellLayout are occupied
1506 * @param blockOccupied The array which represents which cells in the specified block (cellX,
1507 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001508 * @param result Array in which to place the result, or null (in which case a new array will
1509 * be allocated)
1510 * @return The X, Y cell of a vacant area that can contain this object,
1511 * nearest the requested location.
1512 */
1513 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001514 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001515 // Keep track of best-scoring drop area
1516 final int[] bestXY = result != null ? result : new int[2];
1517 float bestDistance = Float.MAX_VALUE;
1518 int bestDirectionScore = Integer.MIN_VALUE;
1519
1520 final int countX = mCountX;
1521 final int countY = mCountY;
1522
1523 for (int y = 0; y < countY - (spanY - 1); y++) {
1524 inner:
1525 for (int x = 0; x < countX - (spanX - 1); x++) {
1526 // First, let's see if this thing fits anywhere
1527 for (int i = 0; i < spanX; i++) {
1528 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001529 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001530 continue inner;
1531 }
1532 }
1533 }
1534
1535 float distance = (float)
1536 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1537 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001538 computeDirectionVector(x - cellX, y - cellY, curDirection);
1539 // The direction score is just the dot product of the two candidate direction
1540 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001541 int curDirectionScore = direction[0] * curDirection[0] +
1542 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001543 boolean exactDirectionOnly = false;
1544 boolean directionMatches = direction[0] == curDirection[0] &&
1545 direction[0] == curDirection[0];
1546 if ((directionMatches || !exactDirectionOnly) &&
1547 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001548 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1549 bestDistance = distance;
1550 bestDirectionScore = curDirectionScore;
1551 bestXY[0] = x;
1552 bestXY[1] = y;
1553 }
1554 }
1555 }
1556
1557 // Return -1, -1 if no suitable location found
1558 if (bestDistance == Float.MAX_VALUE) {
1559 bestXY[0] = -1;
1560 bestXY[1] = -1;
1561 }
1562 return bestXY;
1563 }
1564
Adam Cohen47a876d2012-03-19 13:21:41 -07001565 private int[] findNearestAreaInDirection(int cellX, int cellY, int spanX, int spanY,
1566 int[] direction,boolean[][] occupied,
1567 boolean blockOccupied[][], int[] result) {
1568 // Keep track of best-scoring drop area
1569 final int[] bestXY = result != null ? result : new int[2];
1570 bestXY[0] = -1;
1571 bestXY[1] = -1;
1572 float bestDistance = Float.MAX_VALUE;
1573
1574 // We use this to march in a single direction
Adam Cohen5b53f292012-03-29 14:30:35 -07001575 if ((direction[0] != 0 && direction[1] != 0) ||
1576 (direction[0] == 0 && direction[1] == 0)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001577 return bestXY;
1578 }
1579
1580 // This will only incrememnet one of x or y based on the assertion above
1581 int x = cellX + direction[0];
1582 int y = cellY + direction[1];
1583 while (x >= 0 && x + spanX <= mCountX && y >= 0 && y + spanY <= mCountY) {
1584
1585 boolean fail = false;
1586 for (int i = 0; i < spanX; i++) {
1587 for (int j = 0; j < spanY; j++) {
1588 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1589 fail = true;
1590 }
1591 }
1592 }
1593 if (!fail) {
1594 float distance = (float)
1595 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1596 if (Float.compare(distance, bestDistance) < 0) {
1597 bestDistance = distance;
1598 bestXY[0] = x;
1599 bestXY[1] = y;
1600 }
1601 }
1602 x += direction[0];
1603 y += direction[1];
1604 }
1605 return bestXY;
1606 }
1607
Adam Cohen482ed822012-03-02 14:15:13 -08001608 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001609 int[] direction, ItemConfiguration currentState) {
1610 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001611 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001612 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001613 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1614
Adam Cohen8baab352012-03-20 17:39:21 -07001615 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001616
1617 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001618 c.x = mTempLocation[0];
1619 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001620 success = true;
1621
1622 }
Adam Cohen8baab352012-03-20 17:39:21 -07001623 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001624 return success;
1625 }
1626
Adam Cohen47a876d2012-03-19 13:21:41 -07001627 // This method looks in the specified direction to see if there is an additional view
1628 // immediately adjecent in that direction
1629 private boolean addViewInDirection(ArrayList<View> views, Rect boundingRect, int[] direction,
Adam Cohen19f37922012-03-21 11:59:11 -07001630 boolean[][] occupied, View dragView, ItemConfiguration currentState) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001631 boolean found = false;
1632
Michael Jurkaa52570f2012-03-20 03:18:20 -07001633 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen47a876d2012-03-19 13:21:41 -07001634 Rect r0 = new Rect(boundingRect);
1635 Rect r1 = new Rect();
1636
1637 int deltaX = 0;
1638 int deltaY = 0;
1639 if (direction[1] < 0) {
1640 r0.set(r0.left, r0.top - 1, r0.right, r0.bottom);
1641 deltaY = -1;
1642 } else if (direction[1] > 0) {
1643 r0.set(r0.left, r0.top, r0.right, r0.bottom + 1);
1644 deltaY = 1;
1645 } else if (direction[0] < 0) {
1646 r0.set(r0.left - 1, r0.top, r0.right, r0.bottom);
1647 deltaX = -1;
1648 } else if (direction[0] > 0) {
1649 r0.set(r0.left, r0.top, r0.right + 1, r0.bottom);
1650 deltaX = 1;
1651 }
1652
1653 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001654 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen19f37922012-03-21 11:59:11 -07001655 if (views.contains(child) || child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001656 CellAndSpan c = currentState.map.get(child);
Adam Cohen47a876d2012-03-19 13:21:41 -07001657
Adam Cohen8baab352012-03-20 17:39:21 -07001658 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1659 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001660 if (Rect.intersects(r0, r1)) {
1661 if (!lp.canReorder) {
1662 return false;
1663 }
1664 boolean pushed = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001665 for (int x = c.x; x < c.x + c.spanX; x++) {
1666 for (int y = c.y; y < c.y + c.spanY; y++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001667 boolean inBounds = x - deltaX >= 0 && x -deltaX < mCountX
1668 && y - deltaY >= 0 && y - deltaY < mCountY;
1669 if (inBounds && occupied[x - deltaX][y - deltaY]) {
1670 pushed = true;
1671 }
1672 }
1673 }
1674 if (pushed) {
1675 views.add(child);
Adam Cohen8baab352012-03-20 17:39:21 -07001676 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001677 found = true;
1678 }
1679 }
1680 }
1681 return found;
1682 }
1683
Adam Cohen482ed822012-03-02 14:15:13 -08001684 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohen19f37922012-03-21 11:59:11 -07001685 int[] direction, boolean push, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001686 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001687
Adam Cohen8baab352012-03-20 17:39:21 -07001688 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001689 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001690 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001691 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001692 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001693 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001694 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001695 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001696 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001697 }
1698 }
Adam Cohen8baab352012-03-20 17:39:21 -07001699
1700 @SuppressWarnings("unchecked")
1701 ArrayList<View> dup = (ArrayList<View>) views.clone();
1702 // We try and expand the group of views in the direction vector passed, based on
1703 // whether they are physically adjacent, ie. based on "push mechanics".
Adam Cohen19f37922012-03-21 11:59:11 -07001704 while (push && addViewInDirection(dup, boundingRect, direction, mTmpOccupied, dragView,
Adam Cohen8baab352012-03-20 17:39:21 -07001705 currentState)) {
1706 }
1707
1708 // Mark the occupied state as false for the group of views we want to move.
1709 for (View v: dup) {
1710 CellAndSpan c = currentState.map.get(v);
1711 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1712 }
1713
Adam Cohen47a876d2012-03-19 13:21:41 -07001714 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1715 int top = boundingRect.top;
1716 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001717 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
1718 // for tetris-style interlocking.
1719 for (View v: dup) {
1720 CellAndSpan c = currentState.map.get(v);
1721 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001722 }
1723
Adam Cohen482ed822012-03-02 14:15:13 -08001724 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1725
Adam Cohen8baab352012-03-20 17:39:21 -07001726 if (push) {
1727 findNearestAreaInDirection(boundingRect.left, boundingRect.top, boundingRect.width(),
1728 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1729 } else {
1730 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1731 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1732 }
Adam Cohen482ed822012-03-02 14:15:13 -08001733
Adam Cohen8baab352012-03-20 17:39:21 -07001734 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001735 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001736 int deltaX = mTempLocation[0] - boundingRect.left;
1737 int deltaY = mTempLocation[1] - boundingRect.top;
1738 for (View v: dup) {
1739 CellAndSpan c = currentState.map.get(v);
1740 c.x += deltaX;
1741 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001742 }
1743 success = true;
1744 }
Adam Cohen8baab352012-03-20 17:39:21 -07001745
1746 // In either case, we set the occupied array as marked for the location of the views
1747 for (View v: dup) {
1748 CellAndSpan c = currentState.map.get(v);
1749 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001750 }
1751 return success;
1752 }
1753
1754 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1755 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1756 }
1757
1758 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001759 View ignoreView, ItemConfiguration solution) {
Adam Cohen482ed822012-03-02 14:15:13 -08001760
Adam Cohen8baab352012-03-20 17:39:21 -07001761 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001762 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001763
Adam Cohen8baab352012-03-20 17:39:21 -07001764 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001765 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001766 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001767 if (c != null) {
1768 c.x = cellX;
1769 c.y = cellY;
1770 }
Adam Cohen482ed822012-03-02 14:15:13 -08001771 }
Adam Cohen482ed822012-03-02 14:15:13 -08001772 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1773 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001774 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001775 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001776 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001777 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001778 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001779 if (Rect.intersects(r0, r1)) {
1780 if (!lp.canReorder) {
1781 return false;
1782 }
1783 mIntersectingViews.add(child);
1784 }
1785 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001786
Adam Cohen8baab352012-03-20 17:39:21 -07001787 // We try to move the intersecting views as a block using the push mechanic
Adam Cohen19f37922012-03-21 11:59:11 -07001788 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, true, ignoreView,
1789 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001790 return true;
1791 }
1792 // Try the opposite direction
1793 direction[0] *= -1;
1794 direction[1] *= -1;
Adam Cohen19f37922012-03-21 11:59:11 -07001795 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, true, ignoreView,
1796 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001797 return true;
1798 }
1799 // Switch the direction back
1800 direction[0] *= -1;
1801 direction[1] *= -1;
1802
Adam Cohen8baab352012-03-20 17:39:21 -07001803 // Next we try moving the views as a block , but without requiring the push mechanic
Adam Cohen19f37922012-03-21 11:59:11 -07001804 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, false, ignoreView,
1805 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001806 return true;
1807 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001808
Adam Cohen482ed822012-03-02 14:15:13 -08001809 // Ok, they couldn't move as a block, let's move them individually
1810 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001811 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001812 return false;
1813 }
1814 }
1815 return true;
1816 }
1817
1818 /*
1819 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1820 * the provided point and the provided cell
1821 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001822 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001823 double angle = Math.atan(((float) deltaY) / deltaX);
1824
1825 result[0] = 0;
1826 result[1] = 0;
1827 if (Math.abs(Math.cos(angle)) > 0.5f) {
1828 result[0] = (int) Math.signum(deltaX);
1829 }
1830 if (Math.abs(Math.sin(angle)) > 0.5f) {
1831 result[1] = (int) Math.signum(deltaY);
1832 }
1833 }
1834
Adam Cohen8baab352012-03-20 17:39:21 -07001835 private void copyOccupiedArray(boolean[][] occupied) {
1836 for (int i = 0; i < mCountX; i++) {
1837 for (int j = 0; j < mCountY; j++) {
1838 occupied[i][j] = mOccupied[i][j];
1839 }
1840 }
1841 }
1842
Adam Cohen482ed822012-03-02 14:15:13 -08001843 ItemConfiguration simpleSwap(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1844 int spanY, int[] direction, View dragView, boolean decX, ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001845 // Copy the current state into the solution. This solution will be manipulated as necessary.
1846 copyCurrentStateToSolution(solution, false);
1847 // Copy the current occupied array into the temporary occupied array. This array will be
1848 // manipulated as necessary to find a solution.
1849 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001850
1851 // We find the nearest cell into which we would place the dragged item, assuming there's
1852 // nothing in its way.
1853 int result[] = new int[2];
1854 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1855
1856 boolean success = false;
1857 // First we try the exact nearest position of the item being dragged,
1858 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001859 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1860 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001861
1862 if (!success) {
1863 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1864 // x, then 1 in y etc.
1865 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
1866 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY, direction,
1867 dragView, false, solution);
1868 } else if (spanY > minSpanY) {
1869 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1, direction,
1870 dragView, true, solution);
1871 }
1872 solution.isSolution = false;
1873 } else {
1874 solution.isSolution = true;
1875 solution.dragViewX = result[0];
1876 solution.dragViewY = result[1];
1877 solution.dragViewSpanX = spanX;
1878 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001879 }
1880 return solution;
1881 }
1882
1883 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001884 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001885 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001886 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001887 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001888 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08001889 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07001890 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001891 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001892 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001893 }
Adam Cohen8baab352012-03-20 17:39:21 -07001894 solution.map.put(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08001895 }
1896 }
1897
1898 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
1899 for (int i = 0; i < mCountX; i++) {
1900 for (int j = 0; j < mCountY; j++) {
1901 mTmpOccupied[i][j] = false;
1902 }
1903 }
1904
Michael Jurkaa52570f2012-03-20 03:18:20 -07001905 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001906 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001907 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001908 if (child == dragView) continue;
1909 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001910 CellAndSpan c = solution.map.get(child);
1911 if (c != null) {
1912 lp.tmpCellX = c.x;
1913 lp.tmpCellY = c.y;
1914 lp.cellHSpan = c.spanX;
1915 lp.cellVSpan = c.spanY;
1916 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001917 }
1918 }
1919 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1920 solution.dragViewSpanY, mTmpOccupied, true);
1921 }
1922
1923 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1924 commitDragView) {
1925
1926 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1927 for (int i = 0; i < mCountX; i++) {
1928 for (int j = 0; j < mCountY; j++) {
1929 occupied[i][j] = false;
1930 }
1931 }
1932
Michael Jurkaa52570f2012-03-20 03:18:20 -07001933 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001934 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001935 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001936 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001937 CellAndSpan c = solution.map.get(child);
1938 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07001939 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
1940 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07001941 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001942 }
1943 }
1944 if (commitDragView) {
1945 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1946 solution.dragViewSpanY, occupied, true);
1947 }
1948 }
1949
Adam Cohen19f37922012-03-21 11:59:11 -07001950 // This method starts or changes the reorder hint animations
1951 private void beginOrAdjustHintAnimations(ItemConfiguration solution, View dragView, int delay) {
1952 int childCount = mShortcutsAndWidgets.getChildCount();
1953 int timeForPriorAnimationToComplete = getMaxCompletionTime();
1954 for (int i = 0; i < childCount; i++) {
1955 View child = mShortcutsAndWidgets.getChildAt(i);
1956 if (child == dragView) continue;
1957 CellAndSpan c = solution.map.get(child);
1958 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1959 if (c != null) {
1960 ReorderHintAnimation rha = new ReorderHintAnimation(child, lp.cellX, lp.cellY,
1961 c.x, c.y, c.spanX, c.spanY);
1962 rha.animate(timeForPriorAnimationToComplete);
1963 }
1964 }
1965 }
1966
1967 // Class which represents the reorder hint animations. These animations show that an item is
1968 // in a temporary state, and hint at where the item will return to.
1969 class ReorderHintAnimation {
1970 View child;
1971 float deltaX;
1972 float deltaY;
1973 private static final int DURATION = 140;
1974 private int repeatCount;
1975 private boolean cancelOnCycleComplete = false;
1976 ValueAnimator va;
1977
1978 public ReorderHintAnimation(View child, int cellX0, int cellY0, int cellX1, int cellY1,
1979 int spanX, int spanY) {
1980 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
1981 final int x0 = mTmpPoint[0];
1982 final int y0 = mTmpPoint[1];
1983 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
1984 final int x1 = mTmpPoint[0];
1985 final int y1 = mTmpPoint[1];
1986 final int dX = x1 - x0;
1987 final int dY = y1 - y0;
1988 deltaX = 0;
1989 deltaY = 0;
1990 if (dX == dY && dX == 0) {
1991 } else {
1992 if (dY == 0) {
1993 deltaX = mReorderHintAnimationMagnitude;
1994 } else if (dX == 0) {
1995 deltaY = mReorderHintAnimationMagnitude;
1996 } else {
1997 double angle = Math.atan( (float) (dY) / dX);
1998 deltaX = (int) (Math.cos(angle) * mReorderHintAnimationMagnitude);
1999 deltaY = (int) (Math.sin(angle) * mReorderHintAnimationMagnitude);
2000 }
2001 }
2002 this.child = child;
2003 }
2004
2005 void animate(int delay) {
2006 if (mShakeAnimators.containsKey(child)) {
2007 ReorderHintAnimation oldAnimation = mShakeAnimators.get(child);
2008 oldAnimation.completeAnimation();
2009 mShakeAnimators.remove(child);
2010 }
2011 if (deltaX == 0 && deltaY == 0) {
2012 return;
2013 }
2014 va = ValueAnimator.ofFloat(0f, 1f);
2015 va.setRepeatMode(ValueAnimator.REVERSE);
2016 va.setRepeatCount(ValueAnimator.INFINITE);
2017 va.setDuration(DURATION);
2018 va.addUpdateListener(new AnimatorUpdateListener() {
2019 @Override
2020 public void onAnimationUpdate(ValueAnimator animation) {
2021 float r = ((Float) animation.getAnimatedValue()).floatValue();
2022 float x = r * deltaX;
2023 float y = r * deltaY;
2024 child.setTranslationX(x);
2025 child.setTranslationY(y);
2026 }
2027 });
2028 va.addListener(new AnimatorListenerAdapter() {
2029 public void onAnimationRepeat(Animator animation) {
2030 repeatCount++;
2031 // We make sure to end only after a full period
2032 if (cancelOnCycleComplete && repeatCount % 2 == 0) {
2033 va.cancel();
2034 }
2035 }
2036 });
2037 va.setStartDelay(Math.max(REORDER_ANIMATION_DURATION, delay));
2038 mShakeAnimators.put(child, this);
2039 va.start();
2040 }
2041
2042
2043 private void completeAnimation() {
2044 cancelOnCycleComplete = true;
2045 }
2046
2047 // Returns the time required to complete the current oscillating animation
2048 private int completionTime() {
2049 if (repeatCount % 2 == 0) {
2050 return (int) (va.getDuration() - va.getCurrentPlayTime() + DURATION);
2051 } else {
2052 return (int) (va.getDuration() - va.getCurrentPlayTime());
2053 }
2054 }
2055 }
2056
2057 private void completeAndClearReorderHintAnimations() {
2058 for (ReorderHintAnimation a: mShakeAnimators.values()) {
2059 a.completeAnimation();
2060 }
2061 mShakeAnimators.clear();
2062 }
2063
2064 private int getMaxCompletionTime() {
2065 int maxTime = 0;
2066 for (ReorderHintAnimation a: mShakeAnimators.values()) {
2067 maxTime = Math.max(maxTime, a.completionTime());
2068 }
2069 return maxTime;
2070 }
2071
Adam Cohen482ed822012-03-02 14:15:13 -08002072 private void commitTempPlacement() {
2073 for (int i = 0; i < mCountX; i++) {
2074 for (int j = 0; j < mCountY; j++) {
2075 mOccupied[i][j] = mTmpOccupied[i][j];
2076 }
2077 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002078 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002079 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002080 View child = mShortcutsAndWidgets.getChildAt(i);
2081 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2082 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002083 // We do a null check here because the item info can be null in the case of the
2084 // AllApps button in the hotseat.
2085 if (info != null) {
2086 info.cellX = lp.cellX = lp.tmpCellX;
2087 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002088 info.spanX = lp.cellHSpan;
2089 info.spanY = lp.cellVSpan;
Adam Cohen2acce882012-03-28 19:03:19 -07002090 }
Adam Cohen482ed822012-03-02 14:15:13 -08002091 }
Adam Cohen2acce882012-03-28 19:03:19 -07002092 mLauncher.getWorkspace().updateItemLocationsInDatabase(this);
Adam Cohen482ed822012-03-02 14:15:13 -08002093 }
2094
2095 public void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002096 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002097 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002098 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002099 lp.useTmpCoords = useTempCoords;
2100 }
2101 }
2102
Adam Cohen482ed822012-03-02 14:15:13 -08002103 ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
2104 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2105 int[] result = new int[2];
2106 int[] resultSpan = new int[2];
2107 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null, result,
2108 resultSpan);
2109 if (result[0] >= 0 && result[1] >= 0) {
2110 copyCurrentStateToSolution(solution, false);
2111 solution.dragViewX = result[0];
2112 solution.dragViewY = result[1];
2113 solution.dragViewSpanX = resultSpan[0];
2114 solution.dragViewSpanY = resultSpan[1];
2115 solution.isSolution = true;
2116 } else {
2117 solution.isSolution = false;
2118 }
2119 return solution;
2120 }
2121
2122 public void prepareChildForDrag(View child) {
2123 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002124 }
2125
Adam Cohen19f37922012-03-21 11:59:11 -07002126 /* This seems like it should be obvious and straight-forward, but when the direction vector
2127 needs to match with the notion of the dragView pushing other views, we have to employ
2128 a slightly more subtle notion of the direction vector. The question is what two points is
2129 the vector between? The center of the dragView and its desired destination? Not quite, as
2130 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2131 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2132 or right, which helps make pushing feel right.
2133 */
2134 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2135 int spanY, View dragView, int[] resultDirection) {
2136 int[] targetDestination = new int[2];
2137
2138 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2139 Rect dragRect = new Rect();
2140 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2141 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2142
2143 Rect dropRegionRect = new Rect();
2144 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2145 dragView, dropRegionRect, mIntersectingViews);
2146
2147 int dropRegionSpanX = dropRegionRect.width();
2148 int dropRegionSpanY = dropRegionRect.height();
2149
2150 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2151 dropRegionRect.height(), dropRegionRect);
2152
2153 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2154 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2155
2156 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2157 deltaX = 0;
2158 }
2159 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2160 deltaY = 0;
2161 }
2162
2163 if (deltaX == 0 && deltaY == 0) {
2164 // No idea what to do, give a random direction.
2165 resultDirection[0] = 1;
2166 resultDirection[1] = 0;
2167 } else {
2168 computeDirectionVector(deltaX, deltaY, resultDirection);
2169 }
2170 }
2171
2172 // For a given cell and span, fetch the set of views intersecting the region.
2173 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2174 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2175 if (boundingRect != null) {
2176 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2177 }
2178 intersectingViews.clear();
2179 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2180 Rect r1 = new Rect();
2181 final int count = mShortcutsAndWidgets.getChildCount();
2182 for (int i = 0; i < count; i++) {
2183 View child = mShortcutsAndWidgets.getChildAt(i);
2184 if (child == dragView) continue;
2185 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2186 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2187 if (Rect.intersects(r0, r1)) {
2188 mIntersectingViews.add(child);
2189 if (boundingRect != null) {
2190 boundingRect.union(r1);
2191 }
2192 }
2193 }
2194 }
2195
2196 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2197 View dragView, int[] result) {
2198 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2199 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2200 mIntersectingViews);
2201 return !mIntersectingViews.isEmpty();
2202 }
2203
2204 void revertTempState() {
2205 if (!isItemPlacementDirty() || DESTRUCTIVE_REORDER) return;
2206 final int count = mShortcutsAndWidgets.getChildCount();
2207 for (int i = 0; i < count; i++) {
2208 View child = mShortcutsAndWidgets.getChildAt(i);
2209 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2210 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2211 lp.tmpCellX = lp.cellX;
2212 lp.tmpCellY = lp.cellY;
2213 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2214 0, false, false);
2215 }
2216 }
2217 completeAndClearReorderHintAnimations();
2218 setItemPlacementDirty(false);
2219 }
2220
Adam Cohenbebf0422012-04-11 18:06:28 -07002221 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2222 View dragView, int[] direction, boolean commit) {
2223 int[] pixelXY = new int[2];
2224 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2225
2226 // First we determine if things have moved enough to cause a different layout
2227 ItemConfiguration swapSolution = simpleSwap(pixelXY[0], pixelXY[1], spanX, spanY,
2228 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2229
2230 setUseTempCoords(true);
2231 if (swapSolution != null && swapSolution.isSolution) {
2232 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2233 // committing anything or animating anything as we just want to determine if a solution
2234 // exists
2235 copySolutionToTempState(swapSolution, dragView);
2236 setItemPlacementDirty(true);
2237 animateItemsToSolution(swapSolution, dragView, commit);
2238
2239 if (commit) {
2240 commitTempPlacement();
2241 completeAndClearReorderHintAnimations();
2242 setItemPlacementDirty(false);
2243 } else {
2244 beginOrAdjustHintAnimations(swapSolution, dragView,
2245 REORDER_ANIMATION_DURATION);
2246 }
2247 mShortcutsAndWidgets.requestLayout();
2248 }
2249 return swapSolution.isSolution;
2250 }
2251
Adam Cohen482ed822012-03-02 14:15:13 -08002252 int[] createArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2253 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002254 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002255 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002256
2257 if (resultSpan == null) {
2258 resultSpan = new int[2];
2259 }
2260
Adam Cohen19f37922012-03-21 11:59:11 -07002261 // When we are checking drop validity or actually dropping, we don't recompute the
2262 // direction vector, since we want the solution to match the preview, and it's possible
2263 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002264 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2265 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002266 mDirectionVector[0] = mPreviousReorderDirection[0];
2267 mDirectionVector[1] = mPreviousReorderDirection[1];
2268 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002269 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2270 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2271 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002272 }
2273 } else {
2274 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2275 mPreviousReorderDirection[0] = mDirectionVector[0];
2276 mPreviousReorderDirection[1] = mDirectionVector[1];
2277 }
2278
Adam Cohen482ed822012-03-02 14:15:13 -08002279 ItemConfiguration swapSolution = simpleSwap(pixelX, pixelY, minSpanX, minSpanY,
2280 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2281
2282 // We attempt the approach which doesn't shuffle views at all
2283 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2284 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2285
2286 ItemConfiguration finalSolution = null;
2287 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2288 finalSolution = swapSolution;
2289 } else if (noShuffleSolution.isSolution) {
2290 finalSolution = noShuffleSolution;
2291 }
2292
2293 boolean foundSolution = true;
2294 if (!DESTRUCTIVE_REORDER) {
2295 setUseTempCoords(true);
2296 }
2297
2298 if (finalSolution != null) {
2299 result[0] = finalSolution.dragViewX;
2300 result[1] = finalSolution.dragViewY;
2301 resultSpan[0] = finalSolution.dragViewSpanX;
2302 resultSpan[1] = finalSolution.dragViewSpanY;
2303
2304 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2305 // committing anything or animating anything as we just want to determine if a solution
2306 // exists
2307 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2308 if (!DESTRUCTIVE_REORDER) {
2309 copySolutionToTempState(finalSolution, dragView);
2310 }
2311 setItemPlacementDirty(true);
2312 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2313
Adam Cohen19f37922012-03-21 11:59:11 -07002314 if (!DESTRUCTIVE_REORDER &&
2315 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002316 commitTempPlacement();
Adam Cohen19f37922012-03-21 11:59:11 -07002317 completeAndClearReorderHintAnimations();
2318 setItemPlacementDirty(false);
2319 } else {
2320 beginOrAdjustHintAnimations(finalSolution, dragView,
2321 REORDER_ANIMATION_DURATION);
Adam Cohen482ed822012-03-02 14:15:13 -08002322 }
2323 }
2324 } else {
2325 foundSolution = false;
2326 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2327 }
2328
2329 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2330 setUseTempCoords(false);
2331 }
Adam Cohen482ed822012-03-02 14:15:13 -08002332
Michael Jurkaa52570f2012-03-20 03:18:20 -07002333 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002334 return result;
2335 }
2336
Adam Cohen19f37922012-03-21 11:59:11 -07002337 void setItemPlacementDirty(boolean dirty) {
2338 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002339 }
Adam Cohen19f37922012-03-21 11:59:11 -07002340 boolean isItemPlacementDirty() {
2341 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002342 }
2343
2344 private class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002345 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohen482ed822012-03-02 14:15:13 -08002346 boolean isSolution = false;
2347 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2348
2349 int area() {
2350 return dragViewSpanX * dragViewSpanY;
2351 }
Adam Cohen8baab352012-03-20 17:39:21 -07002352 }
2353
2354 private class CellAndSpan {
2355 int x, y;
2356 int spanX, spanY;
2357
2358 public CellAndSpan(int x, int y, int spanX, int spanY) {
2359 this.x = x;
2360 this.y = y;
2361 this.spanX = spanX;
2362 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002363 }
2364 }
2365
Adam Cohendf035382011-04-11 17:22:04 -07002366 /**
2367 * Find a vacant area that will fit the given bounds nearest the requested
2368 * cell location. Uses Euclidean distance to score multiple vacant areas.
2369 *
2370 * @param pixelX The X location at which you want to search for a vacant area.
2371 * @param pixelY The Y location at which you want to search for a vacant area.
2372 * @param spanX Horizontal span of the object.
2373 * @param spanY Vertical span of the object.
2374 * @param ignoreView Considers space occupied by this view as unoccupied
2375 * @param result Previously returned value to possibly recycle.
2376 * @return The X, Y cell of a vacant area that can contain this object,
2377 * nearest the requested location.
2378 */
2379 int[] findNearestVacantArea(
2380 int pixelX, int pixelY, int spanX, int spanY, View ignoreView, int[] result) {
2381 return findNearestArea(pixelX, pixelY, spanX, spanY, ignoreView, true, result);
2382 }
2383
2384 /**
Adam Cohend41fbf52012-02-16 23:53:59 -08002385 * Find a vacant area that will fit the given bounds nearest the requested
2386 * cell location. Uses Euclidean distance to score multiple vacant areas.
2387 *
2388 * @param pixelX The X location at which you want to search for a vacant area.
2389 * @param pixelY The Y location at which you want to search for a vacant area.
2390 * @param minSpanX The minimum horizontal span required
2391 * @param minSpanY The minimum vertical span required
2392 * @param spanX Horizontal span of the object.
2393 * @param spanY Vertical span of the object.
2394 * @param ignoreView Considers space occupied by this view as unoccupied
2395 * @param result Previously returned value to possibly recycle.
2396 * @return The X, Y cell of a vacant area that can contain this object,
2397 * nearest the requested location.
2398 */
2399 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
2400 int spanX, int spanY, View ignoreView, int[] result, int[] resultSpan) {
Adam Cohen482ed822012-03-02 14:15:13 -08002401 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, true,
2402 result, resultSpan, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08002403 }
2404
2405 /**
Adam Cohendf035382011-04-11 17:22:04 -07002406 * Find a starting cell position that will fit the given bounds nearest the requested
2407 * cell location. Uses Euclidean distance to score multiple vacant areas.
2408 *
2409 * @param pixelX The X location at which you want to search for a vacant area.
2410 * @param pixelY The Y location at which you want to search for a vacant area.
2411 * @param spanX Horizontal span of the object.
2412 * @param spanY Vertical span of the object.
2413 * @param ignoreView Considers space occupied by this view as unoccupied
2414 * @param result Previously returned value to possibly recycle.
2415 * @return The X, Y cell of a vacant area that can contain this object,
2416 * nearest the requested location.
2417 */
2418 int[] findNearestArea(
2419 int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2420 return findNearestArea(pixelX, pixelY, spanX, spanY, null, false, result);
2421 }
2422
Michael Jurka0280c3b2010-09-17 15:00:07 -07002423 boolean existsEmptyCell() {
2424 return findCellForSpan(null, 1, 1);
2425 }
2426
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002427 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002428 * Finds the upper-left coordinate of the first rectangle in the grid that can
2429 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2430 * then this method will only return coordinates for rectangles that contain the cell
2431 * (intersectX, intersectY)
2432 *
2433 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2434 * can be found.
2435 * @param spanX The horizontal span of the cell we want to find.
2436 * @param spanY The vertical span of the cell we want to find.
2437 *
2438 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002439 */
Michael Jurka0280c3b2010-09-17 15:00:07 -07002440 boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08002441 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002442 }
2443
2444 /**
2445 * Like above, but ignores any cells occupied by the item "ignoreView"
2446 *
2447 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2448 * can be found.
2449 * @param spanX The horizontal span of the cell we want to find.
2450 * @param spanY The vertical span of the cell we want to find.
2451 * @param ignoreView The home screen item we should treat as not occupying any space
2452 * @return
2453 */
2454 boolean findCellForSpanIgnoring(int[] cellXY, int spanX, int spanY, View ignoreView) {
Adam Cohen482ed822012-03-02 14:15:13 -08002455 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1,
2456 ignoreView, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002457 }
2458
2459 /**
2460 * Like above, but if intersectX and intersectY are not -1, then this method will try to
2461 * return coordinates for rectangles that contain the cell [intersectX, intersectY]
2462 *
2463 * @param spanX The horizontal span of the cell we want to find.
2464 * @param spanY The vertical span of the cell we want to find.
2465 * @param ignoreView The home screen item we should treat as not occupying any space
2466 * @param intersectX The X coordinate of the cell that we should try to overlap
2467 * @param intersectX The Y coordinate of the cell that we should try to overlap
2468 *
2469 * @return True if a vacant cell of the specified dimension was found, false otherwise.
2470 */
2471 boolean findCellForSpanThatIntersects(int[] cellXY, int spanX, int spanY,
2472 int intersectX, int intersectY) {
2473 return findCellForSpanThatIntersectsIgnoring(
Adam Cohen482ed822012-03-02 14:15:13 -08002474 cellXY, spanX, spanY, intersectX, intersectY, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002475 }
2476
2477 /**
2478 * The superset of the above two methods
2479 */
2480 boolean findCellForSpanThatIntersectsIgnoring(int[] cellXY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002481 int intersectX, int intersectY, View ignoreView, boolean occupied[][]) {
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002482 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08002483 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002484
Michael Jurka28750fb2010-09-24 17:43:49 -07002485 boolean foundCell = false;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002486 while (true) {
2487 int startX = 0;
2488 if (intersectX >= 0) {
2489 startX = Math.max(startX, intersectX - (spanX - 1));
2490 }
2491 int endX = mCountX - (spanX - 1);
2492 if (intersectX >= 0) {
2493 endX = Math.min(endX, intersectX + (spanX - 1) + (spanX == 1 ? 1 : 0));
2494 }
2495 int startY = 0;
2496 if (intersectY >= 0) {
2497 startY = Math.max(startY, intersectY - (spanY - 1));
2498 }
2499 int endY = mCountY - (spanY - 1);
2500 if (intersectY >= 0) {
2501 endY = Math.min(endY, intersectY + (spanY - 1) + (spanY == 1 ? 1 : 0));
2502 }
2503
Winson Chungbbc60d82010-11-11 16:34:41 -08002504 for (int y = startY; y < endY && !foundCell; y++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002505 inner:
Winson Chungbbc60d82010-11-11 16:34:41 -08002506 for (int x = startX; x < endX; x++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002507 for (int i = 0; i < spanX; i++) {
2508 for (int j = 0; j < spanY; j++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002509 if (occupied[x + i][y + j]) {
Winson Chungbbc60d82010-11-11 16:34:41 -08002510 // small optimization: we can skip to after the column we just found
Michael Jurka0280c3b2010-09-17 15:00:07 -07002511 // an occupied cell
Winson Chungbbc60d82010-11-11 16:34:41 -08002512 x += i;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002513 continue inner;
2514 }
2515 }
2516 }
2517 if (cellXY != null) {
2518 cellXY[0] = x;
2519 cellXY[1] = y;
2520 }
Michael Jurka28750fb2010-09-24 17:43:49 -07002521 foundCell = true;
2522 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002523 }
2524 }
2525 if (intersectX == -1 && intersectY == -1) {
2526 break;
2527 } else {
2528 // if we failed to find anything, try again but without any requirements of
2529 // intersecting
2530 intersectX = -1;
2531 intersectY = -1;
2532 continue;
2533 }
2534 }
2535
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002536 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08002537 markCellsAsOccupiedForView(ignoreView, occupied);
Michael Jurka28750fb2010-09-24 17:43:49 -07002538 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002539 }
2540
2541 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002542 * A drag event has begun over this layout.
2543 * It may have begun over this layout (in which case onDragChild is called first),
2544 * or it may have begun on another layout.
2545 */
2546 void onDragEnter() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002547 mDragEnforcer.onDragEnter();
Winson Chungc07918d2011-07-01 15:35:26 -07002548 if (!mDragging) {
2549 // Fade in the drag indicators
2550 if (mCrosshairsAnimator != null) {
2551 mCrosshairsAnimator.animateIn();
2552 }
2553 }
2554 mDragging = true;
2555 }
2556
2557 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002558 * Called when drag has left this CellLayout or has been completed (successfully or not)
2559 */
2560 void onDragExit() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002561 mDragEnforcer.onDragExit();
Joe Onorato4be866d2010-10-10 11:26:02 -07002562 // This can actually be called when we aren't in a drag, e.g. when adding a new
2563 // item to this layout via the customize drawer.
2564 // Guard against that case.
2565 if (mDragging) {
2566 mDragging = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002567
Joe Onorato4be866d2010-10-10 11:26:02 -07002568 // Fade out the drag indicators
2569 if (mCrosshairsAnimator != null) {
2570 mCrosshairsAnimator.animateOut();
2571 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002572 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002573
2574 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002575 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002576 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2577 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002578 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002579 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002580 }
2581
2582 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002583 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002584 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002585 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002586 *
2587 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002588 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002589 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002590 if (child != null) {
2591 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002592 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002593 child.requestLayout();
Romain Guyd94533d2009-08-17 10:01:15 -07002594 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002595 }
2596
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002597 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002598 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002599 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002600 * @param cellX X coordinate of upper left corner expressed as a cell position
2601 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002602 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002603 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002604 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002605 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002606 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002607 final int cellWidth = mCellWidth;
2608 final int cellHeight = mCellHeight;
2609 final int widthGap = mWidthGap;
2610 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002611
Winson Chung4b825dcd2011-06-19 12:41:22 -07002612 final int hStartPadding = getPaddingLeft();
2613 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002614
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002615 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2616 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2617
2618 int x = hStartPadding + cellX * (cellWidth + widthGap);
2619 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002620
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002621 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002622 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002623
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002624 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002625 * Computes the required horizontal and vertical cell spans to always
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002626 * fit the given rectangle.
Winson Chungaafa03c2010-06-11 17:34:16 -07002627 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002628 * @param width Width in pixels
2629 * @param height Height in pixels
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002630 * @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 -08002631 */
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002632 public int[] rectToCell(int width, int height, int[] result) {
Michael Jurka9987a5c2010-10-08 16:58:12 -07002633 return rectToCell(getResources(), width, height, result);
2634 }
2635
2636 public static int[] rectToCell(Resources resources, int width, int height, int[] result) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002637 // Always assume we're working with the smallest span to make sure we
2638 // reserve enough space in both orientations.
Joe Onorato79e56262009-09-21 15:23:04 -04002639 int actualWidth = resources.getDimensionPixelSize(R.dimen.workspace_cell_width);
2640 int actualHeight = resources.getDimensionPixelSize(R.dimen.workspace_cell_height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002641 int smallerSize = Math.min(actualWidth, actualHeight);
Joe Onorato79e56262009-09-21 15:23:04 -04002642
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002643 // Always round up to next largest cell
Winson Chung54c725c2011-08-03 12:03:40 -07002644 int spanX = (int) Math.ceil(width / (float) smallerSize);
2645 int spanY = (int) Math.ceil(height / (float) smallerSize);
Joe Onorato79e56262009-09-21 15:23:04 -04002646
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002647 if (result == null) {
2648 return new int[] { spanX, spanY };
2649 }
2650 result[0] = spanX;
2651 result[1] = spanY;
2652 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002653 }
2654
Michael Jurkaf12c75c2011-01-25 22:41:40 -08002655 public int[] cellSpansToSize(int hSpans, int vSpans) {
2656 int[] size = new int[2];
2657 size[0] = hSpans * mCellWidth + (hSpans - 1) * mWidthGap;
2658 size[1] = vSpans * mCellHeight + (vSpans - 1) * mHeightGap;
2659 return size;
2660 }
2661
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002662 /**
Patrick Dubroy047379a2010-12-19 22:02:04 -08002663 * Calculate the grid spans needed to fit given item
2664 */
2665 public void calculateSpans(ItemInfo info) {
2666 final int minWidth;
2667 final int minHeight;
2668
2669 if (info instanceof LauncherAppWidgetInfo) {
2670 minWidth = ((LauncherAppWidgetInfo) info).minWidth;
2671 minHeight = ((LauncherAppWidgetInfo) info).minHeight;
2672 } else if (info instanceof PendingAddWidgetInfo) {
2673 minWidth = ((PendingAddWidgetInfo) info).minWidth;
2674 minHeight = ((PendingAddWidgetInfo) info).minHeight;
2675 } else {
2676 // It's not a widget, so it must be 1x1
2677 info.spanX = info.spanY = 1;
2678 return;
2679 }
2680 int[] spans = rectToCell(minWidth, minHeight, null);
2681 info.spanX = spans[0];
2682 info.spanY = spans[1];
2683 }
2684
2685 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002686 * Find the first vacant cell, if there is one.
2687 *
2688 * @param vacant Holds the x and y coordinate of the vacant cell
2689 * @param spanX Horizontal cell span.
2690 * @param spanY Vertical cell span.
Winson Chungaafa03c2010-06-11 17:34:16 -07002691 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002692 * @return True if a vacant cell was found
2693 */
2694 public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002695
Michael Jurka0280c3b2010-09-17 15:00:07 -07002696 return findVacantCell(vacant, spanX, spanY, mCountX, mCountY, mOccupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002697 }
2698
2699 static boolean findVacantCell(int[] vacant, int spanX, int spanY,
2700 int xCount, int yCount, boolean[][] occupied) {
2701
Adam Cohen2801caf2011-05-13 20:57:39 -07002702 for (int y = 0; y < yCount; y++) {
2703 for (int x = 0; x < xCount; x++) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002704 boolean available = !occupied[x][y];
2705out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
2706 for (int j = y; j < y + spanY - 1 && y < yCount; j++) {
2707 available = available && !occupied[i][j];
2708 if (!available) break out;
2709 }
2710 }
2711
2712 if (available) {
2713 vacant[0] = x;
2714 vacant[1] = y;
2715 return true;
2716 }
2717 }
2718 }
2719
2720 return false;
2721 }
2722
Michael Jurka0280c3b2010-09-17 15:00:07 -07002723 private void clearOccupiedCells() {
2724 for (int x = 0; x < mCountX; x++) {
2725 for (int y = 0; y < mCountY; y++) {
2726 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002727 }
2728 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002729 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002730
Adam Cohend41fbf52012-02-16 23:53:59 -08002731 public void onMove(View view, int newCellX, int newCellY, int newSpanX, int newSpanY) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002732 markCellsAsUnoccupiedForView(view);
Adam Cohen482ed822012-03-02 14:15:13 -08002733 markCellsForView(newCellX, newCellY, newSpanX, newSpanY, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002734 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002735
Adam Cohend4844c32011-02-18 19:25:06 -08002736 public void markCellsAsOccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002737 markCellsAsOccupiedForView(view, mOccupied);
2738 }
2739 public void markCellsAsOccupiedForView(View view, boolean[][] occupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002740 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002741 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002742 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002743 }
2744
Adam Cohend4844c32011-02-18 19:25:06 -08002745 public void markCellsAsUnoccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002746 markCellsAsUnoccupiedForView(view, mOccupied);
2747 }
2748 public void markCellsAsUnoccupiedForView(View view, boolean occupied[][]) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002749 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002750 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002751 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002752 }
2753
Adam Cohen482ed822012-03-02 14:15:13 -08002754 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2755 boolean value) {
2756 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002757 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2758 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002759 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002760 }
2761 }
2762 }
2763
Adam Cohen2801caf2011-05-13 20:57:39 -07002764 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002765 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002766 (Math.max((mCountX - 1), 0) * mWidthGap);
2767 }
2768
2769 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002770 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002771 (Math.max((mCountY - 1), 0) * mHeightGap);
2772 }
2773
Michael Jurka66d72172011-04-12 16:29:25 -07002774 public boolean isOccupied(int x, int y) {
2775 if (x < mCountX && y < mCountY) {
2776 return mOccupied[x][y];
2777 } else {
2778 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2779 }
2780 }
2781
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002782 @Override
2783 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2784 return new CellLayout.LayoutParams(getContext(), attrs);
2785 }
2786
2787 @Override
2788 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2789 return p instanceof CellLayout.LayoutParams;
2790 }
2791
2792 @Override
2793 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2794 return new CellLayout.LayoutParams(p);
2795 }
2796
Winson Chungaafa03c2010-06-11 17:34:16 -07002797 public static class CellLayoutAnimationController extends LayoutAnimationController {
2798 public CellLayoutAnimationController(Animation animation, float delay) {
2799 super(animation, delay);
2800 }
2801
2802 @Override
2803 protected long getDelayForView(View view) {
2804 return (int) (Math.random() * 150);
2805 }
2806 }
2807
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002808 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2809 /**
2810 * Horizontal location of the item in the grid.
2811 */
2812 @ViewDebug.ExportedProperty
2813 public int cellX;
2814
2815 /**
2816 * Vertical location of the item in the grid.
2817 */
2818 @ViewDebug.ExportedProperty
2819 public int cellY;
2820
2821 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002822 * Temporary horizontal location of the item in the grid during reorder
2823 */
2824 public int tmpCellX;
2825
2826 /**
2827 * Temporary vertical location of the item in the grid during reorder
2828 */
2829 public int tmpCellY;
2830
2831 /**
2832 * Indicates that the temporary coordinates should be used to layout the items
2833 */
2834 public boolean useTmpCoords;
2835
2836 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002837 * Number of cells spanned horizontally by the item.
2838 */
2839 @ViewDebug.ExportedProperty
2840 public int cellHSpan;
2841
2842 /**
2843 * Number of cells spanned vertically by the item.
2844 */
2845 @ViewDebug.ExportedProperty
2846 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002847
Adam Cohen1b607ed2011-03-03 17:26:50 -08002848 /**
2849 * Indicates whether the item will set its x, y, width and height parameters freely,
2850 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2851 */
Adam Cohend4844c32011-02-18 19:25:06 -08002852 public boolean isLockedToGrid = true;
2853
Adam Cohen482ed822012-03-02 14:15:13 -08002854 /**
2855 * Indicates whether this item can be reordered. Always true except in the case of the
2856 * the AllApps button.
2857 */
2858 public boolean canReorder = true;
2859
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002860 // X coordinate of the view in the layout.
2861 @ViewDebug.ExportedProperty
2862 int x;
2863 // Y coordinate of the view in the layout.
2864 @ViewDebug.ExportedProperty
2865 int y;
2866
Romain Guy84f296c2009-11-04 15:00:44 -08002867 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002868
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002869 public LayoutParams(Context c, AttributeSet attrs) {
2870 super(c, attrs);
2871 cellHSpan = 1;
2872 cellVSpan = 1;
2873 }
2874
2875 public LayoutParams(ViewGroup.LayoutParams source) {
2876 super(source);
2877 cellHSpan = 1;
2878 cellVSpan = 1;
2879 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002880
2881 public LayoutParams(LayoutParams source) {
2882 super(source);
2883 this.cellX = source.cellX;
2884 this.cellY = source.cellY;
2885 this.cellHSpan = source.cellHSpan;
2886 this.cellVSpan = source.cellVSpan;
2887 }
2888
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002889 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002890 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002891 this.cellX = cellX;
2892 this.cellY = cellY;
2893 this.cellHSpan = cellHSpan;
2894 this.cellVSpan = cellVSpan;
2895 }
2896
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002897 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap) {
Adam Cohend4844c32011-02-18 19:25:06 -08002898 if (isLockedToGrid) {
2899 final int myCellHSpan = cellHSpan;
2900 final int myCellVSpan = cellVSpan;
Adam Cohen482ed822012-03-02 14:15:13 -08002901 final int myCellX = useTmpCoords ? tmpCellX : cellX;
2902 final int myCellY = useTmpCoords ? tmpCellY : cellY;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002903
Adam Cohend4844c32011-02-18 19:25:06 -08002904 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2905 leftMargin - rightMargin;
2906 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2907 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002908 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2909 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002910 }
2911 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002912
Winson Chungaafa03c2010-06-11 17:34:16 -07002913 public String toString() {
2914 return "(" + this.cellX + ", " + this.cellY + ")";
2915 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002916
2917 public void setWidth(int width) {
2918 this.width = width;
2919 }
2920
2921 public int getWidth() {
2922 return width;
2923 }
2924
2925 public void setHeight(int height) {
2926 this.height = height;
2927 }
2928
2929 public int getHeight() {
2930 return height;
2931 }
2932
2933 public void setX(int x) {
2934 this.x = x;
2935 }
2936
2937 public int getX() {
2938 return x;
2939 }
2940
2941 public void setY(int y) {
2942 this.y = y;
2943 }
2944
2945 public int getY() {
2946 return y;
2947 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002948 }
2949
Michael Jurka0280c3b2010-09-17 15:00:07 -07002950 // This class stores info for two purposes:
2951 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2952 // its spanX, spanY, and the screen it is on
2953 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2954 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2955 // the CellLayout that was long clicked
Michael Jurkae5fb0f22011-04-11 13:27:46 -07002956 static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002957 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002958 int cellX = -1;
2959 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002960 int spanX;
2961 int spanY;
2962 int screen;
Winson Chung3d503fb2011-07-13 17:25:49 -07002963 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002964
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002965 @Override
2966 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002967 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2968 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002969 }
2970 }
Michael Jurkad771c962011-08-09 15:00:48 -07002971
2972 public boolean lastDownOnOccupiedCell() {
2973 return mLastDownOnOccupiedCell;
2974 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002975}